private static void writeMatrix(Matrix4d matrix, JsonGenerator jg) {
   jg.writeStartArray("matrix");
   for (int i = 0; i < 4; i++) {
     for (int j = 0; j < 4; j++) {
       jg.write(matrix.getElement(i, j));
     }
   }
   jg.writeEnd();
 }
 private static void writeAttributes(List<InstanceAttributeDTO> attributes, JsonGenerator jg) {
   jg.writeStartArray("attributes");
   for (InstanceAttributeDTO a : attributes) {
     jg.writeStartObject();
     jg.write("name", a.getName());
     jg.write("type", a.getType().toString());
     jg.write("value", a.getValue());
     jg.writeEnd();
   }
   jg.writeEnd();
 }
예제 #3
0
  @POST
  @Path("entityManager")
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  @Produces(MediaType.APPLICATION_JSON)
  public String create(@FormParam("sessionId") String sessionId, @FormParam("entities") String json)
      throws IcatException {
    List<EntityBaseBean> entities = new ArrayList<>();

    try (JsonParser parser = Json.createParser(new ByteArrayInputStream(json.getBytes()))) {
      EventChecker checker = new EventChecker(parser);
      checker.get(Event.START_ARRAY);
      while (true) {
        Event event = checker.get(Event.START_OBJECT, Event.END_ARRAY);
        if (event == Event.END_ARRAY) {
          break;
        }
        checker.get(Event.KEY_NAME);
        String entityName = parser.getString();
        checker.get(Event.START_OBJECT);
        entities.add(parseEntity(checker, entityName));
        checker.get(Event.END_OBJECT);
      }
    } catch (JsonException e) {
      throw new IcatException(IcatExceptionType.INTERNAL, e.getMessage());
    }
    String userName = beanManager.getUserName(sessionId, manager);

    List<CreateResponse> createResponses =
        beanManager.createMany(userName, entities, manager, userTransaction);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (JsonGenerator gen = Json.createGenerator(baos)) {
      gen.writeStartArray();
      for (CreateResponse createResponse : createResponses) {
        transmitter.processMessage(createResponse.getNotificationMessage());
        gen.write(createResponse.getPk());
      }
      gen.writeEnd();
    } catch (JMSException e) {
      throw new IcatException(
          IcatException.IcatExceptionType.INTERNAL, e.getClass() + " " + e.getMessage());
    }
    return baos.toString();
  }
  public String toJsonString() {
    assert analysis.hasBeenPerformed;

    if (jsonString != null) {
      return jsonString;
    }
    if (json == null) {
      toJson(); // Caches the result in `json`.
      assert json != null;
    }

    StringWriter writer = new StringWriter();
    JsonGenerator generator = jsonGeneratorFactory.createGenerator(writer);
    generator.writeStartArray();
    generator.write(json);
    generator.writeEnd();
    generator.close();
    return writer.toString();
  }
  private static void writeGeometries(List<Geometry> files, JsonGenerator jg) {
    jg.write("qualities", files.size());

    if (!files.isEmpty()) {
      Geometry geometry = files.get(0);
      jg.write("xMin", geometry.getxMin());
      jg.write("yMin", geometry.getyMin());
      jg.write("zMin", geometry.getzMin());
      jg.write("xMax", geometry.getxMax());
      jg.write("yMax", geometry.getyMax());
      jg.write("zMax", geometry.getzMax());
    }

    jg.writeStartArray("files");

    for (Geometry g : files) {
      jg.writeStartObject();
      jg.write("fullName", "api/files/" + g.getFullName());
      jg.writeEnd();
    }
    jg.writeEnd();
  }
예제 #6
0
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   String query = req.getParameter("q");
   long id = Long.parseLong(req.getParameter("id"));
   Set<String> tags;
   try {
     tags = TagExtractor.findMatching(query, id);
   } catch (SQLException e) {
     e.printStackTrace();
     return;
   }
   try (OutputStream os = resp.getOutputStream()) {
     try (final JsonGenerator generator = Json.createGenerator(os)) {
       generator.writeStartArray();
       for (String s : tags) {
         generator.writeStartObject();
         generator.write("value", s);
         generator.writeEnd();
       }
       generator.writeEnd();
     }
   }
 }
