Java Examples for com.googlecode.protobuf.format.JsonFormat

The following java examples will help you to understand the usage of com.googlecode.protobuf.format.JsonFormat. These source code samples are taken from different open source projects.

Example 1
Project: obiba-commons-master  File: JsonIoUtil.java View source code
public static void printCollection(Iterable<? extends Message> messages, Appendable appendable) throws IOException {
    if (messages == null)
        throw new IllegalArgumentException("messages cannot be null");
    if (appendable == null)
        throw new IllegalArgumentException("messages cannot be null");
    // Start the Array
    appendable.append('[');
    boolean first = true;
    for (Message ml : messages) {
        // If this isn't the first item, prepend with a comma
        if (!first)
            appendable.append(',');
        first = false;
        JsonFormat.print(ml, appendable);
    }
    // Close the Array
    appendable.append(']');
}
Example 2
Project: sloot-editor-master  File: UploadToSpritesSlootController.java View source code
private void exportSprites(IPath basePath, IResource resource) throws CoreException, IOException {
    /* Export Entities */
    if (isEntity(resource)) {
        IFile file = (IFile) resource;
        CGEntity cgEntity = CGEntity.parseFrom(file.getContents());
        /* Rewrite fixtures/spritesheet/spritesheetJsonFile path */
        CGEntity.Builder bldr = CGEntity.newBuilder(cgEntity);
        for (CGEntityAnimation.Builder animBldr : bldr.getAnimationsBuilderList()) {
            IPath trimmedBasePath = basePath.removeFirstSegments(basePath.segmentCount() - 1);
            if (!animBldr.getSpritesheetFileBuilder().getResourceFile().isEmpty()) {
                String lastSegmentSpritesheetFile = new Path(animBldr.getSpritesheetFileBuilder().getResourceFile()).lastSegment();
                String rewrittenPath = trimmedBasePath.append(lastSegmentSpritesheetFile).toOSString();
                animBldr.getSpritesheetFileBuilder().setResourceFile(rewrittenPath).setResourceFileAbsolute("");
            }
            if (!animBldr.getSpritesheetJsonFile().getResourceFile().isEmpty()) {
                String lastSegmentSpritesheetJsonFile = new Path(animBldr.getSpritesheetJsonFileBuilder().getResourceFile()).lastSegment();
                String rewrittenPath = trimmedBasePath.append(lastSegmentSpritesheetJsonFile).toOSString();
                animBldr.getSpritesheetJsonFileBuilder().setResourceFile(rewrittenPath).setResourceFileAbsolute("");
            }
            /* For custom collision type */
            if (animBldr.getCollisionType() == CGEntityCollisionType.CUSTOM) {
                String lastSegment = new Path(animBldr.getFixtureFileBuilder().getResourceFile()).lastSegment();
                String rewrittenPath = trimmedBasePath.append(lastSegment).toOSString();
                animBldr.getFixtureFileBuilder().setResourceFile(rewrittenPath).setResourceFileAbsolute("");
            }
        }
        CGEntity modifiedCGEntity = bldr.build();
        /* Step 1 : Generate JSON file and write it to file */
        String json = JsonFormat.printToString(modifiedCGEntity);
        File outputFile = basePath.append(resource.getName()).addFileExtension("json").toFile();
        FileUtils.writeByteArrayToFile(outputFile, json.getBytes());
        /* Step 2 : Generate PNG preview file and write it to file */
        // extract image from
        Entity e = EntityAdapter.asEntity(cgEntity);
        // unmodified information
        Image i = EntitiesUtil.getDefaultFrame(e, 1f);
        String imgOutputFilename = basePath.append(resource.getName()).addFileExtension("png").toOSString();
        ImageLoader il = new ImageLoader();
        il.data = new ImageData[] { i.getImageData() };
        il.save(imgOutputFilename, SWT.IMAGE_PNG);
    }
}
Example 3
Project: MSEC-master  File: RequestDecoder.java View source code
private RpcRequest deserializeHTTPPackage(String request) {
    RpcRequest rpcRequest = new RpcRequest();
    HttpRequestParser httpParser = new HttpRequestParser();
    try {
        httpParser.parseRequest(request);
    } catch (IOException ex) {
        log.error("HTTP Request parse failed." + ex.getMessage());
        rpcRequest.setException(new IllegalArgumentException("Request decode error: HTTP Request parse failed." + ex.getMessage()));
        return rpcRequest;
    } catch (HttpFormatException ex) {
        log.error("HTTP Request parse failed." + ex.getMessage());
        rpcRequest.setException(new IllegalArgumentException("Request decode error: HTTP Request parse failed." + ex.getMessage()));
        return rpcRequest;
    }
    rpcRequest.setHttpCgiName(httpParser.getCgiPath());
    if (httpParser.getCgiPath().compareToIgnoreCase("/list") == 0) {
        return rpcRequest;
    }
    if (httpParser.getCgiPath().compareToIgnoreCase("/invoke") != 0) {
        log.error("HTTP cgi not found: " + httpParser.getCgiPath());
        rpcRequest.setException(new IllegalArgumentException("HTTP cgi not found: " + httpParser.getURI()));
        return rpcRequest;
    }
    String serviceMethodName = httpParser.getQueryString("methodName");
    int pos = serviceMethodName.lastIndexOf('.');
    if (pos == -1 || pos == 0 || pos == serviceMethodName.length() - 1) {
        log.error("Invalid serviceMethodName (" + serviceMethodName + "). Must be in format like *.*");
        rpcRequest.setException(new IllegalArgumentException("Invalid serviceMethodName (" + serviceMethodName + "). Must be in format like *.*"));
        return rpcRequest;
    }
    String serviceName = serviceMethodName.substring(0, pos);
    String methodName = serviceMethodName.substring(pos + 1);
    String seq = httpParser.getQueryString("seq");
    String param = httpParser.getQueryString("param");
    if (param == null || param.isEmpty()) {
        param = httpParser.getMessageBody();
    }
    try {
        param = java.net.URLDecoder.decode(param, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        param = "";
    }
    rpcRequest.setServiceName(serviceName);
    rpcRequest.setMethodName(methodName);
    if (seq == null || seq.isEmpty()) {
        rpcRequest.setSeq(ServiceFactory.generateSequence());
    } else {
        rpcRequest.setSeq(Long.valueOf(seq).longValue());
    }
    log.info("In HTTP package service: " + serviceName + " method: " + methodName + " param: " + param);
    rpcRequest.setFromModule("UnknownModule");
    rpcRequest.setFlowid(rpcRequest.getSeq() ^ NettyCodecUtils.generateColorId(serviceName + methodName));
    AccessMonitor.add("frm.rpc request incoming: " + methodName);
    ServiceFactory.ServiceMethodEntry serviceMethodEntry = ServiceFactory.getServiceMethodEntry(serviceName, methodName);
    if (serviceMethodEntry == null) {
        log.error("No service method registered: " + rpcRequest.getServiceName() + "/" + rpcRequest.getMethodName());
        rpcRequest.setException(new IllegalArgumentException("No service method registered: " + rpcRequest.getServiceName() + "/" + rpcRequest.getMethodName()));
        return rpcRequest;
    }
    Message.Builder builder = serviceMethodEntry.getParamTypeBuilder();
    try {
        builder.clear();
        JsonFormat.merge(param, builder);
    } catch (JsonFormat.ParseException ex) {
        log.error("Json parse failed." + ex.getMessage());
        rpcRequest.setException(new IllegalArgumentException("Request decode error: Json parse failed." + ex.getMessage()));
        return rpcRequest;
    }
    if (!builder.isInitialized()) {
        log.error("Json to Protobuf failed: missing required fields");
        rpcRequest.setException(new IllegalArgumentException("Json to Protobuf failed: missing required fields: " + builder.getInitializationErrorString()));
        return rpcRequest;
    }
    rpcRequest.setParameter(builder.build());
    log.info("RPC Request received. ServiceMethodName: " + rpcRequest.getServiceName() + "/" + rpcRequest.getMethodName() + "\tSeq: " + rpcRequest.getSeq() + "\tParameter: " + rpcRequest.getParameter());
    return rpcRequest;
}
Example 4
Project: iis-master  File: ImportInformationSpaceReducerTest.java View source code
@Test
public void testReduceResultWithRelations() throws Exception {
    // given
    Configuration conf = setOutputDirs(new Configuration());
    doReturn(conf).when(context).getConfiguration();
    reducer.setup(context);
    String resultId = "resultId";
    String id = InfoSpaceConstants.ROW_PREFIX_RESULT + resultId;
    Text key = new Text(id);
    InfoSpaceRecord bodyRecord = new InfoSpaceRecord(new Text(Type.result.name()), new Text(OafBodyWithOrderedUpdates.BODY_QUALIFIER_NAME), new Text(JsonFormat.printToString(buildResultEntity(resultId))));
    String updatedPublisher = "updated publisher";
    InfoSpaceRecord updateRecord = new InfoSpaceRecord(new Text(Type.result.name()), new Text("update"), new Text(JsonFormat.printToString(buildResultEntity(resultId, updatedPublisher, false))));
    String projectId = "projectId";
    InfoSpaceRecord resProjRelRecord = new InfoSpaceRecord(new Text(reducer.resProjColumnFamily), new Text("resProjQualifier"), new Text(JsonFormat.printToString(buildRel(resultId, projectId))));
    String dedupedId = "dedupedId";
    InfoSpaceRecord dedupMappingRelRecord = new InfoSpaceRecord(new Text(reducer.dedupMappingColumnFamily), new Text("dedupQualifier"), new Text(JsonFormat.printToString(buildRel(resultId, dedupedId))));
    List<InfoSpaceRecord> values = Lists.newArrayList(bodyRecord, updateRecord, resProjRelRecord, dedupMappingRelRecord);
    // execute
    reducer.reduce(key, values, context);
    // assert
    verify(context, never()).write(any(), any());
    verify(multipleOutputs, times(3)).write(mosKeyCaptor.capture(), mosValueCaptor.capture());
    // doc meta
    assertEquals(conf.get(OUTPUT_NAME_DOCUMENT_META), mosKeyCaptor.getAllValues().get(0));
    DocumentMetadata docMeta = (DocumentMetadata) mosValueCaptor.getAllValues().get(0).datum();
    assertNotNull(docMeta);
    assertEquals(resultId, docMeta.getId());
    assertEquals(PUBLISHER_DEFAULT, docMeta.getPublisher());
    // result project rel
    assertEquals(conf.get(OUTPUT_NAME_DOCUMENT_PROJECT), mosKeyCaptor.getAllValues().get(1));
    DocumentToProject docProjRel = (DocumentToProject) mosValueCaptor.getAllValues().get(1).datum();
    assertNotNull(docProjRel);
    assertEquals(resultId, docProjRel.getDocumentId());
    assertEquals(projectId, docProjRel.getProjectId());
    // dedup mapping rel
    assertEquals(conf.get(OUTPUT_NAME_DEDUP_MAPPING), mosKeyCaptor.getAllValues().get(2));
    IdentifierMapping dedupMappingRel = (IdentifierMapping) mosValueCaptor.getAllValues().get(2).datum();
    assertNotNull(dedupMappingRel);
    assertEquals(dedupedId, dedupMappingRel.getOriginalId());
    assertEquals(resultId, dedupMappingRel.getNewId());
}
Example 5
Project: spring4-1-showcase-master  File: ProtobufHttpMessageConverter.java View source code
@Override
protected Message readInternal(Class<? extends Message> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    MediaType contentType = inputMessage.getHeaders().getContentType();
    contentType = (contentType != null ? contentType : PROTOBUF);
    Charset charset = getCharset(inputMessage.getHeaders());
    InputStreamReader reader = new InputStreamReader(inputMessage.getBody(), charset);
    try {
        Message.Builder builder = getMessageBuilder(clazz);
        if (MediaType.APPLICATION_JSON.isCompatibleWith(contentType)) {
            JsonFormat.merge(reader, this.extensionRegistry, builder);
        } else if (MediaType.TEXT_PLAIN.isCompatibleWith(contentType)) {
            TextFormat.merge(reader, this.extensionRegistry, builder);
        } else if (MediaType.APPLICATION_XML.isCompatibleWith(contentType)) {
            XmlFormat.merge(reader, this.extensionRegistry, builder);
        } else {
            builder.mergeFrom(inputMessage.getBody(), this.extensionRegistry);
        }
        return builder.build();
    } catch (Exception e) {
        throw new HttpMessageNotReadableException("Could not read Protobuf message: " + e.getMessage(), e);
    }
}
Example 6
Project: ja-micro-master  File: ProtobufUtil.java View source code
public static <TYPE extends Message> TYPE jsonToProtobuf(String request, Class<TYPE> messageClass) {
    if (request == null) {
        return null;
    } else if ("{}".equals(request)) {
        try {
            TYPE.Builder builder = getBuilder(messageClass);
            return (TYPE) builder.getDefaultInstanceForType();
        } catch (Exception e) {
            logger.warn("Error building protobuf object of type {} from json: {}", messageClass.getName(), request);
        }
    }
    try {
        TYPE.Builder builder = getBuilder(messageClass);
        JsonFormat formatter = new JsonFormat();
        try {
            ByteArrayInputStream stream = new ByteArrayInputStream(request.getBytes());
            formatter.merge(stream, builder);
        } catch (IOException e) {
            logger.warn("Error building protobuf object of type {} from json: {}", messageClass.getName(), request);
        }
        return (TYPE) builder.build();
    } catch (Exception e) {
        throw new RuntimeException("Error deserializing json to protobuf", e);
    }
}
Example 7
Project: config-protobuf-spring-java-master  File: AbstractConfigProvider.java View source code
protected Message.Builder populateJsonMessage(Message.Builder builder, InputStream data) throws Exception {
    JsonFormat.merge(new InputStreamReader(data), builder);
    return builder;
}