Java Code Examples for net.sf.json.JSONObject#element()

The following examples show how to use net.sf.json.JSONObject#element() . 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: FieldsMapJsonTest.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testDeserializationOfUnknownFields() throws IOException {
	final FieldsMap map = new FieldsMap();
	map.put("fa", new Date(120));
	final JSONObject parsedJson = JSONObject.fromObject(mapper.writeValueAsString(map));
	parsedJson.element("unknown", Collections.singletonMap("int", 134));
	final String jsonStr = parsedJson.toString();
	LOGGER.info("Serialized in extended form to: {}", jsonStr);

	final FieldsMap dMap = mapper.readValue(jsonStr, FieldsMap.class);
	Assert.assertNull(dMap.get("@types"));
	Assert.assertEquals(2, dMap.size());
	Assert.assertEquals(new Date(120), dMap.get("fa"));
	Assert.assertTrue(dMap.get("unknown") instanceof Map);
	Assert.assertEquals(134, ((Map<String, Object>) dMap.get("unknown")).get("int"));
}
 
Example 2
Source File: ComMailingBaseAction.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private JSONObject calculateRecipients(ComAdmin admin, ComMailingBaseForm form) {
       final JSONObject data = new JSONObject();

       CalculationRecipientsConfig config = conversionService.convert(form, CalculationRecipientsConfig.class);
       config.setSplitId(targetService.getTargetListSplitId(form.getSplitBase(), form.getSplitPart(), form.isWmSplit()));
       config.setCompanyId(admin.getCompanyID());
       config.setConjunction(form.getTargetMode() != Mailing.TARGET_MODE_OR);

       NumberFormat numberFormatCount = NumberFormat.getNumberInstance(admin.getLocale());
       DecimalFormat decimalFormatCount = (DecimalFormat) numberFormatCount;
       decimalFormatCount.applyPattern(",###");

       try {
           data.element("count", decimalFormatCount.format(mailingBaseService.calculateRecipients(config)));
           data.element("success", true);
       } catch (Exception e) {
           logger.error("Error occurred: " + e.getMessage(), e);
           data.element("success", false);
       }

       return data;
}
 
Example 3
Source File: LoadosophiaClient.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
public static JSONObject getQuantilesJSON(Long[] rtimes) {
    JSONObject result = new JSONObject();
    Arrays.sort(rtimes);

    double[] quantiles = {0.25, 0.50, 0.75, 0.80, 0.90, 0.95, 0.98, 0.99, 1.00};

    Stack<Long> timings = new Stack<>();
    timings.addAll(Arrays.asList(rtimes));
    double level = 1.0;
    Object timing = 0;
    for (int qn = quantiles.length - 1; qn >= 0; qn--) {
        double quan = quantiles[qn];
        while (level >= quan && !timings.empty()) {
            timing = timings.pop();
            level -= 1.0 / rtimes.length;
        }
        result.element(String.valueOf(quan * 100), timing);
    }

    return result;
}
 
Example 4
Source File: WorkflowController.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@PostMapping("/getMailingLinks.action")
public ResponseEntity<?> getMailingLinks(ComAdmin admin, @RequestParam int mailingId) {
    Map<Integer, String> links = workflowService.getMailingLinks(mailingId, admin.getCompanyID());

    JSONObject orderedLinks = new JSONObject();
    int index = 0;

    for (Map.Entry<Integer, String> entry : links.entrySet()) {
        JSONObject data = new JSONObject();

        data.element("id", entry.getKey());
        data.element("url", entry.getValue());

        orderedLinks.element(Integer.toString(index++), data);
    }

    return new ResponseEntity<>(orderedLinks, HttpStatus.OK);
}
 
Example 5
Source File: ComMailinglistServiceImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public JSONArray getMailingListsJson(ComAdmin admin) {
    JSONArray mailingListsJson = new JSONArray();

    for (Mailinglist mailinglist : mailinglistDao.getMailinglists(admin.getCompanyID())) {
        JSONObject entry = new JSONObject();

        entry.element("id", mailinglist.getId());
        entry.element("shortname", mailinglist.getShortname());
        entry.element("description", mailinglist.getDescription());
        entry.element("changeDate", DateUtilities.toLong(mailinglist.getChangeDate()));
        entry.element("creationDate", DateUtilities.toLong(mailinglist.getCreationDate()));
        entry.element("isFrequencyCounterEnabled", mailinglist.isFrequencyCounterEnabled());

        mailingListsJson.element(entry);
    }

    return mailingListsJson;
}
 