예제 #7
0
  private void jsonise(EntityBaseBean bean, JsonGenerator gen) throws IcatException {

    gen.write("id", bean.getId())
        .write("createId", bean.getCreateId())
        .write("createTime", bean.getCreateTime().toString())
        .write("modId", bean.getModId())
        .write("modTime", bean.getModTime().toString());

    Class<? extends EntityBaseBean> klass = bean.getClass();
    Map<Field, Method> getters = eiHandler.getGetters(klass);
    Set<Field> atts = eiHandler.getAttributes(klass);
    Set<Field> updaters = eiHandler.getSettersForUpdate(klass).keySet();

    for (Field field : eiHandler.getFields(klass)) {
      Object value = null;
      try {
        value = getters.get(field).invoke(bean);
      } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        throw new IcatException(IcatExceptionType.INTERNAL, e.getClass() + " " + e.getMessage());
      }
      if (value == null) {
        // Ignore null values
      } else if (atts.contains(field)) {
        String type = field.getType().getSimpleName();
        if (type.equals("String")) {
          gen.write(field.getName(), (String) value);
        } else if (type.equals("Integer")) {
          gen.write(field.getName(), value.toString());
        } else if (type.equals("Double")) {
          gen.write(field.getName(), value.toString());
        } else if (type.equals("Long")) {
          gen.write(field.getName(), value.toString());
        } else if (type.equals("boolean")) {
          gen.write(field.getName(), value.toString());
        } else if (field.getType().isEnum()) {
          gen.write(field.getName(), value.toString());
        } else if (type.equals("Date")) {
          synchronized (df8601) {
            gen.write(field.getName(), df8601.format((Date) value));
          }
        } else {
          throw new IcatException(
              IcatExceptionType.INTERNAL, "Don't know how to jsonise field of type " + type);
        }
      } else if (updaters.contains(field)) {
        gen.writeStartObject(field.getName());
        jsonise((EntityBaseBean) value, gen);
        gen.writeEnd();
      } else {
        gen.writeStartArray(field.getName());
        @SuppressWarnings("unchecked")
        List<EntityBaseBean> beans = (List<EntityBaseBean>) value;
        for (EntityBaseBean b : beans) {
          gen.writeStartObject();
          jsonise(b, gen);
          gen.writeEnd();
        }
        gen.writeEnd();
      }
    }
  }
