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

The following examples show how to use org.json.simple.JSONArray#size() . 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: UtilsStaticAnalyzer.java    From apogen with Apache License 2.0 7 votes vote down vote up
/**
 * sets the Edge objects of a class with the information retrieved in the
 * result.json file
 * 
 * @param state
 * @param edges
 * @param s
 */
private static void setConnections(Object state, JSONArray edges, State s) {

	for (int j = 0; j < edges.size(); j++) {
		JSONObject connection = (JSONObject) edges.get(j);

		if (connection.get("from").equals((String) state)) {
			Edge e = new Edge((String) connection.get("from"), (String) connection.get("to"));

			e.setVia((String) connection.get("id"));
			e.setEvent((String) (String) connection.get("eventType"));

			s.addConnection(e);
		}
	}

}
 
Example 2
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 3
Source File: JSONReader.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static V8Breakpoint.ActualLocation[] getActualLocations(JSONArray array) {
    int n = array.size();
    V8Breakpoint.ActualLocation[] locations = new V8Breakpoint.ActualLocation[n];
    for (int i = 0; i < n; i++) {
        JSONObject location = (JSONObject) array.get(i);
        long line = getLong(location, LINE);
        long column = getLong(location, COLUMN);
        String scriptName = getString(location, SCRIPT_NAME);
        if (scriptName != null) {
            locations[i] = new V8Breakpoint.ActualLocation(line, column, scriptName);
        } else {
            long scriptId = getLong(location, SCRIPT_ID);
            locations[i] = new V8Breakpoint.ActualLocation(line, column, scriptId);
        }
    }
    return locations;
}
 
Example 4
Source File: JSONBasicRollupOutputSerializerTest.java    From blueflood with Apache License 2.0 6 votes vote down vote up
@Test
public void setTimers() throws Exception {
    final JSONBasicRollupsOutputSerializer serializer = new JSONBasicRollupsOutputSerializer();
    final MetricData metricData = new MetricData(
            FakeMetricDataGenerator.generateFakeTimerRollups(),
            "unknown");
    
    JSONObject metricDataJSON = serializer.transformRollupData(metricData, PlotRequestParser.DEFAULT_TIMER);
    final JSONArray data = (JSONArray)metricDataJSON.get("values");
    
    Assert.assertEquals(5, data.size());
    for (int i = 0; i < data.size(); i++) {
        final JSONObject dataJSON = (JSONObject)data.get(i);
        
        Assert.assertNotNull(dataJSON.get("numPoints"));
        Assert.assertNotNull(dataJSON.get("average"));
        Assert.assertNotNull(dataJSON.get("rate"));
        
        // bah. I'm too lazy to check equals.
    }
}
 
Example 5
Source File: APIAdminImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public List<BotDetectionData> retrieveBotDetectionData() throws APIManagementException {

    List<BotDetectionData> botDetectionDatalist = new ArrayList<>();
    String appName = AlertMgtConstants.APIM_ALERT_BOT_DETECTION_APP;
    String query = SQLConstants.BotDataConstants.GET_BOT_DETECTED_DATA;

    JSONObject botDataJsonObject = APIUtil.executeQueryOnStreamProcessor(appName, query);
    if (botDataJsonObject != null) {
        JSONArray botDataJsonArray = (JSONArray) botDataJsonObject.get("records");
        if (botDataJsonArray != null && botDataJsonArray.size() != 0) {
            for (Object botData : botDataJsonArray) {
                JSONArray values = (JSONArray) botData;
                BotDetectionData botDetectionData = new BotDetectionData();
                botDetectionData.setCurrentTime((Long) values.get(0));
                botDetectionData.setMessageID((String) values.get(1));
                botDetectionData.setApiMethod((String) values.get(2));
                botDetectionData.setHeaderSet((String) values.get(3));
                botDetectionData.setMessageBody(extractBotDetectionDataContent((String) values.get(4)));
                botDetectionData.setClientIp((String) values.get(5));
                botDetectionDatalist.add(botDetectionData);
            }
        }
    }
    return botDetectionDatalist;
}
 
