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   View source code 9 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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;
}