Java Code Examples for org.json.simple.JSONArray#get()

The following examples show how to use org.json.simple.JSONArray#get() . 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: CartoDBBackendImpl.java    From fiware-cygnus with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public boolean isEmpty(String schema, String tableName) throws Exception {
    // Set the appropiate schema depending on the account type
    schema = (isPersonalAccount ? "public" : schema);
    
    // Do the check
    String query = "SELECT COUNT(*) FROM " + schema + "." + tableName;
    String encodedQuery = URLEncoder.encode(query, "UTF-8");
    String relativeURL = BASE_URL + encodedQuery + "&api_key=" + apiKey;
    JsonResponse response = doRequest("GET", relativeURL, true, null, null);

    // check the status
    if (response.getStatusCode() != 200) {
        throw new CygnusPersistenceError("The query '" + query + "' could not be executed. CartoDB response: "
                + response.getStatusCode() + " " + response.getReasonPhrase());
    } // if
    
    JSONArray rows = (JSONArray) response.getJsonObject().get("rows");
    JSONObject countRow = (JSONObject) rows.get(0);
    Long count = (Long) countRow.get("count");
    return (count == 0);
}
 
Example 2
Source File: Favourite.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static ListResponse<Favourite> parseFavourites(JSONObject jsonObject) throws ParseException
{
	List<Favourite> favourites = new ArrayList<Favourite>();

	JSONObject jsonList = (JSONObject)jsonObject.get("list");
	assertNotNull(jsonList);

	JSONArray jsonEntries = (JSONArray)jsonList.get("entries");
	assertNotNull(jsonEntries);

	for(int i = 0; i < jsonEntries.size(); i++)
	{
		JSONObject jsonEntry = (JSONObject)jsonEntries.get(i);
		JSONObject entry = (JSONObject)jsonEntry.get("entry");
		favourites.add(Favourite.parseFavourite(entry));
	}

	ExpectedPaging paging = ExpectedPaging.parsePagination(jsonList);
	return new ListResponse<Favourite>(paging, favourites);
}
 
Example 3
Source File: UploadPropertiesDialog.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
private ModifiedNameValuePair[] parseProjectJson(String json, boolean initialRefresh) throws ParseException{
	JSONParser parser = new JSONParser();
	JSONObject obj = (JSONObject)parser.parse(json);
	JSONArray projects = (JSONArray)obj.get("projects");
	
	ModifiedNameValuePair[] projectArr = new ModifiedNameValuePair[projects.size()];
	for(int i = 0; i < projectArr.length; i++){
		JSONObject project = (JSONObject)projects.get(i);
		int id = ((Long)project.get("id")).intValue();
		String name = (String)project.get("name");
		projectArr[i] = new ModifiedNameValuePair(name,Integer.toString(id));
	}
	if(projectArr.length > 0) {
		Arrays.sort(projectArr);
		//set the project ids to visible if the names are the same
		for(int i = 0; i < projectArr.length-1; i++){
			if(projectArr[i].getName() != null && projectArr[i].getName().equals(projectArr[i+1].getName())){
				projectArr[i].setUseId(true);
				projectArr[i+1].setUseId(true);
			}
		}
	} else if (!initialRefresh)
		warn(Constant.messages.getString("codedx.refresh.noproject"));
	return projectArr;
}
 
Example 4
Source File: ModelVisualizationJson.java    From opensim-gui with Apache License 2.0 6 votes vote down vote up
/**
 * Whatever GUI operation resulting in Commands for visualizer, these need to be
 * propagated to the corresponding Path points that live in a separate part(s)
 * in the scene graph (e.g. on different bodies)
 * 
 * @param force that has GeometryPath
 * @param prop
 * @param commands 
 */
