Exemplo n.º 1
0
    public void toJson(JsonGenerator gen) throws IOException {
      gen.writeStartObject();

      gen.writeBooleanField("old", oldRecordExists);
      gen.writeBooleanField("new", newRecordExists);
      gen.writeBooleanField("includeSubscriptions", includeSubscriptions);

      if (newRecordType != null) {
        gen.writeBinaryField("newRecordType", newRecordType.getBytes());
      }

      if (oldRecordType != null) {
        gen.writeBinaryField("oldRecordType", oldRecordType.getBytes());
      }

      if (fieldChanges != null) {
        gen.writeArrayFieldStart("fields");

        for (FieldChange fieldChange : fieldChanges) {
          fieldChange.toJson(gen);
        }

        gen.writeEndArray();
      }

      if (indexSubscriptionIds != null) {
        gen.writeArrayFieldStart("subscriptions");
        for (String subscriptionId : indexSubscriptionIds) {
          gen.writeString(subscriptionId);
        }
        gen.writeEndArray();
      }

      gen.writeEndObject();
    }
Exemplo n.º 2
0
  public void toJson(JsonGenerator gen) throws IOException {

    gen.writeStartObject();

    if (type != null) {
      gen.writeStringField("type", type.getName());
    }

    if (tableName != null) {
      gen.writeStringField("tableName", tableName);
    }

    if (versionUpdated != -1) {
      gen.writeNumberField("versionUpdated", versionUpdated);
    }

    if (versionCreated != -1) {
      gen.writeNumberField("versionCreated", versionCreated);
    }

    if (recordTypeChanged) {
      gen.writeBooleanField("recordTypeChanged", true);
    }

    if (updatedFields != null && updatedFields.size() > 0) {
      gen.writeArrayFieldStart("updatedFields");
      for (SchemaId updatedField : updatedFields) {
        gen.writeBinary(updatedField.getBytes());
      }
      gen.writeEndArray();
    }

    if (vtagsToIndex != null && vtagsToIndex.size() > 0) {
      gen.writeArrayFieldStart("vtagsToIndex");
      for (SchemaId vtag : vtagsToIndex) {
        gen.writeBinary(vtag.getBytes());
      }
      gen.writeEndArray();
    }

    if (attributes != null && attributes.size() > 0) {
      gen.writeObjectFieldStart("attributes");
      for (String key : attributes.keySet()) {
        gen.writeStringField(key, attributes.get(key));
      }
      gen.writeEndObject();
    }

    if (indexRecordFilterData != null) {
      gen.writeFieldName("indexFilterData");
      indexRecordFilterData.toJson(gen);
    }

    gen.writeEndObject();
    gen.flush();
  }
Exemplo n.º 3
0
  void toJson(JsonGenerator gen) throws IOException {
    gen.writeStartObject();
    gen.writeArrayFieldStart("sourceSchemas");
    for (Schema schema : schemas) {
      schema.toJson(gen);
    }
    gen.writeEndArray();
    gen.writeObjectFieldStart("fieldAliases");
    for (Map.Entry<String, Map<String, String>> entry : schemaFieldAliases.entrySet()) {
      String schemaName = entry.getKey();
      Map<String, String> aliases = entry.getValue();
      gen.writeObjectField(schemaName, aliases);
    }
    gen.writeEndObject();

    gen.writeArrayFieldStart("groupByFields");
    for (String field : groupByFields) {
      gen.writeString(field);
    }
    gen.writeEndArray();

    if (customPartitionFields != null && !customPartitionFields.isEmpty()) {
      gen.writeArrayFieldStart("customPartitionFields");
      for (String field : customPartitionFields) {
        gen.writeString(field);
      }
      gen.writeEndArray();
    }

    if (rollupFrom != null) {
      gen.writeFieldName("rollupFrom");
      gen.writeString(rollupFrom);
    }

    gen.writeFieldName("commonOrderBy");
    commonCriteria.toJson(gen);

    gen.writeStringField("schemasOrder", schemasOrder.toString());

    // TODO this code should write a map with sourceName
    if (specificCriterias == null || specificCriterias.isEmpty()) {
      initSecondaryCriteriasWithNull();
    }
    gen.writeArrayFieldStart("specificOrderBys");
    for (Criteria c : specificCriterias) {
      if (c == null) {
        gen.writeNull();
      } else {
        c.toJson(gen);
      }
    }
    gen.writeEndArray();
    gen.writeEndObject();
  }