Example 6
Source File: JsonSimpleConfigParser.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
private List<Group> parseGroups(JSONArray groupJson) {
    List<Group> groups = new ArrayList<Group>(groupJson.size());

    for (Object obj : groupJson) {
        JSONObject groupObject = (JSONObject) obj;
        String id = (String) groupObject.get("id");
        String policy = (String) groupObject.get("policy");
        List<Experiment> experiments = parseExperiments((JSONArray) groupObject.get("experiments"), id);
        List<TrafficAllocation> trafficAllocations =
            parseTrafficAllocation((JSONArray) groupObject.get("trafficAllocation"));

        groups.add(new Group(id, policy, experiments, trafficAllocations));
    }

    return groups;
}
 
Example 7
Source File: FavouriteSite.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static ListResponse<FavouriteSite> parseFavouriteSites(JSONObject jsonObject)
{
	JSONObject jsonList = (JSONObject)jsonObject.get("list");
	List<FavouriteSite> favouriteSites = new ArrayList<FavouriteSite>(jsonList.size());
	if(jsonList != null)
	{
		JSONArray jsonEntries = (JSONArray)jsonList.get("entries");
		if(jsonEntries != null)
		{
			for(int i = 0; i < jsonEntries.size(); i++)
			{
				JSONObject jsonEntry = (JSONObject)jsonEntries.get(i);
				JSONObject entry = (JSONObject)jsonEntry.get("entry");
				favouriteSites.add(parseFavouriteSite(entry));
			}
		}
	}

	ExpectedPaging paging = ExpectedPaging.parsePagination(jsonList);
	return new ListResponse<FavouriteSite>(paging, favouriteSites);
}
 
Example 8
Source File: JSONBasicRollupOutputSerializerTest.java    From blueflood with Apache License 2.0 6 votes vote down vote up
@Test
public void testGauges() throws Exception {
    final JSONBasicRollupsOutputSerializer serializer = new JSONBasicRollupsOutputSerializer();
    final MetricData metricData = new MetricData(
            FakeMetricDataGenerator.generateFakeGaugeRollups(),
            "unknown");
    JSONObject metricDataJSON = serializer.transformRollupData(metricData, PlotRequestParser.DEFAULT_GAUGE);
    final JSONArray data = (JSONArray)metricDataJSON.get("values");
    
    Assert.assertEquals(5, data.size());
    for (int i = 0; i < data.size(); i++) {
        final JSONObject dataJSON = (JSONObject)data.get(i);
        
        Assert.assertNotNull(dataJSON.get("numPoints"));
        Assert.assertEquals(1L, dataJSON.get("numPoints"));
        Assert.assertNotNull("latest");
        Assert.assertEquals(i, dataJSON.get("latest"));
        
        // other fields were filtered out.
        Assert.assertNull(dataJSON.get(MetricStat.AVERAGE.toString()));
        Assert.assertNull(dataJSON.get(MetricStat.VARIANCE.toString()));
        Assert.assertNull(dataJSON.get(MetricStat.MIN.toString()));
        Assert.assertNull(dataJSON.get(MetricStat.MAX.toString()));
    }
}
 
Example 9
Source File: JSONReader.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static V8Breakpoint[] getBreakpoints(JSONArray array) {
    int n = array.size();
    V8Breakpoint[] breakpoints = new V8Breakpoint[n];
    for (int i = 0; i < n; i++) {
        breakpoints[i] = getBreakpoint((JSONObject) array.get(i));
    }
    return breakpoints;
}
 
Example 10
Source File: StyleSheetBody.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@code StyleSheetBody} that corresponds to the given JSONObject.
 *
 * @param header header of the style-sheet.
 * @param body JSONObject describing the body of the stylesheet.
 */
StyleSheetBody(StyleSheetHeader header, JSONObject body) {
    styleSheetHeader = header;
    styleSheetId = (String)body.get("styleSheetId"); // NOI18N
    JSONArray cssRules = (JSONArray)body.get("rules"); // NOI18N
    rules = new ArrayList<Rule>(cssRules.size());
    for (Object o : cssRules) {
        JSONObject cssRule = (JSONObject)o;
        Rule rule = new Rule(cssRule);
        rule.setParentStyleSheet(this);
        rules.add(rule);
    }
    text = (String)body.get("text"); // NOI18N
}
 