public void propagateGeometryPathCommandsToPathPoints(Force force, AbstractProperty prop, JSONArray commands) {
    // if anything but show/hide, apply same to first pathpoint
    int lastIndex = commands.size()-1;
    JSONObject lastCommand = (JSONObject) commands.get(lastIndex);
    String commandName = (String) lastCommand.get("name");
    if (commandName.equalsIgnoreCase("SetVisible")){
        lastCommand.put("type", "SetValueCommandMuscle");
    }
    else {
        JSONObject pathpointCommand = (JSONObject) lastCommand.clone();
        if (force.hasGeometryPath()){
            GeometryPath gPath = GeometryPath.safeDownCast(force.getPropertyByName("GeometryPath").getValueAsObject());

            pathpointCommand.put("objectUuid", getFirstPathPointUUID4GeometryPath(gPath).toString());
            commands.add(pathpointCommand);
        }
        else { // internal error, shouldn't be here propagating visualization changes to GeometryPath where none exists
            throw new UnsupportedOperationException("Trying to update GeometryPath of Force that has no GeometryPath:"+force.getName());
        }
    }
}
 
Example 5
Source File: ParserASTJSON.java    From soltix with Apache License 2.0 6 votes vote down vote up
protected void processPragmaDirective(long id, AST ast, JSONObject attributes) throws Exception {
    JSONArray literals = (JSONArray)attributes.get("literals");
    if (literals == null) {
        throw new Exception("Pragma directive without literals attribute");
    }
    if (literals.size() < 1) {
        throw new Exception("Pragma directive with empty literals list");
    }
    String type = (String)literals.get(0);
    String args = null;
    if (literals.size() > 1) {
        args = "";
        for (int i = 1; i < literals.size(); ++i) {
            args += (String)literals.get(i);
        }
    }
    ast.addInnerNode(new ASTPragmaDirective(id, type, args));
}
 
Example 6
Source File: NodeJsDataProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public String getDocForModule(final String moduleName) {
    Object jsonValue;
    JSONArray modules = getModules();
    if (modules != null) {
        for (int i = 0; i < modules.size(); i++) {
            jsonValue = modules.get(i);
            if (jsonValue != null && jsonValue instanceof JSONObject) {
                JSONObject jsonModule = (JSONObject) jsonValue;
                jsonValue = jsonModule.get(NAME);
                if (jsonValue != null && jsonValue instanceof String && moduleName.equals(((String) jsonValue).toLowerCase())) {
                    jsonValue = jsonModule.get(DESCRIPTION);
                    if (jsonValue != null && jsonValue instanceof String) {
                        return (String) jsonValue;
                    }
                }
            }
        }
    }
    return null;
}
 
Example 7
Source File: RestJSONResponseParser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Parse one part of REST server message from JSON response.
 * @param json JSON response.
 * @return One part of REST server message from JSON response.
 */
private MessagePart parseMessagePart(JSONObject json) {
    MessagePart mp = new MessagePart();
    mp.setMessage((String)json.get("message"));
    mp.setProperties(parseProperties(json));
    JSONArray children = (JSONArray)json.get("children");
    if (children != null) {
        mp.children = new ArrayList<>(children.size());
        for (int i = 0 ; i < children.size() ; i++) {
            JSONObject child = (JSONObject)children.get(i);
            mp.children.add(parseMessagePart(child));
        }
    }
    return mp;
}
 
Example 8
Source File: ActivitySummaryParser.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
List<Object> convertJSONArrayToList(JSONArray ja) throws JSONException
{
    List<Object> model = new ArrayList<Object>();
   
    for (int i = 0; i < ja.size(); i++)
    {
        Object o = ja.get(i);
        
        if (o instanceof JSONArray)
        {
            model.add(convertJSONArrayToList((JSONArray)o));
        }
        else if (o instanceof JSONObject)
        {
            model.add(convertJSONObjectToMap((JSONObject)o));
        }
        else if (o == null)
        {
            model.add(null);
        }
        else
        {
            if ((o instanceof String) && autoConvertISO8601 && (matcherISO8601.matcher((String)o).matches()))
            {
                o = ISO8601DateFormat.parse((String)o);
            }
            
            model.add(o);
        }
    }
   
    return model;
}
 