Exemplo n.º 4
0
 @Override
 public void onLoadEnd() throws OseeCoreException {
   super.onLoadEnd();
   try {
     if (wasStarted) {
       writer.writeEndArray();
       writer.writeEndObject();
     }
     writer.writeEndArray();
   } catch (IOException ex) {
     throw new OseeCoreException(ex);
   }
 }
 @SuppressWarnings({"unchecked"})
 @Override
 public void serialize(
     final Object value, final JsonGenerator jgen, final SerializerProvider provider)
     throws IOException, JsonGenerationException {
   if (null == value) {
     provider.defaultSerializeNull(jgen);
   } else {
     Class<?> type = value.getClass();
     if (ClassUtils.isAssignable(type, Collection.class)) {
       jgen.writeStartArray();
       for (Object o : (Collection) value) {
         write(o, jgen, provider);
       }
       jgen.writeEndArray();
     } else if (ClassUtils.isAssignable(type, Map.class)) {
       jgen.writeStartObject();
       for (Map.Entry<String, Object> entry : ((Map<String, Object>) value).entrySet()) {
         jgen.writeFieldName(entry.getKey());
         write(entry.getValue(), jgen, provider);
       }
       jgen.writeEndObject();
     } else {
       write(value, jgen, provider);
     }
   }
 }
