Java Code Examples for org.codehaus.jettison.json.JSONObject#put()

The following examples show how to use org.codehaus.jettison.json.JSONObject#put() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConvertSprintBacklog.java    From ezScrum with GNU General Public License v2.0 7 votes vote down vote up
public static String getSprintJSONString(SprintObject sprint) throws JSONException {
	JSONObject sprintJson = new JSONObject();
	sprintJson.put(SprintPlanUtil.TAG_ID, sprint.getId());
	sprintJson.put(SprintPlanUtil.TAG_SPRINT_GOAL, sprint.getGoal());
	sprintJson.put(SprintPlanUtil.TAG_START_DATE, sprint.getStartDateString());
	sprintJson.put(SprintPlanUtil.TAG_DEMO_DATE, sprint.getDemoDateString());
	sprintJson.put(SprintPlanUtil.TAG_DUE_DATE, sprint.getDueDateString());
	sprintJson.put(SprintPlanUtil.TAG_INTERVAL, sprint.getInterval());
	sprintJson.put(SprintPlanUtil.TAG_MEMBERS, sprint.getTeamSize());
	sprintJson.put(SprintPlanUtil.TAG_HOURS_CAN_COMMIT, sprint.getAvailableHours());
	sprintJson.put(SprintPlanUtil.TAG_DAILY_MEETING, sprint.getDailyInfo());
	sprintJson.put(SprintPlanUtil.TAG_DEMO_PLACE, sprint.getDemoPlace());
	
	JSONArray storiesJsonArray = new JSONArray();
	for(StoryObject story : sprint.getStories()){
		storiesJsonArray.put(story.toJSON());
	}
	
	sprintJson.put("stories", storiesJsonArray);
	return sprintJson.toString();
}
 
Example 2
Source File: StramWebServices.java    From Bats with Apache License 2.0 6 votes vote down vote up
@POST
@Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{opId:\\d+}/ports/{portName}/" + PATH_RECORDINGS_START)
@Produces(MediaType.APPLICATION_JSON)
public JSONObject startRecording(@PathParam("opId") int opId, @PathParam("portName") String portName, String content) throws JSONException
{
  init();
  LOG.debug("Start recording on {}.{} requested", opId, portName);
  JSONObject response = new JSONObject();
  long numWindows = 0;
  if (StringUtils.isNotBlank(content)) {
    JSONObject r = new JSONObject(content);
    numWindows = r.optLong("numWindows", 0);
  }
  String id = getTupleRecordingId();
  dagManager.startRecording(id, opId, portName, numWindows);
  response.put("id", id);
  return response;
}
 
Example 3
Source File: PubSubWebSocketClient.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * <p>openConnection.</p>
 *
 * @param timeoutMillis
 * @throws IOException
 * @throws ExecutionException
 * @throws InterruptedException
 * @throws TimeoutException
 */
public void openConnection(long timeoutMillis) throws IOException, ExecutionException, InterruptedException, TimeoutException
{
  throwable.set(null);

  List<Cookie> cookies = null;
  if (loginUrl != null && userName != null && password != null) {
    // get the session key first before attempting web socket
    JSONObject json = new JSONObject();
    try {
      json.put("userName", userName);
      json.put("password", password);
    } catch (JSONException ex) {
      throw new RuntimeException(ex);
    }
    Response response = client.preparePost(loginUrl).setHeader("Content-Type", "application/json").setBody(json.toString()).execute().get();
    cookies = response.getCookies();
  }
  BoundRequestBuilder brb = client.prepareGet(uri.toString());
  if (cookies != null) {
    for (Cookie cookie : cookies) {
      brb.addCookie(cookie);
    }
  }
  connection = brb.execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new PubSubWebSocket()).build()).get(timeoutMillis, TimeUnit.MILLISECONDS);
}
 
Example 4
Source File: ConvertBurndownChart.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
public void convertTaskPoint(LinkedHashMap<Date, Double> taskPointMap)
		throws JSONException {
	
	DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
	for (Map.Entry<Date, Double> entry : taskPointMap.entrySet()) {
		JSONObject taskPoint = new JSONObject();
		Date date = entry.getKey();
		Double points = entry.getValue();

		String createDate = dateFormat.format(date);
		taskPoint.put(BurndownChartUtil.TAG_DATE, createDate);
		if (points != null) { // sprint在進行中,在還沒到的日期下是不會有story point的
			taskPoint.put(BurndownChartUtil.TAG_POINT, points.toString());
		} else {
			taskPoint.put(BurndownChartUtil.TAG_POINT, "");
		}
		mTaskPoints.put(taskPoint);
	}
}
 