Example 11
Source File: Util.java    From SeedSearcherStandaloneTool with GNU General Public License v3.0 5 votes vote down vote up
public Object generateSearchLists(JSONObject obj, String searchName)  {
	ArrayList<String> list = new ArrayList<String>();
	HashMap<String, String> hashList = new HashMap<String, String>();
	String minecraftVersion = Singleton.getInstance().getMinecraftVersion();
	Map<String, Integer> versions = Version.getVersions();
	for(Iterator iterator = obj.keySet().iterator(); iterator.hasNext();) {
		String key = (String) iterator.next();
		//System.out.println(Integer.valueOf(versions.get(minecraftVersion)));
		if(Integer.valueOf(key) <= Integer.valueOf(versions.get(minecraftVersion))){
			JSONObject subGroup = (JSONObject) obj.get(key);
			for(Iterator iterator1 = subGroup.keySet().iterator(); iterator1.hasNext();){
				String key1 = (String) iterator1.next();
				JSONArray subGArray = (JSONArray)subGroup.get(key1);
				if(searchName == "Biome Sets"){
					list.add(key1);
				} else {
					for(int i = 0; i < subGArray.size(); i++){
                           if(searchName == "getBiomeSets") {
                               hashList.put((String)subGArray.get(i), key1);

                           } else {
                               list.add((String)subGArray.get(i));
                           }
					}
				}
			}
		}
	}
       if(searchName == "getBiomeSets") {
           return hashList;
       } else {
           return list;
       }
}
 
Example 12
Source File: JsonSimpleConfigParser.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
private List<FeatureVariableUsageInstance> parseFeatureVariableInstances(JSONArray featureVariableInstancesJson) {
    List<FeatureVariableUsageInstance> featureVariableUsageInstances =
        new ArrayList<FeatureVariableUsageInstance>(featureVariableInstancesJson.size());

    for (Object obj : featureVariableInstancesJson) {
        JSONObject featureVariableInstanceObject = (JSONObject) obj;
        String id = (String) featureVariableInstanceObject.get("id");
        String value = (String) featureVariableInstanceObject.get("value");

        featureVariableUsageInstances.add(new FeatureVariableUsageInstance(id, value));
    }

    return featureVariableUsageInstances;
}
 
Example 13
Source File: SerializableMetaStore.java    From kettle-beam with Apache License 2.0 5 votes vote down vote up
private void readNamespace( JSONObject jNamespace ) throws MetaStoreException {

    String namespace = (String) jNamespace.get( "name" );
    createNamespace( namespace );

    JSONArray jTypes = (JSONArray) jNamespace.get( "types" );
    for (int t=0;t<jTypes.size();t++) {
      JSONObject jType = (JSONObject) jTypes.get(t);
      readElementType(namespace, jType);
    }
  }
 
Example 14
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 15
Source File: DigitalSTROMJSONImpl.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public List<Integer> getResolutions(String token) {
    String response = null;

    response = transport.execute(
            JSONRequestConstants.JSON_METERING_GET_RESOLUTIONS + JSONRequestConstants.PARAMETER_TOKEN + token);

    JSONObject responseObj = handler.toJSONObject(response);

    if (handler.checkResponse(responseObj)) {
        JSONObject resObj = handler.getResultJSONObject(responseObj);

        if (resObj != null
                && resObj.get(JSONApiResponseKeysEnum.METERING_GET_RESOLUTIONS.getKey()) instanceof JSONArray) {
            JSONArray array = (JSONArray) resObj.get(JSONApiResponseKeysEnum.METERING_GET_RESOLUTIONS.getKey());

            List<Integer> resolutionList = new LinkedList<Integer>();

            for (int i = 0; i < array.size(); i++) {
                if (array.get(i) instanceof org.json.simple.JSONObject) {
                    JSONObject jObject = (JSONObject) array.get(i);

                    if (jObject.get(JSONApiResponseKeysEnum.METERING_GET_RESOLUTION.getKey()) != null) {
                        int val = -1;
                        try {
                            val = Integer.parseInt(jObject
                                    .get(JSONApiResponseKeysEnum.METERING_GET_RESOLUTION.getKey()).toString());
                        } catch (java.lang.NumberFormatException e) {
                            logger.error("NumberFormatException in getResolutions: " + jObject
                                    .get(JSONApiResponseKeysEnum.METERING_GET_RESOLUTION.getKey()).toString());
                        }
                        if (val != -1) {
                            resolutionList.add(val);
                        }
                    }
                }
            }
            return resolutionList;
        }
    }

    return null;
}
 