Exemplo n.º 6
0
  private static void writeTrace(
      final Trace trace, final int traceId, final JsonGenerator generator) throws IOException {
    generator.writeStartObject();
    generator.writeNumberField(JsonTraceCodec.TRACE_ID, traceId);
    generator.writeStringField(JsonTraceCodec.TRACE_NAME, trace.getName());
    generator.writeStringField(JsonTraceCodec.TRACE_RESULT_TYPE, trace.getResultType().toString());
    generator.writeBooleanField(JsonTraceCodec.TRACE_HIDDEN, trace.getHidden());
    generator.writeBooleanField(JsonTraceCodec.TRACE_SYSTEM_HIDDEN, trace.getSystemHidden());

    if (trace.getValue() != null) {
      generator.writeStringField(JsonTraceCodec.TRACE_VALUE, trace.getValue());
    }

    if (trace.getStartNanos() != null) {
      generator.writeNumberField(JsonTraceCodec.TRACE_START_NANOS, trace.getStartNanos());
    }

    if (trace.getEndNanos() != null) {
      generator.writeNumberField(JsonTraceCodec.TRACE_END_NANOS, trace.getEndNanos());
    }

    if (trace.getAttributes() != null && trace.getAttributes().size() > 0) {
      generator.writeArrayFieldStart(JsonTraceCodec.TRACE_ATTRIBUTES);
      for (Map.Entry<String, String> attribute : trace.getAttributes().entrySet()) {
        generator.writeStartObject();
        generator.writeStringField(JsonTraceCodec.TRACE_ATTRIBUTE_KEY, attribute.getKey());
        generator.writeStringField(JsonTraceCodec.TRACE_ATTRIBUTE_VALUE, attribute.getValue());
        generator.writeEndObject();
      }
      generator.writeEndArray();
    }

    generator.writeEndObject();
  }
 @Override
 public void appendTo(JsonGenerator generator) throws IOException {
   generator.writeStartArray();
   generator.writeString(this.bucket);
   generator.writeString(this.key);
   appendKeyData(generator);
   generator.writeEndArray();
 }
    @Override
    public void serialize(
        SimpleEvaluationObject value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {

      synchronized (value) {
        String id = getUpdateManager().register(value);
        jgen.writeStartObject();
        jgen.writeObjectField("type", "SimpleEvaluationObject");
        jgen.writeStringField("update_id", id);
        jgen.writeStringField("expression", value.getExpression());
        jgen.writeObjectField("status", value.getStatus());
        if (value.getMessage() != null) jgen.writeStringField("message", value.getMessage());
        if (value.getProgressBar() > 0)
          jgen.writeNumberField("progressBar", value.getProgressBar());
        if (value.getPayloadChanged()) {
          EvaluationResult o = value.getPayload();
          if (o != null && o.getValue() != null) {
            jgen.writeFieldName("payload");
            if (!getObjectSerializer().writeObject(o, jgen, true)) jgen.writeObject(o.toString());
          } else if (value.getJsonRes() != null) {
            jgen.writeFieldName("payload");
            if (ControlCharacterUtils.containsControlCharacters(value.getJsonRes())) {
              jgen.writeRawValue(ControlCharacterUtils.escapeControlCharacters(value.getJsonRes()));
            } else {
              jgen.writeRawValue(value.getJsonRes());
            }
          }
        }
        if (value.getJsonRes() != null
            && value.getPayload() != null
            && value.getPayload().getValue() != null) {
          logger.trace("adding raw json data: '" + value.getJsonRes() + "'");
          jgen.writeFieldName("jsonres");
          if (ControlCharacterUtils.containsControlCharacters(value.getJsonRes())) {
            jgen.writeRawValue(ControlCharacterUtils.escapeControlCharacters(value.getJsonRes()));
          } else {
            jgen.writeRawValue(value.getJsonRes());
          }
        }
        jgen.writeArrayFieldStart("outputdata");
        for (Object o : value.getOutputdata()) {
          if (o instanceof EvaluationStdOutput) {
            jgen.writeStartObject();
            jgen.writeStringField("type", "out");
            jgen.writeStringField("value", ((EvaluationStdOutput) o).payload);
            jgen.writeEndObject();
          } else if (o instanceof EvaluationStdError) {
            jgen.writeStartObject();
            jgen.writeStringField("type", "err");
            jgen.writeStringField("value", ((EvaluationStdError) o).payload);
            jgen.writeEndObject();
          }
        }
        jgen.writeEndArray();
        jgen.writeEndObject();
      }
    }
Exemplo n.º 9
0
 private static void writeTraces(final Map<Trace, Integer> traceIds, final JsonGenerator generator)
     throws IOException {
   generator.writeArrayFieldStart(JsonTraceCodec.TRACES);
   for (Map.Entry<Trace, Integer> entry : traceIds.entrySet()) {
     final Trace trace = entry.getKey();
     final int traceId = entry.getValue();
     writeTrace(trace, traceId, generator);
   }
   generator.writeEndArray();
 }
Exemplo n.º 10
0
 private void writeCriterias(CriteriaSet criteriaSet) throws IOException {
   writer.writeArrayFieldStart("criteria");
   for (Criteria criteria : criteriaSet.getCriterias()) {
     String value = criteria.toString();
     value = value.replaceAll("\\[", "");
     value = value.replaceAll("\\]", "");
     writer.writeObject(value);
   }
   writer.writeEndArray();
 }
Exemplo n.º 11
0
  @Override
  public void writeTo(
      Object object,
      Class<?> type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap<String, Object> httpHeaders,
      OutputStream entityStream)
      throws IOException, WebApplicationException {
    JsonGenerator writer = null;
    if (type.isAssignableFrom(ArtifactReadable.class)) {
      ArtifactReadable artifact = (ArtifactReadable) object;
      try {
        writer = jsonFactory.createJsonGenerator(entityStream);
        //         writer.setPrettyPrinter(new DefaultPr)
        writer.writeStartObject();
        writer.writeNumberField("uuid", artifact.getLocalId());
        if (matches(IdentityView.class, annotations)) {
          writer.writeStringField("Name", artifact.getName());
        } else {
          AttributeTypes attributeTypes = getAttibuteTypes();
          Collection<? extends IAttributeType> attrTypes = attributeTypes.getAll();
          ResultSet<? extends AttributeReadable<Object>> attributes = artifact.getAttributes();
          if (!attributes.isEmpty()) {
            for (IAttributeType attrType : attrTypes) {
              if (artifact.isAttributeTypeValid(attrType)) {
                List<Object> attributeValues = artifact.getAttributeValues(attrType);
                if (!attributeValues.isEmpty()) {

                  if (attributeValues.size() > 1) {
                    writer.writeArrayFieldStart(attrType.getName());
                    for (Object value : attributeValues) {
                      writer.writeObject(value);
                    }
                    writer.writeEndArray();
                  } else if (attributeValues.size() == 1) {
                    Object value = attributeValues.iterator().next();
                    writer.writeObjectField(attrType.getName(), value);
                  }
                }
              }
            }
          }
        }
        writer.writeEndObject();
      } finally {
        if (writer != null) {
          writer.flush();
        }
      }
    }
  }
 /**
  * Gets the janitor status (e.g. to support an AWS ELB Healthcheck on an instance running
  * JanitorMonkey). Creates GET /api/v1/janitor api which responds 200 OK if JanitorMonkey is
  * running.
  *
  * @param uriInfo the uri info
  * @return the chaos events json response
  * @throws IOException Signals that an I/O exception has occurred.
  */
 @GET
 public Response getJanitorStatus(@Context UriInfo uriInfo) throws IOException {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   JsonGenerator gen = JSON_FACTORY.createJsonGenerator(baos, JsonEncoding.UTF8);
   gen.writeStartArray();
   gen.writeStartObject();
   gen.writeStringField("JanitorMonkeyStatus", "OnLikeDonkeyKong");
   gen.writeEndObject();
   gen.writeEndArray();
   gen.close();
   return Response.status(Response.Status.OK).entity(baos.toString("UTF-8")).build();
 }
Exemplo n.º 13
0
 private void writeQuery(QueryData queryData) throws IOException {
   List<CriteriaSet> criteriaSets = queryData.getCriteriaSets();
   List<SelectSet> selectSets = queryData.getSelectSets();
   writer.writeArrayFieldStart("query");
   for (int index = 0; index < criteriaSets.size(); index++) {
     writer.writeStartObject();
     writer.writeNumberField("level", index);
     writeCriterias(criteriaSets.get(index));
     writeCollect(selectSets.get(index));
     writer.writeEndObject();
   }
   writer.writeEndArray();
 }
  public void dump(OutputStream os, BaseResponse res) {
    D2ResponseMessage d2Response = (D2ResponseMessage) res;

    try {
      OutputStreamWriter writer;

      writer = new OutputStreamWriter(os, charset);

      JsonGenerator generator = objectMapper.getJsonFactory().createJsonGenerator(writer);

      if (pretty) {
        JsonPrettyPrinter pp = new JsonPrettyPrinter();
        generator.setPrettyPrinter(pp);
      }

      //
      generator.writeStartArray();
      {
        List<D2ResponseMessageDoc> list = d2Response.getDocs();

        for (D2ResponseMessageDoc doc : list) {
          generator.writeStartObject();
          {
            generator.writeStringField("md5Lite", Md5Lite.toString(doc.getMd5Lite()));
            generator.writeNumberField("weight", doc.getWeight());

            generator.writeNumberField("indentValue", doc.getIndentValue());
            generator.writeNumberField("indentCount", doc.getIndentCount());
            generator.writeNumberField("indentPage", doc.getIndentPage());

            generator.writeNumberField("po", doc.getPo());
            generator.writeNumberField("ph", doc.getPh());
          }
          generator.writeEndObject();
        }
      }
      generator.writeEndArray();

      //
      generator.flush();
      writer.flush();

    } catch (UnsupportedEncodingException e) {
      logger.error("dump response failed.", e);
    } catch (IOException e) {
      logger.error("dump response failed.", e);
    } finally {

    }
  }
Exemplo n.º 15
0
 protected void writeListProperty(JsonGenerator jg, Property prop) throws IOException {
   jg.writeStartArray();
   if (prop instanceof ArrayProperty) {
     Object[] ar = (Object[]) prop.getValue();
     if (ar == null) {
       jg.writeEndArray();
       return;
     }
     Type itemType = ((ListType) prop.getType()).getFieldType();
     ObjectResolver resolver = itemType.getObjectResolver();
     String path = prop.getPath();
     for (Object o : ar) {
       if (!fetchProperty(jg, resolver, o, path)) {
         writeScalarPropertyValue(jg, ((SimpleType) itemType).getPrimitiveType(), o);
       }
     }
   } else {
     ListProperty listp = (ListProperty) prop;
     for (Property p : listp.getChildren()) {
       writeProperty(jg, p);
     }
   }
   jg.writeEndArray();
 }
Exemplo n.º 16
0
 private void writeErrors() throws IOException {
   if (errors != null && !errors.isEmpty()) {
     Writer errorWriter = context.getErrorWriter();
     if (errorWriter != null && errorWriter != context.getWriter()) {
       for (Throwable th : errors) {
         errorWriter.write(Lib.exceptionToString(th));
       }
     } else {
       writer.writeArrayFieldStart("errors");
       for (Throwable th : errors) {
         writer.writeString(Lib.exceptionToString(th));
       }
       writer.writeEndArray();
     }
   }
 }
Exemplo n.º 17
0
 @Override
 public void serialize(
     final HelloMessage hello, final JsonGenerator jgen, final SerializerProvider provider)
     throws IOException, JsonProcessingException {
   jgen.writeStartObject();
   jgen.writeFieldName(HelloMessage.MESSSAGE_TYPE_FIELD);
   jgen.writeString(hello.getMessageType().toString().toLowerCase());
   jgen.writeFieldName(HelloMessage.UAID_FIELD);
   jgen.writeString(hello.getUAID());
   jgen.writeArrayFieldStart(HelloMessage.CHANNEL_IDS_FIELD);
   for (String channelId : hello.getChannelIds()) {
     jgen.writeString(channelId);
   }
   jgen.writeEndArray();
   jgen.writeEndObject();
 }
Exemplo n.º 18
0
 private static void writeRelationships(
     final Map<Trace, Integer> traceIds, final JsonGenerator generator) throws IOException {
   generator.writeArrayFieldStart(JsonTraceCodec.RELATIONSHIPS);
   for (Map.Entry<Trace, Integer> entry : traceIds.entrySet()) {
     final Trace trace = entry.getKey();
     final int fromId = entry.getValue();
     for (Related<Trace> related : trace.getRelated()) {
       final int toId = traceIds.get(related.getRelated());
       final String relationship = related.getRelationship();
       generator.writeStartObject();
       generator.writeStringField(JsonTraceCodec.RELATIONSHIP_RELATIONSHIP, relationship);
       generator.writeNumberField(JsonTraceCodec.RELATIONSHIP_FROM, fromId);
       generator.writeNumberField(JsonTraceCodec.RELATIONSHIP_TO, toId);
       generator.writeEndObject();
     }
   }
   generator.writeEndArray();
 }
Exemplo n.º 19
0
 @Override
 public void serialize(
     final AckMessage ack, final JsonGenerator jgen, final SerializerProvider provider)
     throws IOException, JsonProcessingException {
   jgen.writeStartObject();
   jgen.writeFieldName(AckMessage.MESSSAGE_TYPE_FIELD);
   jgen.writeString(ack.getMessageType().toString().toLowerCase());
   jgen.writeArrayFieldStart(AckMessage.UPDATES_FIELD);
   for (Update update : ack.getUpdates()) {
     jgen.writeStartObject();
     jgen.writeFieldName("channelID");
     jgen.writeString(update.getChannelId());
     jgen.writeFieldName(AckMessage.VERSION_FIELD);
     jgen.writeNumber(update.getVersion());
     jgen.writeEndObject();
   }
   jgen.writeEndArray();
   jgen.writeEndObject();
 }
 public void writeJson(JsonGenerator g) throws JsonGenerationException, IOException {
   g.writeStartObject();
   g.writeBooleanField(SUCCESS, success);
   g.writeStringField(MESSAGE, message);
   g.writeArrayFieldStart(DATA);
   if (null != list && !list.isEmpty()) {
     for (T model : list) {
       // write model data
       g.writeStartObject();
       g.writeStringField("key", model.getKey());
       g.writeStringField("label", model.getLabel());
       g.writeEndObject();
     }
   }
   g.writeEndArray();
   // write model data end
   g.writeEndObject();
   g.flush();
   g.close();
 }
Exemplo n.º 21
0
 @Override
 public void serialize(
     final NotificationMessage notification,
     final JsonGenerator jgen,
     final SerializerProvider provider)
     throws IOException, JsonProcessingException {
   jgen.writeStartObject();
   jgen.writeFieldName(NotificationMessage.MESSSAGE_TYPE_FIELD);
   jgen.writeString(notification.getMessageType().toString().toLowerCase());
   jgen.writeArrayFieldStart(NotificationMessage.UPDATES_FIELD);
   for (Update update : notification.getUpdates()) {
     jgen.writeStartObject();
     jgen.writeFieldName(RegisterMessage.CHANNEL_ID_FIELD);
     jgen.writeString(update.getChannelId());
     jgen.writeFieldName(NotificationMessage.VERSION_FIELD);
     jgen.writeNumber(update.getVersion());
     jgen.writeEndObject();
   }
   jgen.writeEndArray();
   jgen.writeEndObject();
 }
    void send(List<String> eventLog) throws IOException {
      CloseableHttpClient httpClient = HttpClients.createDefault();
      try {

        JsonFactory factory = new JsonFactory();
        StringWriter writer = new StringWriter();
        JsonGenerator generator = factory.createJsonGenerator(writer);
        generator.writeStartObject();
        generator.writeArrayFieldStart("events");
        for (String eventJson : eventLog) {
          generator.writeRawValue(eventJson);
        }
        generator.writeEndArray();
        generator.writeEndObject();
        generator.close();

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
            AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);

        RestPostProcessorDelegate.LOG.info(
            "Posting " + eventLog.size() + " events to " + targetUrl);
        HttpPost httpPost = new HttpPost(targetUrl);
        httpPost.setEntity(new StringEntity(writer.toString(), ContentType.APPLICATION_JSON));
        CloseableHttpResponse response = httpClient.execute(httpPost, context);
        int statusCode = response.getStatusLine().getStatusCode();
        LOG.info("Status code was " + statusCode + " when invoking " + targetUrl);
        if (statusCode >= 400) {
          throw new RiceRuntimeException(
              "Failed to invoke " + targetUrl + ", response code was " + statusCode);
        }

      } finally {
        httpClient.close();
      }
    }