Example 5
Source File: ReleasePlanHelper.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
private JSONObject updateJsonInfo(JSONObject jsonInfo) {
	try {
		// JSON是call by reference!!! 查memory=>System.identityHashCode(Object
		// x)
		JSONArray sprintJsonArray = (JSONArray) jsonInfo.get("Sprints");
		int sprintCount = jsonInfo.getInt("TotalSprintCount");
		int storyCount = jsonInfo.getInt("TotalStoryCount");
		int storyRemaining = jsonInfo.getInt("TotalStoryCount");
		double idealRange = (double) storyCount / sprintCount;
		for (int i = 0; i < sprintJsonArray.length(); i++) {
			JSONObject sprintJson = sprintJsonArray.getJSONObject(i);
			storyRemaining -= sprintJson.getInt("StoryDoneCount");
			sprintJson.put("StoryRemainingCount", storyRemaining);
			sprintJson.put("StoryIdealCount", storyCount
					- (idealRange * (i + 1)));
		}
		jsonInfo.put("Sprints", sprintJsonArray);
	} catch (JSONException e) {
		e.printStackTrace();
	}
	return jsonInfo;
}
 
Example 6
Source File: MappedXMLStreamWriter.java    From jettison with Apache License 2.0 5 votes vote down vote up
public JSONPropertyObject withProperty(JSONProperty property, boolean add) {
	// Duplicate some code from JSONPropertyObject
	// because we can do things with fewer checks, and
	// therefore more efficiently.
	JSONObject jo = new JSONObject(false,
			                       convention.getIgnoredElements(),
			                       convention.isWriteNullAsString(),
			                       convention.isEscapeForwardSlashAlways());
	try {
		// only add the text property if it's non-empty
		String strValue = getValue().toString();
		if (MIXED_CONTENT_VALUE_KEY == valueKey) {
			strValue = strValue.trim();
		}
		if (strValue.length() > 0) {
			jo.put(valueKey, strValue);
		}
		
		Object value = property.getValue();
		boolean emptyString = value instanceof String && ((String)value).isEmpty();
		if (value instanceof String && !emptyString) {
		    value = convention.convertToJSONPrimitive((String)value);
		}
		if (getSerializedAsArrays().contains(getPropertyArrayKey(property))) {
		    JSONArray values = new JSONArray();
		    if (!convention.isIgnoreEmptyArrayValues() 
		    		|| (!emptyString && value != null)) {
		    	values.put(value);
		    }
			value = values;
		    
		}
		jo.put(property.getKey(), value);
	} catch (JSONException e) {
		// Impossible by construction
		throw new AssertionError(e);				
	}
	return new JSONPropertyObject(getKey(), getParentKey(), jo);
}
 
Example 7
Source File: HistoryEventJsonConversion.java    From incubator-tez with Apache License 2.0 5 votes vote down vote up
private static JSONObject convertVertexInitializedEvent(VertexInitializedEvent event) throws JSONException {
  JSONObject jsonObject = new JSONObject();
  jsonObject.put(ATSConstants.ENTITY, event.getVertexID().toString());
  jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_VERTEX_ID.name());

  // Related entities
  JSONArray relatedEntities = new JSONArray();
  JSONObject vertexEntity = new JSONObject();
  vertexEntity.put(ATSConstants.ENTITY, event.getVertexID().getDAGId().toString());
  vertexEntity.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_DAG_ID.name());
  relatedEntities.put(vertexEntity);
  jsonObject.put(ATSConstants.RELATED_ENTITIES, relatedEntities);

  // Events
  JSONArray events = new JSONArray();
  JSONObject initEvent = new JSONObject();
  initEvent.put(ATSConstants.TIMESTAMP, event.getInitedTime());
  initEvent.put(ATSConstants.EVENT_TYPE,
      HistoryEventType.VERTEX_INITIALIZED.name());
  events.put(initEvent);
  jsonObject.put(ATSConstants.EVENTS, events);

  // Other info
  // TODO fix requested times to be events
  JSONObject otherInfo = new JSONObject();
  otherInfo.put(ATSConstants.VERTEX_NAME, event.getVertexName());
  otherInfo.put(ATSConstants.INIT_REQUESTED_TIME, event.getInitRequestedTime());
  otherInfo.put(ATSConstants.INIT_TIME, event.getInitedTime());
  otherInfo.put(ATSConstants.NUM_TASKS, event.getNumTasks());
  otherInfo.put(ATSConstants.PROCESSOR_CLASS_NAME, event.getProcessorName());
  jsonObject.put(ATSConstants.OTHER_INFO, otherInfo);

  return jsonObject;
}
 
Example 8
Source File: HistoryEventJsonConversion.java    From incubator-tez with Apache License 2.0 5 votes vote down vote up
private static JSONObject convertVertexStartedEvent(VertexStartedEvent event) throws JSONException {
  JSONObject jsonObject = new JSONObject();
  jsonObject.put(ATSConstants.ENTITY, event.getVertexID().toString());
  jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_VERTEX_ID.name());

  // Related entities
  JSONArray relatedEntities = new JSONArray();
  JSONObject vertexEntity = new JSONObject();
  vertexEntity.put(ATSConstants.ENTITY, event.getVertexID().getDAGId().toString());
  vertexEntity.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_DAG_ID.name());
  relatedEntities.put(vertexEntity);
  jsonObject.put(ATSConstants.RELATED_ENTITIES, relatedEntities);

  // Events
  JSONArray events = new JSONArray();
  JSONObject startEvent = new JSONObject();
  startEvent.put(ATSConstants.TIMESTAMP, event.getStartTime());
  startEvent.put(ATSConstants.EVENT_TYPE,
      HistoryEventType.VERTEX_STARTED.name());
  events.put(startEvent);
  jsonObject.put(ATSConstants.EVENTS, events);

  // Other info
  // TODO fix requested times to be events
  JSONObject otherInfo = new JSONObject();
  otherInfo.put(ATSConstants.START_REQUESTED_TIME, event.getStartRequestedTime());
  otherInfo.put(ATSConstants.START_TIME, event.getStartTime());
  jsonObject.put(ATSConstants.OTHER_INFO, otherInfo);

  return jsonObject;
}
 
Example 9
Source File: MainTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadQuestionTemplatesRecursive() throws Exception {
  JSONObject testQuestion1 = new JSONObject();
  testQuestion1.put(
      "instance",
      new JSONObject()
          .put("instanceName", "testQuestion1")
          .put("description", "test question one description"));
  Path question1JsonPath = _folder.newFile("testquestion1.json").toPath();
  CommonUtil.writeFile(question1JsonPath, testQuestion1.toString());

  JSONObject testQuestion2 = new JSONObject();
  testQuestion2.put(
      "instance",
      new JSONObject()
          .put("instanceName", "testQuestion2")
          .put("description", "test question two description"));
  File nestedFolder = _folder.newFolder("nestedFolder");
  Path question2JsonPath = nestedFolder.toPath().resolve("testquestions2.json");
  CommonUtil.writeFile(question2JsonPath, testQuestion2.toString());

  Map<String, String> questionTemplates = Maps.newHashMap();

  readQuestionTemplates(_folder.getRoot().toPath(), questionTemplates);
  assertThat(questionTemplates.keySet(), hasSize(2));
  // Both templates should be present
  assertThat(
      questionTemplates,
      allOf(
          IsMapContaining.hasEntry(
              "testquestion1",
              "{\"instance\":{\"instanceName\":\"testQuestion1\",\"description\":\"test question one description\"}}"),
          IsMapContaining.hasEntry(
              "testquestion2",
              "{\"instance\":{\"instanceName\":\"testQuestion2\",\"description\":\"test question two description\"}}")));
}
 