Example 9
Source File: BungeePlayerInfo.java    From AntiVPN with MIT License 5 votes vote down vote up
private static String nameExpensive(UUID uuid) throws IOException {
    // Currently-online lookup
    ProxiedPlayer player = ProxyServer.getInstance().getPlayer(uuid);
    if (player != null) {
        nameCache.put(player.getName(), uuid);
        return player.getName();
    }

    // Network lookup
    HttpURLConnection conn = JSONWebUtil.getConnection(new URL("https://api.mojang.com/user/profiles/" + uuid.toString().replace("-", "") + "/names"), "GET", 5000, "egg82/PlayerInfo", headers);;
    int status = conn.getResponseCode();

    if (status == 204) {
        // No data exists
        return null;
    } else if (status == 200) {
        try {
            JSONArray json = getJSONArray(conn, status);
            JSONObject last = (JSONObject) json.get(json.size() - 1);
            String name = (String) last.get("name");
            nameCache.put(name, uuid);
            return name;
        } catch (ParseException | ClassCastException ex) {
            throw new IOException(ex.getMessage(), ex);
        }
    }

    throw new IOException("Could not load player data from Mojang (rate-limited?)");
}
 
Example 10
Source File: SSTableExportTest.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
/**
 * Tests CASSANDRA-6892 (key aliases being used improperly for validation)
 */
@Test
public void testColumnNameEqualToDefaultKeyAlias() throws IOException, ParseException
{
    File tempSS = tempSSTableFile("Keyspace1", "UUIDKeys");
    ColumnFamily cfamily = ArrayBackedSortedColumns.factory.create("Keyspace1", "UUIDKeys");
    SSTableWriter writer = new SSTableWriter(tempSS.getPath(), 2, ActiveRepairService.UNREPAIRED_SSTABLE);

    // Add a row
    cfamily.addColumn(column(CFMetaData.DEFAULT_KEY_ALIAS, "not a uuid", 1L));
    writer.append(Util.dk(ByteBufferUtil.bytes(UUIDGen.getTimeUUID())), cfamily);

    SSTableReader reader = writer.closeAndOpenReader();
    // Export to JSON and verify
    File tempJson = File.createTempFile("CFWithColumnNameEqualToDefaultKeyAlias", ".json");
    SSTableExport.export(reader, new PrintStream(tempJson.getPath()), new String[0],
            CFMetaData.sparseCFMetaData("Keyspace1", "UUIDKeys", BytesType.instance));

    JSONArray json = (JSONArray)JSONValue.parseWithException(new FileReader(tempJson));
    assertEquals(1, json.size());

    JSONObject row = (JSONObject)json.get(0);
    JSONArray cols = (JSONArray) row.get("cells");
    assertEquals(1, cols.size());

    // check column name and value
    JSONArray col = (JSONArray) cols.get(0);
    assertEquals(CFMetaData.DEFAULT_KEY_ALIAS, ByteBufferUtil.string(hexToBytes((String) col.get(0))));
    assertEquals("not a uuid", ByteBufferUtil.string(hexToBytes((String) col.get(1))));
}
 
Example 11
Source File: TextClickerPybossaFormatter.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
public void publicTaskTranslationTaskPublishForm(String inputData, ClientApp clientApp, int indexStart, int indexEnd) throws Exception{
    try{
        List<TaskTranslation> outputFormatData = new ArrayList<TaskTranslation>();
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(inputData);

        JSONArray jsonObject = (JSONArray) obj;

        for(int i = indexStart; i < indexEnd; i++){
            JSONObject featureJsonObj = (JSONObject)jsonObject.get(i);
            JSONObject data = (JSONObject) parser.parse((String) featureJsonObj.get("data"));

            Long documentID =  (Long)featureJsonObj.get("documentID");
            JSONObject usr =  (JSONObject)data.get("user");
            String userName = (String)usr.get("name");
            String tweetTxt = (String)data.get("text");
            String tweetID =  String.valueOf(data.get("id"));

            TaskTranslation task = new TaskTranslation(clientApp.getClientAppID(),documentID, tweetID, userName, tweetTxt, TaskTranslation.STATUS_NEW);
            //outputFormatData.add(task);
            translationService.createTranslation(task);

        }
    }
    catch(Exception e){
        System.out.println("publicTaskTranslationTaskPublishForm : " + e);
    }


   // return outputFormatData;
}
 
Example 12
Source File: PaasifyCrawler.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private void parseVersion(String name, JSONObject service, Offering offering) {
    JSONArray versions = (JSONArray) service.get("versions");

    if (versions != null && versions.size() > 0) {
        String version = (String) versions.get(versions.size() - 1);

        if (version.indexOf('*') == -1) {
            if (name.equals("java")) { // per java la versione da prendere non è 1.x, ma 6,7,8..
                version = version.substring(2);
            }

            offering.addProperty(name + "_version", version);
        }
    }
}
 
