Commit cdd05b35 by Harsh Shah

Finish Release-20170926

parents 8161664b 4f975674
...@@ -8,6 +8,14 @@ ...@@ -8,6 +8,14 @@
<property name="nodelete.appwar" value="${nodelete}"/> <property name="nodelete.appwar" value="${nodelete}"/>
<path id="cmsWebApp.lib"> <path id="cmsWebApp.lib">
<pathelement location="${build.target.dir}/overlay/CougarCMS8.2/bin/cmsWebApp"/> <pathelement location="${build.target.dir}/overlay/CougarCMS8.2/bin/cmsWebApp"/>
<fileset dir="${cmsWebApp.lib.dir}">
<include name="**/*.jar"/>
<include name="**/*.zip"/>
<exclude name="**/.new*"/>
</fileset>
</path>
<target name="copylib">
<jsync todir="${cmsWebApp.lib.dir}" flatten="true">
<fileset dir="${build.target.dir}/overlay/CougarCMS8.2/lib/cmsWebApp"> <fileset dir="${build.target.dir}/overlay/CougarCMS8.2/lib/cmsWebApp">
<include name="**/*.jar"/> <include name="**/*.jar"/>
<include name="**/*.zip"/> <include name="**/*.zip"/>
...@@ -32,20 +40,14 @@ ...@@ -32,20 +40,14 @@
<include name="*/lib-no-deploy/*.zip"/> <include name="*/lib-no-deploy/*.zip"/>
<exclude name="*/lib/.new*"/> <exclude name="*/lib/.new*"/>
</fileset> </fileset>
<fileset dir="${libnodeploy.dir}"> <fileset dir="../../CougarCMS8.2/cmsWebApp/lib-no-deploy">
<include name="**/*.jar"/> <include name="**/*.jar"/>
<include name="**/*.zip"/> <include name="**/*.zip"/>
</fileset> </fileset>
<fileset dir="../../CougarCMS8.2/cmsWebApp/lib-no-deploy"> <fileset dir="${libnodeploy.dir}">
<include name="**/*.jar"/> <include name="**/*.jar"/>
<include name="**/*.zip"/> <include name="**/*.zip"/>
</fileset> </fileset>
</path>
<target name="copylib">
<jsync todir="${cmsWebApp.lib.dir}">
<fileset dir="${lib.dir}">
<exclude name="**/.new*"/>
</fileset>
</jsync> </jsync>
</target> </target>
<target name="execute-overlays"> <target name="execute-overlays">
......
<?xml version="1.0" encoding="UTF-8"?>
<!-- @AutoRun -->
<OBJECTS name="" xmlns:oneit="http://www.1iT.com.au"><NODE name="Script" factory="Vector">
<NODE name="DDL" factory="Participant" class="oneit.sql.transfer.DefineTableOperation">
<tableName factory="String">oneit_sec_user_extension</tableName>
<column name="object_id" type="Long" nullable="false" length="11"/>
<column name="object_last_updated_date" type="Date" nullable="false" length="22"/>
<column name="object_created_date" type="Date" nullable="false" length="22"/>
<column name="object_type" type="String" nullable="false" length="30"/>
<column name="forgot_password_mail_send_date" type="Date" nullable="true"/>
<column name="forgot_password_key" type="String" nullable="true" length="10"/>
<column name="user_id" type="Long" length="11" nullable="true"/>
</NODE>
<NODE name="INDEX" factory="Participant" class="oneit.sql.transfer.DefineIndexOperation" tableName="oneit_sec_user_extension" indexName="idx_oneit_sec_user_extension_user_id" isUnique="false"><column name="user_id"/></NODE>
</NODE></OBJECTS>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!-- @AutoRun -->
<OBJECTS name="" xmlns:oneit="http://www.1iT.com.au"><NODE name="Script" factory="Vector">
<NODE name="DDL" factory="Participant" class="oneit.sql.transfer.DefineTableOperation">
<tableName factory="String">tl_industry</tableName>
<column name="object_id" type="Long" nullable="false" length="11"/>
<column name="object_last_updated_date" type="Date" nullable="false" length="22"/>
<column name="object_created_date" type="Date" nullable="false" length="22"/>
<column name="NAME" type="String" nullable="false" length="200"/>
<column name="VALUE" type="String" nullable="false" length="200"/>
<column name="DESCRIPTION" type="String" nullable="true" length="200"/>
<column name="SORT_ORDER" type="Long" nullable="false"/>
<column name="DISABLED" type="Boolean" nullable="false"/>
</NODE>
</NODE></OBJECTS>
\ No newline at end of file
...@@ -10,6 +10,8 @@ ...@@ -10,6 +10,8 @@
<column name="object_created_date" type="Date" nullable="false" length="22"/> <column name="object_created_date" type="Date" nullable="false" length="22"/>
<column name="object_type" type="String" nullable="false" length="30"/> <column name="object_type" type="String" nullable="false" length="30"/>
<column name="phone" type="String" nullable="true" length="30"/> <column name="phone" type="String" nullable="true" length="30"/>
<column name="forgot_password_mail_send_date" type="Date" nullable="true"/>
<column name="forgot_password_key" type="String" nullable="true" length="10"/>
<column name="verification_mail_send_date" type="Date" nullable="true"/> <column name="verification_mail_send_date" type="Date" nullable="true"/>
<column name="verification_key" type="String" nullable="true" length="10"/> <column name="verification_key" type="String" nullable="true" length="10"/>
<column name="is_account_verified" type="Boolean" nullable="true"/> <column name="is_account_verified" type="Boolean" nullable="true"/>
......
<?xml version="1.0" encoding="UTF-8"?>
<!-- @AutoRun -->
<OBJECTS name="" xmlns:oneit="http://www.1iT.com.au"><NODE name="Script" factory="Vector">
<NODE name="DDL" factory="Participant" class="oneit.sql.transfer.DefineTableOperation">
<tableName factory="String">tl_client</tableName>
<column name="object_id" type="Long" nullable="false" length="11"/>
<column name="object_last_updated_date" type="Date" nullable="false" length="22"/>
<column name="object_created_date" type="Date" nullable="false" length="22"/>
<column name="client_name" type="String" nullable="false" length="100"/>
<column name="client_logo" type="BLOB" nullable="true"/>
<column name="email" type="String" nullable="true" length="100"/>
<column name="contact_name" type="String" nullable="true" length="100"/>
<column name="contact_surname" type="String" nullable="true" length="100"/>
<column name="phone" type="String" nullable="true" length="30"/>
<column name="state" type="String" nullable="true" length="200"/>
<column name="country" type="String" nullable="true" length="200"/>
<column name="post_code" type="String" nullable="true" length="10"/>
<column name="city" type="String" nullable="true" length="100"/>
<column name="time_zone" type="String" nullable="true" length="200"/>
<column name="company_id" type="Long" length="11" nullable="false"/>
</NODE>
<NODE name="INDEX" factory="Participant" class="oneit.sql.transfer.DefineIndexOperation" tableName="tl_client" indexName="idx_tl_client_company_id" isUnique="false"><column name="company_id"/></NODE>
</NODE></OBJECTS>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!-- @AutoRun -->
<OBJECTS name="" xmlns:oneit="http://www.1iT.com.au"><NODE name="Script" factory="Vector">
<NODE name="DDL" factory="Participant" class="oneit.sql.transfer.DefineTableOperation">
<tableName factory="String">tl_company</tableName>
<column name="object_id" type="Long" nullable="false" length="11"/>
<column name="object_last_updated_date" type="Date" nullable="false" length="22"/>
<column name="object_created_date" type="Date" nullable="false" length="22"/>
<column name="company_name" type="String" nullable="false" length="100"/>
<column name="company_logo" type="BLOB" nullable="true"/>
<column name="hiring_team_type" type="String" nullable="true" length="200"/>
<column name="industry" type="String" nullable="true" length="200"/>
<column name="time_zone" type="String" nullable="true" length="200"/>
<column name="is_verified" type="Boolean" nullable="true"/>
<column name="state" type="String" nullable="true" length="200"/>
<column name="country" type="String" nullable="true" length="200"/>
<column name="post_code" type="String" nullable="true" length="10"/>
<column name="city" type="String" nullable="true" length="100"/>
<column name="has_client_support" type="Boolean" nullable="true"/>
<column name="added_by_user_id" type="Long" length="11" nullable="false"/>
</NODE>
</NODE></OBJECTS>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!-- @AutoRun -->
<OBJECTS name="" xmlns:oneit="http://www.1iT.com.au"><NODE name="Script" factory="Vector">
<NODE name="DDL" factory="Participant" class="oneit.sql.transfer.DefineTableOperation">
<tableName factory="String">oneit_sec_user_extension</tableName>
<column name="object_id" type="Long" nullable="false" length="11"/>
<column name="object_last_updated_date" type="Date" nullable="false" length="22"/>
<column name="object_created_date" type="Date" nullable="false" length="22"/>
<column name="object_type" type="String" nullable="false" length="30"/>
<column name="forgot_password_mail_send_date" type="Date" nullable="true"/>
<column name="forgot_password_key" type="String" nullable="true" length="10"/>
<column name="role_type" type="String" nullable="true" length="200"/>
<column name="phone" type="String" nullable="true" length="30"/>
<column name="verification_mail_send_date" type="Date" nullable="true"/>
<column name="verification_key" type="String" nullable="true" length="10"/>
<column name="is_account_verified" type="Boolean" nullable="true"/>
<column name="is_email_changed" type="Boolean" nullable="true"/>
<column name="user_id" type="Long" length="11" nullable="true"/>
<column name="company_id" type="Long" length="11" nullable="true"/>
</NODE>
<NODE name="INDEX" factory="Participant" class="oneit.sql.transfer.DefineIndexOperation" tableName="oneit_sec_user_extension" indexName="idx_oneit_sec_user_extension_user_id" isUnique="false"><column name="user_id"/></NODE>
<NODE name="INDEX" factory="Participant" class="oneit.sql.transfer.DefineIndexOperation" tableName="oneit_sec_user_extension" indexName="idx_oneit_sec_user_extension_company_id" isUnique="false"><column name="company_id"/></NODE>
</NODE></OBJECTS>
\ No newline at end of file
...@@ -24,7 +24,10 @@ ...@@ -24,7 +24,10 @@
<column name="state" type="String" nullable="true" length="200"/> <column name="state" type="String" nullable="true" length="200"/>
<column name="country" type="String" nullable="true" length="200"/> <column name="country" type="String" nullable="true" length="200"/>
<column name="level_id" type="Long" length="11" nullable="false"/> <column name="level_id" type="Long" length="11" nullable="false"/>
<column name="secuser_id" type="Long" length="11" nullable="true"/> <column name="client_id" type="Long" length="11" nullable="true"/>
<column name="company_user_id" type="Long" length="11" nullable="true"/>
</NODE> </NODE>
<NODE name="INDEX" factory="Participant" class="oneit.sql.transfer.DefineIndexOperation" tableName="tl_job" indexName="idx_tl_job_client_id" isUnique="false"><column name="client_id"/></NODE>
</NODE></OBJECTS> </NODE></OBJECTS>
\ No newline at end of file
-- DROP TABLE oneit_sec_user_extension;
CREATE TABLE oneit_sec_user_extension (
object_id int NOT NULL ,
object_last_updated_date datetime DEFAULT getdate() NOT NULL ,
object_created_date datetime DEFAULT getdate() NOT NULL
, object_type varchar(30) NOT NULL ,
forgot_password_mail_send_date datetime NULL,
forgot_password_key varchar(10) NULL,
user_id numeric(12) NULL
);
ALTER TABLE oneit_sec_user_extension ADD
CONSTRAINT PK_oneit_sec_user_extension PRIMARY KEY
(
object_id
) ;
CREATE INDEX idx_oneit_sec_user_extension_user_id
ON oneit_sec_user_extension (user_id);
-- DROP TABLE tl_industry;
CREATE TABLE tl_industry (
object_id int NOT NULL ,
object_last_updated_date datetime DEFAULT getdate() NOT NULL ,
object_created_date datetime DEFAULT getdate() NOT NULL
,
NAME varchar(200) NOT NULL,
VALUE varchar(200) NOT NULL,
DESCRIPTION varchar(200) NULL,
SORT_ORDER numeric(12) NOT NULL ,
DISABLED char(1) NOT NULL
);
ALTER TABLE tl_industry ADD
CONSTRAINT PK_tl_industry PRIMARY KEY
(
object_id
) ;
\ No newline at end of file
...@@ -9,6 +9,8 @@ CREATE TABLE oneit_sec_user_extension ( ...@@ -9,6 +9,8 @@ CREATE TABLE oneit_sec_user_extension (
object_created_date datetime DEFAULT getdate() NOT NULL object_created_date datetime DEFAULT getdate() NOT NULL
, object_type varchar(30) NOT NULL , , object_type varchar(30) NOT NULL ,
phone varchar(30) NULL, phone varchar(30) NULL,
forgot_password_mail_send_date datetime NULL,
forgot_password_key varchar(10) NULL,
verification_mail_send_date datetime NULL, verification_mail_send_date datetime NULL,
verification_key varchar(10) NULL, verification_key varchar(10) NULL,
is_account_verified char(1) NULL, is_account_verified char(1) NULL,
......
-- DROP TABLE tl_client;
CREATE TABLE tl_client (
object_id int NOT NULL ,
object_last_updated_date datetime DEFAULT getdate() NOT NULL ,
object_created_date datetime DEFAULT getdate() NOT NULL
,
client_name varchar(100) NOT NULL,
client_logo image NULL,
email varchar(100) NULL,
contact_name varchar(100) NULL,
contact_surname varchar(100) NULL,
phone varchar(30) NULL,
state varchar(200) NULL,
country varchar(200) NULL,
post_code varchar(10) NULL,
city varchar(100) NULL,
time_zone varchar(200) NULL,
company_id numeric(12) NOT NULL
);
ALTER TABLE tl_client ADD
CONSTRAINT PK_tl_client PRIMARY KEY
(
object_id
) ;
CREATE INDEX idx_tl_client_company_id
ON tl_client (company_id);
-- DROP TABLE tl_company;
CREATE TABLE tl_company (
object_id int NOT NULL ,
object_last_updated_date datetime DEFAULT getdate() NOT NULL ,
object_created_date datetime DEFAULT getdate() NOT NULL
,
company_name varchar(100) NOT NULL,
company_logo image NULL,
hiring_team_type varchar(200) NULL,
industry varchar(200) NULL,
time_zone varchar(200) NULL,
is_verified char(1) NULL,
state varchar(200) NULL,
country varchar(200) NULL,
post_code varchar(10) NULL,
city varchar(100) NULL,
has_client_support char(1) NULL,
added_by_user_id numeric(12) NOT NULL
);
ALTER TABLE tl_company ADD
CONSTRAINT PK_tl_company PRIMARY KEY
(
object_id
) ;
\ No newline at end of file
-- DROP TABLE oneit_sec_user_extension;
CREATE TABLE oneit_sec_user_extension (
object_id int NOT NULL ,
object_last_updated_date datetime DEFAULT getdate() NOT NULL ,
object_created_date datetime DEFAULT getdate() NOT NULL
, object_type varchar(30) NOT NULL ,
forgot_password_mail_send_date datetime NULL,
forgot_password_key varchar(10) NULL,
role_type varchar(200) NULL,
phone varchar(30) NULL,
verification_mail_send_date datetime NULL,
verification_key varchar(10) NULL,
is_account_verified char(1) NULL,
is_email_changed char(1) NULL,
user_id numeric(12) NULL,
company_id numeric(12) NULL
);
ALTER TABLE oneit_sec_user_extension ADD
CONSTRAINT PK_oneit_sec_user_extension PRIMARY KEY
(
object_id
) ;
CREATE INDEX idx_oneit_sec_user_extension_user_id
ON oneit_sec_user_extension (user_id);
CREATE INDEX idx_oneit_sec_user_extension_company_id
ON oneit_sec_user_extension (company_id);
...@@ -24,7 +24,8 @@ CREATE TABLE tl_job ( ...@@ -24,7 +24,8 @@ CREATE TABLE tl_job (
state varchar(200) NULL, state varchar(200) NULL,
country varchar(200) NULL, country varchar(200) NULL,
level_id numeric(12) NOT NULL, level_id numeric(12) NOT NULL,
secuser_id numeric(12) NULL client_id numeric(12) NULL,
company_user_id numeric(12) NULL
); );
...@@ -37,3 +38,5 @@ ALTER TABLE tl_job ADD ...@@ -37,3 +38,5 @@ ALTER TABLE tl_job ADD
CREATE INDEX idx_tl_job_client_id
ON tl_job (client_id);
-- DROP TABLE oneit_sec_user_extension;
CREATE TABLE oneit_sec_user_extension (
object_id number(12) NOT NULL ,
object_last_updated_date date DEFAULT SYSDATE NOT NULL ,
object_created_date date DEFAULT SYSDATE NOT NULL
, object_type varchar2(30) NOT NULL ,
forgot_password_mail_send_date date NULL,
forgot_password_key varchar2(10) NULL,
user_id number(12) NULL
);
ALTER TABLE oneit_sec_user_extension ADD
CONSTRAINT PK_oneit_sec_user_extension PRIMARY KEY
(
object_id
) ;
CREATE INDEX idx_oneit_sec_user_extension_user_id
ON oneit_sec_user_extension (user_id);
-- DROP TABLE tl_industry;
CREATE TABLE tl_industry (
object_id number(12) NOT NULL ,
object_last_updated_date date DEFAULT SYSDATE NOT NULL ,
object_created_date date DEFAULT SYSDATE NOT NULL
,
NAME varchar2(200) NOT NULL,
VALUE varchar2(200) NOT NULL,
DESCRIPTION varchar2(200) NULL,
SORT_ORDER number(12) NOT NULL ,
DISABLED char(1) NOT NULL
);
ALTER TABLE tl_industry ADD
CONSTRAINT PK_tl_industry PRIMARY KEY
(
object_id
) ;
\ No newline at end of file
...@@ -10,6 +10,8 @@ CREATE TABLE oneit_sec_user_extension ( ...@@ -10,6 +10,8 @@ CREATE TABLE oneit_sec_user_extension (
object_created_date date DEFAULT SYSDATE NOT NULL object_created_date date DEFAULT SYSDATE NOT NULL
, object_type varchar2(30) NOT NULL , , object_type varchar2(30) NOT NULL ,
phone varchar2(30) NULL, phone varchar2(30) NULL,
forgot_password_mail_send_date date NULL,
forgot_password_key varchar2(10) NULL,
verification_mail_send_date date NULL, verification_mail_send_date date NULL,
verification_key varchar2(10) NULL, verification_key varchar2(10) NULL,
is_account_verified char(1) NULL, is_account_verified char(1) NULL,
......
-- DROP TABLE tl_client;
CREATE TABLE tl_client (
object_id number(12) NOT NULL ,
object_last_updated_date date DEFAULT SYSDATE NOT NULL ,
object_created_date date DEFAULT SYSDATE NOT NULL
,
client_name varchar2(100) NOT NULL,
client_logo blob NULL,
email varchar2(100) NULL,
contact_name varchar2(100) NULL,
contact_surname varchar2(100) NULL,
phone varchar2(30) NULL,
state varchar2(200) NULL,
country varchar2(200) NULL,
post_code varchar2(10) NULL,
city varchar2(100) NULL,
time_zone varchar2(200) NULL,
company_id number(12) NOT NULL
);
ALTER TABLE tl_client ADD
CONSTRAINT PK_tl_client PRIMARY KEY
(
object_id
) ;
CREATE INDEX idx_tl_client_company_id
ON tl_client (company_id);
-- DROP TABLE tl_company;
CREATE TABLE tl_company (
object_id number(12) NOT NULL ,
object_last_updated_date date DEFAULT SYSDATE NOT NULL ,
object_created_date date DEFAULT SYSDATE NOT NULL
,
company_name varchar2(100) NOT NULL,
company_logo blob NULL,
hiring_team_type varchar2(200) NULL,
industry varchar2(200) NULL,
time_zone varchar2(200) NULL,
is_verified char(1) NULL,
state varchar2(200) NULL,
country varchar2(200) NULL,
post_code varchar2(10) NULL,
city varchar2(100) NULL,
has_client_support char(1) NULL,
added_by_user_id number(12) NOT NULL
);
ALTER TABLE tl_company ADD
CONSTRAINT PK_tl_company PRIMARY KEY
(
object_id
) ;
\ No newline at end of file
-- DROP TABLE oneit_sec_user_extension;
CREATE TABLE oneit_sec_user_extension (
object_id number(12) NOT NULL ,
object_last_updated_date date DEFAULT SYSDATE NOT NULL ,
object_created_date date DEFAULT SYSDATE NOT NULL
, object_type varchar2(30) NOT NULL ,
forgot_password_mail_send_date date NULL,
forgot_password_key varchar2(10) NULL,
role_type varchar2(200) NULL,
phone varchar2(30) NULL,
verification_mail_send_date date NULL,
verification_key varchar2(10) NULL,
is_account_verified char(1) NULL,
is_email_changed char(1) NULL,
user_id number(12) NULL,
company_id number(12) NULL
);
ALTER TABLE oneit_sec_user_extension ADD
CONSTRAINT PK_oneit_sec_user_extension PRIMARY KEY
(
object_id
) ;
CREATE INDEX idx_oneit_sec_user_extension_user_id
ON oneit_sec_user_extension (user_id);
CREATE INDEX idx_oneit_sec_user_extension_company_id
ON oneit_sec_user_extension (company_id);
...@@ -25,7 +25,8 @@ CREATE TABLE tl_job ( ...@@ -25,7 +25,8 @@ CREATE TABLE tl_job (
state varchar2(200) NULL, state varchar2(200) NULL,
country varchar2(200) NULL, country varchar2(200) NULL,
level_id number(12) NOT NULL, level_id number(12) NOT NULL,
secuser_id number(12) NULL client_id number(12) NULL,
company_user_id number(12) NULL
); );
...@@ -38,3 +39,5 @@ ALTER TABLE tl_job ADD ...@@ -38,3 +39,5 @@ ALTER TABLE tl_job ADD
CREATE INDEX idx_tl_job_client_id
ON tl_job (client_id);
-- @AutoRun
-- drop table oneit_sec_user_extension;
CREATE TABLE oneit_sec_user_extension (
object_id numeric(12) NOT NULL ,
object_last_updated_date timestamp DEFAULT NOW() NOT NULL ,
object_created_date timestamp DEFAULT NOW() NOT NULL
, object_type varchar(30) NOT NULL ,
forgot_password_mail_send_date timestamp NULL,
forgot_password_key varchar(10) NULL,
user_id numeric(12) NULL
);
ALTER TABLE oneit_sec_user_extension ADD
CONSTRAINT pk_oneit_sec_user_extension PRIMARY KEY
(
object_id
) ;
CREATE INDEX idx_oneit_sec_user_extension_user_id
ON oneit_sec_user_extension (user_id);
-- @AutoRun
-- drop table tl_industry;
CREATE TABLE tl_industry (
object_id numeric(12) NOT NULL ,
object_last_updated_date timestamp DEFAULT NOW() NOT NULL ,
object_created_date timestamp DEFAULT NOW() NOT NULL
,
NAME varchar(200) NOT NULL,
VALUE varchar(200) NOT NULL,
DESCRIPTION varchar(200) NULL,
SORT_ORDER numeric(12) NOT NULL ,
DISABLED char(1) NOT NULL
);
ALTER TABLE tl_industry ADD
CONSTRAINT pk_tl_industry PRIMARY KEY
(
object_id
) ;
\ No newline at end of file
...@@ -10,6 +10,8 @@ CREATE TABLE oneit_sec_user_extension ( ...@@ -10,6 +10,8 @@ CREATE TABLE oneit_sec_user_extension (
object_created_date timestamp DEFAULT NOW() NOT NULL object_created_date timestamp DEFAULT NOW() NOT NULL
, object_type varchar(30) NOT NULL , , object_type varchar(30) NOT NULL ,
phone varchar(30) NULL, phone varchar(30) NULL,
forgot_password_mail_send_date timestamp NULL,
forgot_password_key varchar(10) NULL,
verification_mail_send_date timestamp NULL, verification_mail_send_date timestamp NULL,
verification_key varchar(10) NULL, verification_key varchar(10) NULL,
is_account_verified char(1) NULL, is_account_verified char(1) NULL,
......
-- @AutoRun
-- drop table tl_client;
CREATE TABLE tl_client (
object_id numeric(12) NOT NULL ,
object_last_updated_date timestamp DEFAULT NOW() NOT NULL ,
object_created_date timestamp DEFAULT NOW() NOT NULL
,
client_name varchar(100) NOT NULL,
client_logo bytea NULL,
email varchar(100) NULL,
contact_name varchar(100) NULL,
contact_surname varchar(100) NULL,
phone varchar(30) NULL,
state varchar(200) NULL,
country varchar(200) NULL,
post_code varchar(10) NULL,
city varchar(100) NULL,
time_zone varchar(200) NULL,
company_id numeric(12) NOT NULL
);
ALTER TABLE tl_client ADD
CONSTRAINT pk_tl_client PRIMARY KEY
(
object_id
) ;
CREATE INDEX idx_tl_client_company_id
ON tl_client (company_id);
-- @AutoRun
-- drop table tl_company;
CREATE TABLE tl_company (
object_id numeric(12) NOT NULL ,
object_last_updated_date timestamp DEFAULT NOW() NOT NULL ,
object_created_date timestamp DEFAULT NOW() NOT NULL
,
company_name varchar(100) NOT NULL,
company_logo bytea NULL,
hiring_team_type varchar(200) NULL,
industry varchar(200) NULL,
time_zone varchar(200) NULL,
is_verified char(1) NULL,
state varchar(200) NULL,
country varchar(200) NULL,
post_code varchar(10) NULL,
city varchar(100) NULL,
has_client_support char(1) NULL,
added_by_user_id numeric(12) NOT NULL
);
ALTER TABLE tl_company ADD
CONSTRAINT pk_tl_company PRIMARY KEY
(
object_id
) ;
\ No newline at end of file
-- @AutoRun
-- drop table oneit_sec_user_extension;
CREATE TABLE oneit_sec_user_extension (
object_id numeric(12) NOT NULL ,
object_last_updated_date timestamp DEFAULT NOW() NOT NULL ,
object_created_date timestamp DEFAULT NOW() NOT NULL
, object_type varchar(30) NOT NULL ,
forgot_password_mail_send_date timestamp NULL,
forgot_password_key varchar(10) NULL,
role_type varchar(200) NULL,
phone varchar(30) NULL,
verification_mail_send_date timestamp NULL,
verification_key varchar(10) NULL,
is_account_verified char(1) NULL,
is_email_changed char(1) NULL,
user_id numeric(12) NULL,
company_id numeric(12) NULL
);
ALTER TABLE oneit_sec_user_extension ADD
CONSTRAINT pk_oneit_sec_user_extension PRIMARY KEY
(
object_id
) ;
CREATE INDEX idx_oneit_sec_user_extension_user_id
ON oneit_sec_user_extension (user_id);
CREATE INDEX idx_oneit_sec_user_extension_company_id
ON oneit_sec_user_extension (company_id);
...@@ -25,7 +25,8 @@ CREATE TABLE tl_job ( ...@@ -25,7 +25,8 @@ CREATE TABLE tl_job (
state varchar(200) NULL, state varchar(200) NULL,
country varchar(200) NULL, country varchar(200) NULL,
level_id numeric(12) NOT NULL, level_id numeric(12) NOT NULL,
secuser_id numeric(12) NULL client_id numeric(12) NULL,
company_user_id numeric(12) NULL
); );
...@@ -38,3 +39,5 @@ ALTER TABLE tl_job ADD ...@@ -38,3 +39,5 @@ ALTER TABLE tl_job ADD
CREATE INDEX idx_tl_job_client_id
ON tl_job (client_id);
package performa.form;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import oneit.business.content.Article;
import oneit.components.ParticipantInitialisationContext;
import oneit.email.ConfigurableEmailer;
import oneit.logging.*;
import oneit.net.LoopbackHTTP;
import oneit.objstore.*;
import oneit.objstore.rdbms.filters.EqualsFilter;
import oneit.security.SecUser;
import oneit.servlets.forms.*;
import oneit.servlets.process.*;
import oneit.utils.*;
import performa.orm.*;
import performa.utils.*;
public class ForgotPasswordFP extends SaveFP
{
private static final LoggingArea LOG = LoggingArea.createLoggingArea("ForgotPasswordFP");
protected int DEFAULT_PASSWORD_LENGTH = 6;
protected ConfigurableEmailer resetCodeEmailer;
@Override
public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
{
HttpServletRequest request = submission.getRequest();
ObjectTransaction objTran = process.getTransaction();
Job job = (Job) process.getAttribute("Job");
CompanyUser companyUser = (CompanyUser) request.getAttribute("CompanyUser");
String email = job != null ? job.getEmail() : (companyUser != null ? companyUser.getEmail() : null);
Debug.assertion(StringUtils.subBlanks(email) != null, "Email not avaialble");
email = StringUtils.trim(email);
LogMgr.log(LOG, LogLevel.PROCESSING1, "Started to send pasword reset link email.", email);
SecUser secUser = SecUser.searchNAME (objTran, email);
if(secUser == null)
{
SecUser[] userSearch = SecUser.SearchByALL().andEmail(new EqualsFilter<>(email)).search(objTran);
if(userSearch.length>0)
{
secUser = userSearch[0];
}
}
if(secUser != null)
{
LogMgr.log(LOG, LogLevel.PROCESSING1, "Inside ForgotPasswordFP for send reset pasword link mail to ", email);
Map emailParams;
companyUser = secUser.getExtension(CompanyUser.REFERENCE_CompanyUser);
if(companyUser != null)
{
if(companyUser.getForgotPasswordKey() == null)
{
String resetCode = new RandomStringGen().generateHumanAlphaNum(DEFAULT_PASSWORD_LENGTH);
companyUser.setForgotPasswordKey(resetCode);
}
companyUser.setForgotPasswordMailSendDate(new Date());
emailParams = CollectionUtils.mapEntry("resetcode", companyUser.getForgotPasswordKey())
.mapEntry("url", LoopbackHTTP.getRemoteAccessURL() + "/extensions/adminportal/reset_password.jsp"
+ "?id=" + companyUser.getID()
+ "&key=" + companyUser.getForgotPasswordKey()).toMap();
}
else
{
Candidate candidate = secUser.getExtension(Candidate.REFERENCE_Candidate);
if(candidate == null)
{
throw new BusinessException("Sorry, we don't recognize that email address.");
}
Article applyJobArticle = WebUtils.getArticleByShortCut(objTran, WebUtils.APPLY_JOB);
if(candidate.getForgotPasswordKey() == null)
{
String resetCode = new RandomStringGen().generateHumanAlphaNum(DEFAULT_PASSWORD_LENGTH);
candidate.setForgotPasswordKey(resetCode);
}
candidate.setForgotPasswordMailSendDate(new Date());
emailParams = CollectionUtils.mapEntry("resetcode", candidate.getForgotPasswordKey())
.mapEntry("url", LoopbackHTTP.getRemoteAccessURL(request)
+ applyJobArticle.getLink(request, CollectionUtils.mapEntry("cms.rm", WebUtils.RESET_PASSWORD).toMap(), "/")
+ "&id=" + candidate.getID()
+ "&key=" + candidate.getForgotPasswordKey()
+ "&jid=" + job.getID()).toMap();
}
ObjectTransform transform = Utils.createCompoundTransform(emailParams, secUser);
try
{
Utils.sendMail(resetCodeEmailer, transform, new String[]{email}, null, secUser);
LogMgr.log(LOG, LogLevel.PROCESSING1, "Reset code email sent to :: ", email);
}
catch(Exception e)
{
LogMgr.log(LoggingArea.ALL, LogLevel.PROCESSING1, e, "Error while sending email");
throw new BusinessException("Mail can not be sent. Please contact administrator.");
}
}
else
{
throw new BusinessException("Sorry, we don't recognize that email address.");
}
return super.processForm(process, submission, params);
}
@Override
public void init(ParticipantInitialisationContext context) throws InitialisationException
{
super.init(context);
resetCodeEmailer = (ConfigurableEmailer)(context.getSingleChild("ResetCodeEmailer"));
}
}
\ No newline at end of file
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package performa.form;
import javax.servlet.http.HttpServletRequest;
import oneit.appservices.config.ConfigMgr;
import oneit.security.oauth.form.BaseOAuthLoginFP;
import oneit.servlets.forms.*;
import oneit.utils.CollectionUtils;
/**
*
* @author Pradip Sabhadiya
*/
public class LinkedInOAuthLoginFP extends BaseOAuthLoginFP
{
public static final String LINKEDIN_CLIENTID_ATTR_NAME = "linkedin.clientId";
public static final String LINKEDIN_CLIENTSECRET_ATTR_NAME = "linkedin.clientSecret";
public static final String LINKEDIN_APP_OAUTH_URL = "https://www.linkedin.com/oauth/v2/authorization";
public static final String LINKEDIN_ACCESS_TOKEN_URL = "https://www.linkedin.com/oauth/v2/accessToken";
public static final String LINKEDIN_PROFILE_FROM_TOKEN_URL = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address)";
@Override
public String getOAuthLoginURL(SubmissionDetails submission, String token)
{
String appId = ConfigMgr.getKeyfileString(LINKEDIN_CLIENTID_ATTR_NAME);
String callbackURL = getCallbackURL(submission.getRequest());
return LINKEDIN_APP_OAUTH_URL
+ HTTPRequestDetails.getParamStringURL(CollectionUtils.mapEntry("client_id", appId)
.mapEntry("redirect_uri", callbackURL)
.mapEntry("scope", "r_basicprofile,r_emailaddress")
.mapEntry("response_type", "code")
.mapEntry("state", token).toMap());
}
public static String getCallbackURL(HttpServletRequest request)
{
String urlFirstBit = request.getScheme () + "://" + request.getServerName () + ":" + request.getServerPort ();
return HTTPRequestDetails.getFullURL(urlFirstBit + request.getContextPath() + "/linkedinCallback", new String[0]);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package performa.form;
import java.io.*;
import java.net.*;
import javax.servlet.http.HttpServletRequest;
import oneit.appservices.config.ConfigMgr;
import oneit.components.ParticipantInitialisationContext;
import oneit.logging.*;
import oneit.security.oauth.decorator.OAuthCallbackDecorator;
import oneit.security.oauth.utils.BaseOAuthLoginHandler;
import oneit.servlets.forms.HTTPRequestDetails;
import oneit.utils.*;
import org.json.*;
/**
*
* @author Pradip Sabhadiya
*/
public class LinkedInOAuthLoginHandler extends BaseOAuthLoginHandler
{
protected static final LoggingArea LOG = LoggingArea.createLoggingArea("BaseOAuthLoginHandler");
@Override
public void validateRequest(HttpServletRequest request)
{
LogMgr.log(LOG, LogLevel.DEBUG3, "Validation LinkedIn callback request");
String state = request.getParameter("state");
String token = (String) request.getSession().getAttribute(OAuthCallbackDecorator.TOKEN_ATTRIB_NAME);
Debug.assertion(CollectionUtils.equals(state, token), "Unothorized access to callback url.");
}
@Override
public OAuthLoginInfo getProfileInfo(HttpServletRequest request) throws Exception
{
LogMgr.log(LOG, LogLevel.DEBUG3, "Getting profile data from callback");
String accessToken = getAccessToken(request);
try
{
String profileURL = LinkedInOAuthLoginFP.LINKEDIN_PROFILE_FROM_TOKEN_URL
+ HTTPRequestDetails.getParamStringURL(CollectionUtils.mapEntry("oauth2_access_token", accessToken).mapEntry("format", "json").toMap());
JSONObject json = executeURL(profileURL);
LogMgr.log(LOG, LogLevel.PROCESSING1, "Profile Data found ", json);
OAuthLoginInfo loginInfo = new OAuthLoginInfo();
loginInfo.setId(json.getString("id"));
loginInfo.setFirstName(json.getString("firstName"));
if (json.has("emailAddress"))
{
loginInfo.setEmail(json.getString("emailAddress"));
}
if (json.has("lastName"))
{
loginInfo.setLastName(json.getString("lastName"));
}
return loginInfo;
}
catch (Exception e)
{
LogMgr.log(LOG, LogLevel.SYSTEMERROR1, "Exception occured in getProfileInfo");
throw new NestedException(e, "ERROR while getting user data.");
}
}
public String getAccessToken(HttpServletRequest request) throws Exception
{
String code = request.getParameter("code");
String appId = ConfigMgr.getKeyfileString(LinkedInOAuthLoginFP.LINKEDIN_CLIENTID_ATTR_NAME);
String appSecret = ConfigMgr.getKeyfileString(LinkedInOAuthLoginFP.LINKEDIN_CLIENTSECRET_ATTR_NAME);
String callbackURL = LinkedInOAuthLoginFP.getCallbackURL(request);
@SuppressWarnings("unchecked")
String accessTokenURL = LinkedInOAuthLoginFP.LINKEDIN_ACCESS_TOKEN_URL
+ HTTPRequestDetails.getParamStringURL(CollectionUtils.mapEntry("grant_type", "authorization_code")
.mapEntry("code", code)
.mapEntry("redirect_uri", callbackURL)
.mapEntry("client_id", appId)
.mapEntry("client_secret", appSecret).toMap());
JSONObject data = executeURL(accessTokenURL, "POST");
if(!data.has("access_token"))
{
throw new RuntimeException("ERROR: Access Token Invalid: " + data);
}
return data.getString("access_token");
}
public void init(ParticipantInitialisationContext context) throws InitialisationException
{
context.setObject(this);
}
public static JSONObject executeURL(String urlString)
{
return executeURL(urlString, null);
}
public static JSONObject executeURL(String urlString, String method)
{
LogMgr.log(LoggingArea.ALL, LogLevel.DEBUG3, "Executing url ", urlString);
try
{
URL url = new URL(urlString);
URLConnection urlConnection = url.openConnection();
if(StringUtils.subBlanks(method) != null && method.toUpperCase().equals("POST"))
{
urlConnection.setDoOutput(true);
}
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
return new JSONObject(IOUtils.readerToString(in));
}
catch (IOException e)
{
LogMgr.log(LoggingArea.ALL, LogLevel.SYSTEMERROR1, "Error in Executing url ", urlString, e);
throw new NestedException(e);
}
catch(JSONException je)
{
LogMgr.log(LoggingArea.ALL, LogLevel.SYSTEMERROR1, "Error in Parsing Json Data", urlString, je);
throw new NestedException(je);
}
}
}
package performa.form;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.components.ParticipantInitialisationContext;
import oneit.email.ConfigurableArticleTemplateEmailer;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.objstore.StorageException;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.security.SecUser;
import oneit.servlets.forms.SubmissionDetails;
import oneit.servlets.forms.SuccessfulResult;
import oneit.servlets.process.ORMProcessState;
import oneit.servlets.process.SaveFP;
import oneit.utils.BusinessException;
import oneit.utils.InitialisationException;
import oneit.utils.MultiException;
import oneit.utils.StringUtils;
import performa.orm.CompanyUser;
import performa.utils.Utils;
public class ResendVerificationFP extends SaveFP
{
protected ConfigurableArticleTemplateEmailer emailer;
@Override
protected Map validate(SubmissionDetails submission, MultiException exceptions)
{
HttpServletRequest request = submission.getRequest();
CompanyUser companyUser = (CompanyUser) request.getAttribute("CompanyUser");
SecUser secUser = companyUser.getUser();
if(!companyUser.isLoggedViaSocial())
{
BusinessObjectParser.assertFieldCondition(StringUtils.isEmailAddress(secUser.getUserName()), secUser, SecUser.FIELD_Email, "invalid", exceptions, true, request);
BusinessObjectParser.assertFieldCondition(!Utils.isCompanyUserEmailFound(secUser.getTransaction(), secUser.getUserName(), companyUser), secUser, SecUser.FIELD_UserName, "emailExists", exceptions, true, request);
}
else
{
BusinessObjectParser.assertFieldCondition(!Utils.isCompanyUserEmailFound(secUser.getTransaction(), secUser.getEmail(), companyUser), secUser, SecUser.FIELD_Email, "emailExists", exceptions, true, request);
}
return super.validate(submission, exceptions);
}
@Override
public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
{
HttpServletRequest request = submission.getRequest();
CompanyUser companyUser = (CompanyUser) request.getAttribute("CompanyUser");
LogMgr.log(CompanyUser.LOG, LogLevel.PROCESSING1, "Inside ResendVerificationFP resending verification email to company user : ", companyUser);
if(companyUser != null)
{
Utils.sendEmailChangedMail(companyUser, request, emailer, ResendVerificationFP.class.getName());
}
return super.processForm(process, submission, params);
}
@Override
public void init(ParticipantInitialisationContext context) throws InitialisationException
{
super.init(context);
emailer = (ConfigurableArticleTemplateEmailer) (context.getSingleChild("AccountVerificationEmailer"));
}
}
\ No newline at end of file
package performa.form;
import java.util.Map;
import oneit.logging.*;
import oneit.objstore.StorageException;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.security.SecUser;
import oneit.servlets.forms.*;
import oneit.servlets.process.*;
import oneit.utils.*;
import performa.orm.Candidate;
import performa.orm.CompanyUser;
public class ResetPasswordFP extends SaveFP
{
private static final LoggingArea LOG = LoggingArea.createLoggingArea("ResetPasswordFP");
@Override
public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
{
SecUser user = (SecUser) process.getAttribute("SecUser");
CompanyUser companyUser = user.getExtension(CompanyUser.REFERENCE_CompanyUser);
Candidate candidate = user.getExtension(Candidate.REFERENCE_Candidate);
LogMgr.log(LOG, LogLevel.PROCESSING1, "Inside ResetPasswordFP user:", user," companyUser:", companyUser, " candidate:", candidate);
if(companyUser != null)
{
companyUser.setForgotPasswordKey(null);
}
else if (candidate != null)
{
candidate.setForgotPasswordKey(null);
}
return super.processForm(process, submission, params);
}
@Override
public void validate(ORMProcessState process, SubmissionDetails submission, MultiException exceptions, Map params) throws StorageException
{
super.validate(process, submission, exceptions, params);
SecUser user = (SecUser) process.getAttribute("SecUser");
Debug.assertion(user != null, "No user found for rest password. Call from " + getClass().getName());
BusinessObjectParser.assertFieldCondition(user.getPassword().length() >= 8, user, SecUser.FIELD_Password, exceptions, true, submission.getRequest());
}
}
\ No newline at end of file
package performa.form;
import java.util.Map;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.objstore.StorageException;
import oneit.servlets.forms.SubmissionDetails;
import oneit.servlets.forms.SuccessfulResult;
import oneit.servlets.process.ORMProcessState;
import oneit.servlets.process.SaveFP;
import oneit.utils.BusinessException;
import oneit.utils.CollectionUtils;
import performa.orm.Client;
public class SaveClientFP extends SaveFP
{
@Override
public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
{
Client client = (Client) process.getAttribute("Client");
LogMgr.log(Client.LOG, LogLevel.PROCESSING1,"In SaveClientFP saving client : ", client );
if(CollectionUtils.equals(client.getIsLogoDeleted(), Boolean.TRUE))
{
client.setClientLogo(null);
LogMgr.log(Client.LOG, LogLevel.PROCESSING1,"In SaveClientFP setting client logo to null of client : ", client );
}
return super.processForm(process, submission, params);
}
}
\ No newline at end of file
package performa.form;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.objstore.StorageException;
import oneit.servlets.forms.SubmissionDetails;
import oneit.servlets.forms.SuccessfulResult;
import oneit.servlets.process.ORMProcessState;
import oneit.servlets.process.SaveFP;
import oneit.utils.BusinessException;
import oneit.utils.CollectionUtils;
import performa.orm.Company;
public class SaveCompanyFP extends SaveFP
{
@Override
public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
{
HttpServletRequest request = submission.getRequest();
Company company = process.getAttribute("Company") != null ? (Company) process.getAttribute("Company") : (Company) request.getAttribute("Company");
LogMgr.log(Company.LOG, LogLevel.PROCESSING1,"In SaveCompanyFP saving company : ", company );
if(CollectionUtils.equals(company.getIsLogoDeleted(), Boolean.TRUE))
{
company.setCompanyLogo(null);
LogMgr.log(Company.LOG, LogLevel.PROCESSING1,"In SaveCompanyFP setting comany logo to null of company : ", company );
}
return super.processForm(process, submission, params);
}
}
\ No newline at end of file
...@@ -66,6 +66,11 @@ public class SaveRequirementsTemplateFP extends ORMProcessFormProcessor ...@@ -66,6 +66,11 @@ public class SaveRequirementsTemplateFP extends ORMProcessFormProcessor
BusinessObjectParser.assertFieldCondition(job.getAssessmentTemplateName() != null, job , Job.FIELD_AssessmentTemplateName, "mandatory", exceptions, true, request); BusinessObjectParser.assertFieldCondition(job.getAssessmentTemplateName() != null, job , Job.FIELD_AssessmentTemplateName, "mandatory", exceptions, true, request);
for(AssessmentCriteria criteria: job.getAssessmentCriteriasSet())
{
BusinessObjectParser.assertFieldCondition(criteria.getName() != null, criteria , AssessmentCriteria.FIELD_Name, "mandatory", exceptions, true, request);
}
super.validate(process, submission, exceptions, params); super.validate(process, submission, exceptions, params);
} }
} }
\ No newline at end of file
package performa.form;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.components.ParticipantInitialisationContext;
import oneit.email.ConfigurableArticleTemplateEmailer;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.objstore.ObjectTransaction;
import oneit.objstore.StorageException;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.security.SecUser;
import oneit.servlets.forms.RedisplayResult;
import oneit.servlets.forms.SubmissionDetails;
import oneit.servlets.forms.SuccessfulResult;
import oneit.servlets.process.ORMProcessState;
import oneit.servlets.process.SaveFP;
import oneit.utils.BusinessException;
import oneit.utils.CollectionUtils;
import oneit.utils.InitialisationException;
import oneit.utils.MultiException;
import oneit.utils.StringUtils;
import performa.orm.CompanyUser;
import performa.utils.Utils;
public class SaveUserDetailsFP extends SaveFP
{
protected ConfigurableArticleTemplateEmailer emailer;
@Override
public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
{
HttpServletRequest request = submission.getRequest();
CompanyUser companyUser = (CompanyUser) request.getAttribute("CompanyUser");
SecUser secUser = companyUser.getUser();
LogMgr.log(CompanyUser.LOG, LogLevel.PROCESSING1,"In SaveUserDetailsFP saving CompanyUser : ", companyUser );
SecUser oldSecUser = (SecUser) secUser.getEarliestBackup();
if(oldSecUser != null)
{
if(!companyUser.isLoggedViaSocial() && !CollectionUtils.equals(oldSecUser.getUserName(), secUser.getUserName()))
{
if(companyUser.getConfirmPassword() == null)
{
submission.getRequest().setAttribute("EmailChanged", true);
return RedisplayResult.getInstance();
}
else
{
boolean validPassword = secUser.checkPassword(companyUser.getConfirmPassword());
if(!validPassword)
{
submission.getRequest().setAttribute("EmailChanged", false);
companyUser.setConfirmPassword(null);
}
BusinessObjectParser.assertFieldCondition(validPassword, companyUser, CompanyUser.FIELD_ConfirmPassword, "passwordNotMatch");
if(validPassword)
{
companyUser.setIsAccountVerified(Boolean.FALSE);
companyUser.setIsEmailChanged(Boolean.TRUE);
Utils.sendEmailChangedMail(companyUser, request, emailer, SaveUserDetailsFP.class.getName());
}
}
}
else if (companyUser.isLoggedViaSocial() && !CollectionUtils.equals(oldSecUser.getEmail(), secUser.getEmail()))
{
//send email verification mail
LogMgr.log(CompanyUser.LOG, LogLevel.PROCESSING1,"Sending email resetted mail", companyUser );
companyUser.setIsEmailChanged(Boolean.TRUE);
Utils.sendEmailChangedMail(companyUser, request, emailer, SaveUserDetailsFP.class.getName());
}
}
return super.processForm(process, submission, params);
}
@Override
protected Map validate(SubmissionDetails submission, MultiException exceptions)
{
HttpServletRequest request = submission.getRequest();
CompanyUser companyUser = (CompanyUser) request.getAttribute("CompanyUser");
SecUser secUser = companyUser.getUser();
if(!companyUser.isLoggedViaSocial())
{
BusinessObjectParser.assertFieldCondition(StringUtils.isEmailAddress(secUser.getUserName()), secUser, SecUser.FIELD_Email, "invalid", exceptions, true, request);
BusinessObjectParser.assertFieldCondition(!Utils.isCompanyUserEmailFound(secUser.getTransaction(), secUser.getUserName(), companyUser), secUser, SecUser.FIELD_UserName, "emailExists", exceptions, true, request);
}
else
{
BusinessObjectParser.assertFieldCondition(!Utils.isCompanyUserEmailFound(secUser.getTransaction(), secUser.getEmail(), companyUser), secUser, SecUser.FIELD_Email, "emailExists", exceptions, true, request);
}
BusinessObjectParser.assertFieldCondition(secUser.getFirstName()!= null, secUser, SecUser.FIELD_FirstName, "mandatory", exceptions, true, request);
BusinessObjectParser.assertFieldCondition(secUser.getLastName()!= null, secUser, SecUser.FIELD_LastName, "mandatory", exceptions, true, request);
return super.validate(submission, exceptions);
}
@Override
public void init(ParticipantInitialisationContext context) throws InitialisationException
{
super.init(context);
emailer = (ConfigurableArticleTemplateEmailer) (context.getSingleChild("AccountVerificationEmailer"));
}
}
\ No newline at end of file
package performa.form;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.business.content.Article;
import oneit.components.ParticipantInitialisationContext;
import oneit.email.ConfigurableArticleTemplateEmailer;
import oneit.email.ConfigurableEmailerException;
import oneit.logging.*;
import oneit.net.LoopbackHTTP;
import oneit.objstore.ObjectTransaction;
import oneit.objstore.StorageException;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.security.SecUser;
import oneit.servlets.forms.*;
import oneit.servlets.process.*;
import oneit.servlets.security.SessionSecUserDecorator;
import oneit.utils.*;
import performa.intercom.utils.IntercomUtils;
import performa.orm.*;
import performa.utils.Utils;
import performa.utils.WebUtils;
public class SendCompanyUserInvitesFP extends ORMProcessFormProcessor
{
private static final LoggingArea LOG = LoggingArea.createLoggingArea("SendCompanyUserInvites");
protected ConfigurableArticleTemplateEmailer emailer;
protected ConfigurableArticleTemplateEmailer invitationEmailer;
@Override
public void validate(ORMProcessState process, SubmissionDetails submission, MultiException exceptions, Map params) throws StorageException
{
HttpServletRequest request = submission.getRequest();
Company company = (Company) process.getAttribute("Company");
for(CompanyUser cUser : company.getUsersSet())
{
if(!CollectionUtils.equals(cUser, company.getAddedByUser()))
{
SecUser secUser = cUser.getUser();
BusinessObjectParser.assertFieldCondition(secUser.getEmail()!=null, secUser, SecUser.FIELD_Email, "mandatory", exceptions, true, request);
BusinessObjectParser.assertFieldCondition(!Utils.isCompanyUserEmailFound(process.getTransaction(), secUser.getEmail()), secUser, SecUser.FIELD_Email, "emailExists", exceptions, true, request);
}
}
super.validate(process, submission, exceptions, params);
}
@Override
public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
{
HttpServletRequest request = submission.getRequest();
ObjectTransaction objTran = process.getTransaction();
Company company = (Company) process.getAttribute("Company");
CompanyUser companyUser = company.getAddedByUser();
SecUser secUser = companyUser.getUser();
String nextPage = (String) request.getAttribute("nextPage");
Boolean socialLogin = CollectionUtils.equals(process.getAttribute("socialLogin"), Boolean.TRUE);
LogMgr.log(LOG, LogLevel.PROCESSING1, "Verifing Company User", companyUser, secUser);
companyUser.setIsAccountVerified(Boolean.TRUE);
company.setIsVerified(Boolean.TRUE);
sendAccountCreatedMail(companyUser, request);
if(!socialLogin)
{
secUser.setAttribute("md5:" + SecUser.FIELD_Password, companyUser.getPassword());
request.getSession().setAttribute (SecUser.SEC_USER_ID, secUser);
request.getSession().setAttribute (SessionSecUserDecorator.REFRESH_SECURITY, Boolean.TRUE);
LogMgr.log(LOG, LogLevel.PROCESSING1, "Password resetted", companyUser, secUser);
}
LogMgr.log(LOG, LogLevel.PROCESSING1, "Verifing Company User finished", companyUser, secUser);
//process user invitations
for(CompanyUser cUser : company.getUsersSet())
{
if(!CollectionUtils.equals(cUser, companyUser))
{
Tuple.T2<SecUser, Boolean> userdata = Utils.getSecUserForCompanyIfAvailable(cUser);
SecUser sUser = userdata.get0();
LogMgr.log(LOG, LogLevel.PROCESSING1, "Started to send invitaion email.", cUser);
if(!userdata.get1()) //check user availablility
{
sUser.setUserName(sUser.getEmail().toLowerCase());
}
sUser.setAttribute("md5:" + SecUser.FIELD_Password, CompanyUser.DEFAULT_PASSWORD);
sUser.addRole(Utils.getRole(Utils.ROLE_CLIENT, objTran));
LogMgr.log(LOG, LogLevel.PROCESSING1, "New user created :: ", sUser);
sendInvitationMail(cUser, request);
LogMgr.log(LOG, LogLevel.PROCESSING1, "End of sending invitation email.", cUser);
}
}
// Create company and the first user of it in intercom
performa.intercom.resources.Company intercomCompany = IntercomUtils.createIntercomCompany(company);
IntercomUtils.createIntercomUser(secUser, "Hiring Team", intercomCompany);
process.completeAndRestart();
return new ProcessRedirectResult(nextPage, new String[0]);
}
@Override
public void init(ParticipantInitialisationContext context) throws InitialisationException
{
super.init(context);
emailer = (ConfigurableArticleTemplateEmailer) (context.getSingleChild("AccountCreatedEmailer"));
invitationEmailer = (ConfigurableArticleTemplateEmailer) (context.getSingleChild("InvitationEmailer"));
}
private void sendAccountCreatedMail(CompanyUser companyUser, HttpServletRequest request) throws BusinessException
{
try
{
LogMgr.log(LOG, LogLevel.PROCESSING1, "Sending Account Created mail from SendCompanyUserInvitesFP to :: ", companyUser);
Map defaultParams = CollectionUtils.EMPTY_MAP;
ObjectTransform transform = Utils.createCompoundTransform(defaultParams, companyUser);
Utils.sendMail(emailer, transform, new String[]{companyUser.getEmailAddressFromUser()}, null, companyUser);
LogMgr.log(LOG, LogLevel.PROCESSING1, "Sent Account Created mail successfully from " + SendCompanyUserInvitesFP.class + " to :: ", companyUser);
}
catch (ConfigurableEmailerException ex)
{
LogMgr.log(LOG, LogLevel.SYSTEMERROR1, ex, "Error occured while sending mail for CompanyUser :: " + companyUser);
throw new BusinessException("We are unable to send mail. Please try again or contact Talentology for more details.");
}
}
private void sendInvitationMail(CompanyUser companyUser, HttpServletRequest request) throws BusinessException
{
if(!companyUser.isTrue(companyUser.getIsAccountVerified()))
{
try
{
LogMgr.log(LOG, LogLevel.PROCESSING1, "Sending invitation mail from SendVerificationMailFP to :: ", companyUser);
Article invitationArticle = WebUtils.getArticleByShortCut(companyUser.getTransaction(), WebUtils.COMPANY_ACCOUNT_VERIFICATION);
RandomStringGen random = new RandomStringGen();
//set invitation key and send mail time
companyUser.setVerificationKey(random.generateAlphaNum(6));
companyUser.setVerificationMailSendDate(new Date());
String link = LoopbackHTTP.getRemoteAccessURL(request)
+ invitationArticle.getLink(request, CollectionUtils.EMPTY_MAP, "/")
+ "?id=" + companyUser.getID()
+ "&key=" + companyUser.getVerificationKey();
Map defaultParams = CollectionUtils.mapEntry("link", link).toMap();
ObjectTransform transform = Utils.createCompoundTransform(defaultParams, companyUser);
Utils.sendMail(invitationEmailer, transform, new String[]{companyUser.getEmailAddressFromUser()}, null, companyUser);
LogMgr.log(LOG, LogLevel.PROCESSING1, "Sent invitation mail successfully from " + SendVerificationMailFP.class + " to :: ", companyUser);
}
catch (ConfigurableEmailerException ex)
{
LogMgr.log(LOG, LogLevel.SYSTEMERROR1, ex, "Error occured while sending mail for Candidate :: " + companyUser);
throw new BusinessException("We are unable to send mail. Please try again or contact Talentology for more details.");
}
}
else
{
LogMgr.log(LOG, LogLevel.PROCESSING1, "Call from " + SendVerificationMailFP.class + ". Account is already verified for candidate :: ", companyUser);
}
}
}
\ No newline at end of file
package performa.form;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.business.content.Article;
import oneit.components.ParticipantInitialisationContext;
import oneit.email.ConfigurableArticleTemplateEmailer;
import oneit.email.ConfigurableEmailerException;
import oneit.logging.*;
import oneit.net.LoopbackHTTP;
import oneit.objstore.ObjectTransaction;
import oneit.objstore.StorageException;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.security.SecUser;
import oneit.servlets.forms.*;
import oneit.servlets.process.*;
import oneit.utils.*;
import performa.orm.*;
import performa.utils.Utils;
import performa.utils.WebUtils;
public class SendUserInvitationFP extends SaveFP
{
private static LoggingArea LOG = LoggingArea.createLoggingArea("SendUserInvitationFP");
protected ConfigurableArticleTemplateEmailer invitationEmailer;
@Override
public void validate(ORMProcessState process, SubmissionDetails submission, MultiException exceptions, Map params) throws StorageException
{
HttpServletRequest request = submission.getRequest();
Company company = (Company) process.getAttribute("Company");
CompanyUser resendUser = (CompanyUser) request.getAttribute("ResendUser");
if(resendUser!=null)
{
BusinessObjectParser.assertFieldCondition(StringUtils.isEmailAddress(resendUser.getUser().getUserName()), resendUser, resendUser.FIELD_ObjectID, "invalidEmail", exceptions, false, request);
}
else
{
BusinessObjectParser.assertFieldCondition(company.getUserEmail()!=null, company, Company.FIELD_UserEmail, "mandatory", exceptions, true, request);
BusinessObjectParser.assertFieldCondition(!Utils.isCompanyUserEmailFound(process.getTransaction(), company.getUserEmail()), company, Company.FIELD_UserEmail, "emailExists", exceptions, true, request);
BusinessObjectParser.assertFieldCondition(company.getRoleType()!=null, company, Company.FIELD_RoleType, "mandatory", exceptions, true, request);
}
super.validate(process, submission, exceptions, params);
}
@Override
public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
{
HttpServletRequest request = submission.getRequest();
ObjectTransaction objTran = process.getTransaction();
Company company = (Company) process.getAttribute("Company");
CompanyUser resendUser = (CompanyUser) request.getAttribute("ResendUser");
if(resendUser!=null)
{
LogMgr.log(LOG, LogLevel.PROCESSING1, "Started to re-sending invitaion email.", resendUser);
sendInvitationMail(resendUser, request);
LogMgr.log(LOG, LogLevel.PROCESSING1, "End of re-sending invitation email.", resendUser);
}
else
{
LogMgr.log(LOG, LogLevel.PROCESSING1, "Started to create new use", company);
SecUser secUser = SecUser.searchNAME(objTran, company.getUserEmail());
if(secUser == null)
{
secUser = SecUser.createSecUser(objTran);
secUser.setUserName(company.getUserEmail().toLowerCase());
}
CompanyUser newComUser = secUser.getExtensionOrCreate(CompanyUser.REFERENCE_CompanyUser);
secUser.setEmail(secUser.getUserName());
secUser.setAttribute("md5:" + SecUser.FIELD_Password, CompanyUser.DEFAULT_PASSWORD);
secUser.addRole(Utils.getRole(Utils.ROLE_CLIENT, objTran));
secUser.setFirstName(company.getFirstName());
secUser.setLastName(company.getLastName());
newComUser.setCompany(company);
newComUser.setRole(company.getRoleType());
LogMgr.log(LOG, LogLevel.PROCESSING1, "New user created :: ", secUser);
sendInvitationMail(newComUser, request);
LogMgr.log(LOG, LogLevel.PROCESSING1, "End of sending invitation email.", secUser);
}
return super.processForm(process, submission, params);
}
@Override
public void init(ParticipantInitialisationContext context) throws InitialisationException
{
super.init(context);
invitationEmailer = (ConfigurableArticleTemplateEmailer) (context.getSingleChild("InvitationEmailer"));
}
protected void sendInvitationMail(CompanyUser companyUser, HttpServletRequest request) throws BusinessException
{
if(!companyUser.isTrue(companyUser.getIsAccountVerified()))
{
try
{
LogMgr.log(LOG, LogLevel.PROCESSING1, "Sending invitation mail from SendUserInvitationFP to :: ", companyUser);
Article invitationArticle = WebUtils.getArticleByShortCut(companyUser.getTransaction(), WebUtils.COMPANY_ACCOUNT_VERIFICATION);
//set invitation key and send mail time
if(companyUser.getVerificationKey()==null)
{
RandomStringGen random = new RandomStringGen();
companyUser.setVerificationKey(random.generateAlphaNum(6));
}
companyUser.setVerificationMailSendDate(new Date());
String link = LoopbackHTTP.getRemoteAccessURL(request)
+ invitationArticle.getLink(request, CollectionUtils.EMPTY_MAP, "/")
+ "?id=" + companyUser.getID()
+ "&key=" + companyUser.getVerificationKey();
Map defaultParams = CollectionUtils.mapEntry("link", link).toMap();
ObjectTransform transform = Utils.createCompoundTransform(defaultParams, companyUser);
Utils.sendMail(invitationEmailer, transform, new String[]{companyUser.getEmailAddressFromUser()}, null, companyUser);
LogMgr.log(LOG, LogLevel.PROCESSING1, "Sent invitation mail successfully from " + SendUserInvitationFP.class + " to :: ", companyUser);
}
catch (ConfigurableEmailerException ex)
{
LogMgr.log(LOG, LogLevel.SYSTEMERROR1, ex, "Error occured while sending mail for Candidate :: " + companyUser);
throw new BusinessException("We are unable to send mail. Please try again or contact Talentology for more details.");
}
}
else
{
LogMgr.log(LOG, LogLevel.PROCESSING1, "Call from " + SendUserInvitationFP.class + ". Account is already verified for candidate :: ", companyUser);
}
}
}
\ No newline at end of file
...@@ -17,14 +17,14 @@ import oneit.servlets.forms.*; ...@@ -17,14 +17,14 @@ import oneit.servlets.forms.*;
import oneit.servlets.process.*; import oneit.servlets.process.*;
import oneit.utils.*; import oneit.utils.*;
import performa.orm.*; import performa.orm.*;
import performa.orm.types.RoleType;
import performa.utils.Utils; import performa.utils.Utils;
import performa.utils.WebUtils; import performa.utils.WebUtils;
public class SendVerificationMailFP extends SaveFP public class SendVerificationMailFP extends SaveFP
{ {
private static LoggingArea LOG = LoggingArea.createLoggingArea("SendVerificationLink"); private static final LoggingArea LOG = LoggingArea.createLoggingArea("SendVerificationLink");
private static final String DEFAULT_PASSWORD = "Talentology123";
protected ConfigurableArticleTemplateEmailer emailer; protected ConfigurableArticleTemplateEmailer emailer;
...@@ -33,8 +33,21 @@ public class SendVerificationMailFP extends SaveFP ...@@ -33,8 +33,21 @@ public class SendVerificationMailFP extends SaveFP
{ {
HttpServletRequest request = submission.getRequest(); HttpServletRequest request = submission.getRequest();
Job job = (Job) request.getAttribute("Job"); Job job = (Job) request.getAttribute("Job");
Company company = (Company) request.getAttribute("Company");
Debug.assertion(company != null || job!=null, "BO not avaialble");
if(company!=null)
{
CompanyUser companyUser = company.getAddedByUser();
SecUser secUser = companyUser.getUser();
BusinessObjectParser.assertFieldCondition(!Utils.isCompanyUserEmailFound(process.getTransaction(), secUser.getEmail()), secUser, SecUser.FIELD_Email, "emailExists", exceptions, true, request);
}
else
{
BusinessObjectParser.assertFieldCondition(!job.isEmailFound(), job, Job.FIELD_Email, "emailExists", exceptions, true, request); BusinessObjectParser.assertFieldCondition(!job.isEmailFound(), job, Job.FIELD_Email, "emailExists", exceptions, true, request);
}
super.validate(process, submission, exceptions, params); super.validate(process, submission, exceptions, params);
} }
...@@ -46,33 +59,87 @@ public class SendVerificationMailFP extends SaveFP ...@@ -46,33 +59,87 @@ public class SendVerificationMailFP extends SaveFP
HttpServletRequest request = submission.getRequest(); HttpServletRequest request = submission.getRequest();
ObjectTransaction objTran = process.getTransaction(); ObjectTransaction objTran = process.getTransaction();
Job job = (Job) request.getAttribute("Job"); Job job = (Job) request.getAttribute("Job");
Company company = (Company) request.getAttribute("Company");
if(company!=null)
{
CompanyUser companyUser = company.getAddedByUser();
SecUser secUser = companyUser.getUser();
SecUser availableSecUser = SecUser.searchNAME(objTran, secUser.getEmail());
LogMgr.log(LOG, LogLevel.PROCESSING1, "Started to send varification email.", companyUser);
if(availableSecUser!=null)
{
if(availableSecUser.getExtension(CompanyUser.REFERENCE_CompanyUser)!=null)
{
Debug.assertion(false, "user available", availableSecUser);
}
else
{
LogMgr.log(LOG, LogLevel.PROCESSING1, "SecUser available", availableSecUser);
availableSecUser.addToExtensions(companyUser);
//remove new sec user obj
secUser.removeFromExtensions(companyUser);
secUser.delete();
}
}
else
{
secUser.setUserName(secUser.getEmail().toLowerCase());
secUser.setAttribute("md5:" + SecUser.FIELD_Password, CompanyUser.DEFAULT_PASSWORD);
secUser.addRole(Utils.getRole(Utils.ROLE_CLIENT, objTran));
LogMgr.log(LOG, LogLevel.PROCESSING1, "New user created :: ", secUser);
}
//set default to admin
companyUser.setRole(RoleType.ADMIN);
Utils.sendVerificationMail(companyUser, request, emailer, SendVerificationMailFP.class.getName());
LogMgr.log(LOG, LogLevel.PROCESSING1, "End of sending varification email.", companyUser);
}
else
{
String email = job.getEmail(); String email = job.getEmail();
Debug.assertion(email != null, "Email not avaialble"); Debug.assertion(email != null, "Email not avaialble");
email = email.toLowerCase();
LogMgr.log(LOG, LogLevel.PROCESSING1, "Started to send varification email.", job , email); LogMgr.log(LOG, LogLevel.PROCESSING1, "Started to send varification email.", job , email);
SecUser secUser = SecUser.searchNAME(objTran, email); SecUser secUser = SecUser.searchNAME(objTran, email);
Debug.assertion(secUser == null, "user available", email); if(secUser!=null)
{
Debug.assertion(secUser.getExtension(Candidate.REFERENCE_Candidate)==null, "user available", email, secUser);
}
LogMgr.log(LOG, LogLevel.PROCESSING1, "Inside SendVerificationMailFP for send account verification mail for ", email); LogMgr.log(LOG, LogLevel.PROCESSING1, "Inside SendVerificationMailFP for send account verification mail for ", email);
SecUser newSecUser = SecUser.createSecUser(objTran); if(secUser==null)
{
newSecUser.setUserName(email.toLowerCase()); secUser = SecUser.createSecUser(objTran);
newSecUser.setAttribute("md5:" + SecUser.FIELD_Password, DEFAULT_PASSWORD);
LogMgr.log(LOG, LogLevel.PROCESSING1, "New user created :: ", newSecUser); secUser.setUserName(email);
secUser.setAttribute("md5:" + SecUser.FIELD_Password, CompanyUser.DEFAULT_PASSWORD);
secUser.addRole(Utils.getRole(Utils.ROLE_APPLICANT, objTran));
}
newSecUser.addRole(Utils.getRole(Utils.ROLE_APPLICANT, objTran)); Candidate candidate = secUser.getExtensionOrCreate(Candidate.REFERENCE_Candidate);
Candidate candidate = newSecUser.getExtensionOrCreate(Candidate.REFERENCE_Candidate); LogMgr.log(LOG, LogLevel.PROCESSING1, "New user created :: ", secUser);
sendVerificationMail(candidate, job, request); sendVerificationMail(candidate, job, request);
request.setAttribute("nextPage", request.getAttribute("nextPage") + "&JobID=" + job.getID()); request.setAttribute("nextPage", request.getAttribute("nextPage") + "&JobID=" + job.getID());
}
return super.processForm(process, submission, params); return super.processForm(process, submission, params);
} }
...@@ -87,9 +154,9 @@ public class SendVerificationMailFP extends SaveFP ...@@ -87,9 +154,9 @@ public class SendVerificationMailFP extends SaveFP
} }
protected void sendVerificationMail(Candidate candidate, Job job, HttpServletRequest request) throws BusinessException private void sendVerificationMail(Candidate candidate, Job job, HttpServletRequest request) throws BusinessException
{ {
if(candidate.getIsAccountVerified()!=Boolean.TRUE) if(!candidate.isTrue(candidate.getIsAccountVerified()))
{ {
try try
{ {
......
...@@ -7,6 +7,7 @@ import oneit.security.SecUser; ...@@ -7,6 +7,7 @@ import oneit.security.SecUser;
import oneit.servlets.forms.SubmissionDetails; import oneit.servlets.forms.SubmissionDetails;
import oneit.utils.MultiException; import oneit.utils.MultiException;
import oneit.utils.parsers.FieldException; import oneit.utils.parsers.FieldException;
import performa.orm.CompanyUser;
import performa.utils.Utils; import performa.utils.Utils;
/** /**
...@@ -20,7 +21,9 @@ public class UserLoginFP extends LoginProcessor ...@@ -20,7 +21,9 @@ public class UserLoginFP extends LoginProcessor
{ {
super.checkUserCanLogin(trans, userToCheck, submission, requestParams); super.checkUserCanLogin(trans, userToCheck, submission, requestParams);
if(!Utils.checkAdminPortalAccess(userToCheck)) CompanyUser companyUser = userToCheck.getExtension(CompanyUser.REFERENCE_CompanyUser);
if(!Utils.checkAdminPortalAccess(userToCheck) || companyUser == null || !companyUser.isTrue(companyUser.getIsAccountVerified()))
{ {
throw new FieldException("You're not an authorised user to access this portal.", SecUser.FIELD_UserName); throw new FieldException("You're not an authorised user to access this portal.", SecUser.FIELD_UserName);
} }
......
package performa.form;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.appservices.config.ConfigMgr;
import oneit.components.ParticipantInitialisationContext;
import oneit.email.ConfigurableArticleTemplateEmailer;
import oneit.email.ConfigurableEmailerException;
import oneit.logging.*;
import oneit.objstore.StorageException;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.objstore.validator.AttributeValidator;
import oneit.security.SecUser;
import oneit.servlets.forms.*;
import oneit.servlets.process.*;
import oneit.servlets.security.SessionSecUserDecorator;
import oneit.utils.*;
import oneit.utils.parsers.FieldException;
import performa.intercom.utils.IntercomUtils;
import performa.orm.*;
import performa.utils.Utils;
import performa.utils.WebUtils;
public class VerifyCompanyUserFP extends ORMProcessFormProcessor
{
private static final LoggingArea LOG = LoggingArea.createLoggingArea("VerifyCompanyUser");
protected ConfigurableArticleTemplateEmailer emailer;
@Override
public void validate(ORMProcessState process, SubmissionDetails submission, MultiException exceptions, Map params) throws StorageException
{
HttpServletRequest request = submission.getRequest();
CompanyUser companyUser = (CompanyUser) process.getAttribute("CompanyUser");
Boolean socialLogin = (Boolean) request.getAttribute("socialLogin");
SecUser secUser = companyUser.getUser();
Company company = companyUser.getCompany();
if(socialLogin)
{
BusinessObjectParser.assertFieldCondition(secUser.getEmail()!=null, secUser, SecUser.FIELD_Email, "invalid", exceptions, true, request);
BusinessObjectParser.assertFieldCondition(!Utils.isCompanyUserEmailFound(secUser.getTransaction(), secUser.getEmail()), secUser, SecUser.FIELD_Email, "emailExists", exceptions, true, request);
}
else
{
BusinessObjectParser.assertFieldCondition(StringUtils.isEmailAddress(secUser.getUserName()), secUser, SecUser.FIELD_Email, "invalid", exceptions, true, request);
}
BusinessObjectParser.assertFieldCondition(secUser.getFirstName()!=null, secUser, SecUser.FIELD_FirstName, "mandatory", exceptions, true, request);
BusinessObjectParser.assertFieldCondition(secUser.getLastName()!=null, secUser, SecUser.FIELD_LastName, "mandatory", exceptions, true, request);
if(!company.isTrue(company.getIsVerified()))
{
BusinessObjectParser.assertFieldCondition(company.getCompanyName()!=null, company, Company.FIELD_CompanyName, "mandatory", exceptions, true, request);
}
if(!socialLogin)
{
BusinessObjectParser.assertFieldCondition(companyUser.getPassword()!= null, companyUser, CompanyUser.FIELD_Password, "mandatory", exceptions, true, request);
BusinessObjectParser.assertFieldCondition(companyUser.getConfirmPassword()!= null, companyUser, CompanyUser.FIELD_ConfirmPassword, "mandatory", exceptions, true, request);
BusinessObjectParser.assertFieldCondition(CollectionUtils.equals(companyUser.getPassword(), companyUser.getConfirmPassword()), companyUser, CompanyUser.FIELD_ConfirmPassword, "passwordNotMatch", exceptions, true, request);
//to validate password
AttributeValidator passwordValidator = (AttributeValidator)(ConfigMgr.getConfigObject ("CONFIG.ORMVALIDATOR", "PasswordValidator", null));
try
{
//execute if not null
if (passwordValidator != null)
{
passwordValidator.validate (null, secUser, "Password", companyUser.getPassword());
}
}
catch (FieldException e)
{
exceptions.addException(new FieldException(e, CompanyUser.FIELD_Password));
}
catch (Exception e)
{
throw NestedException.wrap(e);
}
}
super.validate(process, submission, exceptions, params);
}
@Override
public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
{
HttpServletRequest request = submission.getRequest();
CompanyUser companyUser = (CompanyUser) process.getAttribute("CompanyUser");
SecUser secUser = companyUser.getUser();
Company company = companyUser.getCompany();
String nextPage = (String) request.getAttribute("nextPage");
Boolean socialLogin = (Boolean) request.getAttribute("socialLogin");
LogMgr.log(LOG, LogLevel.PROCESSING1, "Verifing User", companyUser, secUser);
if(CollectionUtils.equals(companyUser.getPassword(), companyUser.getConfirmPassword()))
{
if(!company.isTrue(company.getIsVerified()) && CollectionUtils.equals(company.getAddedByUser(), companyUser))
{
process.setAttribute("Company", company);
process.setAttribute("socialLogin", socialLogin);
return new ProcessRedirectResult(nextPage, new String[0]);
}
else
{
nextPage = WebUtils.getArticleByShortCut(process.getTransaction(), WebUtils.ADMIN_HOME).getLink(request);
// Create company user in intercom
performa.intercom.resources.Company intercomCompany = IntercomUtils.findCompanyByID(company);
IntercomUtils.createIntercomUser(secUser, "Hiring Team", intercomCompany);
}
if(!socialLogin)
{
secUser.setAttribute("md5:" + SecUser.FIELD_Password, companyUser.getPassword());
}
companyUser.setIsAccountVerified(Boolean.TRUE);
sendMail(companyUser, request);
request.getSession().setAttribute (SecUser.SEC_USER_ID, secUser);
request.getSession().setAttribute (SessionSecUserDecorator.REFRESH_SECURITY, Boolean.TRUE);
LogMgr.log(LOG, LogLevel.PROCESSING1, "Password resetted", companyUser, secUser);
}
LogMgr.log(LOG, LogLevel.PROCESSING1, "Verifing User finished", companyUser, secUser);
process.completeAndRestart();
return new ProcessRedirectResult(nextPage, new String[0]);
}
@Override
public void init(ParticipantInitialisationContext context) throws InitialisationException
{
super.init(context);
emailer = (ConfigurableArticleTemplateEmailer) (context.getSingleChild("AccountCreatedEmailer"));
}
protected void sendMail(CompanyUser companyUser, HttpServletRequest request) throws BusinessException
{
try
{
LogMgr.log(LOG, LogLevel.PROCESSING1, "Sending Account Created mail from VerifyCompanyUserFP to :: ", companyUser);
Map defaultParams = CollectionUtils.EMPTY_MAP;
ObjectTransform transform = Utils.createCompoundTransform(defaultParams, companyUser);
Utils.sendMail(emailer, transform, new String[]{companyUser.getEmailAddressFromUser()}, null, companyUser);
LogMgr.log(LOG, LogLevel.PROCESSING1, "Sent Account Created mail successfully from " + VerifyCompanyUserFP.class + " to :: ", companyUser);
}
catch (ConfigurableEmailerException ex)
{
LogMgr.log(LOG, LogLevel.SYSTEMERROR1, ex, "Error occured while sending mail for CompanyUser :: " + companyUser);
throw new BusinessException("We are unable to send mail. Please try again or contact Talentology for more details.");
}
}
}
\ No newline at end of file
...@@ -13,6 +13,7 @@ import oneit.servlets.forms.*; ...@@ -13,6 +13,7 @@ import oneit.servlets.forms.*;
import oneit.servlets.process.*; import oneit.servlets.process.*;
import oneit.servlets.security.SessionSecUserDecorator; import oneit.servlets.security.SessionSecUserDecorator;
import oneit.utils.*; import oneit.utils.*;
import performa.intercom.utils.IntercomUtils;
import performa.orm.*; import performa.orm.*;
import performa.utils.Utils; import performa.utils.Utils;
...@@ -74,6 +75,9 @@ public class VerifyIdentityFP extends ORMProcessFormProcessor ...@@ -74,6 +75,9 @@ public class VerifyIdentityFP extends ORMProcessFormProcessor
sendMail(candidate, request); sendMail(candidate, request);
// Create a applicant user in intercom
IntercomUtils.createIntercomUser(secUser, "Applicant", null);
request.getSession().setAttribute (SecUser.SEC_USER_ID, secUser); request.getSession().setAttribute (SecUser.SEC_USER_ID, secUser);
request.getSession().setAttribute (SessionSecUserDecorator.REFRESH_SECURITY, Boolean.TRUE); request.getSession().setAttribute (SessionSecUserDecorator.REFRESH_SECURITY, Boolean.TRUE);
// request.setAttribute("nextPage", nextPage + "&JobID=" + job.getObjectID()); // request.setAttribute("nextPage", nextPage + "&JobID=" + job.getObjectID());
......
package performa.intercom.resources;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.Maps;
import java.util.Map;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Admin extends TypedData implements Replier {
private static final Map<String, String> SENTINEL = Maps.newHashMap();
public static final String TYPE_NOBODY = "nobody_admin";
// don't make public for now
static AdminCollection list(Map<String, String> params)
throws AuthorizationException, ClientException, ServerException, InvalidException, RateLimitException {
return DataResource.list(params, "admins", AdminCollection.class);
}
public static AdminCollection list()
throws AuthorizationException, ClientException, ServerException, InvalidException, RateLimitException {
return DataResource.list(SENTINEL, "admins", AdminCollection.class);
}
@SuppressWarnings("FieldCanBeLocal")
@JsonProperty("type")
private final String type = "admin";
@JsonProperty("id")
private String id;
@JsonProperty("name")
private String name;
@JsonProperty("email")
private String email;
@JsonProperty("created_at")
private long createdAt;
@JsonProperty("updated_at")
private long updatedAt;
@JsonProperty("open")
private long open;
@JsonProperty("closed")
private long closed;
public Admin() {
}
@JsonIgnore
public String getReplyType() {
return getType() + "_reply";
}
public String getType() {
return type;
}
@JsonIgnore
public boolean isNobody() {
return TYPE_NOBODY.equalsIgnoreCase(getType());
}
@JsonIgnore
public boolean isSomebody() {
return (!isNobody()) && (getId() != null);
}
public String getId() {
return id;
}
public Admin setId(String id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public long getCreatedAt() {
return createdAt;
}
public long getUpdatedAt() {
return updatedAt;
}
public long getOpen() {
return open;
}
public long getClosed() {
return closed;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Admin admin = (Admin) o;
if (closed != admin.closed) return false;
if (createdAt != admin.createdAt) return false;
if (open != admin.open) return false;
if (updatedAt != admin.updatedAt) return false;
if (email != null ? !email.equals(admin.email) : admin.email != null) return false;
if (id != null ? !id.equals(admin.id) : admin.id != null) return false;
if (name != null ? !name.equals(admin.name) : admin.name != null) return false;
//noinspection RedundantIfStatement
if (!type.equals(admin.type)) return false;
return true;
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + (id != null ? id.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (email != null ? email.hashCode() : 0);
result = 31 * result + (int) (createdAt ^ (createdAt >>> 32));
result = 31 * result + (int) (updatedAt ^ (updatedAt >>> 32));
result = 31 * result + (int) (open ^ (open >>> 32));
result = 31 * result + (int) (closed ^ (closed >>> 32));
return result;
}
@Override
public String toString() {
return "Admin{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", email='" + email + '\'' +
", createdAt=" + createdAt +
", updatedAt=" + updatedAt +
"} " + super.toString();
}
}
package performa.intercom.resources;
import performa.intercom.resources.Admin;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Iterator;
import java.util.List;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class AdminCollection extends TypedDataCollection<Admin> implements Iterator<Admin> {
protected TypedDataCollectionIterator<Admin> iterator;
public AdminCollection() {
type = "company.list";
iterator = new TypedDataCollectionIterator<Admin>(this);
}
@Override
public AdminCollection nextPage() {
return fetchNextPage(AdminCollection.class);
}
@SuppressWarnings("EmptyMethod")
@JsonProperty("admins")
@Override
public List<Admin> getPage() {
return super.getPage();
}
public boolean hasNext() {
return iterator.hasNext();
}
public Admin next() {
return iterator.next();
}
public void remove() {
iterator.remove();
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.annotations.VisibleForTesting;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class AdminMessage extends TypedData {
@JsonProperty("type")
private final String type = "admin_message";
@JsonProperty("id")
private String id;
@JsonProperty("message_type")
private String messageType;
@JsonProperty("subject")
private String subject=""; // Set default to blank string so null pointer exception won't thrown if messageType = inapp and subject not set
@JsonProperty("body")
private String body;
@JsonProperty("template")
private String template="plain"; // Set default to plain so null pointer exception won't thrown if messageType = inapp and template not set
@JsonProperty("created_at")
private long createdAt;
@JsonProperty("from")
private Admin admin;
@JsonProperty("to")
private User user;
public AdminMessage() {
}
public String getType() {
return type;
}
public String getId() {
return id;
}
@SuppressWarnings("UnusedReturnValue")
@VisibleForTesting
AdminMessage setId(String id) {
this.id = id;
return this;
}
public String getMessageType() {
return messageType;
}
public AdminMessage setMessageType(String messageType) {
this.messageType = messageType;
return this;
}
public String getSubject() {
return subject;
}
public AdminMessage setSubject(String subject) {
this.subject = subject;
return this;
}
public String getBody() {
return body;
}
public AdminMessage setBody(String body) {
this.body = body;
return this;
}
public String getTemplate() {
return template;
}
public AdminMessage setTemplate(String template) {
this.template = template;
return this;
}
public long getCreatedAt() {
return createdAt;
}
@SuppressWarnings("UnusedReturnValue")
public AdminMessage setCreatedAt(long createdAt) {
this.createdAt = createdAt;
return this;
}
public Admin getAdmin() {
return admin;
}
public AdminMessage setAdmin(Admin admin) {
this.admin = admin;
return this;
}
public User getUser() {
return user;
}
public AdminMessage setUser(User user) {
this.user = user;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AdminMessage message = (AdminMessage) o;
if (createdAt != message.createdAt) return false;
if (admin != null ? !admin.equals(message.admin) : message.admin != null) return false;
if (body != null ? !body.equals(message.body) : message.body != null) return false;
if (id != null ? !id.equals(message.id) : message.id != null) return false;
if (messageType != null ? !messageType.equals(message.messageType) : message.messageType != null) return false;
if (subject != null ? !subject.equals(message.subject) : message.subject != null) return false;
if (template != null ? !template.equals(message.template) : message.template != null) return false;
if (!type.equals(message.type)) return false;
//noinspection RedundantIfStatement
if (user != null ? !user.equals(message.user) : message.user != null) return false;
return true;
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + (id != null ? id.hashCode() : 0);
result = 31 * result + (messageType != null ? messageType.hashCode() : 0);
result = 31 * result + (subject != null ? subject.hashCode() : 0);
result = 31 * result + (body != null ? body.hashCode() : 0);
result = 31 * result + (template != null ? template.hashCode() : 0);
result = 31 * result + (int) (createdAt ^ (createdAt >>> 32));
result = 31 * result + (admin != null ? admin.hashCode() : 0);
result = 31 * result + (user != null ? user.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "AdminMessage{" +
"id='" + id + '\'' +
", messageType='" + messageType + '\'' +
", subject='" + subject + '\'' +
", body='" + body + '\'' +
", template='" + template + '\'' +
", createdAt=" + createdAt +
", admin=" + admin +
", user=" + user +
"} " + super.toString();
}
}
package performa.intercom.resources;
import performa.intercom.resources.Admin;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
class AdminMessageResponse extends TypedData {
@JsonProperty("id")
private String id;
@JsonProperty("message_type")
private String messageType;
@JsonProperty("subject")
private String subject;
@JsonProperty("body")
private String body;
@JsonProperty("template")
private String template;
@JsonProperty("created_at")
private long createdAt;
@JsonProperty("updated_at")
private long updatedAt;
@JsonProperty("owner")
private Admin admin;
@JsonProperty("to")
private User user;
public AdminMessageResponse() {
}
public String getType() {
return "admin_message";
}
public String getId() {
return id;
}
public AdminMessageResponse setId(String id) {
this.id = id;
return this;
}
public String getMessageType() {
return messageType;
}
public AdminMessageResponse setMessageType(String messageType) {
this.messageType = messageType;
return this;
}
public String getSubject() {
return subject;
}
public AdminMessageResponse setSubject(String subject) {
this.subject = subject;
return this;
}
public String getBody() {
return body;
}
public AdminMessageResponse setBody(String body) {
this.body = body;
return this;
}
public String getTemplate() {
return template;
}
public AdminMessageResponse setTemplate(String template) {
this.template = template;
return this;
}
public long getCreatedAt() {
return createdAt;
}
public AdminMessageResponse setCreatedAt(long createdAt) {
this.createdAt = createdAt;
return this;
}
public long getUpdatedAt() {
return updatedAt;
}
public AdminMessageResponse setUpdatedAt(long updatedAt) {
this.updatedAt = updatedAt;
return this;
}
public Admin getAdmin() {
return admin;
}
public AdminMessageResponse setAdmin(Admin admin) {
this.admin = admin;
return this;
}
public User getUser() {
return user;
}
public AdminMessageResponse setUser(User user) {
this.user = user;
return this;
}
}
package performa.intercom.resources;
import performa.intercom.resources.Admin;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class AdminReply extends Reply<Admin> {
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
static class AdminStringReply {
private AdminReply reply;
public AdminStringReply(AdminReply reply) {
this.reply = reply;
}
@JsonProperty("type")
public String getType() {
return reply.getType();
}
@JsonProperty("message_type")
public String getMessageType() {
return reply.getMessageType();
}
@JsonProperty("body")
public String getBody() {
return reply.getBody();
}
@JsonProperty("admin_id")
public String getAdminID() {
return reply.getFrom().getId();
}
@JsonProperty("assignee_id")
public String getAssigneeID() {
return reply.getAssigneeID();
}
@JsonProperty("attachment_urls")
private String[] getAttachmentUrls() {
return reply.getAttachmentUrls();
}
}
@JsonProperty("assignee_id")
private String assigneeID;
public AdminReply(Admin admin) {
this.from = admin;
}
public Reply<Admin> setMessageType(String messageType) {
return setMessageReplyType(messageType);
}
public String getAssigneeID() {
return assigneeID;
}
public Reply<Admin> setAssigneeID(String assigneeID) {
this.assigneeID = assigneeID;
this.setMessageType(Conversation.MESSAGE_TYPE_ASSIGNMENT);
return this;
}
@Override
public String toString() {
return "AdminReply{} " + super.toString();
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Author extends TypedData {
@JsonProperty("type")
private String type;
@JsonProperty("id")
private String id;
@JsonProperty("name")
private String name;
@JsonProperty("email")
private String email;
@JsonProperty("user_id")
private String userId;
public Author() {
}
public String getType() {
return type;
}
@JsonIgnore
public boolean isUser() {
return "user".equalsIgnoreCase(getType());
}
@JsonIgnore
public boolean isAdmin() {
return "admin".equalsIgnoreCase(getType());
}
public String getId() {
return id;
}
public Author setId(String id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public Author setName(String name) {
this.name = name;
return this;
}
public String getEmail() {
return email;
}
public Author setEmail(String email) {
this.email = email;
return this;
}
public String getUserId() {
return userId;
}
public Author setUserId(String userId) {
this.userId = userId;
return this;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (email != null ? email.hashCode() : 0);
result = 31 * result + (userId != null ? userId.hashCode() : 0);
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Author author = (Author) o;
if (email != null ? !email.equals(author.email) : author.email != null) return false;
if (id != null ? !id.equals(author.id) : author.id != null) return false;
if (name != null ? !name.equals(author.name) : author.name != null) return false;
//noinspection RedundantIfStatement
if (userId != null ? !userId.equals(author.userId) : author.userId != null) return false;
return true;
}
@Override
public String toString() {
return "Author{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", email='" + email + '\'' +
", userId='" + userId + '\'' +
"} " + super.toString();
}
}
package performa.intercom.resources;
public class AuthorizationException extends IntercomException {
private static final long serialVersionUID = 2917082281352001861L;
public AuthorizationException(String message) {
super(message);
}
public AuthorizationException(String message, Throwable cause) {
super(message, cause);
}
public AuthorizationException(ErrorCollection errorCollection) {
super(errorCollection);
}
public AuthorizationException(ErrorCollection errorCollection, Throwable cause) {
super(errorCollection, cause);
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.net.URI;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public class Avatar extends TypedData {
@JsonProperty("type")
private final String type = "avatar";
@JsonProperty("image_url")
private URI imageURL;
Avatar() {
}
public String getType() {
return type;
}
public URI getImageURL() {
return imageURL;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Avatar avatar = (Avatar) o;
if (imageURL != null ? !imageURL.equals(avatar.imageURL) : avatar.imageURL != null) return false;
//noinspection RedundantIfStatement
if (!type.equals(avatar.type)) return false;
return true;
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + (imageURL != null ? imageURL.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Avatar{" +
"type='" + type + '\'' +
", imageURL=" + imageURL +
"} " + super.toString();
}
}
package performa.intercom.resources;
public class ClientException extends IntercomException {
private static final long serialVersionUID = -2111295679006526646L;
public ClientException(String message) {
super(message);
}
public ClientException(String message, Throwable cause) {
super(message, cause);
}
public ClientException(ErrorCollection errorCollection) {
super(errorCollection);
}
public ClientException(ErrorCollection errorCollection, Throwable cause) {
super(errorCollection, cause);
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Iterator;
import java.util.List;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
public class CompanyCollection extends TypedDataCollection<Company> implements Iterator<Company> {
protected TypedDataCollectionIterator<Company> iterator;
@JsonProperty("total_count")
private long totalCount;
public CompanyCollection() {
type = "company.list";
iterator = new TypedDataCollectionIterator<Company>(this);
}
public CompanyCollection(List<Company> companies) {
this();
this.page = companies;
}
@SuppressWarnings("EmptyMethod")
@JsonProperty("companies")
@Override
public List<Company> getPage() {
return super.getPage();
}
public long getTotalCount() {
return totalCount;
}
@Override
public CompanyCollection nextPage() {
return fetchNextPage(CompanyCollection.class);
}
public boolean hasNext() {
return iterator.hasNext();
}
public Company next() {
return iterator.next();
}
public void remove() {
iterator.remove();
}
@Override
public String toString() {
return "CompanyCollection{" +
", totalCount=" + totalCount +
"} " + super.toString();
}
void addCompany(Company company) {
page.add(company);
}
}
package performa.intercom.resources;
import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import java.util.List;
class CompanyUpdateBuilder {
/**
* Provide restrictions on the company data that can be sent via a user update
*/
static List<CompanyWithStringPlan> buildUserUpdateCompanies(CompanyCollection add, CompanyCollection remove) {
final List<CompanyWithStringPlan> updatableCompanies = Lists.newArrayList();
if (add != null) {
final List<Company> companies = add.getPage();
for (Company company : companies) {
if (!isCompanyInList(company, remove)) {
updatableCompanies.add(prepareUpdatableCompany(company));
}
}
}
if (remove != null) {
final List<Company> companies = remove.getPage();
for (Company company : companies) {
updatableCompanies.add(prepareUpdatableCompany(company).setRemove(Boolean.TRUE));
}
}
return updatableCompanies;
}
private static boolean isCompanyInList(final Company company, CompanyCollection companyCollection) {
if (companyCollection == null) {
return false;
}
return Iterables.any(companyCollection.getPage(), new Predicate<Company>() {
@Override
public boolean apply(Company e) {
return Objects.equal(company.getCompanyID(), e.getCompanyID())
|| Objects.equal(company.getId(), e.getId());
}
});
}
private static CompanyWithStringPlan prepareUpdatableCompany(Company company) {
final CompanyWithStringPlan updatableCompany = new CompanyWithStringPlan();
updatableCompany.setId(company.getId());
updatableCompany.setCompanyID(company.getCompanyID());
updatableCompany.setName(company.getName());
updatableCompany.setSessionCount(company.getSessionCount());
updatableCompany.setMonthlySpend(company.getMonthlySpend());
updatableCompany.setRemoteCreatedAt(company.getRemoteCreatedAt());
if (company.getCustomAttributes() != null) {
updatableCompany.getCustomAttributes().putAll(company.getCustomAttributes());
}
if (company.getPlan() != null) {
updatableCompany.setPlan(company.getPlan().getName());
}
return updatableCompany;
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.Maps;
import java.util.Map;
@SuppressWarnings("UnusedDeclaration")
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
@JsonIgnoreProperties(ignoreUnknown = true)
class CompanyWithStringPlan extends TypedData {
@JsonProperty("id")
private String id;
@JsonProperty("name")
private String name;
@JsonProperty("company_id")
private String companyID;
@JsonProperty("session_count")
private int sessionCount;
@JsonProperty("monthly_spend")
private float monthlySpend;
@JsonProperty("remote_created_at")
private long remoteCreatedAt;
@JsonProperty("plan")
private String plan;
@JsonIgnoreProperties(ignoreUnknown = false)
@JsonProperty("custom_attributes")
private Map<String, CustomAttribute> customAttributes = Maps.newHashMap();
@JsonProperty("remove")
@JsonInclude(JsonInclude.Include.NON_NULL)
private Boolean remove;
public CompanyWithStringPlan() {
}
public String getType() {
return "company";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCompanyID() {
return companyID;
}
public void setCompanyID(String companyID) {
this.companyID = companyID;
}
public Integer getSessionCount() {
return sessionCount;
}
public void setSessionCount(Integer sessionCount) {
this.sessionCount = sessionCount;
}
public float getMonthlySpend() {
return monthlySpend;
}
public void setMonthlySpend(float monthlySpend) {
this.monthlySpend = monthlySpend;
}
public long getRemoteCreatedAt() {
return remoteCreatedAt;
}
public void setRemoteCreatedAt(long remoteCreatedAt) {
this.remoteCreatedAt = remoteCreatedAt;
}
public String getPlan() {
return plan;
}
public void setPlan(String plan) {
this.plan = plan;
}
public Map<String, CustomAttribute> getCustomAttributes() {
return customAttributes;
}
public void setCustomAttributes(Map<String, CustomAttribute> customAttributes) {
this.customAttributes = customAttributes;
}
public Boolean getRemove() {
return remove;
}
public CompanyWithStringPlan setRemove(Boolean remove) {
this.remove = remove;
return this;
}
}
package performa.intercom.resources;
import com.google.common.collect.Lists;
class Conditions {
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null. Variant of Guava's Preconditions that returns an
* InvalidException containing an ErrorCollection
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails
* @return the non-null reference that was validated
* @throws InvalidException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, String errorMessage) {
if (reference == null) {
throw new InvalidException(
new ErrorCollection(
Lists.newArrayList(
new Error("invalid", "item method must be supplied"))));
}
return reference;
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Iterator;
import java.util.List;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
public class ContactCollection extends TypedDataCollection<Contact> implements Iterator<Contact> {
protected TypedDataCollectionIterator<Contact> iterator;
public ContactCollection() {
iterator = new TypedDataCollectionIterator<Contact>(this);
}
public ContactCollection(List<Contact> contacts) {
this();
this.page = contacts;
}
@SuppressWarnings("EmptyMethod")
@JsonProperty("contacts")
@Override
public List<Contact> getPage() {
return super.getPage();
}
@Override
public ContactCollection nextPage() {
return fetchNextPage(ContactCollection.class);
}
public boolean hasNext() {
return iterator.hasNext();
}
public Contact next() {
return iterator.next();
}
public void remove() {
iterator.remove();
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class ContactMessage extends TypedMessage<Contact, ContactMessage> {
public ContactMessage() {
}
@Override
public String toString() {
return "ContactMessage{} " + super.toString();
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Iterator;
import java.util.List;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
public class ConversationCollection extends TypedDataCollection<Conversation> implements Iterator<Conversation> {
protected TypedDataCollectionIterator<Conversation> iterator;
public ConversationCollection() {
type = "conversation.list";
iterator = new TypedDataCollectionIterator<Conversation>(this);
}
@SuppressWarnings("EmptyMethod")
@JsonProperty("conversations")
public List<Conversation> getPage() {
return super.getPage();
}
@Override
public ConversationCollection nextPage() {
return fetchNextPage(ConversationCollection.class);
}
public boolean hasNext() {
return iterator.hasNext();
}
public Conversation next() {
return iterator.next();
}
public void remove() {
iterator.remove();
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
public class ConversationMessage extends TypedData {
@SuppressWarnings("FieldCanBeLocal")
@JsonProperty("type")
private final String type = "conversation_message";
@JsonProperty
private String subject;
@JsonProperty
private String body;
@JsonProperty
private Author author;
public ConversationMessage() {
}
public String getType() {
return type;
}
public String getSubject() {
return subject;
}
public String getBody() {
return body;
}
public Author getAuthor() {
return author;
}
@Override
public int hashCode() {
int result = subject != null ? subject.hashCode() : 0;
result = 31 * result + (body != null ? body.hashCode() : 0);
result = 31 * result + (author != null ? author.hashCode() : 0);
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConversationMessage that = (ConversationMessage) o;
if (author != null ? !author.equals(that.author) : that.author != null) return false;
if (body != null ? !body.equals(that.body) : that.body != null) return false;
//noinspection RedundantIfStatement
if (subject != null ? !subject.equals(that.subject) : that.subject != null) return false;
return true;
}
@Override
public String toString() {
return "ConversationMessage{" +
"type='" + type + '\'' +
", subject='" + subject + '\'' +
", body='" + body + '\'' +
", author=" + author +
"} " + super.toString();
}
}
package performa.intercom.resources;
import performa.intercom.resources.Admin;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
public class ConversationPart extends TypedData {
@JsonProperty("type")
private final String type = "conversation_part";
@JsonProperty
private String id;
@JsonProperty("part_type")
private String partType;
@JsonProperty
private String body;
@JsonProperty
private Author author;
@JsonProperty("assigned_to")
private Admin assignedTo;
@JsonProperty("created_at")
private long createdAt;
@JsonProperty("updated_at")
private long updatedAt;
@JsonProperty("notified_at")
private long NotifiedAt;
public ConversationPart() {
}
public String getType() {
return type;
}
public String getId() {
return id;
}
public String getPartType() {
return partType;
}
public String getBody() {
return body;
}
public Author getAuthor() {
return author;
}
public Admin getAssignedTo() {
return assignedTo;
}
public long getCreatedAt() {
return createdAt;
}
public long getUpdatedAt() {
return updatedAt;
}
public long getNotifiedAt() {
return NotifiedAt;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConversationPart that = (ConversationPart) o;
if (NotifiedAt != that.NotifiedAt) return false;
if (createdAt != that.createdAt) return false;
if (updatedAt != that.updatedAt) return false;
if (assignedTo != null ? !assignedTo.equals(that.assignedTo) : that.assignedTo != null) return false;
if (author != null ? !author.equals(that.author) : that.author != null) return false;
if (body != null ? !body.equals(that.body) : that.body != null) return false;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (partType != null ? !partType.equals(that.partType) : that.partType != null) return false;
//noinspection RedundantIfStatement
if (!type.equals(that.type)) return false;
return true;
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + (id != null ? id.hashCode() : 0);
result = 31 * result + (partType != null ? partType.hashCode() : 0);
result = 31 * result + (body != null ? body.hashCode() : 0);
result = 31 * result + (author != null ? author.hashCode() : 0);
result = 31 * result + (assignedTo != null ? assignedTo.hashCode() : 0);
result = 31 * result + (int) (createdAt ^ (createdAt >>> 32));
result = 31 * result + (int) (updatedAt ^ (updatedAt >>> 32));
result = 31 * result + (int) (NotifiedAt ^ (NotifiedAt >>> 32));
return result;
}
@Override
public String toString() {
return "ConversationPart{" +
"type='" + type + '\'' +
", id='" + id + '\'' +
", partType='" + partType + '\'' +
", body='" + body + '\'' +
", author=" + author +
", assignedTo=" + assignedTo +
", createdAt=" + createdAt +
", updatedAt=" + updatedAt +
", NotifiedAt=" + NotifiedAt +
"} " + super.toString();
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
public class ConversationPartCollection extends TypedDataCollection<ConversationPart> {
public ConversationPartCollection() {
type = "conversation_part.list";
}
@SuppressWarnings("EmptyMethod")
@JsonProperty("conversation_parts")
public List<ConversationPart> getPage() {
return super.getPage();
}
@Override
public ConversationPartCollection nextPage() {
return new ConversationPartCollection();
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.util.Map;
class CountItemDeserializer extends StdDeserializer<Counts.CountItem> {
private static final long serialVersionUID = 8226175715446656115L;
public CountItemDeserializer() {
super(Counts.CountItem.class);
}
@Override
public Counts.CountItem deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
final TreeNode treeNode = jp.getCodec().readTree(jp);
final Map.Entry<String, JsonNode> next = ((ObjectNode) treeNode).fields().next();
return new Counts.CountItem(next.getKey(), next.getValue().asLong());
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
class CountItemSerializer extends StdSerializer<Counts.CountItem> {
public CountItemSerializer() {
super(Counts.CountItem.class);
}
@Override
public void serialize(Counts.CountItem value, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
jgen.writeStartObject();
jgen.writeNumberField(value.getName(), value.getValue());
jgen.writeEndObject();
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.Maps;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Counts {
static Counts countQuery(Map<String, String> query) {
final URI build = UriBuilder.newBuilder()
.path("counts")
.query(query)
.build();
final HttpClient resource = new HttpClient(build);
return resource.get(Counts.class);
}
public static Counts.Totals appTotals() throws InvalidException, AuthorizationException {
final HttpClient resource = new HttpClient(UriBuilder.newBuilder().path("counts").build());
return resource.get(Totals.class);
}
// public static Long userCount() throws InvalidException, AuthorizationException{
// final HashMap<String, String> params = Maps.newHashMap();
// params.put("type", "user");
// return countQuery(params).getUser().getUser();
// }
public static List<CountItem> userTags() throws InvalidException, AuthorizationException {
final HashMap<String, String> params = Maps.newHashMap();
params.put("type", "user");
params.put("count", "tag");
return countQuery(params).getUser().getTags();
}
public static List<CountItem> userSegments() throws InvalidException, AuthorizationException {
final HashMap<String, String> params = Maps.newHashMap();
params.put("type", "user");
params.put("count", "segment");
return countQuery(params).getUser().getSegments();
}
public static Counts.Conversation conversationTotals() throws InvalidException, AuthorizationException {
final HashMap<String, String> params = Maps.newHashMap();
params.put("type", "conversation");
return countQuery(params).getConversation();
}
public static Counts.Conversation conversationAdmins() throws InvalidException, AuthorizationException {
final HashMap<String, String> params = Maps.newHashMap();
params.put("type", "conversation");
params.put("count", "admin");
return countQuery(params).getConversation();
}
// public static Long companyCount() throws InvalidException, AuthorizationException{
// final HashMap<String, String> params = Maps.newHashMap();
// params.put("type", "company");
// return countQuery(params).getCompany().getCompanies();
// }
public static List<CountItem> companySegments() throws InvalidException, AuthorizationException {
final HashMap<String, String> params = Maps.newHashMap();
params.put("type", "company");
params.put("count", "segment");
return countQuery(params).getCompany().getSegments();
}
public static List<CountItem> companyTags() throws InvalidException, AuthorizationException {
final HashMap<String, String> params = Maps.newHashMap();
params.put("type", "company");
params.put("count", "tag");
return countQuery(params).getCompany().getTags();
}
public static List<CountItem> companyUsers() throws InvalidException, AuthorizationException {
final HashMap<String, String> params = Maps.newHashMap();
params.put("type", "company");
params.put("count", "user");
return countQuery(params).getCompany().getUsers();
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public static class Totals {
@JsonProperty("company")
private CountItem company;
@JsonProperty("segment")
private CountItem segment;
@JsonProperty("tag")
private CountItem tag;
@JsonProperty("user")
private CountItem user;
public CountItem getCompany() {
return company;
}
public CountItem getSegment() {
return segment;
}
public CountItem getTag() {
return tag;
}
public CountItem getUser() {
return user;
}
@Override
public String toString() {
return "Totals{" +
"company=" + company +
", segment=" + segment +
", tag=" + tag +
", user=" + user +
'}';
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public static class CountItem {
private String name;
private long value;
public CountItem(String name, long value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public long getValue() {
return value;
}
@Override
public String toString() {
return "CountItem{" +
"name='" + name + '\'' +
", value=" + value +
'}';
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public static class Conversation {
@JsonProperty("admin")
List<Admin> admins;
@JsonProperty("assigned")
private long assigned;
@JsonProperty("closed")
private long closed;
@JsonProperty("open")
private long open;
@JsonProperty("unassigned")
private long unassigned;
Conversation() {
}
public List<Admin> getAdmins() {
return admins;
}
public long getAssigned() {
return assigned;
}
public long getClosed() {
return closed;
}
public long getOpen() {
return open;
}
public long getUnassigned() {
return unassigned;
}
@Override
public String toString() {
return "Conversation{" +
"assigned=" + assigned +
", closed=" + closed +
", open=" + open +
", unassigned=" + unassigned +
", admins=" + admins +
'}';
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public static class User {
@JsonProperty("user")
private long user;
@JsonProperty("tag")
private List<CountItem> tags;
@JsonProperty("segment")
private List<CountItem> segments;
User() {
}
public long getUser() {
return user;
}
public List<CountItem> getTags() {
return tags;
}
public List<CountItem> getSegments() {
return segments;
}
@Override
public String toString() {
return "User{" +
"user=" + user +
", tags=" + tags +
", segments=" + segments +
'}';
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public static class Company {
@JsonProperty("company")
private long companies;
@JsonProperty("tag")
private List<CountItem> tags;
@JsonProperty("user")
private List<CountItem> users;
@JsonProperty("segment")
private List<CountItem> segments;
Company() {
}
public long getCompanies() {
return companies;
}
public List<CountItem> getTags() {
return tags;
}
public List<CountItem> getUsers() {
return users;
}
public List<CountItem> getSegments() {
return segments;
}
@Override
public String toString() {
return "Company{" +
"companies=" + companies +
", tags=" + tags +
", users=" + users +
", segments=" + segments +
'}';
}
}
@JsonProperty("type")
private String type = "count";
@JsonProperty("company")
private Counts.Company company;
@JsonProperty("user")
private Counts.User user;
@JsonProperty("conversation")
private Counts.Conversation conversation;
public String getType() {
return type;
}
public Company getCompany() {
return company;
}
public User getUser() {
return user;
}
public Conversation getConversation() {
return conversation;
}
@Override
public String toString() {
return "Counts{" +
"type='" + type + '\'' +
", company=" + company +
", user=" + user +
", conversation=" + conversation +
'}';
}
}
package performa.intercom.resources;
import com.google.common.collect.Lists;
import java.io.Serializable;
import java.util.ArrayList;
@SuppressWarnings("UnusedDeclaration")
public class CustomAttribute<T> {
@SuppressWarnings("unchecked")
private static final ArrayList<? extends Class<? extends Serializable>> CLASSES = Lists.newArrayList(String.class, Long.class, Float.class, Double.class, Boolean.class, Integer.class);
public static StringAttribute newStringAttribute(String name, String value) {
return new StringAttribute(name, value);
}
public static BooleanAttribute newBooleanAttribute(String name, boolean value) {
return new BooleanAttribute(name, value);
}
public static DoubleAttribute newDoubleAttribute(String name, double value) {
return new DoubleAttribute(name, value);
}
public static LongAttribute newLongAttribute(String name, long value) {
return new LongAttribute(name, value);
}
public static IntegerAttribute newIntegerAttribute(String name, int value) {
return new IntegerAttribute(name, value);
}
public static FloatAttribute newFloatAttribute(String name, float value) {
return new FloatAttribute(name, value);
}
public static class StringAttribute extends CustomAttribute<String> {
private StringAttribute(String name, String value) {
super(name, value, String.class);
}
private StringAttribute(String name, String value, Class<String> clazz) {
super(name, value, clazz);
}
}
public static class BooleanAttribute extends CustomAttribute<Boolean> {
private BooleanAttribute(String name, boolean value) {
super(name, value, Boolean.class);
}
private BooleanAttribute(String name, boolean value, Class<Boolean> clazz) {
super(name, value, clazz);
}
}
public static class DoubleAttribute extends CustomAttribute<Double> {
private DoubleAttribute(String name, double value, Class<Double> clazz) {
super(name, value, clazz);
}
private DoubleAttribute(String name, double value) {
super(name, value, Double.class);
}
}
public static class FloatAttribute extends CustomAttribute<Float> {
private FloatAttribute(String name, float value, Class<Float> clazz) {
super(name, value, clazz);
}
private FloatAttribute(String name, float value) {
super(name, value, Float.class);
}
}
public static class IntegerAttribute extends CustomAttribute<Integer> {
private IntegerAttribute(String name, int value) {
super(name, value, Integer.class);
}
private IntegerAttribute(String name, int value, Class<Integer> clazz) {
super(name, value, clazz);
}
}
public static class LongAttribute extends CustomAttribute<Long> {
public LongAttribute(String name, long value, Class<Long> clazz) {
super(name, value, clazz);
}
public LongAttribute(String name, long value) {
super(name, value, Long.class);
}
}
private String name;
private T value;
private Class<T> clazz;
public CustomAttribute(String name, T value, Class<T> clazz) {
//noinspection SuspiciousMethodCalls
if (!CLASSES.contains(clazz)) {
throw new InvalidException(String.format("cannot accept class type [%s] for custom attribute", clazz.getName()));
}
this.name = name;
this.value = value;
this.clazz = clazz;
}
public Class<T> getValueClass() {
return clazz;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public <C> C as(Class<C> c) {
//noinspection unchecked
return (C) getValue();
}
public long longValue() {
return as(Long.class);
}
public String textValue() {
return as(String.class);
}
public boolean booleanValue() {
return as(Boolean.class);
}
public float floatValue() {
return as(Float.class);
}
public double doubleValue() {
return as(Double.class);
}
public int integerValue() {
return as(Integer.class);
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
result = 31 * result + (clazz != null ? clazz.hashCode() : 0);
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomAttribute that = (CustomAttribute) o;
if (clazz != null ? !clazz.equals(that.clazz) : that.clazz != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
//noinspection RedundantIfStatement
if (value != null ? !value.equals(that.value) : that.value != null) return false;
return true;
}
@Override
public String toString() {
return "CustomAttribute{" +
"name='" + name + '\'' +
", value=" + value +
", clazz=" + clazz +
'}';
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.fasterxml.jackson.databind.node.NumericNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import java.io.IOException;
class CustomAttributeDeserializer extends StdDeserializer<CustomAttribute> {
private static final long serialVersionUID = 5069924730975394938L;
public CustomAttributeDeserializer() {
super(CustomAttribute.class);
}
@Override
public CustomAttribute deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
CustomAttribute cda = null;
final String currentName = jp.getParsingContext().getCurrentName();
final ObjectMapper mapper = (ObjectMapper) jp.getCodec();
final ValueNode vNode = mapper.readTree(jp);
if (vNode.asToken().isScalarValue()) {
if (vNode.getNodeType() == JsonNodeType.BOOLEAN) {
cda = new CustomAttribute<Boolean>(currentName, vNode.asBoolean(), Boolean.class);
} else if (vNode.getNodeType() == JsonNodeType.STRING) {
cda = new CustomAttribute<String>(currentName, vNode.asText(), String.class);
} else if (vNode.getNodeType() == JsonNodeType.NUMBER) {
final NumericNode nNode = (NumericNode) vNode;
if (currentName.endsWith("_at")) {
cda = new CustomAttribute<Long>(currentName, vNode.longValue(), Long.class);
} else if (nNode.isInt()) {
cda = new CustomAttribute<Integer>(currentName, vNode.intValue(), Integer.class);
} else if (nNode.isFloat()) {
cda = new CustomAttribute<Float>(currentName, vNode.floatValue(), Float.class);
} else if (nNode.isDouble()) {
cda = new CustomAttribute<Double>(currentName, vNode.doubleValue(), Double.class);
} else if (nNode.isLong()) {
cda = new CustomAttribute<Long>(currentName, vNode.longValue(), Long.class);
} else {
cda = new CustomAttribute<String>(currentName, vNode.asText(), String.class);
}
} else {
cda = new CustomAttribute<String>(currentName, vNode.asText(), String.class);
}
}
return cda;
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
class CustomAttributeSerializer extends StdSerializer<CustomAttribute> {
public CustomAttributeSerializer() {
super(CustomAttribute.class);
}
@Override
public void serialize(CustomAttribute value, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
// the field name has already been written
jgen.writeObject(value.getValue());
}
}
package performa.intercom.resources;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import java.net.URI;
import java.util.List;
import java.util.Map;
abstract class DataResource {
@SuppressWarnings("SameParameterValue")
public static <T> T find(String id, String collectionPath, Class<T> c) {
final HttpClient resource = new HttpClient(UriBuilder.newBuilder().path(collectionPath).path(id).build());
return resource.get(c);
}
public static <T> T find(Map<String, String> params, String collectionPath, Class<T> c) {
final HttpClient resource = new HttpClient(UriBuilder.newBuilder().path(collectionPath).query(params).build());
return resource.get(c);
}
public static <T, R> R create(T entity, String collectionPath, Class<R> response) {
final HttpClient resource = new HttpClient(UriBuilder.newBuilder().path(collectionPath).build());
return resource.post(response, entity);
}
public static <T, R> R create(T entity, List<String> paths, Class<R> response) {
final HttpClient resource = new HttpClient(UriBuilder.newBuilder().path(paths).build());
return resource.post(response, entity);
}
public static <T, R> R update(T entity, String collectionPath, Class<R> response) {
final HttpClient resource = new HttpClient(UriBuilder.newBuilder().path(collectionPath).build());
return resource.post(response, entity);
}
public static <T, R> R post(T entity, URI path, Class<R> response) {
final HttpClient resource = new HttpClient(path);
return resource.post(response, entity);
}
public static <T, R> R updatePut(T entity, URI collectionPath, Class<R> response) {
final HttpClient resource = new HttpClient(collectionPath);
return resource.put(response, entity);
}
@SuppressWarnings("SameParameterValue")
public static <T, R> R update(T entity, String collectionPath, String id, Class<R> response) {
final HttpClient resource = new HttpClient(UriBuilder.newBuilder().path(collectionPath).path(id).build());
return resource.post(response, entity);
}
public static <T> T delete(String id, String collectionPath, Class<T> c) {
final HttpClient resource = new HttpClient(UriBuilder.newBuilder().path(collectionPath).path(id).build());
return resource.delete(c);
}
public static <C> C list(Map<String, String> params, String collectionPath, Class<C> c) {
final HttpClient resource = new HttpClient(UriBuilder.newBuilder().path(collectionPath).query(params).build());
return resource.get(c);
}
public static <C> C scroll(String scrollParam, String collectionPath, Class<C> c) {
Map<String, String> params = Maps.newHashMap();
if (!Strings.isNullOrEmpty(scrollParam)) {
params.put("scroll_param", scrollParam);
}
final HttpClient resource = new HttpClient(UriBuilder.newBuilder().path(collectionPath + "/scroll").query(params).build());
return resource.get(c);
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Error extends TypedData {
@SuppressWarnings("FieldCanBeLocal")
@JsonProperty("type")
private final String type = "error";
@JsonProperty("code")
private String code;
@JsonProperty("message")
private String message;
public Error() {
}
public Error(String code, String message) {
this.code = code;
this.message = message;
}
public String getType() {
return type;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public int hashCode() {
int result = code != null ? code.hashCode() : 0;
result = 31 * result + (message != null ? message.hashCode() : 0);
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Error error = (Error) o;
if (code != null ? !code.equals(error.code) : error.code != null) return false;
//noinspection RedundantIfStatement
if (message != null ? !message.equals(error.message) : error.message != null) return false;
return true;
}
@Override
public String toString() {
return getType() + "{" +
"code='" + code + '\'' +
", message='" + message + '\'' +
"} " + super.toString();
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import java.util.List;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
public final class ErrorCollection {
@JsonProperty("errors")
private List<Error> errors;
// for jackson
ErrorCollection() {
}
public ErrorCollection(List<Error> errors) {
Preconditions.checkNotNull(errors, "cannot create an error collection with a null error list");
Preconditions.checkArgument(errors.size() > 0, "cannot create an error collection with an empty error list");
this.errors = errors;
}
public List<Error> getErrors() {
return errors;
}
public String getType() {
return "error.list";
}
}
package performa.intercom.resources;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public class Event extends TypedData {
private static final List<String> BULK_METHODS = Lists.newArrayList("post");
private static final ArrayList<String> BULK_PATHS = Lists.newArrayListWithExpectedSize(2);
static {
BULK_PATHS.add("bulk");
BULK_PATHS.add("events");
}
public static void create(Event event) throws InvalidException, AuthorizationException {
validateCreateEvent(event);
if (event.getCreatedAt() == 0L) {
event.setCreatedAt(System.currentTimeMillis() / 1000);
}
DataResource.create(event, "events", Void.class);
}
public static Job submit(List<JobItem<Event>> items)
throws AuthorizationException, ClientException, ServerException, InvalidException, RateLimitException {
return submit(items, null);
}
public static Job submit(List<JobItem<Event>> items, Job job)
throws AuthorizationException, ClientException, ServerException, InvalidException, RateLimitException {
return Job.submit(validateJobItems(items), job, BULK_PATHS);
}
public static JobItemCollection<Event> listJobErrorFeed(String jobID)
throws AuthorizationException, ClientException, ServerException, InvalidException, RateLimitException {
return Job.listJobErrorFeed(jobID, Event.class);
}
@VisibleForTesting
static List<JobItem<Event>> validateJobItems(List<JobItem<Event>> items) {
final JobSupport jobSupport = new JobSupport();
for (JobItem<Event> item : items) {
jobSupport.validateJobItem(item, BULK_METHODS);
validateCreateEvent(item.getData());
}
return items;
}
private static final ErrorCollection INVALID_NAME = new ErrorCollection(
Lists.newArrayList(
new Error("invalid", "an event must supply an event name")));
private static final ErrorCollection INVALID_USER = new ErrorCollection(
Lists.newArrayList(
new Error("invalid", "an event must supply either an email or a user id")));
@VisibleForTesting
static void validateCreateEvent(Event event) {
if (Strings.isNullOrEmpty(event.getEventName())) {
throw new InvalidException(INVALID_NAME);
}
if (Strings.isNullOrEmpty(event.getUserID())
&& Strings.isNullOrEmpty(event.getEmail())) {
throw new InvalidException(INVALID_USER);
}
}
@SuppressWarnings("FieldCanBeLocal")
@JsonProperty("type")
private final String type = "event";
@JsonProperty("event_name")
private String eventName;
@JsonProperty("created_at")
private long createdAt;
@JsonProperty("email")
private String email;
@JsonProperty("user_id")
private String userID;
@JsonProperty("metadata")
private Map<String, Object> metadata = Maps.newHashMap();
public Event() {
}
public String getType() {
return type;
}
public String getEventName() {
return eventName;
}
public Event setEventName(String eventName) {
this.eventName = eventName;
return this;
}
public long getCreatedAt() {
return createdAt;
}
@SuppressWarnings("UnusedReturnValue")
public Event setCreatedAt(long createdAt) {
this.createdAt = createdAt;
return this;
}
public String getEmail() {
return email;
}
public Event setEmail(String email) {
this.email = email;
return this;
}
public String getUserID() {
return userID;
}
public Event setUserID(String userID) {
this.userID = userID;
return this;
}
public Event putMetadata(String name, String value) {
metadata.put(name, value);
return this;
}
public Event putMetadata(String name, boolean value) {
metadata.put(name, value);
return this;
}
public Event putMetadata(String name, int value) {
metadata.put(name, value);
return this;
}
public Event putMetadata(String name, double value) {
metadata.put(name, value);
return this;
}
public Event putMetadata(String name, long value) {
metadata.put(name, value);
return this;
}
public Event putMetadata(String name, float value) {
metadata.put(name, value);
return this;
}
public Map<String, Object> getMetadata() {
return metadata;
}
public Event setMetadata(Map<String, Object> metadata) {
this.metadata = metadata;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Event event = (Event) o;
if (createdAt != event.createdAt) return false;
if (email != null ? !email.equals(event.email) : event.email != null) return false;
if (eventName != null ? !eventName.equals(event.eventName) : event.eventName != null) return false;
if (metadata != null ? !metadata.equals(event.metadata) : event.metadata != null) return false;
if (!type.equals(event.type)) return false;
//noinspection RedundantIfStatement
if (userID != null ? !userID.equals(event.userID) : event.userID != null) return false;
return true;
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + (eventName != null ? eventName.hashCode() : 0);
result = 31 * result + (int) (createdAt ^ (createdAt >>> 32));
result = 31 * result + (email != null ? email.hashCode() : 0);
result = 31 * result + (userID != null ? userID.hashCode() : 0);
result = 31 * result + (metadata != null ? metadata.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Event{" +
"type='" + type + '\'' +
", eventName='" + eventName + '\'' +
", createdAt=" + createdAt +
", email='" + email + '\'' +
", userID='" + userID + '\'' +
", metadata=" + metadata +
"} " + super.toString();
}
}
package performa.intercom.resources;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
public interface HttpConnectorSupplier {
HttpURLConnection connect(URI uri) throws IOException;
HttpConnectorSupplier defaultSupplier = new HttpConnectorSupplier() {
public HttpURLConnection connect(URI uri) throws IOException {
return (HttpURLConnection) uri.toURL().openConnection();
}
};
}
package performa.intercom.resources;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.net.HttpURLConnection;
class IOUtils {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger("intercom-java");
/**
* Close a HttpURLConnection, ignores checked Exceptions and nulls,
* but rethrows RuntimeExceptions.
*
* @param connection the connection to disconnect
*/
public static void disconnectQuietly(HttpURLConnection connection) {
if (connection != null) {
try {
connection.disconnect();
} catch (RuntimeException rethrow) {
throw rethrow;
} catch (Exception e) {
logger.warn(e.getMessage());
}
}
}
/**
* Close a stream, ignores checked Exceptions and nulls,
* but rethrows RuntimeExceptions.
*
* @param stream the object to close
*/
public static void closeQuietly(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (RuntimeException rethrow) {
throw rethrow;
} catch (Exception e) {
logger.warn(e.getMessage());
}
}
}
}
package performa.intercom.resources;
import java.net.URI;
public class Intercom {
private static final URI API_BASE_URI = URI.create("https://api.intercom.io/");
private static volatile URI apiBaseURI = API_BASE_URI;
private static volatile AuthKeyType authKeyType = AuthKeyType.API_KEY;
enum AuthKeyType {
API_KEY,
TOKEN
}
private static final String VERSION = "2.2.7";
public static final String USER_AGENT = "intercom-java/" + Intercom.VERSION;
private static volatile String apiKey;
private static volatile String token;
private static volatile String appID;
private static volatile int connectionTimeout = 3 * 1000;
private static volatile int requestTimeout = 60 * 1000;
private static volatile boolean requestUsingCaches = false;
private static volatile HttpConnectorSupplier httpConnectorSupplier = HttpConnectorSupplier.defaultSupplier;
public static long currentTimestamp() {
return System.currentTimeMillis()/1000;
}
public static int getConnectionTimeout() {
return connectionTimeout;
}
@SuppressWarnings("UnusedDeclaration")
public static void setConnectionTimeout(int connectionTimeout) {
Intercom.connectionTimeout = connectionTimeout;
}
public static int getRequestTimeout() {
return requestTimeout;
}
@SuppressWarnings("UnusedDeclaration")
public static void setRequestTimeout(int requestTimeout) {
Intercom.requestTimeout = requestTimeout;
}
public static boolean isRequestUsingCaches() {
return requestUsingCaches;
}
public static void setRequestUsingCaches(boolean requestUsingCaches) {
Intercom.requestUsingCaches = requestUsingCaches;
}
public static HttpConnectorSupplier getHttpConnectorSupplier() {
return httpConnectorSupplier;
}
public static void setHttpConnectorSupplier(HttpConnectorSupplier supplier) {
Intercom.httpConnectorSupplier = supplier;
}
public static String getAppID() {
return appID;
}
public static void setAppID(String appID) {
Intercom.appID = appID;
}
public static void setToken(String token) {
authKeyType = AuthKeyType.TOKEN;
Intercom.token = token;
}
public static String getApiKey() {
return Intercom.apiKey;
}
public static void setApiKey(String apiKey) {
authKeyType = AuthKeyType.API_KEY;
Intercom.apiKey = apiKey;
}
public static URI getApiBaseURI() {
return Intercom.apiBaseURI;
}
public static void setApiBaseURI(URI apiBaseURI) {
Intercom.apiBaseURI = apiBaseURI;
}
static AuthKeyType getAuthKeyType() {
return authKeyType;
}
public static String getToken() {
return token;
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment