Java Code Examples for org.codehaus.jackson.node.ObjectNode

The following are top voted examples for showing how to use org.codehaus.jackson.node.ObjectNode. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: dcs-sdk-java   File: Directive.java   Source Code and License 10 votes vote down vote up
@Override
public Directive deserialize(JsonParser jp, DeserializationContext ctx)
        throws IOException {
    ObjectReader reader = ObjectMapperUtil.instance().getObjectReader();
    ObjectNode obj = (ObjectNode) reader.readTree(jp);
    Iterator<Map.Entry<String, JsonNode>> elementsIterator = obj.getFields();

    String rawMessage = obj.toString();
    DialogRequestIdHeader header = null;
    JsonNode payloadNode = null;
    ObjectReader headerReader =
            ObjectMapperUtil.instance().getObjectReader(DialogRequestIdHeader.class);
    while (elementsIterator.hasNext()) {
        Map.Entry<String, JsonNode> element = elementsIterator.next();
        if (element.getKey().equals("header")) {
            header = headerReader.readValue(element.getValue());
        }
        if (element.getKey().equals("payload")) {
            payloadNode = element.getValue();
        }
    }
    if (header == null) {
        throw ctx.mappingException("Missing header");
    }
    if (payloadNode == null) {
        throw ctx.mappingException("Missing payload");
    }

    return createDirective(header, payloadNode, rawMessage);
}
 
Example 2
Project: skygiraffe-slackbot   File: JsonUtil.java   Source Code and License 9 votes vote down vote up
public static String createAuthLinkResponse(){

        JsonNodeFactory f = JsonNodeFactory.instance ;
        ObjectNode loginResponse = f.objectNode();
        loginResponse.put("text","Authorization for SkyGiraffe to use Slack details is required.");
        ArrayNode attachments = loginResponse.putArray("attachments");
        ObjectNode att = f.objectNode();
        att.put("fallback", "Please authorize SkyGiraffe to access to your Slack details ...");
        att.put("pretext", "");
        att.put("title", "Please authorize..");
        att.put("title_link", Config.getPropertyValue("SLACK_AUTH_URL_DEV"));
        att.put("text","Once authorized and logged into SkyGiraffe try '/sg help' to see all commands");
        att.put("color", "#7CD197");

        attachments.add(att);
        return loginResponse.toString();

    }
 
Example 3
Project: exhibitor   File: ClusterResource.java   Source Code and License 8 votes vote down vote up
@Path("list")
@GET
@Produces(MediaType.APPLICATION_JSON)
public String   getClusterAsJson() throws Exception
{
    InstanceConfig      config = context.getExhibitor().getConfigManager().getConfig();

    ObjectNode          node = JsonNodeFactory.instance.objectNode();

    ArrayNode           serversNode = JsonNodeFactory.instance.arrayNode();
    ServerList          serverList = new ServerList(config.getString(StringConfigs.SERVERS_SPEC));
    for ( ServerSpec spec : serverList.getSpecs() )
    {
        serversNode.add(spec.getHostname());
    }
    node.put("servers", serversNode);
    node.put("port", config.getInt(IntConfigs.CLIENT_PORT));

    return JsonUtil.writeValueAsString(node);
}
 
Example 4
Project: bdf2   File: CriterionUtils.java   Source Code and License 7 votes vote down vote up
public static Criteria getCriteria(ObjectNode rudeCriteria) throws Exception {
	Criteria criteria = new Criteria();
	if (rudeCriteria.has("criterions")) {
		ArrayNode criterions = (ArrayNode) rudeCriteria.get("criterions");
		if (criterions != null) {
			for (Iterator<JsonNode> it = criterions.iterator(); it.hasNext();) {
				criteria.addCriterion(parseCriterion((ObjectNode) it.next()));
			}
		}
	}

	if (rudeCriteria.has("orders")) {
		ArrayNode orders = (ArrayNode) rudeCriteria.get("orders");
		if (orders != null) {
			for (Iterator<JsonNode> it = orders.iterator(); it.hasNext();) {
				ObjectNode rudeCriterion = (ObjectNode) it.next();
				Order order = new Order(JsonUtils.getString(rudeCriterion, "property"), JsonUtils.getBoolean(rudeCriterion, "desc"));
				criteria.addOrder(order);
			}
		}
	}
	return criteria;
}
 
Example 5
Project: communote-server   File: CreateNoteWidget.java   Source Code and License 7 votes vote down vote up
/**
 * Extracts the crosspost blogs from an autosave and creates a JSON array.
 *
 * @param item
 *            the item that holds the note data
 * @return the array
 */
private ArrayNode extractCrosspostBlogs(AutosaveNoteData item) {
    ArrayNode result = JsonHelper.getSharedObjectMapper().createArrayNode();
    if (item.getCrosspostBlogs() != null) {
        for (BlogData b : item.getCrosspostBlogs()) {
            String title = b.getTitle();
            ObjectNode blog = BlogSearchHelper.createBlogSearchJSONResult(b.getId(),
                    b.getNameIdentifier(), title, false);
            result.add(blog);
        }
    }
    if (result.size() == 0) {
        return null;
    }
    return result;
}
 
Example 6
Project: communote-server   File: ConfluenceAuthenticator.java   Source Code and License 7 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void extractUserData(ObjectNode jsonUser, ExternalUserVO userVO)
        throws AuthenticationServiceException {
    assertFieldsExist(jsonUser, JSON_PARAM_LOGIN, JSON_PARAM_EMAIL, JSON_PARAM_LAST_NAME,
            JSON_PARAM_FIRST_NAME);
    userVO.setExternalUserName(jsonUser.get(JSON_PARAM_LOGIN).asText());
    userVO.setEmail(jsonUser.get(JSON_PARAM_EMAIL).asText());
    userVO.setLastName(jsonUser.get(JSON_PARAM_LAST_NAME).asText());
    userVO.setFirstName(jsonUser.get(JSON_PARAM_FIRST_NAME).asText());
    if (jsonUser.has(JSON_PARAM_LANG)) {
        String lang = jsonUser.get(JSON_PARAM_LANG).asText();
        Locale locale = new Locale(lang);
        userVO.setDefaultLanguage(locale);
    }
}
 
Example 7
Project: skygiraffe-slackbot   File: JsonUtil.java   Source Code and License 7 votes vote down vote up
/**
 * {
 "attachments": [
 {
 "fallback": "Please login into SkyGiraffe to continue ...",
 "pretext": "SkyGiraffe Login",
 "title": "Please login into SkyGiraffe to continue ...",
 "title_link": "https://sgbot-mobilityai.rhcloud.com/SGbot-1.0/skyg/login?key=",
 "text": "Once logged in try '/sg help' to see all commands",
 "color": "#7CD197"
 }
 ]
 }
 * @return
 */
public static String createLoginLinkResponse(String slackUserId, String email, String teamId){

    JsonNodeFactory f = JsonNodeFactory.instance ;
    ObjectNode loginResponse = f.objectNode();
    loginResponse.put("text","Login to SkyGiraffe is required.");
    ArrayNode attachments = loginResponse.putArray("attachments");
    ObjectNode att = f.objectNode();
    att.put("fallback", "Please login into SkyGiraffe to continue ...");
    att.put("pretext", "");
    att.put("title", "Please login..");
    att.put("title_link", Config.getPropertyValue("SGDS_LOGIN_URL_DEV")+slackUserId+"&EMAIL="+email+"&TEAMID="+teamId);
    att.put("text","Once logged in try '/sg help' to see all commands");
    att.put("color", "#7CD197");

    attachments.add(att);

    return loginResponse.toString();

}
 
Example 8
Project: skygiraffe-slackbot   File: SGDSClient.java   Source Code and License 7 votes vote down vote up
public static String authenticate(String userName, String password) throws IOException {
    if (userName == null || userName.isEmpty())
        userName = SGSlackConstants.DEFAULT_USER;
    if (password == null || password.isEmpty())
        password = SGSlackConstants.PASSWORD;

    ObjectMapper m = new ObjectMapper();
    ObjectNode o = m.createObjectNode();
    o.put("UserName",userName);
    o.put("Password",password);
    o.put("OS","webapp");
    o.put("Version","4006000");

    StringEntity input = new StringEntity(o.toString());

    SGDSAuthRes ss = new SGDSAuthRes();
    ss = m.readValue(postSGDS("Authenticate",input), ss.getClass());

    logger.debug("Session id on authentication="+ss.getSessionID());
    return ss.getSessionID();
}
 