Example 13
Source File: SenderTest.java    From gcm with Apache License 2.0 5 votes vote down vote up
private void assertRequestJsonBody(String...expectedRegIds) throws Exception {
  ArgumentCaptor<String> capturedBody = ArgumentCaptor.forClass(String.class);
  verify(sender).post(
      eq(Constants.FCM_SEND_ENDPOINT),
      eq("application/json"),
      capturedBody.capture());
  // parse body
  String body = capturedBody.getValue();
  JSONObject json = (JSONObject) jsonParser.parse(body);
  assertEquals(ttl, ((Long) json.get("time_to_live")).intValue());
  assertEquals(collapseKey, json.get("collapse_key"));
  assertEquals(delayWhileIdle, json.get("delay_while_idle"));
  assertEquals(dryRun, json.get("dry_run"));
  assertEquals(restrictedPackageName, json.get("restricted_package_name"));
  @SuppressWarnings("unchecked")
  Map<String, Object> payload = (Map<String, Object>) json.get("data");
  assertNotNull("no payload", payload);
  assertEquals("wrong payload size", 5, payload.size());
  assertEquals("v0", payload.get("null"));
  assertNull(payload.get("v0"));
  assertEquals("v1", payload.get("k1"));
  assertEquals("v2", payload.get("k2"));
  assertEquals("v3", payload.get("k3"));
  JSONArray actualRegIds = (JSONArray) json.get("registration_ids");
  assertEquals("Wrong number of regIds",
      expectedRegIds.length, actualRegIds.size());
  for (int i = 0; i < expectedRegIds.length; i++) {
    String expectedRegId = expectedRegIds[i];
    String actualRegId = (String) actualRegIds.get(i);
    assertEquals("invalid regId at index " + i, expectedRegId, actualRegId);
  }
}
 
Example 14
Source File: EntityArcGisUtils.java    From fiware-cygnus with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param bodyJSON
 * @return
 */
public List<Entity> createEntities(JSONArray jsonArray, String service, String servicePath) {
    LOGGER.debug("init createEntities(jsonArray --> " + jsonArray + ")");
    List<Entity> listEntity = new ArrayList<Entity>();

    for (int i = 0; i < jsonArray.size(); i++) {
        JSONObject jsonObject = (JSONObject) jsonArray.get(i);
        listEntity.add(createEntity(jsonObject, service, servicePath));
    } // for
    LOGGER.debug("listEntity--> " + listEntity);
    return listEntity;

}
 
Example 15
Source File: AssociationEndCreateViaNPTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * EntityTypeからNP経由でAssociationEndを登録できること.
 * @throws ParseException パースエラー
 */
@Test
public final void EntityTypeからNP経由でAssociationEndを登録できること() throws ParseException {
    String entityType1 = "AssociationEndTestEntity1";

    String assocEntity1of1 = "AssociationEndTestEntity1-1";

    try {
        // EntityType作成
        EntityTypeUtils.create(Setup.TEST_CELL1, MASTER_TOKEN_NAME, Setup.TEST_BOX1, Setup.TEST_ODATA,
                entityType1, HttpStatus.SC_CREATED);

        // AssociationEnd NP経由登録
        AssociationEndUtils.createViaEntityTypeNP(
                MASTER_TOKEN_NAME, Setup.TEST_CELL1, Setup.TEST_BOX1, Setup.TEST_ODATA,
                assocEntity1of1, "*", entityType1, HttpStatus.SC_CREATED);

        // AssociationEndの EntityTypeからのNP経由一覧取得
        TResponse res = AssociationEndUtils.listViaAssociationEndNP(MASTER_TOKEN_NAME, Setup.TEST_CELL1,
                Setup.TEST_BOX1, Setup.TEST_ODATA, "EntityType", entityType1, HttpStatus.SC_OK);
        JSONArray results = (JSONArray) ((JSONObject) res.bodyAsJson().get("d")).get("results");
        assertEquals(1, results.size());
        JSONObject body = (JSONObject) results.get(0);
        assertEquals(assocEntity1of1, body.get("Name"));

    } finally {
        // AssociationEndの削除
        AssociationEndUtils.delete(AbstractCase.MASTER_TOKEN_NAME, Setup.TEST_CELL1, Setup.TEST_ODATA, entityType1,
                Setup.TEST_BOX1, assocEntity1of1, -1);

        // EntityTypeの削除
        EntityTypeUtils.delete(Setup.TEST_ODATA, MASTER_TOKEN_NAME, MediaType.APPLICATION_JSON,
                entityType1, Setup.TEST_BOX1, Setup.TEST_CELL1, -1);
    }
}
 