Exemplo n.º 23
0
  public static void writeConnectivityMapVar(
      EDComponent comp, StringBuilder sb, String name, String parentName, JsonGenerator g)
      throws JsonGenerationException, IOException {

    for (Iterator<EDState> i = comp.state.iterator(); i.hasNext(); ) {
      EDState state = i.next();
      currentBit = currentBit + currentLength + 1;
      while (currentBit % 8 != 0) currentBit++;
      currentLength = (state.integer) - (state.fraction);
      int currentTop = currentBit + currentLength;
      writeSignal(
          parentName + "_statevariable_" + state.type + "_" + name + state.name + "_in",
          currentBit,
          currentTop,
          state.integer,
          state.fraction,
          g);
      sb.append(
          parentName
              + "_statevariable_"
              + state.type
              + "_"
              + name
              + state.name
              + "_out => "
              + parentName
              + "_statevariable_"
              + state.type
              + "_"
              + name
              + state.name
              + "_out_int,\r\n");
      sb.append(
          parentName
              + "_statevariable_"
              + state.type
              + "_"
              + name
              + state.name
              + "_in => to_sfixed (mega_bus_in("
              + currentTop
              + " downto "
              + currentBit
              + "),"
              + state.integer
              + " , "
              + state.fraction
              + "),\r\n");
    }
    for (Iterator<EDDerivedVariable> i = comp.derivedvariables.iterator(); i.hasNext(); ) {
      EDDerivedVariable state = i.next();
      currentBit = currentBit + currentLength + 1;
      while (currentBit % 8 != 0) currentBit++;
      currentLength = (state.integer) - (state.fraction);
      int currentTop = currentBit + currentLength;
      writeSignal(
          parentName + "_statevariable_" + state.type + "_" + name + state.name + "_in",
          currentBit,
          currentTop,
          state.integer,
          state.fraction,
          g);
      sb.append(
          parentName
              + "_statevariable_"
              + state.type
              + "_"
              + name
              + state.name
              + "_out => "
              + parentName
              + "_statevariable_"
              + state.type
              + "_"
              + name
              + state.name
              + "_out_int,\r\n");
      sb.append(
          parentName
              + "_statevariable_"
              + state.type
              + "_"
              + name
              + state.name
              + "_in => to_sfixed (mega_bus_in("
              + currentTop
              + " downto "
              + currentBit
              + "),"
              + state.integer
              + " , "
              + state.fraction
              + "),\r\n");
    }
    for (Iterator<EDConditionalDerivedVariable> i = comp.conditionalderivedvariables.iterator();
        i.hasNext(); ) {
      EDConditionalDerivedVariable state = i.next();
      currentBit = currentBit + currentLength + 1;
      while (currentBit % 8 != 0) currentBit++;
      currentLength = (state.integer) - (state.fraction);
      int currentTop = currentBit + currentLength;
      writeSignal(
          parentName + "_statevariable_" + state.type + "_" + name + state.name + "_in",
          currentBit,
          currentTop,
          state.integer,
          state.fraction,
          g);
      sb.append(
          parentName
              + "_statevariable_"
              + state.type
              + "_"
              + name
              + state.name
              + "_out => "
              + parentName
              + "_statevariable_"
              + state.type
              + "_"
              + name
              + state.name
              + "_out_int,\r\n");
      sb.append(
          parentName
              + "_statevariable_"
              + state.type
              + "_"
              + name
              + state.name
              + "_in => to_sfixed (mega_bus_in("
              + currentTop
              + " downto "
              + currentBit
              + "),"
              + state.integer
              + " , "
              + state.fraction
              + "),\r\n");
    }

    for (Iterator<EDComponent> i = comp.Children.iterator(); i.hasNext(); ) {
      EDComponent item = i.next();
      if (!item.isSynapse) {
        String newName = name + item.name + "_";
        writeConnectivityMapVar(item, sb, newName, parentName, g);
      }
    }

    boolean hasSynapses = false;
    for (Iterator<EDComponent> i = comp.Children.iterator(); i.hasNext(); ) {
      EDComponent item = i.next();
      if (item.isSynapse) {
        hasSynapses = true;
      }
    }
    if (hasSynapses == true) {
      for (Iterator<EDComponent> i = comp.Children.iterator(); i.hasNext(); ) {
        EDComponent item = i.next();
        if (item.isSynapse) {
          g.writeEndArray();
          g.writeArrayFieldStart("SynapseVariablesIn_" + item.name);
          String newName = name + item.name + "_";
          writeConnectivityMapVar(item, sb, newName, parentName, g);
        }
      }
    }
  }