Example 9
Project: SHIKSHAK   File: SignupService.java   Source Code and License 6 votes vote down vote up
@PUT
@Path("/validate")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response userValidation(User userData) {
	try {
		int flag = 0;
		String emailRcvd = "";

		final ObjectNode node = new ObjectMapper().readValue(userData.toString(), ObjectNode.class);

		if (node.has("email")) {
			emailRcvd = node.get("email").toString().replace("\"", "").trim();
		}

		ResultSet rs = dbobj.openConnection("select email from user");
		while (rs.next()) {
			String userEmail = rs.getString("email");
			if (emailRcvd.equals(userEmail)) {
				flag = 1;
				break;
			}
		}
		if (flag == 1) {
			resp.put("response", "false");
			return Response.ok(resp.toJSONString()).build();
		}
		dbobj.closeConnection(rs);
	} catch (SQLException | IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	resp.put("response", "true");
	return Response.ok(resp.toJSONString()).build();
}
 
Example 10
Project: hadoop   File: JobHistoryEventHandler.java   Source Code and License 6 votes vote down vote up
@Private
public JsonNode countersToJSON(Counters counters) {
  ObjectMapper mapper = new ObjectMapper();
  ArrayNode nodes = mapper.createArrayNode();
  if (counters != null) {
    for (CounterGroup counterGroup : counters) {
      ObjectNode groupNode = nodes.addObject();
      groupNode.put("NAME", counterGroup.getName());
      groupNode.put("DISPLAY_NAME", counterGroup.getDisplayName());
      ArrayNode countersNode = groupNode.putArray("COUNTERS");
      for (Counter counter : counterGroup) {
        ObjectNode counterNode = countersNode.addObject();
        counterNode.put("NAME", counter.getName());
        counterNode.put("DISPLAY_NAME", counter.getDisplayName());
        counterNode.put("VALUE", counter.getValue());
      }
    }
  }
  return nodes;
}
 
Example 11
Project: hadoop   File: StateDeserializer.java   Source Code and License 6 votes vote down vote up
@Override
public StatePair deserialize(JsonParser parser, 
                             DeserializationContext context)
throws IOException, JsonProcessingException {
  ObjectMapper mapper = (ObjectMapper) parser.getCodec();
  // set the state-pair object tree
  ObjectNode statePairObject = (ObjectNode) mapper.readTree(parser);
  Class<?> stateClass = null;
  
  try {
    stateClass = 
      Class.forName(statePairObject.get("className").getTextValue().trim());
  } catch (ClassNotFoundException cnfe) {
    throw new RuntimeException("Invalid classname!", cnfe);
  }
  
  String stateJsonString = statePairObject.get("state").toString();
  State state = (State) mapper.readValue(stateJsonString, stateClass);
  
  return new StatePair(state);
}
 
Example 12
Project: aliyun-oss-hadoop-fs   File: JobHistoryEventHandler.java   Source Code and License 6 votes vote down vote up
@Private
public JsonNode countersToJSON(Counters counters) {
  ObjectMapper mapper = new ObjectMapper();
  ArrayNode nodes = mapper.createArrayNode();
  if (counters != null) {
    for (CounterGroup counterGroup : counters) {
      ObjectNode groupNode = nodes.addObject();
      groupNode.put("NAME", counterGroup.getName());
      groupNode.put("DISPLAY_NAME", counterGroup.getDisplayName());
      ArrayNode countersNode = groupNode.putArray("COUNTERS");
      for (Counter counter : counterGroup) {
        ObjectNode counterNode = countersNode.addObject();
        counterNode.put("NAME", counter.getName());
        counterNode.put("DISPLAY_NAME", counter.getDisplayName());
        counterNode.put("VALUE", counter.getValue());
      }
    }
  }
  return nodes;
}
 
Example 13
Project: aliyun-oss-hadoop-fs   File: StateDeserializer.java   Source Code and License 6 votes vote down vote up
@Override
public StatePair deserialize(JsonParser parser, 
                             DeserializationContext context)
throws IOException, JsonProcessingException {
  ObjectMapper mapper = (ObjectMapper) parser.getCodec();
  // set the state-pair object tree
  ObjectNode statePairObject = (ObjectNode) mapper.readTree(parser);
  Class<?> stateClass = null;
  
  try {
    stateClass = 
      Class.forName(statePairObject.get("className").getTextValue().trim());
  } catch (ClassNotFoundException cnfe) {
    throw new RuntimeException("Invalid classname!", cnfe);
  }
  
  String stateJsonString = statePairObject.get("state").toString();
  State state = (State) mapper.readValue(stateJsonString, stateClass);
  
  return new StatePair(state);
}
 
Example 14
Project: Java-education   File: UpdateOrder.java   Source Code and License 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    PrintWriter out = resp.getWriter();
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode root = mapper.getNodeFactory().objectNode();

    HttpSession session = req.getSession(false);
    int orderId = (int)session.getAttribute("currentOrder");
    int userId = -1;
    if(orderId != -1){
        boolean success = (boolean)session.getAttribute("success");
        if(success){
            userId = (int)session.getAttribute("id_user");
        }
        OrderDBManager orderDBManager = new OrderDBManager();
        root.put("orderProperties",orderCollection(orderDBManager.get(orderId)));

    }
    root.put("currentUser",userId);
    root.put("order",orderId);
    out.append(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root));
    out.flush();
}
 
Example 15
Project: Java-education   File: UpdateOrder.java   Source Code and License 6 votes vote down vote up
public ArrayNode orderCollection(Collection<Order> collection) {
    ArrayNode array = JsonNodeFactory.instance.arrayNode();
    for(Order param : collection){
        ObjectNode obj =  JsonNodeFactory.instance.objectNode();
        obj.put("orderId", param.getId() );
        obj.put("mile", param.getMilesage() );
        obj.put("price", param.getPrice() );
        obj.put("sold", param.getSold() );
        obj.put("carName", param.getCar().getName() );
        obj.put("carId", param.getCar().getId() );
        obj.put("modelId", param.getCar().getModel().getId() );
        obj.put("bodyId", param.getCar().getBody().getId() );
        obj.put("drivetype", param.getCar().getDriveType().getId());
        obj.put("engineId", param.getCar().getEngine().getId() );
        obj.put("transsmId", param.getCar().getTransmission().getId() );
        obj.put("data", param.getRelease().getTime());
        obj.put("userId", param.getUser().getId() );
        array.add(obj);
    }
    return array;
}
 
Example 16
Project: exhibitor   File: UIResource.java   Source Code and License 6 votes vote down vote up
@Path("backup-config")
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getBackupConfig() throws Exception
{
    ArrayNode           node = JsonNodeFactory.instance.arrayNode();

    if ( context.getExhibitor().getBackupManager().isActive() )
    {
        EncodedConfigParser parser = context.getExhibitor().getBackupManager().getBackupConfigParser();
        List<BackupConfigSpec>  configs = context.getExhibitor().getBackupManager().getConfigSpecs();
        for ( BackupConfigSpec c : configs )
        {
            ObjectNode      n = JsonNodeFactory.instance.objectNode();
            String          value = parser.getValue(c.getKey());

            n.put("key", c.getKey());
            n.put("name", c.getDisplayName());
            n.put("help", c.getHelpText());
            n.put("value", (value != null) ? value : "");
            n.put("type", c.getType().name().toLowerCase().substring(0, 1));

            node.add(n);
        }
    }

    return JsonUtil.writeValueAsString(node);
}
 
Example 17
Project: skygiraffe-slackbot   File: SGDSClient.java   Source Code and License 6 votes vote down vote up
public static String getAppList(String sessionId) throws IOException {

        if (sessionId == null || sessionId.isEmpty())
            throw new IllegalArgumentException("Session Id is empty. Please login.");

        ObjectMapper m = new ObjectMapper();
        ObjectNode o = m.createObjectNode();
        o.put("SessionID",sessionId);
        StringEntity inputApps = new StringEntity(o.toString());
        return postSGDS("GetAppsList", inputApps);
    }
 