Example 16
Source File: TextClickerPybossaFormatter.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
private String[] getQuestion(ClientAppAnswer clientAppAnswer, JSONParser parser) throws ParseException {
    String answerKey =   clientAppAnswer.getAnswer();
    System.out.println("getQuestion : " + answerKey);
    JSONArray questionArrary =   (JSONArray) parser.parse(answerKey) ;
    int questionSize =  questionArrary.size();
    String[] questions = new String[questionSize];

    for(int i=0; i< questionSize; i++){
        JSONObject obj = (JSONObject)questionArrary.get(i);
        questions[i] =   (String)obj.get("qa");
    }

    return questions;
}
 
Example 17
Source File: TestLinkBean.java    From sqoop-on-spark with Apache License 2.0 4 votes vote down vote up
@Test
public void testLinkSerialization() {
  Date created = new Date();
  Date updated = new Date();
  MLink link = BeanTestUtil.createLink("ahoj", "link1", 22L, created, updated);

  // Fill some data at the beginning
  MStringInput input = (MStringInput) link.getConnectorLinkConfig().getConfigs().get(0)
      .getInputs().get(0);
  input.setValue("Hi there!");

  // Serialize it to JSON object
  LinkBean linkBean = new LinkBean(link);
  JSONObject json = linkBean.extract(false);

  // Check for sensitivity
  JSONObject linkObj = (JSONObject) json.get(LinkBean.LINK);
  JSONArray linkConfigs = (JSONArray) linkObj.get(LinkBean.LINK_CONFIG_VALUES);
  JSONObject linkConfig = (JSONObject) linkConfigs.get(0);
  JSONArray inputs = (JSONArray) linkConfig.get(ConfigInputConstants.CONFIG_INPUTS);
  for (Object in : inputs) {
    assertTrue(((JSONObject) in).containsKey(ConfigInputConstants.CONFIG_INPUT_SENSITIVE));
  }

  // "Move" it across network in text form
  String linkJsonString = json.toJSONString();

  // Retrieved transferred object
  JSONObject parsedLinkJson = JSONUtils.parse(linkJsonString);
  LinkBean retrievedBean = new LinkBean();
  retrievedBean.restore(parsedLinkJson);
  MLink retrievedLink = retrievedBean.getLinks().get(0);

  // Check id and name
  assertEquals(22L, retrievedLink.getPersistenceId());
  assertEquals("link1", retrievedLink.getName());
  assertEquals("admin", retrievedLink.getCreationUser());
  assertEquals(created, retrievedLink.getCreationDate());
  assertEquals("user", retrievedLink.getLastUpdateUser());
  assertEquals(updated, retrievedLink.getLastUpdateDate());
  assertEquals(false, retrievedLink.getEnabled());

  // Test that value was correctly moved
  MStringInput retrievedLinkInput = (MStringInput) retrievedLink.getConnectorLinkConfig().getConfigs().get(0)
      .getInputs().get(0);
  assertEquals("Hi there!", retrievedLinkInput.getValue());
}
 
Example 18
Source File: ArffFileFromRun.java    From NLIWOD with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
HAWK hawk = new HAWK();
SINA sina = new SINA();
QAKIS qakis = new QAKIS();
YODA yoda = new YODA();

/*
 * For multilable classification:
 */

ArrayList<String> fvhawk = new ArrayList<String>();
fvhawk.add("1");
fvhawk.add("0");
Attribute hawkatt = new Attribute("hawk", fvhawk);

ArrayList<String> fvqakis = new ArrayList<String>();
fvqakis.add("1");
fvqakis.add("0");
Attribute qakisatt = new Attribute("qakis", fvqakis);

