org.apache.sling.commons.json.JSONException Java Examples

The following examples show how to use org.apache.sling.commons.json.JSONException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HealthCheckExecutorServlet.java    From aem-healthcheck with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a JSON representation of the given HealthCheckExecutionResult list.
 * @param executionResults
 * @param resultJson
 * @return
 * @throws JSONException
 */
private static JSONObject generateResponse(List<HealthCheckExecutionResult> executionResults,
                                            JSONObject resultJson) throws JSONException {
    JSONArray resultsJsonArr = new JSONArray();
    resultJson.put("results", resultsJsonArr);

    for (HealthCheckExecutionResult healthCheckResult : executionResults) {
        JSONObject result = new JSONObject();
        result.put("name", healthCheckResult.getHealthCheckMetadata() != null ?
                           healthCheckResult.getHealthCheckMetadata().getName() : "");
        result.put("status", healthCheckResult.getHealthCheckResult().getStatus());
        result.put("timeMs", healthCheckResult.getElapsedTimeInMs());
        resultsJsonArr.put(result);
    }
    return resultJson;
}
 
Example #2
Source File: StringUtil.java    From aem-solr-search with Apache License 2.0 6 votes vote down vote up
/**
 * Converts an array into a JSON array.
 *
 * @param array
 * @return A compatible JSON array on success, and an empty JSON array otherwise.
 */
public static String arrayToJson(String[] array) {

    if (null == array) {return EMPTY_JSON_ARRAY;}

    StringWriter stringWriter = new StringWriter();
    JSONWriter jsonWriter = new JSONWriter(stringWriter);

    try {
        jsonWriter.array();
        for (String item: array) {
            jsonWriter.value(item);
        }
        jsonWriter.endArray();

    } catch (JSONException e) {
        LOG.error("Can't convert array '{}' to JSON", array, e);
        return EMPTY_JSON_ARRAY;
    }

    return stringWriter.toString();
}
 
Example #3
Source File: SolrSchemaIndexedFieldsServlet.java    From aem-solr-search with Apache License 2.0 6 votes vote down vote up
@Override
public void getJSONWriter(PrintWriter writer)  {

    JSONWriter jsonWriter = new JSONWriter(writer);

    try {
        jsonWriter.array();
        for(String field: solrConfigurationService.getIndexedFieldsFromLuke(getSolrCore())) {
            jsonWriter.object();
            jsonWriter.key("text");
            jsonWriter.value(field);
            jsonWriter.key("value");
            jsonWriter.value(field);
            jsonWriter.endObject();
        }
        jsonWriter.endArray();
    } catch (JSONException e) {
        LOG.error("Error creating indexed fields JSON", e);
    }
}
 
Example #4
Source File: SolrSchemaStoredFieldsServlet.java    From aem-solr-search with Apache License 2.0 6 votes vote down vote up
@Override
public void getJSONWriter(PrintWriter writer) {

    JSONWriter jsonWriter = new JSONWriter(writer);

    try {
        jsonWriter.array();
        for(String field: solrConfigurationService.getStoredFields(getSolrCore())) {
            jsonWriter.object();
            jsonWriter.key("text");
            jsonWriter.value(field);
            jsonWriter.key("value");
            jsonWriter.value(field);
            jsonWriter.endObject();
        }
        jsonWriter.endArray();
    } catch (JSONException e) {
        LOG.error("Error creating stored fields JSON", e);
    }
}
 
Example #5
Source File: SolrCoreServlet.java    From aem-solr-search with Apache License 2.0 6 votes vote down vote up
@Override
public void getJSONWriter(PrintWriter writer)  {

    JSONWriter jsonWriter = new JSONWriter(writer);

    try {
        jsonWriter.array();
        for(String core: solrConfigurationService.getCores()) {
            jsonWriter.object();
            jsonWriter.key("text");
            jsonWriter.value(core);
            jsonWriter.key("value");
            jsonWriter.value(core);
            jsonWriter.endObject();
        }
        jsonWriter.endArray();

    } catch (JSONException e) {
        LOG.error("Error creating solr cores JSON", e);
    }
}
 
Example #6
Source File: AdminServlet.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Send the JSON response.
 *
 * @param writer The PrintWriter.
 * @param header The header to send.
 * @param message The message to send.
 * @param data The data, probably JSON string
 */