Example 16
Source File: DateManagerServiceImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public DateManagerValidation validateSignupMeetings(String siteId, JSONArray signupMeetings) throws Exception {
	DateManagerValidation meetingsValidate = new DateManagerValidation();
	List<DateManagerError> errors = new ArrayList<>();
	List<Object> updates = new ArrayList<>();

	boolean canUpdate = signupService.isAllowedToCreateinSite(getCurrentUserId(), getCurrentSiteId());
	String toolTitle = toolManager.getTool(DateManagerConstants.COMMON_ID_SIGNUP).getTitle();
	if (!canUpdate) {
		errors.add(new DateManagerError("signup", rb.getString("error.update.permission.denied"), "signupMeetings", toolTitle, 0));
	}
	for (int i = 0; i < signupMeetings.size(); i++) {
		JSONObject jsonMeeting = (JSONObject)signupMeetings.get(i);
		int idx = Integer.parseInt(jsonMeeting.get("idx").toString());

		try {

			Long meetingId = (Long)jsonMeeting.get("id");
			if (meetingId == null) {
				errors.add(new DateManagerError("signup", rb.getFormattedMessage("error.item.not.found", new Object[]{rb.getString("tool.signup.item.name")}), "signupMeetings", toolTitle, idx));
				continue;
			}

			Instant openDate = userTimeService.parseISODateInUserTimezone((String)jsonMeeting.get("open_date")).toInstant();
			Instant dueDate = userTimeService.parseISODateInUserTimezone((String)jsonMeeting.get("due_date")).toInstant();
			boolean errored = false;
			if (openDate == null) {
				errors.add(new DateManagerError("open_date", rb.getString("error.open.date.not.found"), "signupMeetings", toolTitle, idx));
				errored = true;
			}
			if (dueDate == null) {
				errors.add(new DateManagerError("due_date", rb.getString("error.due.date.not.found"), "signupMeetings", toolTitle, idx));
				errored = true;
			}
			if (errored) {
				continue;
			}

			SignupMeeting meeting = signupService.loadSignupMeeting(meetingId, getCurrentUserId(), getCurrentSiteId());
			if (meeting == null) {
				errors.add(new DateManagerError("signup", rb.getFormattedMessage("error.item.not.found", new Object[]{rb.getString("tool.signup.item.name")}), "signupMeetings", toolTitle, idx));
				continue;
			}

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

		} catch (Exception ex) {
			errors.add(new DateManagerError("open_date", rb.getString("error.uncaught"), "signupMeetings", toolTitle, idx));
			log.error("Error trying to validate Sign Up {}", ex);
		}
	}
	meetingsValidate.setErrors(errors);
	meetingsValidate.setUpdates(updates);
	return meetingsValidate;
}
 
Example 17
Source File: CDTClassifierMultilable.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 {		
/*
 * For multilable classification:
 */

//The classifier
RAkELd PSt_Classifier = new RAkELd();
//load the data
Path datapath= Paths.get("./src/main/resources/old/Qald6Logs.arff");
BufferedReader reader = new BufferedReader(new FileReader(datapath.toString()));
ArffReader arff = new ArffReader(reader);
Instances data = arff.getData();
data.setClassIndex(6);
PSt_Classifier.buildClassifier(data);		/*
 * Test the trained system
 */

JSONObject qald6test = loadTestQuestions();
JSONArray questions = (JSONArray) qald6test.get("questions");
ArrayList<String> testQuestions = Lists.newArrayList();
for(int i = 0; i < questions.size(); i++){
	JSONObject questionData = (JSONObject) questions.get(i);
	JSONArray questionStrings = (JSONArray) questionData.get("question");
	JSONObject questionEnglish = (JSONObject) questionStrings.get(0);
	testQuestions.add((String) questionEnglish.get("string"));
}


ArrayList<String> systems = Lists.newArrayList("KWGAnswer", "NbFramework", "PersianQA", "SemGraphQA", "UIQA_withoutManualEntries", "UTQA_English" );
double ave_f = 0;
Double ave_bestp = 0.0;
Double ave_bestr = 0.0;

for(int j = 0; j < data.size(); j++){
	Instance ins = data.get(j);
	double[] confidences = PSt_Classifier.distributionForInstance(ins);
	int argmax = -1;
	double max = -1;
		for(int i = 0; i < 6; i++){
			if(confidences[i]>max){
				max = confidences[i];
				argmax = i;
			}
		}
		//compare trained system with best possible system
		
		String sys2ask = systems.get(systems.size() - argmax -1);
		float p = Float.parseFloat(loadSystemP(sys2ask).get(j));				
		float r = Float.parseFloat(loadSystemR(sys2ask).get(j));
		
		double bestp = 0;
		double bestr = 0;
		String bestSystemp = "";
		String bestSystemr = ""; 
		for(String system:systems){
			if(Double.parseDouble(loadSystemP(system).get(j)) > bestp){bestSystemp = system; bestp = Double.parseDouble(loadSystemP(system).get(j));}; 
			if(Double.parseDouble(loadSystemR(system).get(j)) > bestr){bestSystemr = system; bestr = Double.parseDouble(loadSystemR(system).get(j));}; 
			}
		ave_bestp += bestp;
		ave_bestr += bestr;
		System.out.println(testQuestions.get(j));
		System.out.println(j + "... asked " + sys2ask + " with p " + loadSystemP(sys2ask).get(j) + "... best possible p: " + bestp + " was achieved by " + bestSystemp);
		System.out.println(j + "... asked " + sys2ask + " with r " + loadSystemR(sys2ask).get(j) + "... best possible r: " + bestr + " was achieved by " + bestSystemr);
		if(p>0&&r>0){ave_f += 2*p*r/(p + r);}

		}
System.out.println("macro F : " + ave_f/data.size());
}
 
