Search in sources :

Example 26 with MarketoException

use of org.talend.components.marketo.runtime.client.type.MarketoException in project components by Talend.

the class MarketoBaseRESTClient method getToken.

public void getToken() throws MarketoException {
    try {
        URL basicURI = new URL(endpoint);
        current_uri = // 
        new StringBuilder(basicURI.getProtocol()).append(// 
        "://").append(// 
        basicURI.getHost()).append(// 
        API_PATH_IDENTITY_OAUTH_TOKEN).append(// 
        fmtParams("client_id", userId)).append(fmtParams("client_secret", secretKey));
        URL url = new URL(current_uri.toString());
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("GET");
        urlConn.setRequestProperty(REQUEST_PROPERTY_ACCEPT, REQUEST_VALUE_APPLICATION_JSON);
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            InputStream inStream = urlConn.getInputStream();
            Reader reader = new InputStreamReader(inStream);
            Gson gson = new Gson();
            LinkedTreeMap js = (LinkedTreeMap) gson.fromJson(reader, Object.class);
            Object ac = js.get("access_token");
            if (ac != null) {
                accessToken = ac.toString();
                LOG.debug("MarketoRestExecutor.getAccessToken GOT token");
            } else {
                LinkedTreeMap err = (LinkedTreeMap) ((ArrayList) js.get(FIELD_ERRORS)).get(0);
                throw new MarketoException(REST, err.get("code").toString(), err.get("message").toString());
            }
        } else {
            throw new MarketoException(REST, responseCode, "Marketo Authentication failed! Please check your " + "setting!");
        }
    } catch (ProtocolException | SocketTimeoutException | SocketException e) {
        LOG.error("AccessToken error: {}.", e.getMessage());
        throw new MarketoException(REST, "Marketo Authentication failed : " + e.getMessage());
    } catch (IOException e) {
        LOG.error("AccessToken error: {}.", e.getMessage());
        throw new MarketoException(REST, "Marketo Authentication failed : " + e.getMessage());
    }
}
Also used : ProtocolException(java.net.ProtocolException) SocketException(java.net.SocketException) InputStreamReader(java.io.InputStreamReader) LinkedTreeMap(com.google.gson.internal.LinkedTreeMap) InputStream(java.io.InputStream) MarketoException(org.talend.components.marketo.runtime.client.type.MarketoException) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) Gson(com.google.gson.Gson) IOException(java.io.IOException) URL(java.net.URL) SocketTimeoutException(java.net.SocketTimeoutException) JsonObject(com.google.gson.JsonObject) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 27 with MarketoException

use of org.talend.components.marketo.runtime.client.type.MarketoException in project components by Talend.

the class MarketoBaseRESTClient method executePostRequest.

public RequestResult executePostRequest(Class<?> resultClass, JsonObject inputJson) throws MarketoException {
    try {
        URL url = new URL(current_uri.toString());
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod(QUERY_METHOD_POST);
        urlConn.setRequestProperty(REQUEST_PROPERTY_CONTENT_TYPE, REQUEST_VALUE_APPLICATION_JSON);
        urlConn.setRequestProperty(REQUEST_PROPERTY_ACCEPT, REQUEST_VALUE_TEXT_JSON);
        urlConn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream());
        wr.write(inputJson.toString());
        wr.flush();
        wr.close();
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            InputStream inStream = urlConn.getInputStream();
            InputStreamReader reader = new InputStreamReader(inStream);
            Gson gson = new Gson();
            // LOG.error("{}", convertStreamToString(inStream));
            return (RequestResult) gson.fromJson(reader, resultClass);
        } else {
            LOG.error("POST request failed: {}", responseCode);
            throw new MarketoException(REST, responseCode, "Request failed! Please check your request setting!");
        }
    } catch (IOException e) {
        LOG.error("GET request failed: {}", e.getMessage());
        throw new MarketoException(REST, e.getMessage());
    }
}
Also used : RequestResult(org.talend.components.marketo.runtime.client.rest.response.RequestResult) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) MarketoException(org.talend.components.marketo.runtime.client.type.MarketoException) Gson(com.google.gson.Gson) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 28 with MarketoException

use of org.talend.components.marketo.runtime.client.type.MarketoException in project components by Talend.

the class MarketoLeadClientTest method testSyncLead.