Example 6
Source File: CalendarController.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@RequestMapping(value = "/calendar/moveMailing.action", method = RequestMethod.POST)
public @ResponseBody
ResponseEntity<?> moveMailing(ComAdmin admin, @RequestParam("mailingId") int mailingId, @RequestParam("date") String newDate) {
    JSONObject result = new JSONObject();
    LocalDate date = DateUtilities.parseDate(newDate, DATE_FORMATTER);

    if (mailingId <= 0 || Objects.isNull(date)) {
        return ResponseEntity.badRequest().build();
    }

    boolean isSuccess = calendarService.moveMailing(admin, mailingId, date);

    result.element("success", isSuccess);

    return ResponseEntity.ok().body(result);
}
 
Example 7
Source File: DeliveryServiceImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private JSONObject mapToJson(final DeliveryInfo deliveryInfo) {
    final JSONObject entry = new JSONObject();

    entry.element("timestamp", DateUtilities.toLong(deliveryInfo.getTimestamp()));
    entry.element("dsn", deliveryInfo.getDsn());
    entry.element("status", deliveryInfo.getStatus());

    final String relay = deliveryInfo.getRelay();
    if(StringUtils.startsWith(relay, "[")){
        entry.element("relay", JSONUtils.quote(deliveryInfo.getRelay()));
    } else {
        entry.element("relay", deliveryInfo.getRelay());
    }

    return entry;
}
 
Example 8
Source File: ComRecipientAction.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private JSONObject checkAddress(ComAdmin admin, String email, int recipientId) {
    JSONObject data = new JSONObject();
    data.element("address", email);
    int existingRecipientId = recipientDao.getRecipientIdByAddress(StringUtils.trimToEmpty(email), recipientId, admin.getCompanyID());
    data.element("inUse", existingRecipientId > 0);
    data.element("existingRecipientId", existingRecipientId);
    data.element("isBlacklisted", blacklistService.blacklistCheck(StringUtils.trimToEmpty(email), admin.getCompanyID()));
    return data;
}
 
Example 9
Source File: GogsWebHook.java    From gogs-webhook-plugin with MIT License 5 votes vote down vote up
/**
 * Exit the WebHook
 *
 * @param result GogsResults
 */
private void exitWebHook(GogsResults result, StaplerResponse resp) throws IOException {
    if (result.getStatus() != 200) {
        LOGGER.warning(result.getMessage());
    }
    //noinspection MismatchedQueryAndUpdateOfCollection
    JSONObject json = new JSONObject();
    json.element("result", result.getStatus() == 200 ? "OK" : "ERROR");
    json.element("message", result.getMessage());
    resp.setStatus(result.getStatus());
    resp.addHeader("Content-Type", "application/json");
    PrintWriter printer = resp.getWriter();
    printer.print(json.toString());
}
 
Example 10
Source File: WorkflowController.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@GetMapping("/getCurrentAdminTime.action")
public ResponseEntity<JSONObject> getCurrentAdminTime(ComAdmin admin) {
    GregorianCalendar calendar = new GregorianCalendar(AgnUtils.getTimeZone(admin));

    final JSONObject resultJson = new JSONObject();
    resultJson.element("hour", calendar.get(GregorianCalendar.HOUR_OF_DAY));
    resultJson.element("minute",  calendar.get(GregorianCalendar.MINUTE));
    return ResponseEntity.ok(resultJson);
}
 
Example 11
Source File: WorkflowController.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@PostMapping("/validateDependency.action")
public ResponseEntity<?> validateDependency(ComAdmin admin, WorkflowDependencyValidationForm form) {
    WorkflowDependencyType type = form.getType();
    int workflowId = form.getWorkflowId();

    // A workflowId = 0 value is reserved for a new workflow.
    if (type == null || workflowId < 0) {
        // Type parameter is missing or invalid.
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    } else {
        WorkflowDependency dependency = null;

        if (form.getEntityId() > 0) {
            dependency = type.forId(form.getEntityId());
        } else if (StringUtils.isNotEmpty(form.getEntityName())) {
            dependency = type.forName(form.getEntityName());
        }

        if (dependency == null) {
            // Either identifier or a name is required.
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        } else {
            JSONObject data = new JSONObject();
            data.element("valid", workflowService.validateDependency(admin.getCompanyID(), workflowId, dependency));
            return new ResponseEntity<>(data, HttpStatus.OK);
        }
    }
}
 