Example 10
Source File: HistoryEventJsonConversion.java    From tez with Apache License 2.0 5 votes vote down vote up
private static JSONObject convertTaskStartedEvent(TaskStartedEvent event) throws JSONException {
  JSONObject jsonObject = new JSONObject();
  jsonObject.put(ATSConstants.ENTITY, event.getTaskID().toString());
  jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_TASK_ID.name());

  // Related entities
  JSONArray relatedEntities = new JSONArray();
  JSONObject vertexEntity = new JSONObject();
  vertexEntity.put(ATSConstants.ENTITY, event.getTaskID().getVertexID().toString());
  vertexEntity.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_VERTEX_ID.name());
  relatedEntities.put(vertexEntity);
  jsonObject.put(ATSConstants.RELATED_ENTITIES, relatedEntities);

  // Events
  JSONArray events = new JSONArray();
  JSONObject startEvent = new JSONObject();
  startEvent.put(ATSConstants.TIMESTAMP, event.getStartTime());
  startEvent.put(ATSConstants.EVENT_TYPE,
      HistoryEventType.TASK_STARTED.name());
  events.put(startEvent);
  jsonObject.put(ATSConstants.EVENTS, events);

  // Other info
  // TODO fix schedule/launch time to be events
  JSONObject otherInfo = new JSONObject();
  otherInfo.put(ATSConstants.START_TIME, event.getStartTime());
  otherInfo.put(ATSConstants.SCHEDULED_TIME, event.getScheduledTime());
  jsonObject.put(ATSConstants.OTHER_INFO, otherInfo);

  return jsonObject;
}
 
Example 11
Source File: JsonWriter.java    From vespa with Apache License 2.0 5 votes vote down vote up
public void fillInJson(CurrentUnitState stateData, JSONObject json) throws Exception {
    JSONObject stateJson = new JSONObject();
    json.put("state", stateJson);
    Map<String, UnitState> state = stateData.getStatePerType();
    for (Map.Entry<String, UnitState> e : state.entrySet()) {
        String stateType = e.getKey();
        UnitState unitState = e.getValue();
        JSONObject stateTypeJson = new JSONObject()
                .put("state", unitState.getId())
                .put("reason", unitState.getReason());
        stateJson.put(stateType, stateTypeJson);
    }
}
 
Example 12
Source File: ConvertSprintBacklog.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
public static String getStoriesIdJsonStringInSprint(ArrayList<StoryObject> stories) throws JSONException {
	JSONObject storiesIdJsonString = new JSONObject();
	JSONArray storyArray = new JSONArray();
	for (StoryObject story : stories) {
		JSONObject stroyJson = new JSONObject();
		stroyJson.put("id", story.getId());
		stroyJson.put("point", story.getEstimate());
		stroyJson.put("status", story.getStatusString());
		storyArray.put(stroyJson);
	}
	storiesIdJsonString.put(SprintPlanUtil.TAG_STORIES, storyArray);
	return storiesIdJsonString.toString();
}
 
Example 13
Source File: OperatorDiscoverer.java    From Bats with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void addDefaultValue(String className, JSONObject oper) throws Exception
{
  ObjectMapper defaultValueMapper = ObjectMapperFactory.getOperatorValueSerializer();
  Class<? extends GenericOperator> clazz = (Class<? extends GenericOperator>)classLoader.loadClass(className);
  if (clazz != null) {
    GenericOperator operIns = clazz.newInstance();
    String s = defaultValueMapper.writeValueAsString(operIns);
    oper.put("defaultValue", new JSONObject(s).get(className));
  }
}
 
Example 14
Source File: UserEvent.java    From hadoop-arch-book with Apache License 2.0 5 votes vote down vote up
public JSONObject getJSONObject() throws JSONException {
  JSONObject jsonObject = new JSONObject();
  jsonObject.put("userId", userId);
  jsonObject.put("timeStamp", timeStamp);
  jsonObject.put("ipAddress", ipAddress);
  jsonObject.put("countryCode", countryCode);
  jsonObject.put("zipCode", zipCode);
  jsonObject.put("itemCategory", itemCategory);
  jsonObject.put("paymentAmount", paymentAmount);
  jsonObject.put("vendorId", vendorId);
  jsonObject.put("isCardPresent", isCardPresent);
  return jsonObject;
}
 
Example 15
Source File: HistoryEventJsonConversion.java    From tez with Apache License 2.0 5 votes vote down vote up
private static JSONObject convertTaskFinishedEvent(TaskFinishedEvent event) throws JSONException {
  JSONObject jsonObject = new JSONObject();
  jsonObject.put(ATSConstants.ENTITY, event.getTaskID().toString());
  jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_TASK_ID.name());

  // Events
  JSONArray events = new JSONArray();
  JSONObject finishEvent = new JSONObject();
  finishEvent.put(ATSConstants.TIMESTAMP, event.getFinishTime());
  finishEvent.put(ATSConstants.EVENT_TYPE,
      HistoryEventType.TASK_FINISHED.name());
  events.put(finishEvent);
  jsonObject.put(ATSConstants.EVENTS, events);

  JSONObject otherInfo = new JSONObject();
  otherInfo.put(ATSConstants.START_TIME, event.getStartTime());
  otherInfo.put(ATSConstants.FINISH_TIME, event.getFinishTime());
  otherInfo.put(ATSConstants.TIME_TAKEN, (event.getFinishTime() - event.getStartTime()));
  otherInfo.put(ATSConstants.STATUS, event.getState().name());
  otherInfo.put(ATSConstants.DIAGNOSTICS, event.getDiagnostics());
  otherInfo.put(ATSConstants.COUNTERS,
      DAGUtils.convertCountersToJSON(event.getTezCounters()));
  if (event.getSuccessfulAttemptID() != null) {
    otherInfo.put(ATSConstants.SUCCESSFUL_ATTEMPT_ID, event.getSuccessfulAttemptID().toString());
  }

  jsonObject.put(ATSConstants.OTHER_INFO, otherInfo);

  return jsonObject;
}
 
Example 16
Source File: SimpleKafkaProducerApplication.java    From SimpleKafkaExampleSpringBoot with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Function to send some test messages to Kafka.
 * We'll get the Kafka producer object as a parameter to this function.
 * We'll generate some test messages, both simple strings and JSON objects, in a couple of
 * loops inside the function. We'll send these test messages to the topic in Kafka.
 *
 * @param producer The Kafka producer we created in the run() method earlier.
 */
private void sendTestMessagesToKafka(KafkaProducer<String, String> producer) {
    /*
    Creating a loop which iterates 10 times, from 0 to 9, and sending a
    simple message to Kafka.
     */
    for (int index = 0; index < 10; index++) {
        sendKafkaMessage("The index is now: " + index, producer, theTechCheckTopicName);
    }

    /*
    Creating a loop which iterates 10 times, from 0 to 9, and creates an instance of JSONObject
    in each iteration. We'll use this simple JSON object to illustrate how we can send a JSON
    object as a message in Kafka.
     */
    for (int index = 0; index < 10; index++) {

        /*
        We'll create a JSON object which will have a bunch of fields, and another JSON object,
        which will be nested inside the first JSON object. This is just to demonstrate how
        complex objects could be serialized and sent to topics in Kafka.
         */
        JSONObject jsonObject = new JSONObject();
        JSONObject nestedJsonObject = new JSONObject();

        try {
            /*
            Adding some random data into the JSON object.
             */
            jsonObject.put("index", index);
            jsonObject.put("message", "The index is now: " + index);

            /*
            We're adding a field in the nested JSON object.
             */
            nestedJsonObject.put("nestedObjectMessage", "This is a nested JSON object with index: " + index);

            /*
            Adding the nexted JSON object to the main JSON object.
             */
            jsonObject.put("nestedJsonObject", nestedJsonObject);

        } catch (JSONException e) {
            logger.error(e.getMessage());
        }

        /*
        We'll now serialize the JSON object we created above, and send it to the same topic in Kafka,
        using the same function we used earlier.
        You can use any JSON library for this, just make sure it serializes your objects properly.
        A popular alternative to the one I've used is Gson.
         */
        sendKafkaMessage(jsonObject.toString(), producer, theTechCheckTopicName);
    }
}
 