Exemplo n.º 24
0
  public static void writeNeuronCoreTop(
      EDSimulation sim,
      StringBuilder sb,
      JsonGenerator g,
      Map<String, Float> initialState,
      String neuronName)
      throws JsonGenerationException, IOException {
    currentBit = 511; // 5119;
    currentLength = 0;
    Integer = 0;
    sb.append(
        "\r\n"
            + "library ieee;\r\n"
            + "use ieee.std_logic_1164.all;\r\n"
            + "use ieee.std_logic_unsigned.all;\r\n"
            + "library ieee_proposed;\r\n"
            + "use ieee_proposed.fixed_pkg.all;\r\n"
            + "use ieee_proposed.fixed_float_types.ALL;\r\n"
            + "use std.textio.all;\r\n"
            + "use ieee.std_logic_textio.all; -- if you're saving this type of signal\r\n"
            + "use IEEE.numeric_std.all;\r\n"
            + "");

    sb.append(
        "\r\n"
            + "entity neuroncore_top is\r\n"
            + "    Port ( clk : in STD_LOGIC; --SYSTEM CLOCK, THIS ITSELF DOES NOT SIGNIFY TIME STEPS - AKA A SINGLE TIMESTEP MAY TAKE MANY CLOCK CYCLES\r\n"
            + "           init_model : in STD_LOGIC; --SYNCHRONOUS RESET\r\n"
            + "		   step_once_go : in STD_LOGIC; --signals to the neuron from the core that a time step is to be simulated\r\n"
            + "		   step_once_complete : out STD_LOGIC; --signals to the core that a time step has finished\r\n"
            + "		   \r\n"
            + "           mega_bus_in : in STD_LOGIC_Vector (99999 downto 0 );\r\n"
            + "           mega_bus_out : out STD_LOGIC_Vector (99999 downto 0 )\r\n"
            + "		   );\r\n"
            + "end neuroncore_top;\r\n"
            + "\r\n"
            + "---------------------------------------------------------------------\r\n"
            + "\r\n"
            + "architecture top of neuroncore_top is\r\n");

    EDComponent neuron = sim.neuronComponents.get(0);
    for (int i = 0; i < sim.neuronComponents.size(); i++) {
      if (sim.neuronComponents.get(i).name.matches(neuronName)) {
        neuron = sim.neuronComponents.get(i);
        break;
      }
    }

    sb.append(
        "\r\n"
            + "component top_synth\r\n"
            + "    Port ( clk : in STD_LOGIC; --SYSTEM CLOCK, THIS ITSELF DOES NOT SIGNIFY TIME STEPS - AKA A SINGLE TIMESTEP MAY TAKE MANY CLOCK CYCLES\r\n"
            + "           init_model : in STD_LOGIC; --SYNCHRONOUS RESET\r\n"
            + "		   step_once_go : in STD_LOGIC; --signals to the neuron from the core that a time step is to be simulated\r\n"
            + "		   step_once_complete : out STD_LOGIC; --signals to the core that a time step has finished\r\n"
            + "		   eventport_in_spike_aggregate : in STD_LOGIC_VECTOR(511 downto 0);\r\n"
            +
            // "		   SelectSpikesIn :  in STD_LOGIC_VECTOR(4607 downto 0);\r\n" +
            "		   ");

    String name = "";
    for (Iterator<EDEventPort> i = neuron.eventports.iterator(); i.hasNext(); ) {
      EDEventPort item = i.next();
      sb.append(
          "			"
              + neuron.name
              + "_eventport_"
              + item.direction
              + "_"
              + item.name
              + " : "
              + item.direction
              + " STD_LOGIC;\r\n");
    }

    if (neuron.regimes.size() > 0) {
      sb.append(
          "			"
              + neuron.name
              + "current_regime_in_stdlv : in STD_LOGIC_VECTOR(1 downto 0);\r\n"
              + "			"
              + neuron.name
              + "current_regime_out_stdlv : out STD_LOGIC_VECTOR(1 downto 0);\r\n");
    }
    TopSynth.writeEntitySignals(neuron, sb, name, neuron.name + "_");
    sb.append(
        "\r\n"
            + "           sysparam_time_timestep : sfixed (-6 downto -22);\r\n"
            + "           sysparam_time_simtime : sfixed (6 downto -22)\r\n"
            + "		   );\r\n"
            + "end component;\r\n"
            + "\r\n"
            + "\r\n"
            + "	\r\n"
            + "	");

    for (Iterator<EDEventPort> i = neuron.eventports.iterator(); i.hasNext(); ) {
      EDEventPort item = i.next();
      sb.append(
          "signal "
              + neuron.name
              + "_eventport_"
              + item.direction
              + "_"
              + item.name
              + "_internal : std_logic;\r\n");
    }
    if (neuron.regimes.size() > 0) {
      sb.append(
          "signal "
              + neuron.name
              + "_current_regime_out_stdlv_int :  STD_LOGIC_VECTOR(1 downto 0);\r\n");
    }
    writeStateSignals(neuron, sb, "", neuron.name);

    g.writeObjectFieldStart(neuron.name);
    g.writeObjectFieldStart("SpikesIn");
    g.writeNumberField("bottom", 0);
    g.writeNumberField("top", 511);
    g.writeEndObject();
    g.writeArrayFieldStart("NeuronVariablesIn");

    sb.append(
        "begin\r\n"
            + "\r\n"
            + "top_synth_uut : neuron_model \r\n"
            + "    port map (	clk => clk,\r\n"
            + "				init_model => init_model, \r\n"
            + "		   step_once_go  => step_once_go,\r\n"
            + "		   step_once_complete  => step_once_complete,\r\n"
            + "		   eventport_in_spike_aggregate =>  mega_bus_in(511 downto 0),\r\n"
            +
            // "		   SelectSpikesIn => mega_bus_in(5119 downto 512),\r\n" +
            "		   ");

    for (Iterator<EDEventPort> i = neuron.eventports.iterator(); i.hasNext(); ) {
      EDEventPort item = i.next();
      sb.append(
          "			"
              + neuron.name
              + "_eventport_"
              + item.direction
              + "_"
              + item.name
              + " => "
              + neuron.name
              + "_eventport_"
              + item.direction
              + "_"
              + item.name
              + "_internal ,\r\n");
    }

    if (neuron.regimes.size() > 0) {
      currentBit = currentBit + currentLength + 1;
      while (currentBit % 8 != 0) currentBit++;
      currentLength = 1;
      int currentTop = currentBit + currentLength;
      writeSignal("regime", currentBit, currentTop, 0, 0, g);
      sb.append(
          ""
              + neuron.name
              + "current_regime_in_stdlv =>  mega_bus_in("
              + currentTop
              + " downto "
              + currentBit
              + "),\r\n");
      sb.append(
          ""
              + neuron.name
              + "current_regime_out_stdlv => "
              + neuron.name
              + "_current_regime_out_stdlv_int,\r\n");
    }
    writeConnectivityMapVar(neuron, sb, "", neuron.name, g);

    g.writeEndArray();
    g.writeArrayFieldStart("NeuronParameters");
    writeConnectivityMapPar(neuron, sb, "", neuron.name, g);

    currentBit = currentBit + currentLength + 1;
    currentLength = 16;
    int currentTop = currentBit + currentLength;
    sb.append(
        "sysparam_time_timestep => to_sfixed (mega_bus_in("
            + currentTop
            + " downto "
            + currentBit
            + "),-6 , -22),");

    currentBit = currentBit + currentLength + 1;
    currentLength = 28;
    currentTop = currentBit + currentLength;
    sb.append(
        "sysparam_time_simtime => to_sfixed (mega_bus_in("
            + currentTop
            + " downto "
            + currentBit
            + "),6, -22)");
    sb.append("\r\n" + "		   );\r\n");
    g.writeEndArray();
    g.writeArrayFieldStart("NeuronVariablesOut");

    currentBit = -1;
    currentLength = 0;

    if (neuron.regimes.size() > 0) {
      currentBit = currentBit + currentLength + 1;
      while (currentBit % 8 != 0) currentBit++;
      currentLength = 1;
      currentTop = currentBit + currentLength;
      writeSignal("regime", currentBit, currentTop, 0, 0, g);
      sb.append(
          " mega_bus_out("
              + currentTop
              + " downto "
              + currentBit
              + ") <= "
              + neuron.name
              + "_current_regime_out_stdlv_int;\r\n");
    }

    writeStateToBusSignals(neuron, sb, "", neuron.name, g);

    for (Iterator<EDEventPort> i = neuron.eventports.iterator(); i.hasNext(); ) {
      EDEventPort item = i.next();
      currentBit = currentBit + currentLength + 1;
      while (currentBit % 8 != 0) currentBit++;
      sb.append(
          " mega_bus_out("
              + currentBit
              + ") <= "
              + neuron.name
              + "_eventport_"
              + item.direction
              + "_"
              + item.name
              + "_internal;\r\n");
    }
    sb.append("\r\n" + "end top;\r\n" + "");

    g.writeEndArray();
    g.writeEndObject();
  }