protected void sendResponse(final PrintWriter writer, final String header, final String message, final String data) {
    try {
        JSONObject json = new JSONObject();

        json.put("header", header);
        json.put("message", message);

        if (StringUtils.isNotBlank(data)) {
            json.put("data", data);
        }

        writer.write(json.toString());
    } catch (JSONException e) {
        LOGGER.error("Could not write JSON", e);

        if (StringUtils.isNotBlank(data)) {
            writer.write(String.format("{\"header\" : \"%s\", \"message\" : \"%s\", \"data\" :  \"%s\"}", header, message, data));
        } else {
            writer.write(String.format("{\"header\" : \"%s\", \"message\" : \"%s\"}", header, message));
        }
    }
}
 
Example #7
Source File: JsonMessageFormatter.java    From otroslogviewer with Apache License 2.0 6 votes vote down vote up
@Override
public String format(String message) {
  final ArrayList<SubText> jsonFragments = jsonFinder.findJsonFragments(message);
  StringBuilder sb = new StringBuilder();
  int lastEnd = 0;
  for (SubText jsonFragment : jsonFragments) {
    sb.append(message.substring(lastEnd, jsonFragment.getStart()));
    final String group = jsonFragment.subString(message);
    String toAppend = group;
    try {
      JSONObject o = new JSONObject(group);
      final String jsonFormatted = o.toString(2);
      toAppend = jsonFormatted;
    } catch (JSONException e) {
      LOGGER.debug("There is no need to format {}", group);
    }
    if (!sb.toString().endsWith("\n")) {
      sb.append("\n");
    }
    sb.append(toAppend).append("\n");
    lastEnd = jsonFragment.getEnd();
  }
  sb.append(message.substring(lastEnd));
  return sb.toString().trim();
}
 
Example #8
Source File: JsonExtractor.java    From otroslogviewer with Apache License 2.0 6 votes vote down vote up
public List<String> extractFieldValues(String json, String field) {
  final List<String> lines = Arrays.stream(json.split("\n")).map(String::trim).collect(Collectors.toList());
  StringBuilder buffer = new StringBuilder();
  List<String> result = new ArrayList<>();
  for (String line : lines) {
    buffer.append(line);
    if (isJson(buffer.toString())) {
      try {
        final JSONObject jsonObject = new JSONObject(buffer.toString());
        buffer.setLength(0);
        Optional.ofNullable(toMap(jsonObject).get(field))
          .ifPresent(result::add);
      } catch (JSONException ignore) {
        //;
      }
    }
  }
  return result;
}
 