Example 12
Source File: CalendarCommentServiceImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private JSONArray commentsAsJson(List<ComCalendarComment> comments, ComAdmin admin) {
    JSONArray array = new JSONArray();

    TimeZone timezone = AgnUtils.getTimeZone(admin);
    DateFormat dateFormat = DateUtilities.getFormat(DD_MM_YYYY, timezone);
    DateFormat dateTimeFormat = DateUtilities.getFormat(DD_MM_YYYY_HH_MM, timezone);

    Map<Integer, String> adminNameMap = adminService.getAdminsNamesMap(admin.getCompanyID());

    for (ComCalendarComment comment : comments) {
        JSONObject object = new JSONObject();

        object.element("recipients", getRecipients(comment));
        object.element("commentId", comment.getCommentId());
        object.element("comment", comment.getComment());
        object.element("adminId", comment.getAdminId());
        object.element("adminName", adminNameMap.get(comment.getAdminId()));
        object.element("deadline", comment.isDeadline());
        object.element("notified", comment.isNotified());
        object.element("date", DateUtilities.format(comment.getDate(), dateFormat));
        object.element("plannedSendDates", DateUtilities.format(comment.getPlannedSendDate(), dateTimeFormat));

        array.add(object);
    }

    return array;
}
 
Example 13
Source File: CalendarServiceImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private JSONArray mailingsAsJson(List<Map<String, Object>> mailings, Map<Integer, Integer> openers, Map<Integer, Integer> clickers, ComAdmin admin) {
    TimeZone timezone = AgnUtils.getTimeZone(admin);
    Locale locale = admin.getLocale();

    DateFormat dateFormat = DateUtilities.getFormat(DATE_FORMAT, timezone);
    DateFormat timeFormat = DateUtilities.getFormat(TIME_FORMAT, timezone);

    JSONArray result = new JSONArray();

    for (Map<String, Object> mailing : mailings) {
        JSONObject object = new JSONObject();

        Date sendDate = (Date) mailing.get("senddate");
        int mailingId = getIntValue(mailing, "mailingId");
        boolean isSent = getIntValue(mailing, "genstatus") > MaildropGenerationStatus.SCHEDULED.getCode();

        //hardcode because dao returns keys in different case (depends on db)
        object.element("shortname", getShortname(mailing));
        object.element("mailingId", mailing.get("mailingid"));
        object.element("workstatus", mailing.get("workstatus"));
        object.element("workstatusIn", I18nString.getLocaleString((String) mailing.get("workstatus"), locale));
        object.element("preview_component", mailing.get("preview_component"));
        object.element("mailsSent", mailing.get("mailssent"));
        object.element("genstatus", mailing.get("genstatus"));
        object.element("statusfield", mailing.get("statusfield"));

        object.element("subject", mailing.get("subject"));
        object.element("planned", mailing.get("planned"));
        object.element("plannedInPast", mailing.get("plannedInPast"));
        object.element("sendDate", DateUtilities.format(sendDate, dateFormat));
        object.element("sendTime", DateUtilities.format(sendDate, timeFormat));
        object.element("sent", isSent);
        object.element("openers", openers.getOrDefault(mailingId, 0));
        object.element("clickers", clickers.getOrDefault(mailingId, 0));

        result.add(object);
    }

    return result;
}
 
Example 14
Source File: ComOptimizationServiceImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public JSONArray getOptimizationsAsJson(ComAdmin admin, LocalDate startDate, LocalDate endDate, DateTimeFormatter formatter) {
	JSONArray result = new JSONArray();

	if (startDate.isAfter(endDate)) {
	    return result;
       }

       ZoneId zoneId = AgnUtils.getZoneId(admin);
	Date start = DateUtilities.toDate(startDate, zoneId);
	Date end = DateUtilities.toDate(endDate.plusDays(1).atStartOfDay().minusNanos(1), zoneId);

	List<ComOptimization> optimizations = optimizationDao.getOptimizationsForCalendar_New(admin.getCompanyID(), start, end);

	for (ComOptimization optimization : optimizations) {
           JSONObject object = new JSONObject();

           object.element("id", optimization.getId());
           object.element("shortname", optimization.getShortname());
           object.element("campaignID", optimization.getCampaignID());
           object.element("workflowId", optimization.getWorkflowId());
           object.element("autoOptimizationStatus", optimization.getAutoOptimizationStatus());
           object.element("sendDate", DateUtilities.format(optimization.getSendDate(), zoneId, formatter));

           result.add(object);
       }

	return result;
}
 