@Test
public void testSyncLead() throws Exception {
    oprops.afterOutputOperation();
    oprops.beforeMappingInput();
    IndexedRecord record = new Record(MarketoConstants.getRESTOutputSchemaForSyncLead());
    record.put(0, 12345);
    record.put(1, "t@t.com");
    // 
    doThrow(new MarketoException("REST", "error")).when(client).executePostRequest(eq(SyncResult.class), any(JsonObject.class));
    mktoSR = client.syncLead(oprops, record);
    assertFalse(mktoSR.isSuccess());
    assertFalse(mktoSR.getErrorsString().isEmpty());
    // 
    doReturn(new SyncResult()).when(client).executePostRequest(eq(SyncResult.class), any(JsonObject.class));
    mktoSR = client.syncLead(oprops, record);
    assertFalse(mktoSR.isSuccess());
    // 
    SyncResult sr = new SyncResult();
    sr.setSuccess(true);
    List<SyncStatus> ssr = new ArrayList<>();
    SyncStatus ss = new SyncStatus();
    ss.setStatus("created");
    ss.setMarketoGUID("mkto-123456");
    ss.setSeq(0);
    ss.setId(12345);
    ss.setErrorMessage("");
    ssr.add(ss);
    sr.setResult(ssr);
    doReturn(sr).when(client).executePostRequest(eq(SyncResult.class), any(JsonObject.class));
    mktoSR = client.syncLead(oprops, record);
    assertTrue(mktoSR.isSuccess());
    assertTrue(mktoSR.getErrorsString().isEmpty());
}
Also used : IndexedRecord(org.apache.avro.generic.IndexedRecord) MarketoException(org.talend.components.marketo.runtime.client.type.MarketoException) SyncStatus(org.talend.components.marketo.runtime.client.rest.type.SyncStatus) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) Record(org.apache.avro.generic.GenericData.Record) ListRecord(org.talend.components.marketo.runtime.client.rest.type.ListRecord) IndexedRecord(org.apache.avro.generic.IndexedRecord) LeadChangeRecord(org.talend.components.marketo.runtime.client.rest.type.LeadChangeRecord) LeadActivityRecord(org.talend.components.marketo.runtime.client.rest.type.LeadActivityRecord) SyncResult(org.talend.components.marketo.runtime.client.rest.response.SyncResult) MarketoSyncResult(org.talend.components.marketo.runtime.client.type.MarketoSyncResult) Test(org.junit.Test)

Example 29 with MarketoException

use of org.talend.components.marketo.runtime.client.type.MarketoException in project components by Talend.

the class MarketoLeadClientTest method testGetLeadActivity.

@Test
public void testGetLeadActivity() throws Exception {
    iprops.inputOperation.setValue(InputOperation.getLeadActivity);
    iprops.leadKeyTypeREST.setValue(LeadKeyTypeREST.id);
    iprops.leadKeyValues.setValue("12345");
    iprops.includeTypes.type.setValue(Arrays.asList(IncludeExcludeFieldsREST.AddToList.name()));
    iprops.afterInputOperation();
    List<Field> moreFields = new ArrayList<>();
    moreFields.add(new Field("attrName", AvroUtils._string(), "", null));
    moreFields.add(new Field("campaignId", AvroUtils._int(), "", null));
    iprops.schemaInput.schema.setValue(MarketoUtils.newSchema(iprops.schemaInput.schema.getValue(), "test", moreFields));
    iprops.beforeMappingInput();
    // 
    doThrow(new MarketoException("REST", "error")).when(client).executeGetRequest(LeadActivitiesResult.class);
    mktoRR = client.getLeadActivity(iprops, null);
    assertFalse(mktoRR.isSuccess());
    assertFalse(mktoRR.getErrorsString().isEmpty());
    // 
    doReturn(new LeadActivitiesResult()).when(client).executeGetRequest(LeadActivitiesResult.class);
    mktoRR = client.getLeadActivity(iprops, null);
    assertFalse(mktoRR.isSuccess());
    // 
    LeadActivitiesResult lar = new LeadActivitiesResult();
    lar.setSuccess(true);
    List<LeadActivityRecord> lars = new ArrayList<>();
    LeadActivityRecord larecord = new LeadActivityRecord();
    larecord.setId(123456);
    larecord.setMarketoGUID("ABC-123-DEF");
    larecord.setLeadId(12345);
    larecord.setActivityTypeId(1);
    larecord.setActivityTypeValue("Visit Webpage");
    larecord.setPrimaryAttributeValue("changed");
    larecord.setPrimaryAttributeValueId(123);
    larecord.setActivityDate(new Date());
    larecord.setCampaignId(456);
    List<Map<String, Object>> attributes = new ArrayList<>();
    Map<String, Object> attribute = new HashMap<>();
    attribute.put("name", "attrName");
    attribute.put("value", "attrValue");
    attributes.add(attribute);
    larecord.setAttributes(attributes);
    lars.add(larecord);
    lar.setResult(lars);
    doReturn(lar).when(client).executeGetRequest(LeadActivitiesResult.class);
    mktoRR = client.getLeadActivity(iprops, null);
    assertTrue(mktoRR.isSuccess());
    List<IndexedRecord> records = mktoRR.getRecords();
    assertNotNull(records);
    IndexedRecord record = records.get(0);
    assertNotNull(record);
    Schema refSchema = iprops.schemaInput.schema.getValue();
    assertEquals(refSchema, record.getSchema());
    assertEquals(123456, record.get(refSchema.getField("id").pos()));
    assertEquals("ABC-123-DEF", record.get(refSchema.getField("marketoGUID").pos()));
    assertEquals(12345, record.get(refSchema.getField("leadId").pos()));
    assertEquals(1, record.get(refSchema.getField("activityTypeId").pos()));
    assertEquals("Visit Webpage", record.get(refSchema.getField("activityTypeValue").pos()));
    assertEquals(123, record.get(refSchema.getField("primaryAttributeValueId").pos()));
    assertEquals(456, record.get(refSchema.getField("campaignId").pos()));
    assertEquals("changed", record.get(refSchema.getField("primaryAttributeValue").pos()));
    assertTrue(record.get(refSchema.getField("activityDate").pos()) instanceof Long);
    assertEquals("attrValue", record.get(refSchema.getField("attrName").pos()));
}
Also used : LeadActivitiesResult(org.talend.components.marketo.runtime.client.rest.response.LeadActivitiesResult) IndexedRecord(org.apache.avro.generic.IndexedRecord) HashMap(java.util.HashMap) MarketoException(org.talend.components.marketo.runtime.client.type.MarketoException) Schema(org.apache.avro.Schema) ArrayList(java.util.ArrayList) Matchers.anyString(org.mockito.Matchers.anyString) Date(java.util.Date) Field(org.apache.avro.Schema.Field) JsonObject(com.google.gson.JsonObject) LeadActivityRecord(org.talend.components.marketo.runtime.client.rest.type.LeadActivityRecord) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.Test)