Example 18
Project: exhibitor   File: IndexResource.java   Source Code and License 6 votes vote down vote up
@Path("dataTable/{index-name}/{search-handle}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getDataTableData
    (
        @PathParam("index-name") String indexName,
        @PathParam("search-handle") String searchHandle,
        @QueryParam("iDisplayStart") int iDisplayStart,
        @QueryParam("iDisplayLength") int iDisplayLength,
        @QueryParam("sEcho") String sEcho
    ) throws Exception
{
    LogSearch logSearch = getLogSearch(indexName);
    if ( logSearch == null )
    {
        return "{}";
    }
    ObjectNode          node;
    try
    {
        CachedSearch        cachedSearch = logSearch.getCachedSearch(searchHandle);
        DateFormat          dateFormatter = new SimpleDateFormat(DATE_FORMAT_STR);
        ArrayNode           dataTab = JsonNodeFactory.instance.arrayNode();
        for ( int i = iDisplayStart; i < (iDisplayStart + iDisplayLength); ++i )
        {
            if ( i < cachedSearch.getTotalHits() )
            {
                ObjectNode      data = JsonNodeFactory.instance.objectNode();
                int             docId = cachedSearch.getNthDocId(i);
                SearchItem      item = logSearch.toResult(docId);
                
                data.put("DT_RowId", "index-query-result-" + docId);
                data.put("0", getTypeName(EntryTypes.getFromId(item.getType())));
                data.put("1", dateFormatter.format(item.getDate()));
                data.put("2", trimPath(item.getPath()));

                dataTab.add(data);
            }
        }

        node = JsonNodeFactory.instance.objectNode();
        node.put("sEcho", sEcho);
        node.put("iTotalRecords", logSearch.getDocQty());
        node.put("iTotalDisplayRecords", cachedSearch.getTotalHits());
        node.put("aaData", dataTab);
    }
    finally
    {
        context.getExhibitor().getIndexCache().releaseLogSearch(logSearch.getFile());
    }

    return node.toString();
}
 
Example 19
Project: photon-model   File: LibraryClient.java   Source Code and License 6 votes vote down vote up
public ObjectNode loadLib(String libId) throws IOException, RpcException {
    RpcRequest call = newCall("com.vmware.content.library", "get");
    bindToSession(call, this.sessionId);

    call.params.input = newNode();
    call.params.input
            .putObject(K_STRUCTURE)
            .putObject(K_OPERATION_INPUT)
            .put("library_id", libId);
    RpcResponse resp = rpc(call);
    throwIfError("Cannot load library " + libId, resp);

    ObjectNode result = resp.result;
    if (result == null) {
        return null;
    }

    return (ObjectNode) result
            .get(K_OUTPUT)
            .get(K_STRUCTURE)
            .get("com.vmware.content.library_model");
}
 
Example 20
Project: photon-model   File: LibraryClient.java   Source Code and License 6 votes vote down vote up
private ObjectNode makeSpec(ManagedObjectReference datastore,
        VirtualMachineDefinedProfileSpec pbmSpec, String vmName,
        Map<String, String> networkMappings,
        VirtualDiskType diskType) {
    ObjectNode res = newNode();
    ObjectNode t = res.putObject(K_STRUCTURE)
            .putObject("com.vmware.vcenter.ovf.library_item.resource_pool_deployment_spec");
    t.put("accept_all_EULA", true);

    // Only one of datastore / policy can be set. Not both. If datastore is present that will
    // be given preference
    if (datastore != null) {
        t.putObject("default_datastore_id").put(K_OPTIONAL, datastore.getValue());
    } else if (pbmSpec != null) {
        t.putObject("storage_profile_id").put(K_OPTIONAL, pbmSpec.getProfileId());
    }

    if (diskType != null) {
        t.putObject("storage_provisioning").put(K_OPTIONAL, diskType.value());
    }

    t.putObject("name").put(K_OPTIONAL, vmName);
    return res;
}
 
Example 21
Project: photon-model   File: TaggingClient.java   Source Code and License 6 votes vote down vote up
public ObjectNode getTagModel(String tagId) throws IOException, RpcException {
    RpcRequest call = newCall("com.vmware.cis.tagging.tag", "get");
    bindToSession(call, this.sessionId);

    call.params.input = newNode();
    call.params.input
            .putObject(K_STRUCTURE)
            .putObject(K_OPERATION_INPUT)
            .put("tag_id", tagId);

    RpcResponse resp = rpc(call);
    throwIfError("Cannot get model for tag " + tagId, resp);

    return (ObjectNode) resp.result
            .get(K_OUTPUT)
            .get(K_STRUCTURE)
            .get("com.vmware.cis.tagging.tag_model");
}
 
Example 22
Project: photon-model   File: VSphereAdapterImageEnumerationService.java   Source Code and License 6 votes vote down vote up
private ImageState makeImageFromItem(ObjectNode lib, ObjectNode item) {
    ImageState res = new ImageState();

    String itemName = VapiClient.getString(item, "name", VapiClient.K_OPTIONAL);
    String libraryName = VapiClient.getString(lib, "name", VapiClient.K_OPTIONAL);
    res.name = libraryName + " / " + itemName;

    res.description = VapiClient.getString(item, "description", VapiClient.K_OPTIONAL);
    res.id = VapiClient.getString(item, "id", VapiClient.K_OPTIONAL);

    CustomProperties.of(res)
            .put(CustomProperties.IMAGE_LIBRARY_ID,
                    VapiClient.getString(item, "library_id", VapiClient.K_OPTIONAL));

    return res;
}
 
Example 23
Project: exhibitor   File: ExplorerResource.java   Source Code and License 6 votes vote down vote up
@GET
@Path("node-data")
@Produces("application/json")
public String   getNodeData(@QueryParam("key") String key) throws Exception
{
    ObjectNode node = JsonNodeFactory.instance.objectNode();
    try
    {
        Stat stat = context.getExhibitor().getLocalConnection().checkExists().forPath(key);
        byte[]          bytes = context.getExhibitor().getLocalConnection().getData().storingStatIn(stat).forPath(key);

        if (bytes != null) {
            node.put("bytes", bytesToString(bytes));
            node.put("str", new String(bytes, "UTF-8"));
        } else {
            node.put("bytes", "");
            node.put("str", "");
        }
        node.put("stat", reflectToString(stat));
    }
    catch ( KeeperException.NoNodeException dummy )
    {
        node.put("bytes", "");
        node.put("str", "");
        node.put("stat", "* not found * ");
    }
    catch ( Throwable e )
    {
        node.put("bytes", "");
        node.put("str", "Exception");
        node.put("stat", e.getMessage());
    }
    return node.toString();
}
 
Example 24
Project: printos-device-api-example-java   File: Device.java   Source Code and License 6 votes vote down vote up
public static boolean postRealTimeData(HttpClient client, String url, String deviceToken) throws ParseException, IOException {
  HttpPost post = new HttpPost(url);
  post.addHeader("Cookie", Constants.X_SMS_AUTH_TOKEN + "=" + deviceToken);

  long MINS_AHEAD = 1000 * 60 * 30;   // Pretend we have 30 minutes of print time left
  int jobsInQueue = 6;                // and 6 jobs left in the queue
  String status = "DS_PRINTING";      // and we're currently printing

  Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  Timestamp printCompleteTime = new Timestamp(cal.getTime().getTime() + MINS_AHEAD);
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  String date = format.format(printCompleteTime.getTime());

  ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();
  ObjectNode jsonNode = mapper.createObjectNode();

  jsonNode.put("deviceStatus", status);
  jsonNode.put("totalJobs", jobsInQueue);
  jsonNode.put("printTimeComplete", date);

  StringEntity entity = new StringEntity(jsonNode.toString());
  post.setEntity(entity);

  HttpResponse response = HttpClientWrapper.executeHttpCommand(client, post);
  if (response != null) {
    if (response.getStatusLine().getStatusCode() != 204) {
      HttpClientWrapper.logErrorResponse(response, "Failed To post data");
      return false;
    } else {
      EntityUtils.consumeQuietly(response.getEntity());
      log.info("Sucessfully posted data");
      System.out.println("Successfully posted data.");
      return false;
    }
  } else {
    log.error("No response returned from post data");
    return false;
  }
}
 
Example 25
Project: printos-device-api-example-java   File: User.java   Source Code and License 6 votes vote down vote up
public static String loginAndGetToken(HttpClient client, String url, String login, String password)
  throws ParseException, IOException
{
  String token = null;
  HttpPost loginPost = new HttpPost(url);

  ObjectMapper mapper = new ObjectMapper();
  ObjectNode jsonNode = mapper.createObjectNode();

  jsonNode.put("login", login);
  jsonNode.put("password", password);

  StringEntity entity = new StringEntity(jsonNode.toString());
  loginPost.setEntity(entity);

  HttpResponse response = HttpClientWrapper.executeHttpCommand(client, loginPost);
  if (response != null)
  {
    if(response.getStatusLine().getStatusCode() == 200)
    {
      token = HttpClientWrapper.getTokenFromResponse(response);
      EntityUtils.consumeQuietly(response.getEntity());
    }
    else {
      HttpClientWrapper.logErrorResponse(response, "Failed To login");
    }
  }else {
    log.error("No response returned from login call");
  }

  return token;
}
 
Example 26
Project: communote-server   File: MaxUploadSizeExceededExceptionResolver.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a model and view to transport the error message
 *
 * @param request
 *            the current HTTP request
 * @param response
 *            the current HTTP response
 * @param view
 *            the name of the view to use, can be null if the request should be handled as Ajax
 *            upload or there is no mapping for the request and the default non-ajax upload view
 *            should be used
 * @return the created model and view or null if the response was written as JSON
 */
private ModelAndView prepareAjaxModelAndView(HttpServletRequest request,
        HttpServletResponse response, String errorMessage) {
    ObjectNode jsonResponse = JsonRequestHelper.createJsonErrorResponse(errorMessage);
    try {
        // Note: the JSON cannot be written directly to the response since this is not supported
        // by exception resolvers. Main problem is that some headers like encoding won't be set
        // correctly and response is written twice
        return ControllerHelper.prepareModelAndViewForJsonResponse(request, response,
                jsonResponse, false);
    } catch (IOException e) {
        // should not occur because response is not written directly
        LOGGER.error("Unexpected exception handling MaxUploadSizeExceededException", e);
        return null;
    }
}
 
Example 27
Project: communote-server   File: UserProfileActionController.java   Source Code and License 6 votes vote down vote up
/**
 * Deletion of the current user account.
 *
 * @param request
 *            the servlet request
 * @param response
 *            the servlet response
 *
 * @throws IOException
 *             in case of a IO error
 */
public void deleteAccount(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    ObjectNode jsonResponse = JsonHelper.getSharedObjectMapper().createObjectNode();
    String errorMessage = null;
    String mode = getDeleteMode(request);
    if (mode == null) {
        errorMessage = MessageHelper.getText(request, "user.delete.account.failed");
    } else {
        errorMessage = doDeleteAccount(request, mode);
    }
    if (errorMessage != null) {
        jsonResponse.put("message", errorMessage);
        jsonResponse.put("status", ApiResult.ResultStatus.ERROR.name());
    } else {
        // log user out
        AuthenticationHelper.removeAuthentication();
        jsonResponse.put("status", ApiResult.ResultStatus.OK.name());
    }
    JsonHelper.writeJsonTree(response.getWriter(), jsonResponse);
}
 
Example 28
Project: communote-server   File: UserProfileActionController.java   Source Code and License 6 votes vote down vote up
/**
 * Upload an image using AJAX. The response will be returned as JSON object.
 *
 * @param request
 *            the servlet request
 * @param userId
 *            the ID of the user whose image will be updated
 * @return the JSON response object
 */
private ObjectNode doUploadImageAjax(HttpServletRequest request, Long userId) {

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    CommonsMultipartFile cFile = (CommonsMultipartFile) multipartRequest.getFile("file");
    String errorMessage = null;
    if (cFile != null && cFile.getSize() > 0) {
        if (cFile.getSize() < getMaxUploadSize()) {
            errorMessage = storeImage(request, cFile, userId);
        } else {
            errorMessage = MessageHelper.getText(request, "user.profile.upload.filesize.error",
                    new Object[] { FileUtils.byteCountToDisplaySize(getMaxUploadSize()) });
        }
    } else {
        errorMessage = MessageHelper.getText(request, "user.profile.upload.empty.image");
    }
    if (errorMessage != null) {
        return JsonRequestHelper.createJsonErrorResponse(errorMessage);
    }
    return JsonRequestHelper.createJsonSuccessResponse(null, createSuccessResult(userId));
}
 
Example 29
Project: communote-server   File: UserProfileActionController.java   Source Code and License 6 votes vote down vote up
/**
 * handles the upload process of the user image.
 *
 * @param request
 *            the servlet request
 * @param response
 *            the servlet response
 * @return The model and view.
 * @throws IOException
 *             in case sending the response failed
 */
public ModelAndView imageUpload(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    String action = ParameterHelper.getParameterAsString(request.getParameterMap(),
            PARAM_FORM_ACTION);
    Long userId = SecurityHelper.getCurrentUserId();
    ObjectNode jsonResponse = JsonHelper.getSharedObjectMapper().createObjectNode();

    if (action.equals(FormAction.UPLOAD_IMAGE_FILE_AJAX)) {
        jsonResponse = doUploadImageAjax(request, userId);
    } else if (action.equals(FormAction.RESET_USER_IMAGE_AJAX)) {
        jsonResponse = doRemoveImageAjax(request, userId);
    } else if (action.equals(FormAction.REFRESH_EXTERNAL_USER_IMAGE_AJAX)) {
        jsonResponse = doRefreshExternalImageAjax(request, userId);
    } else {
        jsonResponse = JsonRequestHelper.createJsonErrorResponse("Unsupported operation");
    }

    return ControllerHelper.prepareModelAndViewForJsonResponse(request, response, jsonResponse,
            true);
}
 
Example 30
Project: communote-server   File: UserSearchHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Creates an array of JSON objects which hold details about the found users or groups.
 * 
 * @param list
 *            the search result to process
 * @param addSummary
 *            if true a summary JSON object will be added to the top of the array. The JSON
 *            object will be created with {@link #createSearchSummaryStatement(PageableList)} .
 * @param imageSize
 *            the size of the user logo to include in the image path, can be null to not include
 *            the image path into the JSON object. For groups no image will be included.
 * @return the JSON array with the details about the users
 */
public static ArrayNode createEntitySearchJSONResult(
        PageableList<CommunoteEntityData> list, boolean addSummary,
        ImageSizeType imageSize) {
    JsonNodeFactory nodeFactory = JsonHelper.getSharedObjectMapper()
            .getNodeFactory();
    ArrayNode result = nodeFactory.arrayNode();
    if (addSummary) {
        result.add(UserSearchHelper.createSearchSummaryStatement(list));
    }
    for (CommunoteEntityData item : list) {
        String imagePath = null;
        boolean isGroup = (item instanceof EntityGroupListItem);
        if (!isGroup && imageSize != null) {
            imagePath = ImageUrlHelper.buildUserImageUrl(item.getEntityId(), imageSize);
        }
        ObjectNode entry = createUserSearchJSONResult(item.getEntityId(),
                item.getShortDisplayName(), item.getDisplayName(),
                imagePath, item.getAlias());
        entry.put("isGroup", isGroup);
        result.add(entry);
    }
    return result;
}
 
Example 31
Project: communote-server   File: UserSearchHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a JSON Object with key value pairs from the parameters passed to this method. Only
 * the values (and keys) which are not null will be added.
 * 
 * @param userId
 *            the ID of the user, if null this information is not added to the JSON object
 * @param shortName
 *            a short version of the user name, if null this information is not added to the
 *            JSON object
 * @param longName
 *            a long version of the user name, if null this information is not added to the JSON
 *            object
 * @param imagePath
 *            the path to the user image, if null this information is not added to the JSON
 *            object
 * @param alias
 *            the alias of the user, if null this information is not added to the JSON object
 * @return the JSON object
 */
public static ObjectNode createUserSearchJSONResult(Long userId,
        String shortName, String longName, String imagePath, String alias) {
    ObjectNode resultObj = JsonHelper.getSharedObjectMapper()
            .createObjectNode();
    if (imagePath != null) {
        resultObj.put(JSON_KEY_USER_IMAGE_PATH, imagePath);
    }
    if (longName != null) {
        resultObj.put(JSON_KEY_USER_LONG_NAME, longName);
    }
    if (shortName != null) {
        resultObj.put(JSON_KEY_USER_SHORT_NAME, shortName);
    }
    if (alias != null) {
        resultObj.put(JSON_KEY_USER_ALIAS, alias);
    }
    if (userId != null) {
        resultObj.put(JSON_KEY_ID, userId);
    }
    return resultObj;
}
 
Example 32
Project: communote-server   File: BlogSearchHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Add the JSON objects of the blogs to the JSON response.
 * 
 * @param jsonResponse
 *            the response object to write to
 * @param list
 *            list to process
 * @param includeDescription
 *            whether to include the description
 * @param includeImagePath
 *            whether to include the path to the image
 */
private static void addBlogsToJsonResponse(ArrayNode jsonResponse,
        Collection<BlogData> list, boolean includeDescription, boolean includeImagePath) {
    for (BlogData item : list) {
        ObjectNode entry;
        if (includeDescription) {
            entry = BlogSearchHelper.createBlogSearchJSONResult(item.getId(),
                    item.getNameIdentifier(), item.getTitle(), item.getDescription(),
                    includeImagePath);
        } else {
            entry = BlogSearchHelper.createBlogSearchJSONResult(item.getId(),
                    item.getNameIdentifier(), item.getTitle(), includeImagePath);
        }
        jsonResponse.add(entry);
    }
}
 
Example 33
Project: communote-server   File: InstallationJSONController.java   Source Code and License 6 votes vote down vote up
/**
 * Ajax method to initialize the application after completing the installation.
 *
 * @param request
 *            the current request
 * @param response
 *            the response to write to
 * @throws IOException
 *             in case writing the response failed
 */
public void completeInstallation(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    // only support POST
    if (!StringUtils.equalsIgnoreCase(request.getMethod(), METHOD_POST)) {
        return;
    }
    ObjectNode jsonResponse = JsonHelper.getSharedObjectMapper().createObjectNode();
    try {
        CommunoteRuntime.getInstance().getInstaller().initializeApplicationAfterInstallation();
        jsonResponse.put(JSON_RESPONSE_FIELD_STATUS, JSON_RESPONSE_STATUS_TYPE_OK);
    } catch (ApplicationInitializationException e) {
        LOGGER.error("Completing the installation failed", e);
        jsonResponse.put(JSON_RESPONSE_FIELD_STATUS, JSON_RESPONSE_STATUS_TYPE_ERROR);
    }
    JsonHelper.writeJsonTree(response.getWriter(), jsonResponse);
}
 
Example 34
Project: communote-server   File: CreateNoteWidget.java   Source Code and License 6 votes vote down vote up
/**
 * Createsa JSON object with note data for reply case.
 *
 * @param parentNoteId
 *            the id of the parent note for the reply
 * @param locale
 *            the locale of the current user
 * @param plaintextOnly
 *            true if the client expects the content in plaintext and not HTML
 * @param authorNotification
 *            true if the notification syntax to inform the author of the reply should be added
 * @param inheritTags
 *            true if the reply should inherit all the tags of the parent note
 * @throws NoteNotFoundException
 *             in case the note to edit cannot be found
 * @throws AuthorizationException
 *             in case the user has no read access to the note
 * @return the note with initial data for a reply
 */
private ObjectNode createJsonNoteObjectForReply(long parentNoteId, Locale locale,
        boolean plaintextOnly, boolean authorNotification, boolean inheritTags)
                throws NoteNotFoundException, AuthorizationException {
    if (parentNoteId <= 0) {
        throw new NoteNotFoundException("Parent note does not exist");
    }
    NoteData parentNoteItem = getNoteManagement().getNote(parentNoteId,
            new NoteRenderContext(null, locale));
    NoteData newNoteItem = new NoteData();
    getRequest().setAttribute("isDirectReply", parentNoteItem.isDirect());
    newNoteItem.setBlog(parentNoteItem.getBlog());
    String notifier = getNotifier(authorNotification, parentNoteItem);
    newNoteItem.setContent(notifier);
    newNoteItem.setDirect(parentNoteItem.isDirect());
    if (inheritTags) {
        newNoteItem.setTags(parentNoteItem.getTags());
    }
    return this.createJsonNoteObject(newNoteItem, false, plaintextOnly);
}
 
Example 35
Project: communote-server   File: CreateNoteWidget.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a JSON object with autosave data.
 *
 * @param noteId
 *            ID of the note
 * @param parentNoteId
 *            the ID of the parent note
 * @param repostNoteId
 *            Id of a possible repost note.
 * @param locale
 *            the locale of the current user
 * @param plaintextOnly
 *            true if the client expects the content in plaintext and not HTML
 * @return Response as JSON
 */
private ObjectNode createJsonNoteObjectFromAutosave(long noteId, long parentNoteId,
        long repostNoteId, Locale locale, boolean plaintextOnly) {
    Long nId = noteId < 0 ? null : noteId;
    Long parentId = parentNoteId < 0 ? null : parentNoteId;
    ArrayList<StringPropertyTO> properties = null;

    // add repost property if the repostNoteId is set
    if (repostNoteId >= 0) {
        properties = new ArrayList<>();
        properties.add(new StringPropertyTO(String.valueOf(repostNoteId),
                PropertyManagement.KEY_GROUP, RepostNoteStoringPreProcessor.KEY_ORIGIN_NOTE_ID,
                null));
    }
    AutosaveNoteData autosave = getNoteManagement().getAutosave(nId, parentId, properties,
            locale);
    if (autosave != null) {
        ObjectNode jsonObject = createJsonNoteObject(autosave, true, plaintextOnly);
        jsonObject.put("autosaveNoteId", autosave.getId());
        jsonObject.put("autosaveVersion", autosave.getVersion());
        jsonObject.put("crosspostBlogs", extractCrosspostBlogs(autosave));
        return jsonObject;
    }
    return null;
}
 
Example 36
Project: communote-server   File: CreateNoteWidget.java   Source Code and License 6 votes vote down vote up
/**
 * Extracts the tags from a note and creates a JSON array.
 *
 * @param item
 *            the item that holds the note data
 * @return the array
 */
private ArrayNode extractTags(NoteData item) {
    ArrayNode result = JsonHelper.getSharedObjectMapper().createArrayNode();
    // create items manually because TagData POJO is incompatible to REST API TagResource
    if (item.getTags() != null) {
        for (TagData tagItem : item.getTags()) {
            ObjectNode tag = result.addObject();
            tag.put("tagId", tagItem.getId());
            tag.put("tagStoreAlias", tagItem.getTagStoreAlias());
            tag.put("tagStoreTagId", tagItem.getTagStoreTagId());
            String languageCode = null;
            if (tagItem.getLocale() != null) {
                languageCode = tagItem.getLocale().toString().toLowerCase();
            }
            tag.put("languageCode", languageCode);
            tag.put("name", tagItem.getName());
            tag.put("description", tagItem.getDescription());
            tag.put("defaultName", tagItem.getDefaultName());
        }
    }
    return result;
}
 
Example 37
Project: communote-server   File: CreateNoteWidget.java   Source Code and License 6 votes vote down vote up
/**
 * Extracts the users to notify from a note and creates a JSON array.
 *
 * @param item
 *            the item that holds the note data
 * @return the array
 */
private ArrayNode extractUsersToNotify(NoteData item) {
    ArrayNode result = JsonHelper.getSharedObjectMapper().createArrayNode();
    if (item.getNotifiedUsers() != null) {
        for (DetailedUserData ul : item.getNotifiedUsers()) {
            ObjectNode user = UserSearchHelper.createUserSearchJSONResult(ul,
                    ImageSizeType.MEDIUM);
            result.add(user);
        }
    }
    // add @@ mentions by building fake users
    if (item.isMentionDiscussionAuthors()) {
        result.add(UserSearchHelper.createUserSearchJSONResult(null, null,
                MessageHelper.getText(getRequest(), "autosuggest.atat.discussion"), null,
                NoteManagement.CONSTANT_MENTION_DISCUSSION_PARTICIPANTS));
    }
    if (item.isMentionTopicAuthors()) {
        result.add(UserSearchHelper.createUserSearchJSONResult(null, null,
                MessageHelper.getText(getRequest(), "autosuggest.atat.authors"), null,
                NoteManagement.CONSTANT_MENTION_TOPIC_AUTHORS));
    }
    if (item.isMentionTopicReaders()) {
        result.add(UserSearchHelper.createUserSearchJSONResult(null, null,
                MessageHelper.getText(getRequest(), "autosuggest.atat.all"), null,
                NoteManagement.CONSTANT_MENTION_TOPIC_READERS));
    }
    if (item.isMentionTopicManagers()) {
        result.add(UserSearchHelper.createUserSearchJSONResult(null, null,
                MessageHelper.getText(getRequest(), "autosuggest.atat.managers"), null,
                NoteManagement.CONSTANT_MENTION_TOPIC_MANAGERS));
    }
    if (result.size() == 0) {
        return null;
    }
    return result;
}
 
Example 38
Project: communote-server   File: CreateNoteWidget.java   Source Code and License 6 votes vote down vote up
/**
 * Adds the data of the default blog if it is activated
 *
 * @param noteData
 *            the data to modify
 * @return the ID of the default blog if enabled, null otherwise
 *
 */
private Long putDefaultBlogInfo(ObjectNode noteData) {
    Long defaultBlogId = null;
    Blog defaultBlog = null;
    JsonNode defaultBlogTitle;
    JsonNode defaultBlogAlias;
    defaultBlog = getDefaultBlog();
    JsonNodeFactory factory = JsonHelper.getSharedObjectMapper().getNodeFactory();
    if (defaultBlog != null) {
        defaultBlogId = defaultBlog.getId();
        defaultBlogTitle = factory.textNode(defaultBlog.getTitle());
        defaultBlogAlias = factory.textNode(defaultBlog.getNameIdentifier());
    } else {
        defaultBlogTitle = factory.nullNode();
        defaultBlogAlias = factory.nullNode();
    }
    noteData.put("defaultBlogId",
            defaultBlogId == null ? factory.nullNode() : factory.numberNode(defaultBlogId));
    noteData.put("defaultBlogTitle", defaultBlogTitle);
    noteData.put("defaultBlogAlias", defaultBlogAlias);
    return defaultBlogId;
}
 
Example 39
Project: communote-server   File: GlobalIdUploadImageController.java   Source Code and License 6 votes vote down vote up
/**
 * Method to reset the image of the given entity to the default type.
 *
 * @param request
 *            The send request.
 * @param response
 *            The response.
 * @param entityId
 *            Id of the entity to change.
 * @param imageType
 *            Type of the image.
 * @throws IOException
 *             Thrown, when the output can't be written.
 */
@RequestMapping(method = RequestMethod.POST, produces = "application/json", params = "widgetAction=reset_default")
public void setDefault(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "entityId", required = true) String entityId,
        @RequestParam(value = "imageType", required = true) String imageType)
        throws IOException {
    ObjectNode jsonResponse;
    try {
        ServiceLocator.findService(EntityImageManagement.class).setDefault(entityId,
                EntityImageManagement.ImageType.getType(imageType));
        jsonResponse = JsonRequestHelper.createJsonSuccessResponse(
                ResourceBundleManager.instance().getText(
                        "widget.globalid-upload-image.reset.success",
                        SessionHandler.instance().getCurrentLocale(request)),
                createResult(request, entityId, imageType));
    } catch (Exception e) {
        LOGGER.error("Setting default image for entity with ID {} and type {} failed",
                entityId, imageType, e);
        Status status = ServiceLocator.findService(ExceptionMapperManagement.class)
                .mapException(e);
        jsonResponse = JsonRequestHelper.createJsonErrorResponse(status.getMessage().toString(
                SessionHandler.instance().getCurrentLocale(request)));
    }
    JsonHelper.writeJsonTree(response.getWriter(), jsonResponse);
}
 
Example 40
Project: communote-server   File: NoteTemplateTool.java   Source Code and License 6 votes vote down vote up
/**
 * Create a JSON with blog details.
 *
 * @param blog
 *            the blog to process
 * @param xmlEncode
 *            whether characters that are reserved in XML should be encoded in the returned
 *            string
 * @return the JSON object as string
 */
public String blogAsJson(MinimalBlogData blog, boolean xmlEncode) {
    // TODO should we handle the DELETED/REGISTERED status?
    ObjectMapper mapper = JsonHelper.getSharedObjectMapper();
    ObjectNode rootNode = mapper.getNodeFactory().objectNode();
    if (blog != null) {
        // the attributes are the same as in REST API
        rootNode.put("alias", blog.getAlias());
        rootNode.put("title", blog.getTitle());
        rootNode.put("topicId", blog.getId());
        // TODO add anything else?
    }
    String jsonString = JsonHelper.writeJsonTreeAsString(rootNode);
    if (xmlEncode) {
        jsonString = StringEscapeHelper.escapeXml(jsonString);
    }
    return jsonString;
}
 
Example 41
Project: communote-server   File: NoteTemplateTool.java   Source Code and License 6 votes vote down vote up
/**
 * Create a JSON with user details.
 *
 * @param user
 *            the user to process
 * @param xmlEncode
 *            whether characters that are reserved in XML should be encoded in the returned
 *            string
 * @return the JSON object as string
 */
public String userAsJson(UserData user, boolean xmlEncode) {
    // TODO should we handle the DELETED/REGISTERED status?
    ObjectMapper mapper = JsonHelper.getSharedObjectMapper();
    ObjectNode rootNode = mapper.getNodeFactory().objectNode();
    if (user != null) {
        // the attributes are the same as in REST API
        rootNode.put("alias", user.getAlias());
        rootNode.put("firstName", user.getFirstName());
        rootNode.put("lastName", user.getLastName());
        rootNode.put("userId", user.getId());
        rootNode.put("salutation", user.getSalutation());
    }
    String jsonString = JsonHelper.writeJsonTreeAsString(rootNode);
    if (xmlEncode) {
        jsonString = StringEscapeHelper.escapeXml(jsonString);
    }
    return jsonString;
}
 
Example 42
Project: communote-server   File: EntityTopicAccessRightsChangedEventListener.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void fillTemplateProperties(ObjectNode rootNode,
        EntityTopicAccessRightsChangedEvent event) {
    rootNode.put("topicId", event.getTopicId());
    rootNode.put("topicTitle", event.getTopicTitle());
    rootNode.put("userId", event.getGrantingUserId());
    rootNode.put("isGroup", event.isGroup());
    if (event.getOldRole() != null) {
        rootNode.put("oldRole", event.getOldRole().getValue());
    }
    if (event.getNewRole() != null) {
        rootNode.put("newRole", event.getNewRole().getValue());
    }
    if (event.isGroup()) {
        rootNode.put("groupName", userGroupManagement.findGroupById(event.getGrantedEntityId(),
                new Converter<Group, String>() {
                    @Override
                    public String convert(Group source) {
                        return source.getName();
                    }
                }));
    } else {
        rootNode.put("grantedUserId", event.getGrantedEntityId());
    }
}
 
Example 43
Project: communote-server   File: EmbedController.java   Source Code and License 6 votes vote down vote up
public static Object createNotePropertyFilter(String keyGroup, String key, String value,
        PropertyFilter.MatchMode matchMode, boolean negate) {
    ObjectNode propsObj = JsonHelper.getSharedObjectMapper().createObjectNode();
    propsObj.put("name", "npf");
    ArrayNode filterData = propsObj.putArray("value");
    filterData.add("Note");
    filterData.add(keyGroup);
    filterData.add(key);
    filterData.add(value);
    filterData.add(matchMode.name());
    // negation flag is optional
    if (negate) {
        filterData.add(true);
    }
    return propsObj;
}
 
Example 44
Project: bdf2   File: CriterionUtils.java   Source Code and License 5 votes vote down vote up
private static Criterion parseCriterion(ObjectNode rudeCriterion) throws Exception {
	String junction = JsonUtils.getString(rudeCriterion, "junction");
	if (StringUtils.isNotEmpty(junction)) {
		Junction junctionCrition;
		if ("or".equals(junction)) {
			junctionCrition = new Or();
		} else {
			junctionCrition = new And();
		}
		ArrayNode criterions = (ArrayNode) rudeCriterion.get("criterions");
		if (criterions != null) {
			for (Iterator<JsonNode> it = criterions.iterator(); it.hasNext();) {
				junctionCrition.addCriterion(parseCriterion((ObjectNode) it.next()));
			}
		}
		return junctionCrition;
	} else {
		String property = JsonUtils.getString(rudeCriterion, "property");
		String expression = JsonUtils.getString(rudeCriterion, "expression");
		String dataTypeName = JsonUtils.getString(rudeCriterion, "dataType");
		DataType dataType = null;
		ViewManager viewManager = ViewManager.getInstance();
		if (StringUtils.isNotEmpty(dataTypeName)) {
			dataType = viewManager.getDataType(dataTypeName);
		}
		return viewManager.getFilterCriterionParser().createFilterCriterion(property, dataType, expression);
	}
}
 
Example 45
Project: defense-solutions-proofs-of-concept   File: MLOBIOutboundTransport.java   Source Code and License 5 votes vote down vote up
private String createFeatureWithOID(JsonNode feature, String oid) throws IOException
{
	JsonNode attributes = feature.get("attributes");
	String oidField = "objectId";
	if (attributes.has(oidField))
		((ObjectNode) attributes).remove(oidField);
	if (oid != null)
		((ObjectNode) attributes).put(oidField, Integer.parseInt(oid));
	String newFeatureString = mapper.writeValueAsString(feature);
	return newFeatureString;
}
 
Example 46
Project: samza-sql-tools   File: JsonRelConverterFactory.java   Source Code and License 5 votes vote down vote up
@Override
public KV<Object, Object> convertToSamzaMessage(SamzaSqlRelMessage relMessage) {

  String jsonValue;
  ObjectNode node = mapper.createObjectNode();

  List<String> fieldNames = relMessage.getFieldNames();
  List<Object> values = relMessage.getFieldValues();

  for (int index = 0; index < fieldNames.size(); index++) {
    Object value = values.get(index);
    if (value == null) {
      continue;
    }

    // TODO limited support right now.
    if (Long.class.isAssignableFrom(value.getClass())) {
      node.put(fieldNames.get(index), (Long) value);
    } else if (Integer.class.isAssignableFrom(value.getClass())) {
      node.put(fieldNames.get(index), (Integer) value);
    } else if (Double.class.isAssignableFrom(value.getClass())) {
      node.put(fieldNames.get(index), (Double) value);
    } else if (String.class.isAssignableFrom(value.getClass())) {
      node.put(fieldNames.get(index), (String) value);
    } else {
      node.put(fieldNames.get(index), value.toString());
    }
  }
  try {
    jsonValue = mapper.writeValueAsString(node);
  } catch (IOException e) {
    throw new SamzaException("Error json serializing object", e);
  }

  return new KV<>(relMessage.getKey(), jsonValue.getBytes());
}
 
Example 47
Project: ditb   File: TestModelBase.java   Source Code and License 5 votes vote down vote up
public void testToJSON() throws Exception {
  try {
    ObjectNode expObj = mapper.readValue(AS_JSON, ObjectNode.class);
    ObjectNode actObj = mapper.readValue(toJSON(buildTestModel()), ObjectNode.class);
    assertEquals(expObj, actObj);
  } catch(Exception e) {
    assertEquals(AS_JSON, toJSON(buildTestModel()));
  }
}
 
Example 48
Project: Java-education   File: FilterOrder.java   Source Code and License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    PrintWriter out = resp.getWriter();
    Map<String, Integer> map = new HashMap<>();
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode root = mapper.getNodeFactory().objectNode();
    try {
        map = mapper.readValue(req.getParameter("filter"),new TypeReference<HashMap<String, Integer>>(){});
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    HttpSession session = req.getSession(false);
    Integer userId = -1;
    if(session != null){
        boolean success = (boolean)session.getAttribute("success");
        if(success){
            userId = (int)session.getAttribute("id_user");
        }
    }
    OrderDBManager orderDBManager = new OrderDBManager();
    root.put("currentUser",userId);
    root.put("orders",convert(orderDBManager.getOrderByCriteria(map)));
    out.append(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root));
    out.flush();
}
 
