List of usage examples for java.util Scanner hasNext
public boolean hasNext()
From source file:org.xwiki.commons.internal.DefaultMailSender.java
@Override public int sendMailFromTemplate(String templateDocFullName, String from, String to, String cc, String bcc, String language, VelocityContext vContext) { if (!documentAccessBridge.hasProgrammingRights()) // Forbids the use of a template created by a user having no // programming rights {/*from ww w . ja v a 2 s . c o m*/ logger.error( "No mail has been sent : The author of the document needs programming rights to be able to use the sendMailFromTemplate method"); return 0; } try { ExecutionContext context = this.execution.getContext(); XWikiContext xwikiContext = (XWikiContext) context.getProperty("xwikicontext"); if (vContext == null) vContext = velocityManager.getVelocityContext(); vContext.put("from.name", from); vContext.put("from.address", from); vContext.put("to.name", to); vContext.put("to.address", to); vContext.put("to.cc", cc); vContext.put("to.bcc", bcc); vContext.put("bounce", from); String wiki = documentAccessBridge.getCurrentDocumentReference().getWikiReference().getName(); String templateSpace = ""; String templatePage = ""; Scanner scan = new Scanner(templateDocFullName); scan.useDelimiter("\\."); if (scan.hasNext()) templateSpace = scan.next(); if (scan.hasNext()) templatePage = scan.next(); else { logger.error("Template reference is invalid"); return 0; } DocumentReference template = new DocumentReference(wiki, templateSpace, templatePage); boolean hasRight = checkAccess(template, xwikiContext); if (!hasRight) // If the current user is not allowed to view the page of the template, he can't use it to // send mails { logger.error("You haven't the right to use this mail template !"); return 0; } DocumentReference mailClass = new DocumentReference(wiki, "XWiki", "Mail"); int n = -1; n = documentAccessBridge.getObjectNumber(template, mailClass, "language", language); if (n == -1) { n = documentAccessBridge.getObjectNumber(template, mailClass, "language", "en"); logger.warn("No mail object found with language = " + language); } if (n == -1) { logger.error("No mail object found in the document " + templateDocFullName); return 0; } String subject = documentAccessBridge.getProperty(template, mailClass, n, "subject").toString(); subject = XWikiVelocityRenderer.evaluate(subject, templateDocFullName, vContext, xwikiContext); String text = documentAccessBridge.getProperty(template, mailClass, n, "text").toString(); text = XWikiVelocityRenderer.evaluate(text, templateDocFullName, vContext, xwikiContext); String html = documentAccessBridge.getProperty(template, mailClass, n, "html").toString(); html = XWikiVelocityRenderer.evaluate(html, templateDocFullName, vContext, xwikiContext); Mail mail = new Mail(); mail.setFrom(from); mail.setTo(to); mail.setCc(cc); mail.setBcc(bcc); mail.setSubject(subject); mail.addContent("text/plain", text); if (!StringUtils.isEmpty(html)) mail.addContent("text/html", html); return this.send(mail); } catch (Exception e) { return 0; } }
From source file:org.apache.taverna.activities.rest.ui.config.RESTActivityConfigurationPanel.java
private String[] getMediaTypes() { if (mediaTypes != null) { return mediaTypes; }//w w w .j a va 2 s .c o m List<String> types = new ArrayList<String>(); InputStream typesStream = getClass().getResourceAsStream("mediatypes.txt"); try { // media types must be ASCII and can't have whitespace Scanner scanner = new Scanner(typesStream, "ascii"); while (scanner.hasNext()) { types.add(scanner.next()); } scanner.close(); } finally { try { typesStream.close(); } catch (IOException ex) { } } mediaTypes = types.toArray(new String[0]); return mediaTypes; }
From source file:Balo.MainFram.java
public void getDataFileToJTable() { String fileNameDefined = "src/Balo/Data_3.csv"; File file = new File(fileNameDefined); int i = 0;// w w w . j a va 2 s . c o m dvDynamic[0] = new Dovat(); //Get value from csv file try { Scanner inputStream = new Scanner(file); inputStream.useDelimiter(","); while (inputStream.hasNext()) { dvDynamic[i + 1] = dvGreedy[i] = new Dovat(); dvDynamic[i + 1].ten = dvGreedy[i].ten = inputStream.next().trim(); dvDynamic[i + 1].soluong = dvGreedy[i].soluong = Integer.valueOf(inputStream.next().trim()); dvDynamic[i + 1].giatri = dvGreedy[i].giatri = Integer.valueOf(inputStream.next().trim()); dvDynamic[i + 1].trongluong = dvGreedy[i].trongluong = Integer.valueOf(inputStream.next().trim()); i++; } //Set number of Items numOfItem = i; //Get weight bag weightBag = Integer.parseInt(TextW.getText()); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } //Set value for JTable for (int item = 0; item < numOfItem; item++) { Object[] row = new Object[4]; row[0] = dvGreedy[item].ten; row[1] = dvGreedy[item].soluong; row[2] = dvGreedy[item].giatri; row[3] = dvGreedy[item].trongluong; model.addRow(row); } }
From source file:files.populate.java
void populate_business(Connection connection, String filename) { String fileName = "/Users/yash/Documents/workspace/HW 3/data/yelp_business.json"; Path path = Paths.get(fileName); Scanner scanner = null; try {/*from ww w . jav a 2s . c om*/ scanner = new Scanner(path); } catch (IOException e) { e.printStackTrace(); } //read file line by line scanner.useDelimiter("\n"); int i = 0; while (scanner.hasNext()) { if (i < 500) { JSONParser parser = new JSONParser(); String s = (String) scanner.next(); s = s.replace("'", "''"); JSONObject obj; try { obj = (JSONObject) parser.parse(s); String add = (String) obj.get("full_address"); add = add.replace("\n", ""); //insertion into business table String query = "insert into yelp_business values ('" + obj.get("business_id") + "','" + add + "','" + obj.get("open") + "','" + obj.get("city") + "','" + obj.get("state") + "','" + obj.get("latitude") + "','" + obj.get("longitude") + "','" + obj.get("review_count") + "','" + obj.get("name") + "','" + obj.get("stars") + "','" + obj.get("type") + "')"; Statement statement = connection.createStatement(); System.out.println(query); statement.executeUpdate(query); //end //inserting into hours table Map hours = (Map) obj.get("hours"); Set keys = hours.keySet(); Object[] days = keys.toArray(); for (int j = 0; j < days.length; ++j) { // String thiskey = days[j].toString(); Map timings = (Map) hours.get(thiskey); // String q3 = "insert into business_hours values ('" + obj.get("business_id") + "','" + thiskey + "','" + timings.get("close") + "','" + timings.get("open") + "')"; // statement.executeUpdate(q3); } //end //insertion into cat table // System.out.println(s); String[] mainCategories = { "Active Life", "Arts & Entertainment", "Automotive", "Car Rental", "Cafes", "Beauty & Spas", "Convenience Stores", "Dentists", "Doctors", "Drugstores", "Department Stores", "Education", "Event Planning & Services", "Flowers & Gifts", "Food", "Health & Medical", "Home Services", "Home & Garden", "Hospitals", "Hotels & Travel", "Hardware Stores", "Grocery", "Medical Centers", "Nurseries & Gardening", "Nightlife", "Restaurants", "Shopping", "Transportation" }; List<String> mainCategories1 = Arrays.asList(mainCategories); ArrayList<String> categories = (ArrayList<String>) obj.get("categories"); for (int j = 0; j < categories.size(); ++j) { String q; if (mainCategories1.contains(categories.get(j))) { q = "insert into business_cat values ('" + obj.get("business_id") + "','" + categories.get(j) + "','main')"; } else { q = "insert into business_cat values ('" + obj.get("business_id") + "','" + categories.get(j) + "','sub')"; } // System.out.println(q); statement.executeUpdate(q); } //end //insertion into neighborhood table ArrayList<String> hood = (ArrayList<String>) obj.get("neighborhoods"); for (int j = 0; j < hood.size(); ++j) { String q = "insert into business_hood values ('" + obj.get("business_id") + "','" + hood.get(j) + "')"; // System.out.println(q); statement.executeUpdate(q); } //end //insertion into attributes and ambience table Map<String, ?> att = (Map<String, ?>) obj.get("attributes"); System.out.println(att + "\n\n"); Set keys1 = att.keySet(); Object[] attname = keys1.toArray(); for (int j = 0; j < attname.length; ++j) { // String thiskey = attname[j].toString(); String att_query = new String(); if (att.get(thiskey) instanceof JSONObject) { Map<String, ?> subatt = (Map<String, ?>) att.get(thiskey); Set keys2 = subatt.keySet(); Object[] attname2 = keys2.toArray(); for (int k = 0; k < attname2.length; ++k) { String thiskey2 = attname2[k].toString(); String subcat_value = (String) String.valueOf(subatt.get(thiskey2)); att_query = "insert into business_attributes values ('" + obj.get("business_id") + "','" + thiskey + "','" + thiskey2 + "','" + subcat_value + "')"; // System.out.println("subkey="+thiskey2 + "value = "+subcat_value); // System.out.println(att_query); statement.executeUpdate(att_query); } } else { String attvalues = (String) String.valueOf(att.get(thiskey)); att_query = "insert into business_attributes values ('" + obj.get("business_id") + "','n/a','" + thiskey + "','" + attvalues + "')"; // System.out.println("key="+thiskey + "value = "+attvalues); statement.executeUpdate(att_query); } // String q3 = "insert into business_hours values ('"+obj.get("business_id")+"','"+thiskey+"','"+timings.get("close")+"','"+timings.get("open")+"')"; // System.out.println(q3); // statement.executeUpdate(q3); } statement.close(); // } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } i++; } else { break; } } }
From source file:org.apache.openaz.xacml.admin.util.RESTfulPAPEngine.java
/** * Send a request to the PAP Servlet and get the response. * //from w ww.j a v a 2 s. c om * The content is either an InputStream to be copied to the Request OutputStream * OR it is an object that is to be encoded into JSON and pushed into the Request OutputStream. * * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller. * * @param method * @param content - EITHER an InputStream OR an Object to be encoded in JSON * @param collectionTypeClass * @param responseContentClass * @param parameters * @return * @throws Exception */ private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, String... parameters) throws PAPException { HttpURLConnection connection = null; try { String fullURL = papServletURLString; if (parameters != null && parameters.length > 0) { String queryString = ""; for (String p : parameters) { queryString += "&" + p; } fullURL += "?" + queryString.substring(1); } // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP if (method.equals("GET") && content instanceof PDP && responseContentClass == StdPDPStatus.class) { // Adjust the url and properties appropriately fullURL = ((PDP) content).getId() + "?type=Status"; content = null; } URL url = new URL(fullURL); // // Open up the connection // connection = (HttpURLConnection) url.openConnection(); // // Setup our method and headers // connection.setRequestMethod(method); // connection.setRequestProperty("Accept", "text/x-java-properties"); // connection.setRequestProperty("Content-Type", "text/x-java-properties"); connection.setUseCaches(false); // // Adding this in. It seems the HttpUrlConnection class does NOT // properly forward our headers for POST re-direction. It does so // for a GET re-direction. // // So we need to handle this ourselves. // connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setDoInput(true); if (content != null) { if (content instanceof InputStream) { try { // // Send our current policy configuration // try (OutputStream os = connection.getOutputStream()) { int count = IOUtils.copy((InputStream) content, os); if (logger.isDebugEnabled()) { logger.debug("copied to output, bytes=" + count); } } } catch (Exception e) { logger.error("Failed to write content in '" + method + "'", e); throw e; } } else { // The content is an object to be encoded in JSON ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(connection.getOutputStream(), content); } } // // Do the connect // connection.connect(); if (connection.getResponseCode() == 204) { logger.info("Success - no content."); return null; } else if (connection.getResponseCode() == 200) { logger.info("Success. We have a return object."); // get the response content into a String String json = null; // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream()); scanner.useDelimiter("\\A"); json = scanner.hasNext() ? scanner.next() : ""; scanner.close(); logger.info("JSON response from PAP: " + json); // convert Object sent as JSON into local object ObjectMapper mapper = new ObjectMapper(); if (collectionTypeClass != null) { // collection of objects expected final CollectionType javaType = mapper.getTypeFactory() .constructCollectionType(collectionTypeClass, responseContentClass); Object objectFromJSON = mapper.readValue(json, javaType); return objectFromJSON; } else { // single value object expected Object objectFromJSON = mapper.readValue(json, responseContentClass); return objectFromJSON; } } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { // redirection String newURL = connection.getHeaderField("Location"); if (newURL == null) { logger.error( "No Location header to redirect to when response code=" + connection.getResponseCode()); throw new IOException( "No redirect Location header when response code=" + connection.getResponseCode()); } int qIndex = newURL.indexOf("?"); if (qIndex > 0) { newURL = newURL.substring(0, qIndex); } logger.info("Redirect seen. Redirecting " + fullURL + " to " + newURL); return newURL; } else { logger.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage()); } } catch (Exception e) { logger.error("HTTP Request/Response to PAP: " + e, e); throw new PAPException("Request/Response threw :" + e); } finally { // cleanup the connection if (connection != null) { try { // For some reason trying to get the inputStream from the connection // throws an exception rather than returning null when the InputStream does not exist. InputStream is = null; try { is = connection.getInputStream(); } catch (Exception e1) { //NOPMD // ignore this } if (is != null) { is.close(); } } catch (IOException ex) { logger.error("Failed to close connection: " + ex, ex); } connection.disconnect(); } } }
From source file:ml.shifu.shifu.core.processor.stats.MapReducerStatsWorker.java
/** * Calculate the PSI/*from w ww. java 2 s . com*/ * * @throws IOException * in scanners read exception */ public void runPSI() throws IOException { log.info("Run PSI to use {} to compute the PSI ", modelConfig.getPsiColumnName()); ColumnConfig columnConfig = CommonUtils.findColumnConfigByName(columnConfigList, modelConfig.getPsiColumnName()); if (columnConfig == null || (!columnConfig.isMeta() && !columnConfig.isCategorical())) { log.warn( "Unable to use the PSI column {} specify in ModelConfig to compute PSI\n" + "neither meta nor categorical type", columnConfig != null ? columnConfig.getColumnName() : "unknown"); return; } log.info("Start to use {} to compute the PSI ", columnConfig.getColumnName()); Map<String, String> paramsMap = new HashMap<>(); paramsMap.put("delimiter", CommonUtils.escapePigString(modelConfig.getDataSetDelimiter())); paramsMap.put("PSIColumn", modelConfig.getPsiColumnName().trim()); paramsMap.put("column_parallel", Integer.toString(columnConfigList.size() / 10)); paramsMap.put("value_index", "2"); PigExecutor.getExecutor().submitJob(modelConfig, pathFinder.getScriptPath("scripts/PSI.pig"), paramsMap); List<Scanner> scanners = ShifuFileUtils.getDataScanners(pathFinder.getPSIInfoPath(), modelConfig.getDataSet().getSource()); if (CollectionUtils.isEmpty(scanners)) { log.info("The PSI got failure during the computation"); return; } String delimiter = Environment.getProperty(Constants.SHIFU_OUTPUT_DATA_DELIMITER, Constants.DEFAULT_DELIMITER); Splitter splitter = Splitter.on(delimiter).trimResults(); List<String> unitStats = new ArrayList<String>(this.columnConfigList.size()); for (Scanner scanner : scanners) { while (scanner.hasNext()) { //String[] output = scanner.nextLine().trim().split("\\|"); String[] output = Lists.newArrayList(splitter.split(scanner.nextLine())).toArray(new String[0]); try { int columnNum = Integer.parseInt(output[0]); ColumnConfig config = this.columnConfigList.get(columnNum); config.setPSI(Double.parseDouble(output[1])); unitStats.add(output[0] + "|" + output[2]); // config.setUnitStats( // Arrays.asList(StringUtils.split(output[2], CalculateStatsUDF.CATEGORY_VAL_SEPARATOR))); } catch (Exception e) { log.error("error in parsing", e); } } // close scanner IOUtils.closeQuietly(scanner); } // write unit stat into a temporary file ShifuFileUtils.createDirIfNotExists(new SourceFile(Constants.TMP, RawSourceData.SourceType.LOCAL)); String ccUnitStatsFile = this.pathFinder.getColumnConfigUnitStatsPath(); ShifuFileUtils.writeLines(unitStats, ccUnitStatsFile, RawSourceData.SourceType.LOCAL); log.info("The Unit Stats is stored in - {}.", ccUnitStatsFile); log.info("Run PSI - done."); }
From source file:org.apache.openaz.xacml.std.json.JSONRequest.java
/** * Read characters from the given <code>InputStream</code> and parse them into an XACML * {@link org.apache.openaz.xacml.api.Request} object. * * @param is//from w w w .j a v a 2s. co m * @return * @throws JSONStructureException */ public static Request load(InputStream is) throws JSONStructureException { // TODO - ASSUME that order of members within an object does not matter (Different from XML, in JSON // everything is handled as Maps so order does not matter) // ensure shorthand map is set up if (shorthandMap == null) { initShorthandMap(); } // ensure that we have an instance of the DataTypeFactory for generating AttributeValues by DataType if (dataTypeFactory == null) { try { dataTypeFactory = DataTypeFactory.newInstance(); if (dataTypeFactory == null) { throw new NullPointerException("No DataTypeFactory found"); } } catch (FactoryException e) { throw new JSONStructureException("Unable to find DataTypeFactory, e=" + e); } } // create a new Request object to be filled in StdMutableRequest stdMutableRequest = null; String json = null; ObjectMapper mapper = null; try { // read the inputStream into a buffer (trick found online scans entire input looking for // end-of-file) java.util.Scanner scanner = new java.util.Scanner(is); scanner.useDelimiter("\\A"); json = scanner.hasNext() ? scanner.next() : ""; scanner.close(); mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY); // TODO - ASSUME that any duplicated component is a bad thing (probably indicating an error in the // incoming JSON) mapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); Map<?, ?> root = mapper.readValue(json, Map.class); // // Does the request exist? // Map<?, ?> jsonRequestMap = (Map<?, ?>) root.remove("Request"); if (jsonRequestMap == null) { throw new JSONStructureException("No \"Request\" property found."); } checkUnknown("Top-level message", root); stdMutableRequest = new StdMutableRequest(); // // Is there a Category? // Object categoryList = jsonRequestMap.remove("Category"); if (categoryList != null && !(categoryList instanceof List)) { throw new JSONStructureException( "Category must contain list of objects, not '" + categoryList.getClass() + "'"); } if (categoryList != null) { // // Iterate each Category // Iterator<?> iter = ((List<?>) categoryList).iterator(); while (iter.hasNext()) { Object category = iter.next(); if (!(category instanceof Map)) { throw new JSONStructureException( "Category list must contain objects contained within curly braces ({})"); } parseCategory((Map<?, ?>) category, "Category", null, stdMutableRequest); } } // The following may be either a single instance or an array. This allows multiple decisions to // work with the Default Category objects. // Example: // "AccessSubject" : [ {attributes group one}, // {attributes group two} // ] // // Look for default Shorthand AccessSubject // parseDefaultCategory(jsonRequestMap, "AccessSubject", "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject", stdMutableRequest); // // Provide backward compatibility for our PEP's // parseDefaultCategory(jsonRequestMap, "Subject", "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject", stdMutableRequest); // // Look for default Shorthand Action // parseDefaultCategory(jsonRequestMap, "Action", "urn:oasis:names:tc:xacml:3.0:attribute-category:action", stdMutableRequest); // // Look for default Shorthand Resource // parseDefaultCategory(jsonRequestMap, "Resource", "urn:oasis:names:tc:xacml:3.0:attribute-category:resource", stdMutableRequest); // // Look for default Shorthand Environment // parseDefaultCategory(jsonRequestMap, "Environment", "urn:oasis:names:tc:xacml:3.0:attribute-category:environment", stdMutableRequest); // // Look for default Shorthand RecipientSubject // parseDefaultCategory(jsonRequestMap, "RecipientSubject", "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject", stdMutableRequest); // // Look for default Shorthand IntermediarySubject // parseDefaultCategory(jsonRequestMap, "IntermediarySubject", "urn:oasis:names:tc:xacml:1.0:subject-category:intermediary-subject", stdMutableRequest); // // Look for default Shorthand Codebase // parseDefaultCategory(jsonRequestMap, "Codebase", "urn:oasis:names:tc:xacml:1.0:subject-category:codebase", stdMutableRequest); // // Look for default Shorthand RequestingMachine // parseDefaultCategory(jsonRequestMap, "RequestingMachine", "urn:oasis:names:tc:xacml:1.0:subject-category:requesting-machine", stdMutableRequest); // // MultiRequest // Map<?, ?> multiRequests = (Map<?, ?>) jsonRequestMap.remove("MultiRequests"); if (multiRequests != null) { if (!(multiRequests instanceof Map)) { throw new JSONStructureException("MultiRequests must be object structure, not single value"); } List<?> requestReferenceList = (List<?>) multiRequests.remove("RequestReference"); if (requestReferenceList == null) { throw new JSONStructureException("MultiRequest must contain a RequestReference element"); } if (requestReferenceList.size() < 1) { throw new JSONStructureException( "MultiRequest must contain at least one element in the RequestReference list"); } checkUnknown("MultiRequest", multiRequests); for (Object requestReferenceMapObject : requestReferenceList) { if (!(requestReferenceMapObject instanceof Map)) { throw new JSONStructureException("MultiRequest RequestReference must be object"); } Map<?, ?> requestReferenceMap = (Map<?, ?>) requestReferenceMapObject; // each object within the list must contain a ReferenceId and only a ReferenceId Object referenceIdListObject = requestReferenceMap.remove("ReferenceId"); if (referenceIdListObject == null) { throw new JSONStructureException( "MultiRequest RequestReference list element must contain ReferenceId"); } List<?> referenceIdList = (List<?>) referenceIdListObject; if (referenceIdList.size() == 0) { // the spec does not disallow empty list RequestReference objects continue; } checkUnknown("RequestReference", requestReferenceMap); // create reference corresponding to RequestReference list element StdMutableRequestReference requestReference = new StdMutableRequestReference(); for (Object referenceId : referenceIdList) { // add attributes to the reference // Since the order of the JSON is not constrained, we could process this section // before the section containing attribute being referenced, // so we cannot do a cross-check here to verify that the attribute reference exists. // That will happen later when the PDP attempts to find the attribute. StdRequestAttributesReference requestAttributesReference = new StdRequestAttributesReference( (String) referenceId); requestReference.add(requestAttributesReference); } stdMutableRequest.add(requestReference); } } // // ReturnPolicyIdList // // If omitted this is set to a default of false by the StdMutableRequest constructor. // Object returnPolicyIdList = jsonRequestMap.remove("ReturnPolicyIdList"); Boolean returnPolicyIdListBoolean = makeBoolean(returnPolicyIdList, "ReturnPolicyIdList"); if (returnPolicyIdList != null) { stdMutableRequest.setReturnPolicyIdList(returnPolicyIdListBoolean); } // // CombinedDecision // // If omitted this is set to a default of false by the StdMutableRequest constructor. // Object combinedDecision = jsonRequestMap.remove("CombinedDecision"); Boolean combinedDecisionBoolean = makeBoolean(combinedDecision, "CombinedDecision"); if (combinedDecision != null) { stdMutableRequest.setCombinedDecision(combinedDecisionBoolean); } // // XPath // // The JSON spec says that this has a default value, implying that if it is missing in the Request // we should fill it in. // However the XML (DOM) version does not do that. If the value is missing it leaves the // requestDefaults object blank. // We are following the XML approach and ignoring the Default value for this field in the spec. // TODO - Assume that no value for XPathVersion means "leave as null", not "fill in the default // value from spec. This violates the JSON spec Object xPath = jsonRequestMap.remove("XPathVersion"); if (xPath != null) { // XPath is given in the JSON input if (!(xPath instanceof String)) { throw new JSONStructureException("XPathVersion not a URI passed as a String"); } URI xPathUri = null; try { xPathUri = new URI(xPath.toString()); } catch (Exception e) { throw new JSONStructureException("XPathVersion not a valid URI: '" + xPath + "'", e); } StdRequestDefaults requestDefaults = new StdRequestDefaults(xPathUri); stdMutableRequest.setRequestDefaults(requestDefaults); } checkUnknown("Request", jsonRequestMap); } catch (JsonParseException e) { // try to point to problem area in JSON input, if possible JsonLocation location = e.getLocation(); String locationOfError = "(unavailable)"; if (location != null && location != JsonLocation.NA) { String jsonText = json; if (location.getLineNr() > 1) { String[] jsonArray = jsonText.split("\\r?\\n|\\r"); jsonText = jsonArray[location.getLineNr()]; } if (location.getCharOffset() < jsonText.length()) { if (location.getCharOffset() > 0) { locationOfError = jsonText.substring((int) location.getCharOffset() - 1); } if (locationOfError.length() > 30) { locationOfError = locationOfError.substring(0, 30); } } } throw new JSONStructureException("Unable to parse JSON starting at text'" + locationOfError + "', input was '" + json + "', exception: " + e, e); } catch (JsonMappingException e) { throw new JSONStructureException("Unable to map JSON '" + json + "', exception: " + e, e); } catch (IOException e) { throw new JSONStructureException("Unable to read JSON input, exception: " + e, e); } // all done return new StdRequest(stdMutableRequest); }
From source file:org.opencastproject.composer.gstreamer.AbstractGSEncoderEngine.java
/** * Parses image extraction configuration in the following format: #{image_time_1}:#{image_width}x#{image_height}. * Multiple extraction configurations can be separated by comma. * //from ww w .j a va 2 s .c o m * @param configuration * Configuration for image extraction * @param outputTemplate * output path template. Should be in the form /some_file_name_#{time}.jpg so that each image will have it's * unique path. * @return parsed List for image extraction */ protected List<ImageExtractionProperties> parseImageExtractionConfiguration(String configuration, String outputTemplate) { LinkedList<ImageExtractionProperties> propertiesList = new LinkedList<AbstractGSEncoderEngine.ImageExtractionProperties>(); Scanner scanner = new Scanner(configuration); scanner.useDelimiter(","); int counter = 0; while (scanner.hasNext()) { String nextToken = scanner.next().trim(); if (!nextToken.matches("[0-9]+:[0-9]+[x|X][0-9]+")) { throw new IllegalArgumentException("Invalid token found: " + nextToken); } String[] properties = nextToken.split("[:|x|X]"); String output = outputTemplate.replaceAll("#\\{time\\}", properties[0]); if (output.equals(outputTemplate)) { logger.warn("Output filename does not contain #{time} template: multiple images will overwrite"); } if (new File(output).exists()) { String outputFile = FilenameUtils.removeExtension(output); String extension = FilenameUtils.getExtension(output); output = outputFile + "_reencode." + extension; } ImageExtractionProperties imageProperties = new ImageExtractionProperties(counter++, Long.parseLong(properties[0]), Integer.parseInt(properties[1]), Integer.parseInt(properties[2]), output); propertiesList.add(imageProperties); } Collections.sort(propertiesList, new Comparator<ImageExtractionProperties>() { @Override public int compare(ImageExtractionProperties o1, ImageExtractionProperties o2) { return (int) (o2.timeInSeconds - o1.timeInSeconds); } }); return propertiesList; }
From source file:com.zero_x_baadf00d.partialize.Partialize.java
/** * Build a JSON object from data taken from the scanner and * the given class type and instance./* www.jav a 2 s . c o m*/ * * @param depth The current depth * @param fields The field names to requests * @param clazz The class of the object to render * @param instance The instance of the object to render * @param partialObject The partial JSON document * @return A JSON Object * @since 16.01.18 */ private ObjectNode buildPartialObject(final int depth, String fields, final Class<?> clazz, final Object instance, final ObjectNode partialObject) { if (depth <= this.maximumDepth) { if (clazz.isAnnotationPresent(com.zero_x_baadf00d.partialize.annotation.Partialize.class)) { final List<String> closedFields = new ArrayList<>(); List<String> allowedFields = Arrays.asList(clazz .getAnnotation(com.zero_x_baadf00d.partialize.annotation.Partialize.class).allowedFields()); List<String> defaultFields = Arrays.asList(clazz .getAnnotation(com.zero_x_baadf00d.partialize.annotation.Partialize.class).defaultFields()); if (allowedFields.isEmpty()) { allowedFields = new ArrayList<>(); for (final Method m : clazz.getDeclaredMethods()) { final String methodName = m.getName(); if (methodName.startsWith("get") || methodName.startsWith("has")) { final char[] c = methodName.substring(3).toCharArray(); c[0] = Character.toLowerCase(c[0]); allowedFields.add(new String(c)); } else if (methodName.startsWith("is")) { final char[] c = methodName.substring(2).toCharArray(); c[0] = Character.toLowerCase(c[0]); allowedFields.add(new String(c)); } } } if (defaultFields.isEmpty()) { defaultFields = allowedFields.stream().map(f -> { if (this.aliases != null && this.aliases.containsValue(f)) { for (Map.Entry<String, String> e : this.aliases.entrySet()) { if (e.getValue().compareToIgnoreCase(f) == 0) { return e.getKey(); } } } return f; }).collect(Collectors.toList()); } if (fields == null || fields.length() == 0) { fields = defaultFields.stream().collect(Collectors.joining(",")); } Scanner scanner = new Scanner(fields); scanner.useDelimiter(com.zero_x_baadf00d.partialize.Partialize.SCANNER_DELIMITER); while (scanner.hasNext()) { String word = scanner.next(); String args = null; if (word.compareTo("*") == 0) { final StringBuilder sb = new StringBuilder(); if (scanner.hasNext()) { scanner.useDelimiter("\n"); sb.append(","); sb.append(scanner.next()); } final Scanner newScanner = new Scanner( allowedFields.stream().filter(f -> !closedFields.contains(f)).map(f -> { if (this.aliases != null && this.aliases.containsValue(f)) { for (Map.Entry<String, String> e : this.aliases.entrySet()) { if (e.getValue().compareToIgnoreCase(f) == 0) { return e.getKey(); } } } return f; }).collect(Collectors.joining(",")) + sb.toString()); newScanner.useDelimiter(com.zero_x_baadf00d.partialize.Partialize.SCANNER_DELIMITER); scanner.close(); scanner = newScanner; } if (word.contains("(")) { while (scanner.hasNext() && (StringUtils.countMatches(word, "(") != StringUtils.countMatches(word, ")"))) { word += "," + scanner.next(); } final Matcher m = this.fieldArgsPattern.matcher(word); if (m.find()) { word = m.group(1); args = m.group(2); } } final String aliasField = word; final String field = this.aliases != null && this.aliases.containsKey(aliasField) ? this.aliases.get(aliasField) : aliasField; if (allowedFields.stream().anyMatch( f -> f.toLowerCase(Locale.ENGLISH).compareTo(field.toLowerCase(Locale.ENGLISH)) == 0)) { if (this.accessPolicyFunction != null && !this.accessPolicyFunction.apply(new AccessPolicy(clazz, instance, field))) { continue; } closedFields.add(aliasField); try { final Method method = clazz.getMethod("get" + WordUtils.capitalize(field)); final Object object = method.invoke(instance); this.internalBuild(depth, aliasField, field, args, partialObject, clazz, object); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ignore) { try { final Method method = clazz.getMethod(field); final Object object = method.invoke(instance); this.internalBuild(depth, aliasField, field, args, partialObject, clazz, object); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { if (this.exceptionConsumer != null) { this.exceptionConsumer.accept(ex); } } } } } return partialObject; } else if (instance instanceof Map<?, ?>) { if (fields == null || fields.isEmpty() || fields.compareTo("*") == 0) { for (Map.Entry<?, ?> e : ((Map<?, ?>) instance).entrySet()) { this.internalBuild(depth, String.valueOf(e.getKey()), String.valueOf(e.getKey()), null, partialObject, e.getValue() == null ? Object.class : e.getValue().getClass(), e.getValue()); } } else { final Map<?, ?> tmpMap = (Map<?, ?>) instance; for (final String k : fields.split(",")) { if (k.compareTo("*") != 0) { final Object o = tmpMap.get(k); this.internalBuild(depth, k, k, null, partialObject, o == null ? Object.class : o.getClass(), o); } else { for (Map.Entry<?, ?> e : ((Map<?, ?>) instance).entrySet()) { this.internalBuild(depth, String.valueOf(e.getKey()), String.valueOf(e.getKey()), null, partialObject, e.getValue() == null ? Object.class : e.getValue().getClass(), e.getValue()); } } } } } else { throw new RuntimeException("Can't convert " + clazz.getCanonicalName()); } } return partialObject; }
From source file:com.jsmartframework.web.manager.FilterControl.java
@SuppressWarnings("resource") private String convertResourceToString(String resource) { InputStream is = FilterControl.class.getClassLoader().getResourceAsStream(resource); Scanner scanner = new Scanner(is).useDelimiter("\\A"); return scanner.hasNext() ? scanner.next() : ""; }