Example 15
Source File: ComMailingSendActionBasic.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private JSONObject saveStatusmailOnErrorOnly(HttpServletRequest request) {
    String isStatusmailOnErrorOnlyParam = request.getParameter("statusmailOnErrorOnly");
    String mailingIdParam = request.getParameter("mailingId");
    boolean isUpdated = false;

    if (StringUtils.isNotBlank(isStatusmailOnErrorOnlyParam) && StringUtils.isNotBlank(mailingIdParam)) {
        boolean isStatusmailOnErrorOnly = BooleanUtils.toBoolean(isStatusmailOnErrorOnlyParam);
        int mailingId = NumberUtils.toInt(mailingIdParam);
        ComAdmin admin = AgnUtils.getAdmin(request);

        try {
            // creation of UAL entry
            Mailing mailing = mailingService.getMailing(admin.getCompanyID(), mailingId);
            String action = "switched mailing statusmailonerroronly";
            String description = String.format("statusmailonerroronly: %s, mailing type: %s. %s(%d)",
            		isStatusmailOnErrorOnly ? "true" : "false",
                    mailingTypeToString(mailing.getMailingType()),
                    mailing.getShortname(),
                    mailing.getId());

            if (mailingService.switchStatusmailOnErrorOnly(admin.getCompanyID(), mailingId, isStatusmailOnErrorOnly)) {
                isUpdated = true;
                writeUserActivityLog(admin, action, description);
            }
        } catch (Exception e) {
            logger.error("Error occurred: " + e.getMessage(), e);
        }
    }

    JSONObject response = new JSONObject();
    response.element("success", isUpdated);
    return response;
}
 
Example 16
Source File: GetMailingTrackableLinks.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected JSONObject processRequestJson(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    JSONObject responseJson = new JSONObject();

    ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    ComTrackableLinkService trackableLinkService = applicationContext.getBean("TrackeableLinkService", ComTrackableLinkService.class);

    try {
        int mailingId = Integer.parseInt(request.getParameter("mailingId"));
        List<TrackableLinkListItem> mailingLinks = trackableLinkService.getMailingLinks(mailingId, AgnUtils.getCompanyID(request));

        if(!mailingLinks.isEmpty()) {
         JSONArray items = new JSONArray();
         for (TrackableLinkListItem mailingLink : mailingLinks) {
          JSONObject item = new JSONObject();
          item.element("id", mailingLink.getId());
          item.element("value", mailingLink.getFullUrl());
          items.add(item);
         }
         responseJson.element("mailingId", mailingId);
         responseJson.element("links", items);
        }
    } catch (NumberFormatException e) {
        logger.error("Invalid mailingId parameter: " + e.getMessage(), e);
        return null;
    }

    return responseJson;
}
 
Example 17
Source File: PhabricatorNotifierTest.java    From phabricator-jenkins-plugin with MIT License 5 votes vote down vote up
@Test
public void testPostToHarbormasterValidLint() throws Exception {
    JSONObject json = new JSONObject();
    LintResults result = new LintResults();
    result.add(new LintResult("test", "testcode", "error", "to/path", 10, 3, "test description"));
    json.element("lint", result);
    FreeStyleBuild build = buildWithConduit(getFetchDiffResponse(), null, json);

    assertEquals(Result.SUCCESS, build.getResult());
}
 
Example 18
Source File: HarbormasterClient.java    From phabricator-jenkins-plugin with MIT License 4 votes vote down vote up
/**
 * Sets a sendHarbormasterMessage build status
 *
 * @param phid Phabricator object ID
 * @param pass whether or not the build passed
 * @param unitResults the results from the unit tests
 * @param coverage the results from the coverage provider
 * @param lintResults
 * @return the Conduit API response
 * @throws IOException if there is a network error talking to Conduit
 * @throws ConduitAPIException if any error is experienced talking to Conduit
 */
public JSONObject sendHarbormasterMessage(
        String phid,
        boolean pass,
        UnitResults unitResults,
        Map<String, String> coverage,
        LintResults lintResults) throws ConduitAPIException, IOException {

    List<JSONObject> unit = new ArrayList<JSONObject>();

    if (unitResults != null) {
        unit.addAll(unitResults.toHarbormaster());
    }

    List<JSONObject> lint = new ArrayList<JSONObject>();

    if (lintResults != null) {
        lint.addAll(lintResults.toHarbormaster());
    }

    if (coverage != null) {
        JSONObject coverageUnit = new JSONObject()
                .element("result", "pass")
                .element("name", "Coverage Data")
                .element("coverage", coverage);
        unit.add(coverageUnit);
    }

    JSONObject params = new JSONObject();
    params.element("type", pass ? "pass" : "fail")
            .element("buildTargetPHID", phid);

    if (!unit.isEmpty()) {
        params.element("unit", unit);
    }

    if (!lint.isEmpty()) {
        params.element("lint", lint);
    }

    return conduit.perform("harbormaster.sendmessage", params);
}
 
