Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.apigee.smartdocs.config.rest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.simple.JSONValue;
import org.yaml.snakeyaml.Yaml;
import com.apigee.smartdocs.config.utils.ServerProfile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpMethods;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.apache.ApacheHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.client.util.Key;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.internal.LinkedTreeMap;
public class PortalRestUtil {
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
static final HttpTransport APACHE_HTTP_TRANSPORT = new ApacheHttpTransport();
static final JsonFactory JSON_FACTORY = new JacksonFactory();
static String versionRevision;
static Logger logger = LogManager.getLogger(PortalRestUtil.class);
static String accessToken = null;
static HttpRequestFactory REQUEST_FACTORY = HTTP_TRANSPORT
.createRequestFactory(new HttpRequestInitializer() {
// @Override
public void initialize(HttpRequest request) {
request.setParser(JSON_FACTORY.createJsonObjectParser());
XTrustProvider.install();
FakeHostnameVerifier _hostnameVerifier = new FakeHostnameVerifier();
// Install the all-trusting host name verifier:
HttpsURLConnection.setDefaultHostnameVerifier(_hostnameVerifier);
}
});
static HttpRequestFactory APACHE_REQUEST_FACTORY = APACHE_HTTP_TRANSPORT
.createRequestFactory(new HttpRequestInitializer() {
// @Override
public void initialize(HttpRequest request) {
request.setParser(JSON_FACTORY.createJsonObjectParser());
XTrustProvider.install();
FakeHostnameVerifier _hostnameVerifier = new FakeHostnameVerifier();
// Install the all-trusting host name verifier:
HttpsURLConnection.setDefaultHostnameVerifier(_hostnameVerifier);
}
});
// Header values to ensure headers are set and then stored.
public static Boolean headersSet = false;
public static HttpHeaders headers = null;
// Class to handle our authentication response.
public static class AuthObject {
@Key
public String token;
public String sessid;
public String session_name;
}
public static class SpecObject {
public LinkedTreeMap info;
public String getName(String portalModelNameConfig) {
if(portalModelNameConfig == null) {
return info.get("title").toString().replace(" ", "-");
} else {
return getConfigModelName(portalModelNameConfig);
}
}
private String getConfigModelName(String portalModelNameConfig) {
//default return
String returnString = getName(null);
if(portalModelNameConfig == null) {
return returnString;
}
//Generate Model Name From Config
ArrayList al = new ArrayList();
String[] nameParts = portalModelNameConfig.split("\\^");
LinkedTreeMap jo = info;
for (String namePart : nameParts) {
//Reset head of tree to info
jo = info;
//Split each config name into model information
String[] namePartPaths = namePart.split("\\|");
for (String namePartPath : namePartPaths) {
// Only traverse down if the key exists.
if (jo.containsKey(namePartPath)) {
Object o = jo.get(namePartPath);
// If we still need to go deeper, we have a tree.
if (o instanceof LinkedTreeMap) {
jo = (LinkedTreeMap) o;
} else {
// Otherwise, store the value in our ArrayList
al.add(o.toString().replace(".", "-").replace(" ","-"));
}
}
}
}
if(al.isEmpty()) {
return returnString;
}
returnString = "";
Iterator it = al.iterator();
while (it.hasNext()) {
String namePart = (String) it.next();
returnString += namePart;
//Separate fields with dash
if(it.hasNext()) {
returnString += "-";
}
}
//Clean the return string to only include Alphanumeric characters and the dash character
returnString = returnString.replaceAll("[^A-Za-z0-9-]","");
//set Max length to be 255
if(returnString.length() > 255) {
returnString = returnString.substring(0,255);
}
logger.debug("API Model Name: " + returnString);
return returnString;
}
public String getTitle() {
return info.get("title").toString();
}
public String getDescription() {
if (info.get("description") != null) {
return info.get("description").toString();
}
return "";
}
@Override
public String toString() {
return "(SpecObject) Name: " + getName(null) + "; Title: " + getTitle();
}
}
public static class APIDocResponseObject {
public JSONAPI jsonapi;
public List data;
public Object links;
}
public static class APIDocObject {
public JSONAPI jsonapi;
public Data data;
public Object links;
}
public static class ImageDocObject {
public JSONAPI jsonapi;
public Data data;
public Object links;
}
public static class APIErrorObject {
public JSONAPI jsonapi;
public List errors;
}
public static class JSONAPI {
public String version;
public Object meta;
}
public static class Error{
public String title;
public String status;
public String detail;
}
public static class Data {
public String type;
public String id;
public Attributes attributes;
public Relationships relationships;
public Object links;
}
public static class Attributes {
public boolean status;
public String title;
public String name;
public Body body;
public String field_apidoc_spec_file_source;
public Object relationships;
public FileLink file_link;
public Object links;
}
public static class Body{
public String value;
public String format;
}
public static class Relationships{
public Relationships_Spec field_apidoc_spec;
public Relationships_Spec field_image;
}
public static class Relationships_Data{
public String type;
public String id;
}
public static class Relationships_Spec{
public Relationships_Data data;
}
public static class FileLink{
public String uri;
}
// Get headers that have been set.
public static HttpHeaders getHeaders() {
return headers;
}
// Store/update headers.
public static HttpHeaders setHeaders(HttpHeaders tempHeaders) {
headers = tempHeaders;
return headers;
}
/**
* Authenticate against the Developer portal and set necessary headers to
* facilitate additional transactions.
*/
public static HttpResponse authenticate(ServerProfile profile) throws IOException {
HttpResponse response = null;
if (headersSet == false) {
String payload = "{\"username\": \"" + profile.getPortalUserName()
+ "\", \"password\":\"" + profile.getPortalPassword() + "\"}";
ByteArrayContent content = new ByteArrayContent("application/json",
payload.getBytes());
HttpRequest restRequest = REQUEST_FACTORY
.buildPostRequest(new GenericUrl(
profile.getPortalURL() + "/" + profile.getPortalPath()
+ "/user/login.json"), content);
restRequest.setReadTimeout(0);
try {
// Call execute directly since we don't have headers yet.
response = restRequest.execute();
InputStream source = response.getContent(); //Get the data in the entity
Reader reader = new InputStreamReader(source);
Gson gson = new Gson();
AuthObject auth = gson.fromJson(reader, AuthObject.class);
headersSet = true;
HttpHeaders tempHeaders = new HttpHeaders();
tempHeaders.setCookie(auth.session_name + "=" + auth.sessid);
tempHeaders.set("X-CSRF-Token", auth.token);
setHeaders(tempHeaders);
} catch (HttpResponseException e) {
logger.error(e.getMessage());
// Throw an error as there is no point in continuing.
throw e;
}
}
return response;
}
/**
* Run Cron
*/
public static void runCron(ServerProfile profile) throws IOException {
try {
// First authenticate.
authenticate(profile);
HttpRequest restRequest = REQUEST_FACTORY
.buildGetRequest(new GenericUrl(profile.getPortalURL() + "/cron.php?cron_key="+ profile.getPortalCronKey()));
restRequest.setReadTimeout(0);
logger.info("Running Cron");
PortalRestUtil.executeRequest(restRequest);
} catch (HttpResponseException e) {
throw e;
}
}
/**
* Helper function to build the body for API Doc creations and updates.
*/
private static ByteArrayContent constructAPIDocRequestBody(ServerProfile profile, SpecObject spec, String uuid, String docId, String imageId, boolean isUpdate) throws IOException {
boolean hasImage = false;
File imageFile = null;
Gson gson = new Gson();
JsonObject body = new JsonObject();
if (spec.getDescription() != null) {
body.addProperty("value", StringEscapeUtils.escapeJava(spec.getDescription()));
}
body.addProperty("format", profile.getPortalAPIDocFormat());
JsonObject attributes = new JsonObject();
attributes.addProperty("status", true);
attributes.addProperty("title", spec.getTitle());
attributes.add("body", body);
attributes.addProperty("field_apidoc_spec_file_source", "file");
JsonObject relationships = new JsonObject();
//config
if(profile.getConfigFile()!=null && !profile.getConfigFile().equalsIgnoreCase("")) {
FileContent tempFileContent = new FileContent("application/json", new File(profile.getConfigFile()).getAbsoluteFile());
Reader reader = new InputStreamReader(tempFileContent.getInputStream());
Map result = new ObjectMapper().readValue(reader, HashMap.class);
if(result!=null && result.size()>0) {
//For Custom Fields
Map fieldsMap = (Map) result.get("fields");
if(fieldsMap!=null && fieldsMap.size()>0) {
for (String key : fieldsMap.keySet()) {
if(fieldsMap.get(key) instanceof List){
attributes.add(key, gson.toJsonTree(fieldsMap.get(key)));
}
//no need to add to attributes for "field_image"
else if (key!=null && key.equals("field_image")){
hasImage = true;
imageFile = new File(profile.getPortalDirectory()+"/"+(String)fieldsMap.get(key));
}
else
attributes.addProperty(key, (String)fieldsMap.get(key));
}
}
//For Custom taxonomy_terms
List