ArrayList<String> fvyoda = new ArrayList<String>();
fvyoda.add("1");
fvyoda.add("0");
Attribute yodaatt = new Attribute("yoda", fvyoda);

ArrayList<String> fvsina = new ArrayList<String>();
fvsina.add("1");
fvsina.add("0");
Attribute sinaatt = new Attribute("sina", fvsina);


/*
 * 
 */

// 1. Learn on the training data for each system a classifier to find
// out which system can answer which question

// 1.1 load the questions and how good each system answers
log.debug("Load the questions and how good each system answers");
List<IQuestion> trainQuestions = LoaderController.load(Dataset.QALD6_Train_Multilingual);
List<ASystem> systems = Lists.newArrayList(hawk, sina, qakis, yoda);
JSONArray traindata = RunProducer.loadRunData(Dataset.QALD6_Train_Multilingual);

// 1.2 calculate the features per question and system
log.debug("Calculate the features per question and system");
Analyzer analyzer = new Analyzer();
ArrayList<Attribute> fvfinal = analyzer.fvWekaAttributes;

fvfinal.add(0, hawkatt);
fvfinal.add(0, yodaatt);
fvfinal.add(0, sinaatt);
fvfinal.add(0,qakisatt);


Instances trainingSet = new Instances("training_classifier: -C 4" , fvfinal, trainQuestions.size());
log.debug("Start collection of training data for each system");

	
for (int i = 0; i < traindata.size(); i++) {
	JSONObject questiondata = (JSONObject) traindata.get(i);
	JSONObject allsystemsdata = (JSONObject) questiondata.get("answers");
	String question = (String) questiondata.get("question");
	Instance tmp = analyzer.analyze(question);

	tmp.setValue(hawkatt, 0);
	tmp.setValue(yodaatt, 0);
	tmp.setValue(sinaatt, 0);
	tmp.setValue(qakisatt, 0);

	for(ASystem system: systems){
		JSONObject systemdata = (JSONObject) allsystemsdata.get(system.name());
		if(new Double(systemdata.get("fmeasure").toString()) > 0)
			switch (system.name()){
			case "hawk": tmp.setValue(hawkatt, 1); break;
			case "yoda": tmp.setValue(yodaatt, 1); break;
			case "sina": tmp.setValue(sinaatt, 1); break;
			case "qakis": tmp.setValue(qakisatt, 1); break;
			}
		}

	trainingSet.add(tmp);
	}
log.debug(trainingSet.toString());

try (FileWriter file = new FileWriter("./src/main/resources/old/Train.arff")) {
	file.write(trainingSet.toString());
} catch (IOException e) {
	e.printStackTrace();
}				
}
 