Example 17
Source File: OperatorDiscoverer.java    From Bats with Apache License 2.0 4 votes vote down vote up
private JSONArray getClassProperties(Class<?> clazz, int level) throws IntrospectionException
{
  JSONArray arr = new JSONArray();
  TypeDiscoverer td = new TypeDiscoverer();
  try {
    for (PropertyDescriptor pd : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) {
      Method readMethod = pd.getReadMethod();
      if (readMethod != null) {
        if (readMethod.getDeclaringClass() == java.lang.Enum.class) {
          // skip getDeclaringClass
          continue;
        } else if ("class".equals(pd.getName())) {
          // skip getClass
          continue;
        }
      } else {
        // yields com.datatorrent.api.Context on JDK6 and com.datatorrent.api.Context.OperatorContext with JDK7
        if ("up".equals(pd.getName()) && org.lealone.bats.api.Context.class.isAssignableFrom(pd.getPropertyType())) {
          continue;
        }
      }
      //LOG.info("name: " + pd.getName() + " type: " + pd.getPropertyType());

      Class<?> propertyType = pd.getPropertyType();
      if (propertyType != null) {
        JSONObject propertyObj = new JSONObject();
        propertyObj.put("name", pd.getName());
        propertyObj.put("canGet", readMethod != null);
        propertyObj.put("canSet", pd.getWriteMethod() != null);
        if (readMethod != null) {
          for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
            OperatorClassInfo oci = classInfo.get(c.getName());
            if (oci != null) {
              MethodInfo getMethodInfo = oci.getMethods.get(readMethod.getName());
              if (getMethodInfo != null) {
                addTagsToProperties(getMethodInfo, propertyObj);
                break;
              }
            }
          }
          // type can be a type symbol or parameterized type
          td.setTypeArguments(clazz, readMethod.getGenericReturnType(), propertyObj);
        } else {
          if (pd.getWriteMethod() != null) {
            td.setTypeArguments(clazz, pd.getWriteMethod().getGenericParameterTypes()[0], propertyObj);
          }
        }
        //if (!propertyType.isPrimitive() && !propertyType.isEnum() && !propertyType.isArray() && !propertyType
        // .getName().startsWith("java.lang") && level < MAX_PROPERTY_LEVELS) {
        //  propertyObj.put("properties", getClassProperties(propertyType, level + 1));
        //}
        arr.put(propertyObj);
      }
    }
  } catch (JSONException ex) {
    throw new RuntimeException(ex);
  }
  return arr;
}
 
Example 18
Source File: CommentsRestClient.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void addCommentJSON(String sid, Long docID) throws Exception {

		String url = BASE_PATH + "/services/mobile/comments/addcomment/$SID/$ID";
		url = url.replace("$SID", sid);
		url = url.replace("$ID", docID.toString());

		CloseableHttpClient httpclient = getHTTPClient("admin", "admin123");

			//Use Jackson to fill just one attribute
			JSONObject site = new JSONObject();
			site.put("content", "This is an incomplete CommentVO");
			String jsonstr = site.toString();

			// Just to show Jackson's complete object mapping
			if (1 == 2) {
				CommentVO comment = new CommentVO();
				comment.setContent("Jackson's complete object mapping");

				ObjectMapper mapper = new ObjectMapper();
				jsonstr = mapper.writeValueAsString(comment);
			}

			System.out.println("json : " + jsonstr);
			
			HttpPost httppost = new HttpPost(url);
			httppost.addHeader(new BasicHeader("Accept", "application/json"));
			
			StringEntity entity = new StringEntity(jsonstr, ContentType.create("application/json", Consts.UTF_8));
			httppost.setEntity(entity);			

			CloseableHttpResponse response = httpclient.execute(httppost);
			
			int code = response.getStatusLine().getStatusCode();
			System.out.println("HTTPstatus code: "+ code);
			if (code == HttpStatus.SC_OK) {
			} else {
				//log.warn("status code is invalid: {}", code);
				System.err.println("status code is invalid: "+ code);
				throw new Exception(response.getStatusLine().getReasonPhrase());
			}				
			
			try {
				HttpEntity rent = response.getEntity();
				if (rent != null) {
					String respoBody = EntityUtils.toString(rent, "UTF-8");
					System.out.println(respoBody);
				}
			} catch (Exception e) {
				throw new Exception("Exception in adding bucket : " + e);
			} finally {
				response.close();
			} 
	}
 