Example 18
Source File: ReportGenUtil.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Get microgateway request summary report as a pdf.
 * @param username
 * @param date month with year. Format should be yyyy-mm (ex: 2018-07)
 * @return inputstream InputStream of the pdf
 * @throws APIManagementException exception
 */
public static InputStream getMicroGatewayRequestSummaryReport(String username, String date)
        throws APIManagementException {
    InputStream pdfInputStream = null;
    // get data
    String value = "0"; //default 
    String appName = "APIM_ACCESS_SUMMARY";
    String query = "from ApiUserPerAppAgg on gatewayType=='MICRO' within '" + date 
            + "-** **:**:**' per 'months' SELECT sum(totalRequestCount) as sum;";
    
    JSONObject jsonObj = APIUtil.executeQueryOnStreamProcessor(appName, query);
    JSONArray jarray =  (JSONArray) jsonObj.get("records");
    if(jarray != null && jarray.size() != 0) {
        JSONArray val = (JSONArray) jarray.get(0);
        Long result = (Long) val.get(0);
        value = String.valueOf(result);
    }

    //build data object to pass for generation
    TableData table = new TableData();
    String[] columnHeaders = { "", "Date", "Number of requests" };
    table.setColumnHeaders(columnHeaders);
    
    List<RowEntry> rowData = new ArrayList<RowEntry>();
    RowEntry entry = new RowEntry();
    entry.setEntry("1");
    entry.setEntry(date);
    entry.setEntry(value);
    rowData.add(entry);
    table.setRows(rowData);

    // generate the pdf
    ReportGenerator generator = new ReportGenerator();

    try {
        pdfInputStream =  generator.generateMGRequestSummeryPDF(table);
    } catch (COSVisitorException | IOException e) {
        String msg = "Error while generating the pdf for micro gateway request summary";
        log.error(msg, e);
        throw new APIManagementException(msg, e);
    }
    return pdfInputStream;
}
 
Example 19
Source File: ParserASTJSON.java    From soltix with Apache License 2.0 4 votes vote down vote up
protected void processTupleExpression(long id, AST ast, JSONObject attributes) throws Exception {
    Object isInlineArray = attributes.get("isInlineArray");
    String tupleType = (String)attributes.get("type");
    JSONArray components = (JSONArray)attributes.get("components");
    ArrayList<Boolean> tupleComponents = null;
    ArrayList<ASTNode> replacementChildren = null;

    if (components != null) {
     //   System.out.println( " !!!!!!!!!!!!!!! " + tupleType + " HAS " + components.size() + " COMPONENTS ");

        // See comments in ASTTupleExpression on the ultra-awkward tuple handling.
        //
        // If the components attribute is set, it contains the JSON objects (identifiers
        // that would otherwise be contained in the children item. So we go over the
        // components and apply our parse tree construction functionfor each of them
        tupleComponents = new ArrayList<Boolean>();
        for (int i = 0; i < components.size(); ++i) {
            JSONObject currentComponent = (JSONObject)components.get(i);
            if (currentComponent == null) {
                tupleComponents.add(false);
            } else {
                tupleComponents.add(true);
                AST tmpAST = new AST();
                //processJSONObject(tmpAST, currentComponent, 0);
                JSONObjectToAST(tmpAST, currentComponent, 0);
                //System.out.println( ">>>>>>> sub root node = " + tmpAST.getRoot().toSolidityCode());
                if (replacementChildren == null) {
                    replacementChildren = new ArrayList<ASTNode>();
                }
                replacementChildren.add(tmpAST.getRoot());
            }
        }
    }

    ASTNode tupleExpressionNode = new ASTTupleExpression(id, isInlineArray != null? (Boolean)isInlineArray: false, tupleType, tupleComponents);
    if (replacementChildren != null) {
        tupleExpressionNode.setChildren(replacementChildren);
        for (int i = 0; i < tupleComponents.size(); ++i) System.out.println("   " + i + " = " + tupleComponents.get(i));
    }
    ast.addInnerNode(tupleExpressionNode);
}
 