Example 49
Project: Shop-for-JavaWeb   File: ActProcessService.java   Source Code and License 5 votes vote down vote up
/**
 * 将部署的流程转换为模型
 * @param procDefId
 * @throws UnsupportedEncodingException
 * @throws XMLStreamException
 */
@Transactional(readOnly = false)
public org.activiti.engine.repository.Model convertToModel(String procDefId) throws UnsupportedEncodingException, XMLStreamException {
	
	ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(procDefId).singleResult();
	InputStream bpmnStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(),
	processDefinition.getResourceName());
	XMLInputFactory xif = XMLInputFactory.newInstance();
	InputStreamReader in = new InputStreamReader(bpmnStream, "UTF-8");
	XMLStreamReader xtr = xif.createXMLStreamReader(in);
	BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);

	BpmnJsonConverter converter = new BpmnJsonConverter();
	ObjectNode modelNode = converter.convertToJson(bpmnModel);
	org.activiti.engine.repository.Model modelData = repositoryService.newModel();
	modelData.setKey(processDefinition.getKey());
	modelData.setName(processDefinition.getResourceName());
	modelData.setCategory(processDefinition.getCategory());//.getDeploymentId());
	modelData.setDeploymentId(processDefinition.getDeploymentId());
	modelData.setVersion(Integer.parseInt(String.valueOf(repositoryService.createModelQuery().modelKey(modelData.getKey()).count()+1)));

	ObjectNode modelObjectNode = new ObjectMapper().createObjectNode();
	modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, processDefinition.getName());
	modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, modelData.getVersion());
	modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, processDefinition.getDescription());
	modelData.setMetaInfo(modelObjectNode.toString());

	repositoryService.saveModel(modelData);

	repositoryService.addModelEditorSource(modelData.getId(), modelNode.toString().getBytes("utf-8"));

	return modelData;
}
 