예제 #8
0
  @GET
  @Path("entityManager")
  @Produces(MediaType.APPLICATION_JSON)
  public String search(
      @QueryParam("sessionId") String sessionId,
      @QueryParam("query") String query,
      @QueryParam("id") Long id)
      throws IcatException {

    if (sessionId == null) {
      throw new IcatException(IcatExceptionType.BAD_PARAMETER, "sessionId is not set");
    }
    if (query == null) {
      throw new IcatException(IcatExceptionType.BAD_PARAMETER, "query is not set");
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JsonGenerator gen = Json.createGenerator(baos);

    String userName = beanManager.getUserName(sessionId, manager);
    if (id == null) {
      gen.writeStartArray();

      for (Object result : beanManager.search(userName, query, manager, userTransaction)) {
        if (result == null) {
          gen.writeNull();
        } else if (result instanceof EntityBaseBean) {
          gen.writeStartObject();
          gen.writeStartObject(result.getClass().getSimpleName());
          jsonise((EntityBaseBean) result, gen);
          gen.writeEnd();
          gen.writeEnd();
        } else if (result instanceof Long) {
          gen.write((Long) result);
        } else if (result instanceof Double) {
          if (Double.isNaN((double) result)) {
            gen.writeNull();
          } else {
            gen.write((Double) result);
          }
        } else if (result instanceof String) {
          gen.write((String) result);
        } else if (result instanceof Boolean) {
          gen.write((Boolean) result);
        } else {
          throw new IcatException(
              IcatException.IcatExceptionType.INTERNAL,
              "Don't know how to jsonise " + result.getClass());
        }
      }

      gen.writeEnd();
    } else {
      EntityBaseBean result = beanManager.get(userName, query, id, manager, userTransaction);
      gen.writeStartObject();
      gen.writeStartObject(result.getClass().getSimpleName());
      jsonise(result, gen);
      gen.writeEnd();
      gen.writeEnd();
    }

    gen.close();
    return baos.toString();
  }
  private void generateJSONResponse(OutputStream outputStream, QueryResult queryResult)
      throws UnsupportedEncodingException, NamingException {

    String charSet = "UTF-8";
    JsonGenerator jg = Json.createGenerator(new OutputStreamWriter(outputStream, charSet));
    jg.writeStartArray();

    List<String> selects = queryResult.getQuery().getSelects();
    List<String> partIterationSelectedAttributes = getPartIterationSelectedAttributes(selects);
    List<String> pathDataSelectedAttributes = getPathDataSelectedAttributes(selects);

    context = new InitialContext();
    IProductInstanceManagerLocal productInstanceService =
        (IProductInstanceManagerLocal)
            context.lookup(
                "java:global/docdoku-server-ear/docdoku-server-ejb/ProductInstanceManagerBean");

    for (QueryResultRow row : queryResult.getRows()) {

      QueryContext queryContext = row.getContext();

      PartRevision part = row.getPartRevision();
      PartIteration lastCheckedInIteration = part.getLastCheckedInIteration();

      jg.writeStartObject();

      jg.write(QueryField.PART_REVISION_PART_KEY, part.getPartNumber() + '-' + part.getVersion());

      // PartMaster data

      if (selects.contains(QueryField.PART_MASTER_NUMBER)) {
        jg.write(QueryField.PART_MASTER_NUMBER, part.getPartNumber());
      }

      if (selects.contains(QueryField.PART_MASTER_NAME)) {
        String sName = part.getPartName();
        jg.write(QueryField.PART_MASTER_NAME, sName != null ? sName : "");
      }

      if (selects.contains(QueryField.PART_MASTER_TYPE)) {
        String sType = part.getType();
        jg.write(QueryField.PART_MASTER_TYPE, sType != null ? sType : "");
      }

      // PartRevision data

      if (selects.contains(QueryField.PART_REVISION_MODIFICATION_DATE)) {
        PartIteration pi = part.getLastIteration();
        if (pi != null) {
          writeDate(jg, QueryField.PART_REVISION_MODIFICATION_DATE, pi.getModificationDate());
        }
      }

      if (selects.contains(QueryField.PART_REVISION_CREATION_DATE)) {
        writeDate(jg, QueryField.PART_REVISION_CREATION_DATE, part.getCreationDate());
      }

      if (selects.contains(QueryField.PART_REVISION_CHECKOUT_DATE)) {
        writeDate(jg, QueryField.PART_REVISION_CHECKOUT_DATE, part.getCheckOutDate());
      }

      if (selects.contains(QueryField.PART_REVISION_CHECKIN_DATE)) {
        writeDate(
            jg,
            QueryField.PART_REVISION_CHECKIN_DATE,
            lastCheckedInIteration != null ? lastCheckedInIteration.getCheckInDate() : null);
      }

      if (selects.contains(QueryField.PART_REVISION_VERSION)) {
        String version = part.getVersion();
        jg.write(QueryField.PART_REVISION_VERSION, version);
      }

      if (selects.contains(QueryField.PART_REVISION_LIFECYCLE_STATE)) {
        String lifeCycleState = part.getLifeCycleState();
        jg.write(
            QueryField.PART_REVISION_LIFECYCLE_STATE, lifeCycleState != null ? lifeCycleState : "");
      }

      if (selects.contains(QueryField.PART_REVISION_STATUS)) {
        PartRevision.RevisionStatus status = part.getStatus();
        jg.write(QueryField.PART_REVISION_STATUS, status.toString());
      }

      if (selects.contains(QueryField.AUTHOR_LOGIN)) {
        User user = part.getAuthor();
        jg.write(QueryField.AUTHOR_LOGIN, user.getLogin());
      }

      if (selects.contains(QueryField.AUTHOR_NAME)) {
        User user = part.getAuthor();
        jg.write(QueryField.AUTHOR_NAME, user.getName());
      }

      if (selects.contains(QueryField.CTX_DEPTH)) {
        jg.write(QueryField.CTX_DEPTH, row.getDepth());
      }

      if (selects.contains(QueryField.PART_ITERATION_LINKED_DOCUMENTS)) {

        StringBuilder sb = new StringBuilder();

        if (null != queryContext && null != queryContext.getSerialNumber()) {
          try {

            ProductInstanceMaster productInstanceMaster =
                productInstanceService.getProductInstanceMaster(
                    new ProductInstanceMasterKey(
                        queryContext.getSerialNumber(),
                        queryContext.getWorkspaceId(),
                        queryContext.getConfigurationItemId()));
            ProductInstanceIteration lastIteration = productInstanceMaster.getLastIteration();
            ProductBaseline basedOn = lastIteration.getBasedOn();
            PartCollection partCollection = basedOn.getPartCollection();
            BaselinedPart baselinedPart =
                partCollection.getBaselinedPart(
                    new BaselinedPartKey(
                        partCollection.getId(),
                        queryContext.getWorkspaceId(),
                        part.getPartNumber()));
            PartIteration targetPart = baselinedPart.getTargetPart();
            Set<DocumentLink> linkedDocuments = targetPart.getLinkedDocuments();
            DocumentCollection documentCollection = basedOn.getDocumentCollection();

            for (DocumentLink documentLink : linkedDocuments) {
              DocumentRevision targetDocument = documentLink.getTargetDocument();
              BaselinedDocument baselinedDocument =
                  documentCollection.getBaselinedDocument(
                      new BaselinedDocumentKey(
                          documentCollection.getId(),
                          queryContext.getWorkspaceId(),
                          targetDocument.getDocumentMasterId(),
                          targetDocument.getVersion()));
              if (null != baselinedDocument) {
                DocumentIteration targetDocumentIteration = baselinedDocument.getTargetDocument();
                sb.append(targetDocumentIteration.toString() + ",");
              }
            }

          } catch (UserNotFoundException
              | UserNotActiveException
              | WorkspaceNotFoundException
              | ProductInstanceMasterNotFoundException e) {
            LOGGER.log(Level.FINEST, null, e);
          }
        } else {
          if (lastCheckedInIteration != null) {
            Set<DocumentLink> linkedDocuments = lastCheckedInIteration.getLinkedDocuments();

            for (DocumentLink documentLink : linkedDocuments) {
              DocumentRevision targetDocument = documentLink.getTargetDocument();
              DocumentIteration targetDocumentLastCheckedInIteration =
                  targetDocument.getLastCheckedInIteration();
              if (targetDocumentLastCheckedInIteration != null) {
                sb.append(targetDocumentLastCheckedInIteration.toString() + ",");
              }
            }
          }
        }

        jg.write(QueryField.PART_ITERATION_LINKED_DOCUMENTS, sb.toString());
      }

      for (String attributeSelect : partIterationSelectedAttributes) {

        String attributeSelectType =
            attributeSelect
                .substring(0, attributeSelect.indexOf("."))
                .substring(QueryField.PART_REVISION_ATTRIBUTES_PREFIX.length());

        String attributeSelectName = attributeSelect.substring(attributeSelect.indexOf(".") + 1);

        String attributeValue = "";

        PartIteration pi = part.getLastIteration();

        if (pi != null) {
          List<InstanceAttribute> attributes = pi.getInstanceAttributes();

          if (attributes != null) {
            jg.writeStartArray(attributeSelect);

            for (InstanceAttribute attribute : attributes) {
              InstanceAttributeDescriptor attributeDescriptor =
                  new InstanceAttributeDescriptor(attribute);

              if (attributeDescriptor.getName().equals(attributeSelectName)
                  && attributeDescriptor.getStringType().equals(attributeSelectType)) {

                attributeValue = attribute.getValue() + "";

                if (attribute instanceof InstanceDateAttribute) {
                  attributeValue =
                      getFormattedDate(((InstanceDateAttribute) attribute).getDateValue());
                } else if (attribute instanceof InstanceListOfValuesAttribute) {
                  attributeValue = ((InstanceListOfValuesAttribute) attribute).getSelectedName();
                }

                jg.write(attributeValue);
              }
            }

            jg.writeEnd();

          } else {
            jg.write(attributeSelect, attributeValue);
          }

        } else {
          // TODO: maybe this line is useless and should be removed
          jg.write(attributeSelect, attributeValue);
        }
      }

      for (String attributeSelect : pathDataSelectedAttributes) {

        String attributeSelectType =
            attributeSelect
                .substring(0, attributeSelect.indexOf("."))
                .substring(QueryField.PATH_DATA_ATTRIBUTES_PREFIX.length());

        String attributeSelectName = attributeSelect.substring(attributeSelect.indexOf(".") + 1);

        String attributeValue = "";

        PathDataIteration pdi = row.getPathDataIteration();

        if (pdi != null) {
          List<InstanceAttribute> attributes = pdi.getInstanceAttributes();

          if (attributes != null) {
            jg.writeStartArray(attributeSelect);

            for (InstanceAttribute attribute : attributes) {
              InstanceAttributeDescriptor attributeDescriptor =
                  new InstanceAttributeDescriptor(attribute);

              if (attributeDescriptor.getName().equals(attributeSelectName)
                  && attributeDescriptor.getStringType().equals(attributeSelectType)) {

                attributeValue = attribute.getValue() + "";

                if (attribute instanceof InstanceDateAttribute) {
                  attributeValue =
                      getFormattedDate(((InstanceDateAttribute) attribute).getDateValue());
                } else if (attribute instanceof InstanceListOfValuesAttribute) {
                  attributeValue = ((InstanceListOfValuesAttribute) attribute).getSelectedName();
                }

                jg.write(attributeValue);
              }
            }

            jg.writeEnd();

          } else {
            jg.write(attributeSelect, attributeValue);
          }
        }
      }

      if (selects.contains(QueryField.CTX_PRODUCT_ID)) {
        String configurationItemId =
            queryContext != null ? queryContext.getConfigurationItemId() : "";
        jg.write(QueryField.CTX_PRODUCT_ID, configurationItemId);
      }
      if (selects.contains(QueryField.CTX_SERIAL_NUMBER)) {
        String serialNumber = queryContext != null ? queryContext.getSerialNumber() : "";
        jg.write(QueryField.CTX_SERIAL_NUMBER, serialNumber != null ? serialNumber : "");
      }
      if (selects.contains(QueryField.CTX_AMOUNT)) {
        String amount = row.getAmount() + "";
        jg.write(QueryField.CTX_AMOUNT, amount);
      }

      if (selects.contains(QueryField.CTX_P2P_SOURCE)) {
        Map<String, List<PartLinkList>> sources = row.getSources();
        String partLinksAsString = Tools.getPartLinksAsHumanString(sources);
        jg.write(QueryField.CTX_P2P_SOURCE, partLinksAsString);
      }

      if (selects.contains(QueryField.CTX_P2P_TARGET)) {
        Map<String, List<PartLinkList>> targets = row.getTargets();
        String partLinksAsString = Tools.getPartLinksAsHumanString(targets);
        jg.write(QueryField.CTX_P2P_TARGET, partLinksAsString);
      }

      if (selects.contains(QueryField.PART_MASTER_IS_STANDARD)) {
        boolean isStandard = row.getPartRevision().getPartMaster().isStandardPart();
        jg.write(QueryField.PART_MASTER_IS_STANDARD, isStandard);
      }

      jg.writeEnd();
    }

    jg.writeEnd();
    jg.flush();
  }