Example 19
Source File: OperatorDiscoveryTest.java    From attic-apex-core with Apache License 2.0 4 votes vote down vote up
@Test
  public void testLogicalPlanConfiguration() throws Exception
  {
    TestOperator<String, Map<String, Number>> bean = new InputTestOperator<>();
    bean.map.put("key1", new Structured());
    bean.stringArray = new String[]{"one", "two", "three"};
    bean.stringList = Lists.newArrayList("four", "five");
    bean.props = new Properties();
    bean.props.setProperty("key1", "value1");
    bean.structuredArray = new Structured[]{new Structured()};
    bean.genericArray = new String[]{"s1"};
    bean.structuredArray[0].name = "s1";
    bean.color = Color.BLUE;
    bean.booleanProp = true;
    bean.realName = "abc";

    ObjectMapper mapper = ObjectMapperFactory.getOperatorValueSerializer();
    String s = mapper.writeValueAsString(bean);
//    LOG.debug(new JSONObject(s).toString(2));
    //
    Assert.assertTrue("Shouldn't contain field 'realName' !", !s.contains("realName"));
    Assert.assertTrue("Should contain property 'alias' !", s.contains("alias"));
    Assert.assertTrue("Shouldn't contain property 'getterOnly' !", !s.contains("getterOnly"));
    JSONObject jsonObj = new JSONObject(s);

    // create the json dag representation
    JSONObject jsonPlan = new JSONObject();
    jsonPlan.put("streams", new JSONArray());
    JSONObject jsonOper = new JSONObject();
    jsonOper.put("name", "Test Operator");
    jsonOper.put("class", InputTestOperator.class.getName());
    jsonOper.put("properties", jsonObj);
    jsonPlan.put("operators", new JSONArray(Lists.newArrayList(jsonOper)));

    Configuration conf = new Configuration(false);
    LogicalPlanConfiguration lpc = new LogicalPlanConfiguration(conf);
    // create logical plan from the json
    LogicalPlan lp = lpc.createFromJson(jsonPlan, "jsontest");
    OperatorMeta om = lp.getOperatorMeta("Test Operator");
    Assert.assertTrue(om.getOperator() instanceof InputTestOperator);
    @SuppressWarnings("rawtypes")
    TestOperator beanBack = (InputTestOperator)om.getOperator();

    // The operator deserialized back from json should be same as original operator
    Assert.assertEquals(bean.map, beanBack.map);
    Assert.assertArrayEquals(bean.stringArray, beanBack.stringArray);
    Assert.assertEquals(bean.stringList, beanBack.stringList);
    Assert.assertEquals(bean.props, beanBack.props);
    Assert.assertArrayEquals(bean.structuredArray, beanBack.structuredArray);
    Assert.assertArrayEquals(bean.genericArray, beanBack.genericArray);
    Assert.assertEquals(bean.color, beanBack.color);
    Assert.assertEquals(bean.booleanProp, beanBack.booleanProp);
    Assert.assertEquals(bean.realName, beanBack.realName);
    Assert.assertEquals(bean.getterOnly, beanBack.getterOnly);

  }
 
Example 20
Source File: MRJobStatusOperator.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@Override
public void process(MRStatusObject mrStatusObj)
{

  if (jobMap == null) {
    jobMap = new HashMap<String, MRStatusObject>();
  }

  if (jobMap.size() >= maxJobs) {
    return;
  }

  if ("delete".equalsIgnoreCase(mrStatusObj.getCommand())) {
    removeJob(mrStatusObj.getJobId());
    JSONObject outputJsonObject = new JSONObject();
    try {
      outputJsonObject.put("id", mrStatusObj.getJobId());
      outputJsonObject.put("removed", "true");
      output.emit(outputJsonObject.toString());
    } catch (JSONException e) {
      LOG.warn("Error creating JSON: {}", e.getMessage());
    }
    return;
  }
  if ("clear".equalsIgnoreCase(mrStatusObj.getCommand())) {
    clearMap();
    return;
  }

  if (jobMap.get(mrStatusObj.getJobId()) != null) {
    mrStatusObj = jobMap.get(mrStatusObj.getJobId());
  }
  if (mrStatusObj.getHadoopVersion() == 2) {
    getJsonForJob(mrStatusObj);
  } else if (mrStatusObj.getHadoopVersion() == 1) {
    getJsonForLegacyJob(mrStatusObj);
  }
  mrStatusObj.setStatusHistoryCount(statusHistoryTime);
  iterator = jobMap.values().iterator();
  emitHelper(mrStatusObj);
}