Example 50
Project: Shop-for-JavaWeb   File: ActModelService.java   Source Code and License 5 votes vote down vote up
/**
 * 创建模型
 * @throws UnsupportedEncodingException 
 */
public org.activiti.engine.repository.Model create(String name, String key, String description, String category) throws UnsupportedEncodingException {
	ObjectMapper objectMapper = new ObjectMapper();
	ObjectNode editorNode = objectMapper.createObjectNode();
	editorNode.put("id", "canvas");
	editorNode.put("resourceId", "canvas");
	ObjectNode stencilSetNode = objectMapper.createObjectNode();
	stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
	editorNode.put("stencilset", stencilSetNode);
	org.activiti.engine.repository.Model modelData = repositoryService.newModel();

	description = StringUtils.defaultString(description);
	modelData.setKey(StringUtils.defaultString(key));
	modelData.setName(name);
	modelData.setCategory(category);
	modelData.setVersion(Integer.parseInt(String.valueOf(repositoryService.createModelQuery().modelKey(modelData.getKey()).count()+1)));

	ObjectNode modelObjectNode = objectMapper.createObjectNode();
	modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
	modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, modelData.getVersion());
	modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
	modelData.setMetaInfo(modelObjectNode.toString());
	
	repositoryService.saveModel(modelData);
	repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
	
	return modelData;
}
 