Exemplo n.º 25
0
  public static void writeConnectivityMapPar(
      EDComponent comp, StringBuilder sb, String name, String parentName, JsonGenerator g)
      throws JsonGenerationException, IOException {
    for (Iterator<EDParameter> i = comp.parameters.iterator(); i.hasNext(); ) {
      EDParameter item = i.next();
      currentBit = currentBit + currentLength + 1;
      while (currentBit % 8 != 0) currentBit++;
      currentLength = (item.integer) - (item.fraction);
      int currentTop = currentBit + currentLength;
      writeSignal(
          parentName + "_param_" + item.type + "_" + name + item.name,
          currentBit,
          currentTop,
          item.integer,
          item.fraction,
          g);
      sb.append(
          parentName
              + "_param_"
              + item.type
              + "_"
              + name
              + item.name
              + " => to_sfixed ( mega_bus_in("
              + currentTop
              + " downto "
              + currentBit
              + "),"
              + item.integer
              + " , "
              + item.fraction
              + "),\r\n");
    }

    for (Iterator<EDComponent> i = comp.Children.iterator(); i.hasNext(); ) {
      EDComponent item = i.next();
      if (!item.isSynapse) {
        String newName = name + item.name + "_";
        writeConnectivityMapPar(item, sb, newName, parentName, g);
      }
    }

    boolean hasSynapses = false;
    for (Iterator<EDComponent> i = comp.Children.iterator(); i.hasNext(); ) {
      EDComponent item = i.next();
      if (item.isSynapse) {
        hasSynapses = true;
      }
    }
    if (hasSynapses == true) {
      int count = 0;
      for (Iterator<EDComponent> i = comp.Children.iterator(); i.hasNext(); ) {
        EDComponent item = i.next();
        if (item.isSynapse) {
          g.writeEndArray();
          g.writeArrayFieldStart("SynapseParameters_" + item.name);
          String newName = name + item.name + "_";
          writeConnectivityMapVar(item, sb, newName, parentName, g);
        }
      }
    }
  }