Example 19
Source File: ComWorkflowServiceImpl.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public JSONArray getWorkflowListJson(ComAdmin admin) {
    JSONArray mailingListsJson = new JSONArray();

    for (Workflow workflow: getWorkflowsOverview(admin)) {
        JSONObject entry = new JSONObject();
        JSONObject statusJson = new JSONObject();
        JSONObject startDateJson = new JSONObject();
        JSONObject endDateJson = new JSONObject();
        JSONObject reactionJson = new JSONObject();

        WorkflowForm.WorkflowStatus status = WorkflowForm.WorkflowStatus.valueOf(workflow.getStatusString());
        statusJson.element("name", status.getName());
        statusJson.element("messageKey", status.getMessageKey());

        Long startDateLong = DateUtilities.toLong(workflow.getGeneralStartDate());
        startDateJson.element("dateLong", startDateLong);
        int startEventTypeId = -1;
        if(workflow.getGeneralStartEvent() != null) {
            startEventTypeId = workflow.getGeneralStartEvent().getId();
        }
        startDateJson.element("startTypeId", startEventTypeId);

        Long endDateLong = DateUtilities.toLong(workflow.getGeneralEndDate());
        endDateJson.element("dateLong", endDateLong);
        int endEventTypeId = -1;
        if(workflow.getEndType() != null) {
            endEventTypeId = workflow.getEndType().getId();
        }
        endDateJson.element("endTypeId", endEventTypeId);

        String iconClass = "";
        String name = "";
        if(workflow.getGeneralStartReaction() != null) {
            iconClass = workflow.getGeneralStartReaction().getIconClass();
            name = workflow.getGeneralStartReaction().getName();
        }
        reactionJson.element("iconClass", iconClass);
        reactionJson.element("name", name);

        entry.element("id", workflow.getWorkflowId());
        entry.element("status", statusJson);
        entry.element("shortname", workflow.getShortname());
        entry.element("description", workflow.getDescription());
        entry.element("startDate", startDateJson);
        entry.element("stopDate", endDateJson);
        entry.element("reaction", reactionJson);

        mailingListsJson.element(entry);
    }

    return mailingListsJson;
}
 
Example 20
Source File: ProvRest.java    From mobi with GNU Affero General Public License v3.0 4 votes vote down vote up
private JSONObject createReturnObj(List<Activity> activities) {
    JSONArray activityArr = new JSONArray();
    Model entitiesModel = mf.createModel();
    Map<String, List<String>> repoToEntities = new HashMap<>();
    activities.forEach(activity -> {
        Model entityModel = mf.createModel(activity.getModel());
        entityModel.remove(activity.getResource(), null, null);
        entitiesModel.addAll(entityModel);
        entityModel.filter(null, vf.createIRI("http://www.w3.org/ns/prov#atLocation"), null).forEach(statement -> {
            Resource entityIRI = statement.getSubject();
            String repoId = statement.getObject().stringValue();
            if (repoToEntities.containsKey(repoId)) {
                repoToEntities.get(repoId).add("<" + entityIRI + ">");
            } else {
                repoToEntities.put(repoId, new ArrayList<>(Collections.singletonList("<" + entityIRI + ">")));
            }
        });
        Model activityModel = mf.createModel(activity.getModel()).filter(activity.getResource(), null, null);
        activityArr.add(RestUtils.getObjectFromJsonld(RestUtils.modelToJsonld(activityModel, transformer)));
    });
    StopWatch watch = new StopWatch();
    repoToEntities.keySet().forEach(repoId -> {
        LOG.trace("Start collecting entities for prov activities in " + repoId);
        watch.start();
        Repository repo = repositoryManager.getRepository(repoId).orElseThrow(() ->
                new IllegalStateException("Repository " + repoId + " could not be found"));
        try (RepositoryConnection entityConn = repo.getConnection()) {
            String entityQueryStr = GET_ENTITIES_QUERY.replace("#ENTITIES#",
                    String.join(" ", repoToEntities.get(repoId)));
            GraphQuery entityQuery = entityConn.prepareGraphQuery(entityQueryStr);
            entitiesModel.addAll(QueryResults.asModel(entityQuery.evaluate(), mf));
            watch.stop();
            LOG.trace("End collecting entities for prov activities in " + repoId + ": " + watch.getTime() + "ms");
            watch.reset();
        }
    });
    JSONObject object = new JSONObject();
    object.element("activities", activityArr);
    object.element("entities", RestUtils.modelToJsonld(entitiesModel, transformer));
    return object;
}