Example 51
Project: NoSQLDataEngineering   File: RawSchemaGen.java   Source Code and License 5 votes vote down vote up
private static SchemaComponent deSchema(String name, ObjectNode o)
{
	ObjectSC schema = new ObjectSC();
	
	SortedSet<String> fields = new TreeSet<String>();
	o.getFieldNames().forEachRemaining(fields::add);
	fields.forEach(f -> schema.add(Pair.of(f, deSchema(f, o.get(f)))));
	
	return schema;
}
 
Example 52
Project: photon-model   File: LibraryClient.java   Source Code and License 5 votes vote down vote up
public ObjectNode deployOvfLibItem(
        String itemId,
        String vmName,
        ManagedObjectReference vmFolder,
        ManagedObjectReference datastore,
        VirtualMachineDefinedProfileSpec pbmSpec,
        ManagedObjectReference resourcePool,
        Map<String, String> networkMappings,
        VirtualDiskType diskType) throws IOException, RpcException {

    RpcRequest call = newCall("com.vmware.vcenter.ovf.library_item", "deploy");
    bindToSession(call, this.sessionId);

    call.params.input = newNode();
    ObjectNode opInput = call.params.input
            .putObject(K_STRUCTURE)
            .putObject(K_OPERATION_INPUT);

    ObjectNode target = makeTarget(vmFolder.getValue(), resourcePool.getValue());
    ObjectNode spec = makeSpec(datastore, pbmSpec, vmName, networkMappings, diskType);

    opInput.put("deployment_spec", spec);
    opInput.put("ovf_library_item_id", itemId);
    opInput.put("target", target);

    RpcResponse resp = rpc(call);
    logger.info("Deploying library item {} : {}", itemId, resp.error != null ? resp.error : "");

    throwIfError("Cannot deploy library item " + itemId, resp);

    ObjectNode result = resp.result;
    if (result == null) {
        return null;
    }

    return (ObjectNode) result
            .get(K_OUTPUT)
            .get(K_STRUCTURE)
            .get("com.vmware.vcenter.ovf.library_item.deployment_result");
}
 