Example 20
Source File: DateManagerServiceImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public DateManagerValidation validateForums(String siteId, JSONArray forums) throws Exception {
	DateManagerValidation forumValidate = new DateManagerValidation();
	List<DateManagerError> errors = new ArrayList<>();
	List<Object> updates = new ArrayList<>();
	String toolTitle = toolManager.getTool(DateManagerConstants.COMMON_ID_FORUMS).getTitle();
	for (int i = 0; i < forums.size(); i++) {
		JSONObject jsonForum = (JSONObject)forums.get(i);
		int idx = Integer.parseInt(jsonForum.get("idx").toString());

		try {

			Long forumId = (Long)jsonForum.get("id");
			if (forumId == null) {
				errors.add(new DateManagerError("forum", rb.getFormattedMessage("error.item.not.found", new Object[]{rb.getString("tool.forum.topic.item.name")}), "forums", toolTitle, idx));
				continue;
			}

			Instant openDate = userTimeService.parseISODateInUserTimezone((String)jsonForum.get("open_date")).toInstant();
			Instant dueDate = userTimeService.parseISODateInUserTimezone((String)jsonForum.get("due_date")).toInstant();
			boolean errored = false;
			if (openDate == null) {
				errors.add(new DateManagerError("open_date", rb.getString("error.open.date.not.found"), "forums", toolTitle, idx));
				errored = true;
			}
			if (dueDate == null) {
				errors.add(new DateManagerError("due_date", rb.getString("error.due.date.not.found"), "forums", toolTitle, idx));
				errored = true;
			}
			if (errored) {
				continue;
			}

			String entityType = (String)jsonForum.get("extraInfo");
			DateManagerUpdate update;
			if("forum".equals(entityType)) {
				BaseForum forum = forumManager.getForumById(true, forumId);
				if (forum == null) {
					errors.add(new DateManagerError("forum",rb.getFormattedMessage("error.item.not.found", new Object[]{rb.getString("tool.forums.item.name")}), "forums", toolTitle, idx));
					continue;
				}

				/*boolean canUpdate = contentHostingService.allowUpdateResource(resourceId);
				if (!canUpdate) {
					errors.add(new DateManagerError("forum", rb.getString("error.update.permission.denied"), "forums", toolTitle, idx));
				}*/
				update = new DateManagerUpdate(forum, openDate, dueDate, null);
			} else {
				Topic topic = forumManager.getTopicById(true, forumId);
				if (topic == null) {
					errors.add(new DateManagerError("forum", rb.getFormattedMessage("error.item.not.found", new Object[]{rb.getString("tool.topics.item.name")}), "forums", toolTitle, idx));
					continue;
				}

				/*boolean canUpdate = contentHostingService.allowUpdateCollection(resourceId);
				if (!canUpdate) {
					errors.add(new DateManagerError("forum", rb.getString("error.update.permission.denied"), "forums", toolTitle, idx));
				}*/
				update = new DateManagerUpdate(topic, openDate, dueDate, null);
			}

			if (!update.openDate.isBefore(update.dueDate)) {
				errors.add(new DateManagerError("open_date", rb.getString("error.open.date.before.close.date"), "forums", toolTitle, idx));
				continue;
			}
			updates.add(update);

		} catch(Exception e) {
			errors.add(new DateManagerError("open_date", rb.getString("error.uncaught"), "forums", toolTitle, idx));
			log.error("Error trying to validate Forums {}", e);
		}
	}

	forumValidate.setErrors(errors);
	forumValidate.setUpdates(updates);
	return forumValidate;
}