Example 19
Source File: DateManagerServiceImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public DateManagerValidation validateAssessments(String siteId, JSONArray assessments) throws Exception {
	DateManagerValidation assessmentValidate = new DateManagerValidation();
	List<DateManagerError> errors = new ArrayList<>();
	List<Object> updates = new ArrayList<>();
	String toolTitle = toolManager.getTool(DateManagerConstants.COMMON_ID_ASSESSMENTS).getTitle();
	for (int i = 0; i < assessments.size(); i++) {
		JSONObject jsonAssessment = (JSONObject)assessments.get(i);
		Long assessmentId = Long.parseLong(jsonAssessment.get("id").toString());
		int idx = Integer.parseInt(jsonAssessment.get("idx").toString());

		try {

			/* VALIDATE IF USER CAN UPDATE THE ASSESSMENT */

			Instant openDate = userTimeService.parseISODateInUserTimezone((String)jsonAssessment.get("open_date")).toInstant();
			Instant dueDate = userTimeService.parseISODateInUserTimezone((String)jsonAssessment.get("due_date")).toInstant();
			Instant acceptUntil = userTimeService.parseISODateInUserTimezone((String)jsonAssessment.get("accept_until")).toInstant();
			boolean isDraft = Boolean.parseBoolean(jsonAssessment.get("is_draft").toString());

			Object assessment;
			AssessmentAccessControlIfc control;
			if (isDraft) {
				assessment = assessmentServiceQueries.getAssessment(assessmentId);
				control = ((AssessmentFacade) assessment).getAssessmentAccessControl();
			} else {
				assessment = pubAssessmentServiceQueries.getPublishedAssessment(assessmentId);
				control = ((PublishedAssessmentFacade) assessment).getAssessmentAccessControl();
			}
			boolean lateHandling = control.getLateHandling() != null && control.getLateHandling() == AssessmentAccessControlIfc.ACCEPT_LATE_SUBMISSION;

			if (assessment == null) {
				errors.add(new DateManagerError("assessment", rb.getFormattedMessage("error.item.not.found", new Object[]{rb.getString("tool.assessments.item.name")}), "assessments", toolTitle, idx));
				continue;
			}
			boolean errored = false;

			if (openDate == null) {
				errors.add(new DateManagerError("open_date", rb.getString("error.open.date.not.found"), "assessments", toolTitle, idx));
				errored = true;
			}
			if (dueDate == null) {
				errors.add(new DateManagerError("due_date", rb.getString("error.due.date.not.found"), "assessments", toolTitle, idx));
				errored = true;
			}
			if (acceptUntil == null && lateHandling) {
				errors.add(new DateManagerError("accept_until", rb.getString("error.accept.until.not.found"), "assessments", toolTitle, i));
				errored = true;
			}

			if (errored) {
				continue;
			}

			log.debug("Open {} ; Due {} ; Until {}", jsonAssessment.get("open_date_label"), jsonAssessment.get("due_date_label"), jsonAssessment.get("accept_until_label"));
			if(StringUtils.isBlank((String)jsonAssessment.get("due_date_label"))) {
				dueDate = null;
			}
			if(StringUtils.isBlank((String)jsonAssessment.get("accept_until_label"))) {
				acceptUntil = null;
			}

			DateManagerUpdate update = new DateManagerUpdate(assessment, openDate, dueDate, acceptUntil);

			if (dueDate != null && !update.openDate.isBefore(update.dueDate)) {
				errors.add(new DateManagerError("open_date", rb.getString("error.open.date.before.due.date"), "assessments", toolTitle, idx));
				continue;
			}

			if (lateHandling && dueDate != null && acceptUntil != null && update.dueDate.isAfter(update.acceptUntilDate)) {
				errors.add(new DateManagerError("due_date", rb.getString("error.due.date.before.accept.until"), "assessments", toolTitle, idx));
				continue;
			}

			updates.add(update);

		} catch (Exception ex) {
			errors.add(new DateManagerError("open_date", rb.getString("error.uncaught"), "assessments", toolTitle, idx));
			log.error("Error trying to validate Tests & Quizzes {}", ex);
		}
	}

	assessmentValidate.setErrors(errors);
	assessmentValidate.setUpdates(updates);
	return assessmentValidate;
}
 
Example 20
Source File: Updater.java    From askyblock with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Make a connection to the BukkitDev API and request the newest file's details.
 *
 * @return true if successful.
 */
private boolean read() {
    try {
        final URLConnection conn = this.url.openConnection();
        conn.setConnectTimeout(5000);

        if (this.apiKey != null) {
            conn.addRequestProperty("X-API-Key", this.apiKey);
        }
        conn.addRequestProperty("User-Agent", Updater.USER_AGENT);

        conn.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.isEmpty()) {
            this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id);
            this.result = UpdateResult.FAIL_BADID;
            return false;
        }

        JSONObject latestUpdate = (JSONObject) array.get(array.size() - 1);
        this.versionName = (String) latestUpdate.get(Updater.TITLE_VALUE);
        this.versionLink = (String) latestUpdate.get(Updater.LINK_VALUE);
        this.versionType = (String) latestUpdate.get(Updater.TYPE_VALUE);
        this.versionGameVersion = (String) latestUpdate.get(Updater.VERSION_VALUE);

        return true;
    } catch (final IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            this.plugin.getLogger().severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
            this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct.");
            this.result = UpdateResult.FAIL_APIKEY;
        } else {
            this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating.");
            this.plugin.getLogger().severe("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
            this.result = UpdateResult.FAIL_DBO;
        }
        this.plugin.getLogger().log(Level.SEVERE, null, e);
        return false;
    }
}