Example 53
Project: photon-model   File: LibraryClient.java   Source Code and License 5 votes vote down vote up
private ObjectNode makeTarget(String folderId, String resourcePoolId) {
    ObjectNode res = newNode();
    ObjectNode t = res.putObject(K_STRUCTURE)
            .putObject("com.vmware.vcenter.ovf.library_item.deployment_target");
    t.putObject("folder_id").put(K_OPTIONAL, folderId);
    t.put("resource_pool_id", resourcePoolId);
    return res;
}
 
Example 54
Project: photon-model   File: VapiClient.java   Source Code and License 5 votes vote down vote up
protected ObjectNode newDynamicId(ManagedObjectReference ref) {
    ObjectNode res = newNode();

    ObjectNode obj = res
            .putObject(K_STRUCTURE)
            .putObject("com.vmware.vapi.std.dynamic_ID");

    obj.put("id", ref.getValue());
    obj.put("type", ref.getType());

    return res;
}
 
Example 55
Project: photon-model   File: VapiClient.java   Source Code and License 5 votes vote down vote up
protected List<String> toStringList(ObjectNode result) {
    if (result == null) {
        return Collections.emptyList();
    }
    JsonNode jsonNode = result.get(K_OUTPUT);
    if (jsonNode == null) {
        return Collections.emptyList();
    }
    return StreamSupport.stream(jsonNode.spliterator(), false)
            .map(JsonNode::asText)
            .collect(Collectors.toList());
}
 