Example 30 with MarketoException

use of org.talend.components.marketo.runtime.client.type.MarketoException in project components by Talend.

the class MarketoLeadClientTest method testDeleteLeads.

@Test
public void testDeleteLeads() throws Exception {
    IndexedRecord record = new Record(MarketoConstants.getDeleteLeadsSchema());
    record.put(0, 12345);
    // 
    doThrow(new MarketoException("REST", "error")).when(client).executePostRequest(eq(SyncResult.class), any(JsonObject.class));
    mktoSR = client.deleteLeads(new Integer[] { 12345 });
    mktoSR = client.deleteLeads(Arrays.asList(record));
    assertFalse(mktoSR.isSuccess());
    assertFalse(mktoSR.getErrorsString().isEmpty());
    // 
    doReturn(new SyncResult()).when(client).executePostRequest(eq(SyncResult.class), any(JsonObject.class));
    mktoSR = client.deleteLeads(new Integer[] { 12345 });
    assertFalse(mktoSR.isSuccess());
    // 
    SyncResult sr = new SyncResult();
    sr.setSuccess(true);
    List<SyncStatus> ssr = new ArrayList<>();
    SyncStatus ss = new SyncStatus();
    ss.setStatus("created");
    ss.setMarketoGUID("mkto-123456");
    ss.setSeq(0);
    ss.setId(12345);
    ss.setErrorMessage("");
    ssr.add(ss);
    sr.setResult(ssr);
    doReturn(sr).when(client).executePostRequest(eq(SyncResult.class), any(JsonObject.class));
    mktoSR = client.deleteLeads(new Integer[] { 12345 });
    assertTrue(mktoSR.isSuccess());
    assertTrue(mktoSR.getErrorsString().isEmpty());
}
Also used : IndexedRecord(org.apache.avro.generic.IndexedRecord) MarketoException(org.talend.components.marketo.runtime.client.type.MarketoException) SyncStatus(org.talend.components.marketo.runtime.client.rest.type.SyncStatus) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) Record(org.apache.avro.generic.GenericData.Record) ListRecord(org.talend.components.marketo.runtime.client.rest.type.ListRecord) IndexedRecord(org.apache.avro.generic.IndexedRecord) LeadChangeRecord(org.talend.components.marketo.runtime.client.rest.type.LeadChangeRecord) LeadActivityRecord(org.talend.components.marketo.runtime.client.rest.type.LeadActivityRecord) SyncResult(org.talend.components.marketo.runtime.client.rest.response.SyncResult) MarketoSyncResult(org.talend.components.marketo.runtime.client.type.MarketoSyncResult) Test(org.junit.Test)

Aggregations

MarketoException (org.talend.components.marketo.runtime.client.type.MarketoException)37 Test (org.junit.Test)18 ArrayList (java.util.ArrayList)12 JsonObject (com.google.gson.JsonObject)11 MarketoRecordResult (org.talend.components.marketo.runtime.client.type.MarketoRecordResult)10 URL (java.net.URL)9 IndexedRecord (org.apache.avro.generic.IndexedRecord)9 IOException (java.io.IOException)8 InputStream (java.io.InputStream)8 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)8 InputStreamReader (java.io.InputStreamReader)7 Schema (org.apache.avro.Schema)7 Field (org.apache.avro.Schema.Field)7 Gson (com.google.gson.Gson)6 SyncResult (org.talend.components.marketo.runtime.client.rest.response.SyncResult)6 Record (org.apache.avro.generic.GenericData.Record)5 MarketoError (org.talend.components.marketo.runtime.client.type.MarketoError)5 OutputStreamWriter (java.io.OutputStreamWriter)4 LinkedTreeMap (com.google.gson.internal.LinkedTreeMap)3 Reader (java.io.Reader)3