Example #9
Source File: MockURLStreamHandler.java    From development with Apache License 2.0 6 votes vote down vote up
private static String respStacks() {
    try {
        JSONObject response = new JSONObject();
        JSONObject state = new JSONObject();
        state.put("label", "OK");
        state.put("id", "OK");
        response.put("state", state);
        response.put("id", "1234");
        response.put("stack", "1234");
        response.put("name", "Appliance1");
        response.put("projectUri",
                "http://test.com/cloud/api/projects/54346");
        JSONObject stack = new JSONObject();
        stack.put("id", "idValue");
        response.put("stack", stack);
        return response.toString();
    } catch (JSONException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #10
Source File: AbstractStackRequest.java    From development with Apache License 2.0 6 votes vote down vote up
protected void put(String key, Object value) {
    if (key == null) {
        throw new IllegalArgumentException(
                "JSON object key must not be null!");
    }
    if (!(value instanceof String) && !(value instanceof JSONObject)) {
        throw new IllegalArgumentException("Object type "
                + (value == null ? "NULL" : value.getClass().getName())
                + " not allowed as JSON value.");
    }
    try {
        request.put(key, value);
    } catch (JSONException e) {
        // this can basically not happen
        throw new IllegalArgumentException(e.getMessage());
    }
}
 
Example #11
Source File: MockURLStreamHandler.java    From development with Apache License 2.0 5 votes vote down vote up
public static String respServerDetail(String serverName, String serverId,
        ServerStatus status, String tenant_id) {
    try {
        JSONObject response = new JSONObject();
        JSONObject server = new JSONObject();
        response.put("server", server);
        server.put("name", serverName);
        server.put("id", serverId);
        server.put("status", status);
        server.put("tenant_id", tenant_id);
        server.put("accessIPv4", "192.0.2.0");
        JSONObject flavor = new JSONObject();
        flavor.put("id", 1);
        server.put("flavor", flavor);
        JSONObject addresses = new JSONObject();
        JSONArray networkDetail = new JSONArray();
        JSONObject fixedNetwork = new JSONObject();
        JSONObject floatingNetwork = new JSONObject();
        fixedNetwork.put("OS-EXT-IPS-MAC:mac_addr", "fa:16:3e:e5:b7:f8");
        fixedNetwork.put("version", "4");
        fixedNetwork.put("addr", "192.168.0.4");
        fixedNetwork.put("OS-EXT-IPS:type", "fixed");
        floatingNetwork.put("OS-EXT-IPS-MAC:mac_addr", "fa:16:3e:e5:b7:f8");
        floatingNetwork.put("version", "4");
        floatingNetwork.put("addr", "133.162.161.216");
        floatingNetwork.put("OS-EXT-IPS:type", "floating");
        networkDetail.put(fixedNetwork);
        networkDetail.put(floatingNetwork);
        addresses.put(serverName + "-network", networkDetail);
        server.put("addresses", addresses);

        return response.toString();
    } catch (JSONException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #12
Source File: MockURLStreamHandler.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * @param string
 * @return
 */
public static String respFlavor(int id, String flavorName) {
    try {
        JSONObject response = new JSONObject();
        JSONObject flavor = new JSONObject();
        flavor.put("id", id);
        flavor.put("name", flavorName);

        response.put("flavor", flavor);
        return response.toString();
    } catch (JSONException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #13
Source File: RcpServlet.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
private static void write(JSONWriter w, RcpTask rcpTask) throws JSONException {
    w.object();
    w.key(RcpServlet.PARAM_ID).value(rcpTask.getId());
    w.key(RcpServlet.PARAM_SRC).value(rcpTask.getSource().toString());
    w.key(RcpServlet.PARAM_DST).value(rcpTask.getDestination());
    w.key(RcpServlet.PARAM_RECURSIVE).value(rcpTask.isRecursive());
    w.key(RcpServlet.PARAM_BATCHSIZE).value(rcpTask.getRcp().getBatchSize());
    w.key(RcpServlet.PARAM_UPDATE).value(rcpTask.getRcp().isUpdate());
    w.key(RcpServlet.PARAM_ONLY_NEWER).value(rcpTask.getRcp().isOnlyNewer());
    w.key(RcpServlet.PARAM_NO_ORDERING).value(rcpTask.getRcp().isNoOrdering());
    w.key(RcpServlet.PARAM_THROTTLE).value(rcpTask.getRcp().getThrottle());
    w.key(RcpServlet.PARAM_RESUME_FROM).value(rcpTask.getRcp().getResumeFrom());
    if (rcpTask.getExcludes().size() > 0) {
        w.key(RcpServlet.PARAM_EXCLUDES).array();
        for (String exclude: rcpTask.getExcludes()) {
            w.value(exclude);
        }
        w.endArray();
    }
    w.key("status").object();
    w.key(RcpServlet.PARAM_STATE).value(rcpTask.getResult().getState().name());
    w.key("currentPath").value(rcpTask.getRcp().getCurrentPath());
    w.key("lastSavedPath").value(rcpTask.getRcp().getLastKnownGood());
    w.key("totalNodes").value(rcpTask.getRcp().getTotalNodes());
    w.key("totalSize").value(rcpTask.getRcp().getTotalSize());
    w.key("currentSize").value(rcpTask.getRcp().getCurrentSize());
    w.key("currentNodes").value(rcpTask.getRcp().getCurrentNumNodes());
    w.key("error").value(rcpTask.getResult().getThrowable() == null ? "" : rcpTask.getResult().getThrowable().toString());
    w.endObject();
    w.endObject();
}
 
Example #14
Source File: EmailServlet.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Send the JSON response.
 *
 * @param writer The PrintWriter.
 * @param status The status such as 200 or 500.
 * @param message The message to send.
 */
private void sendResponse(PrintWriter writer, int status, String message) {
    try {
        writer.write(new JSONObject()
            .put("status", status)
            .put("message", message)
            .toString());
    } catch (JSONException e) {
        LOGGER.error("Could not write JSON", e);
    }
}
 
Example #15
Source File: MockURLStreamHandler.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * @return
 */
private static String repServers(List<String> serverNames) {
    try {
        JSONObject response = new JSONObject();
        JSONArray servers = new JSONArray();
        for (int i = 0; i < serverNames.size(); i++) {
            JSONObject server = new JSONObject();
            JSONArray links = new JSONArray();
            JSONObject linkSelf = new JSONObject();
            JSONObject linkBookmark = new JSONObject();
            String instanceId = Integer.toString(i) + "-Instance-"
                    + serverNames.get(i);
            server.put("id", instanceId);
            linkSelf.put("href",
                    "http://novaendpoint/v2/servers/" + instanceId);
            linkSelf.put("rel", "self");
            links.put(linkSelf);
            linkBookmark.put("href",
                    "http://novaendpoint/servers/" + instanceId);
            linkBookmark.put("rel", "self");
            links.put(linkBookmark);
            server.put("links", links);
            server.put("name", serverNames.get(i));
            servers.put(server);
        }
        response.put("servers", servers);
        return response.toString();
    } catch (JSONException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #16
Source File: BackupServlet.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Get a JSONObject from the JCR package configured for the Angular model.
 *
 * @param jcrPackage The JCR Package to retrieve data from.
 * @return the JSON Object configured for the Angular model.
 * @throws JSONException
 * @throws RepositoryException
 * @throws IOException
 */
private JSONObject getJsonFromJcrPackage(final JcrPackage jcrPackage)
        throws JSONException, RepositoryException, IOException {

    final JSONObject json = new JSONObject();
    final SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);

    json.put(JSON_SIZE_PROPERTY, getSize(jcrPackage.getPackage().getSize()));
    json.put(JSON_DATE_PROPERTY, dateFormat.format(jcrPackage.getPackage().getCreated().getTime()));
    json.put(JSON_NAME_PROPERTY, jcrPackage.getDefinition().getId().getName());
    json.put(JSON_PATH_PROPERTY, jcrPackage.getNode().getPath());
    json.put(JSON_ID_PROPERTY, jcrPackage.getDefinition().getId().toString());

    return json;
}
 
Example #17
Source File: BackupServlet.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Return all packages on a GET request in order of newest to oldest.
 */
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    final PrintWriter writer = response.getWriter();

    response.setCharacterEncoding(CharEncoding.UTF_8);
    response.setContentType("application/json");

    List<JcrPackage> packages = packageService.getPackageList(request);

    try {
        JSONArray jsonArray = new JSONArray();

        for (JcrPackage jcrPackage : packages) {
            final JSONObject json = getJsonFromJcrPackage(jcrPackage);

            jsonArray.put(json);
        }

        response.setStatus(SlingHttpServletResponse.SC_OK);
        writer.write(jsonArray.toString());
    } catch (JSONException | RepositoryException e) {
        LOGGER.error("Could not write JSON", e);
        response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
 
Example #18
Source File: CommentServlet.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Return all comments on a GET request in order of newest to oldest.
 */
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    final PrintWriter writer = response.getWriter();

    response.setCharacterEncoding(CharEncoding.UTF_8);
    response.setContentType("application/json");

    List<Resource> comments = commentService.getComments(request);

    try {
        JSONArray jsonArray = new JSONArray();

        for (Resource comment : comments) {
            final JSONObject json = new JSONObject();
            final ValueMap properties = comment.getValueMap();
            final Resource post = commentService.getParentPost(comment);

            json.put(PublickConstants.COMMENT_PROPERTY_COMMENT,
                    properties.get(PublickConstants.COMMENT_PROPERTY_COMMENT, String.class));
            json.put(JSON_ID, properties.get(JcrConstants.JCR_UUID, String.class));
            json.put(JSON_EDITED, properties.get(PublickConstants.COMMENT_PROPERTY_EDITED, false));
            json.put(JSON_REPLIES, commentService.numberOfReplies(comment));
            json.put(JSON_SPAM, properties.get(PublickConstants.COMMENT_PROPERTY_SPAM, false));
            json.put(JSON_POST, new JSONObject()
                    .put(JSON_POST_TEXT, post.getValueMap().get(PublickConstants.COMMENT_PROPERTY_TITLE, String.class))
                    .put(JSON_POST_LINK, linkRewriter.rewriteLink(post.getPath(), request.getServerName())));

            jsonArray.put(json);
        }

        response.setStatus(SlingHttpServletResponse.SC_OK);
        writer.write(jsonArray.toString());
    } catch (JSONException e) {
        LOGGER.error("Could not write JSON", e);
        response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
 
Example #19
Source File: JsonPatternParserEditor.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
private Map<String, String> toMap(StringBuilder sb) {
  final String text = sb.toString();
  try {
    final JSONObject jsonObject = new JSONObject(text);
    return JsonExtractor.toMap(jsonObject);
  } catch (JSONException e) {
    return new HashMap<>(0);
  }
}
 
Example #20
Source File: SessionDeserializer.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<List<Session>> deserialize(String data) {
  final ArrayList<Session> sessions = new ArrayList<>();
  try {
    final JSONArray array = new JSONArray(data);
    for (int i = 0; i < array.length(); i++) {
      final JSONObject jsonObject = array.getJSONObject(i);
      String name = jsonObject.getString("name");
      final ArrayList<FileToOpen> fileToOpens = new ArrayList<>();
      final JSONArray filesArray = jsonObject.optJSONArray("filesToOpen");
      if (filesArray != null){
        for (int j = 0; j < filesArray.length(); j++) {
          final JSONObject filesToOpen = filesArray.getJSONObject(j);
          String uri = filesToOpen.getString("uri");
          Level level = Level.parse(filesToOpen.getString("level"));
          OpenMode openMode = OpenMode.valueOf(filesToOpen.getString("openMode"));
          String logImporter = filesToOpen.optString("logImporter", null);
          fileToOpens.add(new FileToOpen(uri, openMode, level, Optional.ofNullable(logImporter)));
        }
      }
      sessions.add(new Session(name, fileToOpens));
    }
  } catch (JSONException e) {
    LOGGER.error("Can't deserialize sessions: ", e);
    Optional.empty();
  }
  LOGGER.info("Returning deserialized sessions: " + sessions.size());
  return Optional.of(sessions);
}
 
Example #21
Source File: JsonExtractor.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
private static Map<String, String> toMap(JSONObject j, Map<String, String> map, String prefix) throws JSONException {
  final Iterator<String> keys = j.keys();
  while (keys.hasNext()) {
    final String key = keys.next();
    final Object o = j.get(key);
    if (o instanceof JSONObject) {
      JSONObject jso = (JSONObject) o;
      toMap(jso, map, prefix + key + VALUES_SEPARATOR);
    } else {
      map.put(prefix + key, j.getString(key));
    }
  }
  return map;
}
 
Example #22
Source File: JsonExtractor.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
private boolean isJson(String s) {
  try {
    Validator.validate(s);
    return true;
  } catch (JSONException e) {
    return false;
  }
}
 
Example #23
Source File: MockURLStreamHandler.java    From development with Apache License 2.0 5 votes vote down vote up
public static String respStacksInstanceName(StackStatus status,
        boolean withStatusReason, String... stackStatusReason) {
    String reason;
    if (stackStatusReason == null || stackStatusReason.length == 0) {
        reason = "SSR";
    } else {
        reason = Arrays.toString(stackStatusReason);
    }
    try {
        JSONObject response = new JSONObject();
        JSONObject stack = new JSONObject();
        response.put("stack", stack);
        stack.put("stack_name", "SN");
        stack.put("id", "ID");
        stack.put("stack_status",
                status == null ? "bullshit" : status.name());
        if (withStatusReason) {
            stack.put("stack_status_reason", reason);
        }
        JSONArray outputs = new JSONArray();
        JSONObject output = new JSONObject();
        output.put("output_key", "OK");
        output.put("output_value", "OV");
        outputs.put(output);
        stack.put("outputs", outputs);
        return response.toString();
    } catch (JSONException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #24
Source File: JsonExtractor.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to parse log event in json form using selected date format
 *
 * @param s          log fragment
 * @param dateFormat instance of DateFormat
 * @return Optional of LogData if log event can be extracted, empty if not.
 */
protected Optional<LogData> parseJsonLog(String s, DateFormat dateFormat) {
  try {
    Validator.validate(s);
    final JSONObject jsonObject = new JSONObject(s);
    final Map<String, String> map = toMap(jsonObject);
    return mapToLogData(map, dateFormat);
  } catch (JSONException e) {
    return Optional.empty();

  }
}
 
Example #25
Source File: MockURLStreamHandler.java    From development with Apache License 2.0 5 votes vote down vote up
public static String respStacksResources(List<String> serverNames,
        String resourceType) {
    try {
        JSONObject response = new JSONObject();
        JSONArray resources = new JSONArray();
        response.put("resources", resources);

        JSONObject volume = new JSONObject();
        volume.put("resource_name", "sys-vol");
        volume.put("physical_resource_id", "12345");
        volume.put("resource_type", "OS::Cinder::Volume");
        resources.put(volume);

        for (int i = 0; i < serverNames.size(); i++) {
            JSONObject server = new JSONObject();
            server.put("resource_name", serverNames.get(i));
            server.put("physical_resource_id", Integer.toString(i)
                    + "-Instance-" + serverNames.get(i));
            server.put("resource_type", resourceType);
            resources.put(server);
        }

        return response.toString();
    } catch (JSONException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #26
Source File: MockURLStreamHandler.java    From development with Apache License 2.0 5 votes vote down vote up
public static String respServer(String serverName, String serverId) {
    try {
        JSONObject response = new JSONObject();
        JSONObject server = new JSONObject();
        response.put("server", server);
        server.put("name", serverName);
        server.put("id", serverId);

        return response.toString();
    } catch (JSONException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #27
Source File: MockURLStreamHandler.java    From development with Apache License 2.0 4 votes vote down vote up
public static String respTokens(boolean addPublicURL,
        boolean addPublicURLNova, boolean https) {
    try {
        JSONObject response = new JSONObject();
        JSONObject token = new JSONObject();
        JSONArray serviceCatalog = new JSONArray();

        JSONObject endpointsHeat = new JSONObject();
        JSONArray endpointsListHeat = new JSONArray();
        String httpMethod = https == true ? "https://" : "http://";
        endpointsHeat.put("endpoints", endpointsListHeat);
        if (addPublicURL) {
            JSONObject publicUrl = new JSONObject();
            publicUrl.put("name", KeystoneClient.TYPE_HEAT);
            publicUrl.put("url", httpMethod + "heatendpoint/");
            publicUrl.put("interface", "public");
            endpointsListHeat.put(publicUrl);
        }

        endpointsHeat.put("type", KeystoneClient.TYPE_HEAT);
        serviceCatalog.put(endpointsHeat);

        JSONObject endpointsNova = new JSONObject();

        JSONArray endpointsListNova = new JSONArray();
        endpointsNova.put("endpoints", endpointsListNova);
        if (addPublicURLNova) {
            JSONObject publicUrlNova = new JSONObject();
            publicUrlNova.put("name", KeystoneClient.TYPE_NOVA);
            publicUrlNova.put("url", httpMethod + "novaendpoint/");
            endpointsListNova.put(publicUrlNova);
        }

        endpointsNova.put("type", KeystoneClient.TYPE_NOVA);
        serviceCatalog.put(endpointsNova);

        token.put("id", "authId");
        token.put("catalog", serviceCatalog);

        response.put("token", token);

        return response.toString();
    } catch (JSONException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #28
Source File: Log4j2JsonLogParser.java    From otroslogviewer with Apache License 2.0 4 votes vote down vote up
@Override
public LogData parse(String line, ParsingContext parsingContext) {

  final StringBuilder unmatchedLog = parsingContext.getUnmatchedLog();
  if (unmatchedLog.length() == 0 && !(line.matches("[,\\s\u0000]*\\{.*"))) {
    return null;
  }

  if (unmatchedLog.length() == 0 && (line.matches("[,\u0000].*"))) {
    unmatchedLog.append(line.substring(1)).append("\n");
  } else {
    unmatchedLog.append(line).append("\n");
  }

  String s = unmatchedLog.toString();
  try {
    Validator.validate(s);
    final Gson gson = new GsonBuilder()

      .registerTypeAdapter(new TypeToken<Thrown>() {
      }.getType(), new ThrownDeserializer())
      .create();

    final Log4j2JsonEvent log4j2JsonEvent = gson.fromJson(s, Log4j2JsonEvent.class);

    unmatchedLog.setLength(0);

    final Optional<Source> source = Optional.ofNullable(log4j2JsonEvent.getSource());

    final Optional<String> exception = Optional
      .ofNullable(log4j2JsonEvent.getThrown())
      .map(Thrown::getStacktrace);

    final long timestamp = Optional.ofNullable(log4j2JsonEvent.getInstant())
      .map(Log4j2JsonEvent.Instant::timestamp)
      .orElse(log4j2JsonEvent.getTimeMillis());

    return new LogDataBuilder()
      .withLevel(levelMap.get(log4j2JsonEvent.getLevel()))
      .withDate(new Date(timestamp))
      .withLoggerName(log4j2JsonEvent.getLoggerName())
      .withClass(log4j2JsonEvent.getLoggerName())
      .withMessage(log4j2JsonEvent.getMessage() + exception.map(e -> "\n" + e).orElse(""))
      .withThread(log4j2JsonEvent.getThread())
      .withMethod(source.map(Source::getMethod).orElse(""))
      .withFile(source.map(Source::getFile).orElse(""))
      .withLineNumber(source.map(s1 -> s1.getLine().toString()).orElse(""))
      .withProperties(log4j2JsonEvent.getContextMap())
      .build();

  } catch (JSONException ignored) {
  }

  return null;
}
 
Example #29
Source File: PropertyHandler.java    From development with Apache License 2.0 4 votes vote down vote up
public JSONObject getTemplateParameters() {
    JSONObject parameters = new JSONObject();
    // created security Group array , user can add security group separated
    // by comma
    JSONArray securityGroupSecurityGroup = new JSONArray();
    Set<String> keySet = settings.getParameters().keySet();
    String securityGroup = null;
    try {

        for (String key : keySet) {
            if (key.startsWith(TEMPLATE_PARAMETER_PREFIX)) {
                if (key.startsWith(TEMPLATE_PARAMETER_ARRAY_PREFIX)) {
                    // below if execute only if technical service parameter
                    // have a
                    // security group parameters
                    securityGroup = key.substring(
                            TEMPLATE_PARAMETER_ARRAY_PREFIX.length());
                    String securityGroupArray[] = settings.getParameters()
                            .get(key).getValue().split(",");
                    for (String groupName : securityGroupArray) {
                        securityGroupSecurityGroup.put(groupName);
                    }
                    parameters.put(securityGroup,
                            securityGroupSecurityGroup);

                } else {
                    parameters.put(
                            key.substring(
                                    TEMPLATE_PARAMETER_PREFIX.length()),
                            settings.getParameters().get(key).getValue());
                }
            }

        }
        // remove the empty parameter from object
        parameters.remove("");
    } catch (JSONException e) {
        // should not happen with Strings
        throw new RuntimeException(
                "JSON error when collection template parameters", e);
    }
    return parameters;
}
 
Example #30
Source File: HealthCheckExecutorServlet.java    From aem-healthcheck with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
                                                    throws ServletException, IOException {
    response.setContentType("application/json");
    response.setHeader("Cache-Control", "must-revalidate,no-cache,no-store");

    // parse query parameters
    String tagsStr = StringUtils.defaultString(request.getParameter(PARAM_TAGS));
    String[] tags = tagsStr.split("[, ;]+");
    String combineTagsOr = StringUtils.defaultString(request.getParameter(PARAM_COMBINE_TAGS_OR), "true");

    // execute health checks
    HealthCheckExecutionOptions options = new HealthCheckExecutionOptions();
    options.setCombineTagsWithOr(Boolean.valueOf(combineTagsOr));
    options.setForceInstantExecution(true);
    List<HealthCheckExecutionResult> results = healthCheckExecutor.execute(options, tags);

    // check results
    boolean allOk = true;
    for(HealthCheckExecutionResult result : results) {
        if(!result.getHealthCheckResult().isOk()) {
            allOk = false;
            break;
        }
    }

    // set appropriate status code
    if(!allOk) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else {
        response.setStatus(HttpServletResponse.SC_OK);
    }

    // write out JSON response
    JSONObject resultJson = new JSONObject();
    try {
        generateResponse(results, resultJson);
    } catch(JSONException ex) {
        logger.error("Could not serialize result into JSON", ex);
    }
    response.getWriter().write(resultJson.toString());
}