Example 56
Project: photon-model   File: VapiClient.java   Source Code and License 5 votes vote down vote up
public static String getString(ObjectNode obj, String... path) {
    JsonNode res = obj;
    for (String key : path) {
        res = res.get(key);
        if (res == null) {
            return null;
        }
    }

    return res.asText();
}
 
Example 57
Project: photon-model   File: VSphereAdapterImageEnumerationService.java   Source Code and License 5 votes vote down vote up
private void processAllLibraries(Set<String> oldImages, String endpointLink, String taskLink,
        LibraryClient libraryClient, List<String> tenantLinks)
        throws IOException, RpcException {
    Phaser phaser = new Phaser(1);

    for (String libId : libraryClient.listLibs()) {
        ObjectNode libModel = libraryClient.loadLib(libId);
        for (String itemId : libraryClient.listItemsInLib(libId)) {
            ObjectNode itemModel = libraryClient.loadItem(itemId);

            String type = VapiClient.getString(itemModel, "type", VapiClient.K_OPTIONAL);
            if (!"ovf".equals(type)) {
                // only ovfs can be deployed
                continue;
            }

            ImageState state = makeImageFromItem(libModel, itemModel);
            state.documentSelfLink = buildStableImageLink(endpointLink, state.id);
            state.endpointLink = endpointLink;
            state.tenantLinks = tenantLinks;
            state.regionId = "";

            oldImages.remove(state.documentSelfLink);
            phaser.register();

            Operation.createPost(PhotonModelUriUtils.createInventoryUri(getHost(), ImageService.FACTORY_LINK))
                    .setBody(state)
                    .setCompletion((o, e) -> phaser.arrive())
                    .sendWith(this);
        }
    }

    phaser.arriveAndAwaitAdvance();
}
 
Example 58
Project: printos-device-api-example-java   File: Device.java   Source Code and License 5 votes vote down vote up
public static DeviceInfo create(String aaaPrefix, HttpClient client, String userToken,
                              Properties settings, Properties credentials) throws ParseException, IOException {
  String url = aaaPrefix + "/organizations/devices";
  String pspPassword = credentials.getProperty("psp_password");
  HttpPost post = new HttpPost(url);
  post.addHeader("Cookie", Constants.X_SMS_AUTH_TOKEN + "=" + userToken);

  // Device model and type must match correctly; see etc/devicelist.csv for a list of currently supported
  // combinations.  Note that serial number must be unique, or the same device will get replaced.

  ObjectMapper mapper = new ObjectMapper();
  ObjectNode jsonNode = mapper.createObjectNode();

  String serialNumber = getSerialNumber(settings.getProperty("serial_number"));
  jsonNode.put("name", settings.getProperty("device_name"));
  jsonNode.put("description", settings.getProperty("device_description"));
  jsonNode.put("serialNumber", serialNumber);
  jsonNode.put("model", settings.getProperty("device_model"));
  jsonNode.put("type", settings.getProperty("device_type"));
  jsonNode.put("securityPassword", pspPassword);

  StringEntity entity = new StringEntity(jsonNode.toString());
  post.setEntity(entity);

  HttpResponse response = HttpClientWrapper.executeHttpCommand(client, post);
  if (response != null) {
    String resp = EntityUtils.toString(response.getEntity());

    if (response.getStatusLine().getStatusCode() == 200) {
      JsonParser jp = mapper.getJsonFactory().createJsonParser(resp);
      JsonNode rootNode = mapper.readTree(jp);
      JsonNode node = rootNode.findValue("credentials");
      JsonNode node2 = rootNode.findValue("device");
      String deviceId = node2.findValue("deviceId").getTextValue();

      String deviceLogin = null;
      String devicePassword = null;
      if (node == null || node.findValue("login") == null) {
        System.out.println("Device is marked as non-provisionable, no login/password will be returned.");
      } else {
        deviceLogin = node.findValue("login").getTextValue();
        devicePassword = node.findValue("password").getTextValue();
        System.out.println("device_login=" + deviceLogin);
        System.out.println("device_password=" + devicePassword);
      }

      System.out.println("device_id=" + deviceId);
      System.out.println("Device created successfully.  Remember these values, this is the only time they'll be shown.");
      EntityUtils.consumeQuietly(response.getEntity());
      return new DeviceInfo(deviceLogin, devicePassword, deviceId, serialNumber);

    } else {
      System.out.println("Error executing command.  Does that device already exist?");
      EntityUtils.consumeQuietly(response.getEntity());
      return null;
    }

  } else {
    System.out.println("No response returned from create device");
    return null;
  }
}
 
Example 59
Project: communote-server   File: JsonRequestHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Create a JSON response object
 *
 * @param success
 *            whether a success or error response should be created
 * @param message
 *            the message to put into the response object, can be null
 * @return the JSON
 */
private static ObjectNode createJsonResponse(boolean success, String message) {
    ObjectNode jsonResponse = JsonHelper.getSharedObjectMapper().createObjectNode();
    // using same status values as REST API
    jsonResponse.put("status", success ? "OK" : "ERROR");
    if (message != null) {
        jsonResponse.put("message", message);
    }
    return jsonResponse;
}
 
Example 60
Project: communote-server   File: JsonRequestHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Write a JSON error to the response without throwing exceptions in case of errors.
 *
 * @param response
 *            the response
 * @param errorMessage
 *            the message to send
 */
public static void writeJsonErrorResponseQuietly(HttpServletResponse response, String errorMessage) {
    ObjectNode node = JsonRequestHelper.createJsonErrorResponse(errorMessage);
    try {
        writeJsonResponse(response, node);
    } catch (Exception e) {
        LOGGER.error("Error writing JSON error message {}", errorMessage, e);
    }
}