List of usage examples for java.lang StringBuilder append
@Override public StringBuilder append(double d)
From source file:net.modelbased.proasense.storage.reader.StorageReaderScrapRateTestClient.java
public static void main(String[] args) { // Get client properties from properties file // StorageReaderMongoServiceTestClient client = new StorageReaderMongoServiceTestClient(); // client.loadClientProperties(); // Hardcoded client properties (simple test client) String STORAGE_READER_SERVICE_URL = "http://192.168.84.34:8080/storage-reader"; String QUERY_SIMPLE_SENSORID = "1000692"; String QUERY_SIMPLE_STARTTIME = "1387565891068"; String QUERY_SIMPLE_ENDTIME = "1387565996633"; String QUERY_SIMPLE_PROPERTYKEY = "value"; // Default HTTP client and common properties for requests HttpClient client = new DefaultHttpClient(); StringBuilder requestUrl = null; List<NameValuePair> params = null; String queryString = null;//from w w w. j av a 2 s . c o m // Default HTTP response and common properties for responses HttpResponse response = null; ResponseHandler<String> handler = null; int status = 0; String body = null; // Default query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/default"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query11 = new HttpGet(requestUrl.toString()); query11.setHeader("Content-type", "application/json"); response = client.execute(query11); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.DEFAULT: " + body); // The result is an array of simple events serialized as JSON using Apache Thrift. // The simple events can be deserialized into Java objects using Apache Thrift. ObjectMapper mapper = new ObjectMapper(); JsonNode nodeArray = mapper.readTree(body); for (JsonNode node : nodeArray) { byte[] bytes = node.toString().getBytes(); TDeserializer deserializer = new TDeserializer(new TJSONProtocol.Factory()); SimpleEvent event = new SimpleEvent(); deserializer.deserialize(event, bytes); System.out.println(event.toString()); } } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/average"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", QUERY_SIMPLE_PROPERTYKEY)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query12 = new HttpGet(requestUrl.toString()); query12.setHeader("Content-type", "application/json"); response = client.execute(query12); // Get status code status = response.getStatusLine().getStatusCode(); if (status == 200) { // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.AVERAGE: " + body); } else System.out.println("Error code: " + status); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/maximum"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", QUERY_SIMPLE_PROPERTYKEY)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query13 = new HttpGet(requestUrl.toString()); query13.setHeader("Content-type", "application/json"); response = client.execute(query13); // Get status code if (status == 200) { // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.MAXIMUM: " + body); } else System.out.println("Error code: " + status); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/minimum"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", QUERY_SIMPLE_PROPERTYKEY)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query14 = new HttpGet(requestUrl.toString()); query14.setHeader("Content-type", "application/json"); response = client.execute(query14); // Get status code if (status == 200) { // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.MINIMUM: " + body); } else System.out.println("Error code: " + status); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:eu.skqs.bertie.standalone.BertieStandalone.java
public static void main(String[] args) { // Options/*from www.jav a2 s.co m*/ Option file = OptionBuilder.withArgName("file").withLongOpt("file").hasArg() .withDescription("File to annotate").create("f"); Option directory = OptionBuilder.withArgName("directory").withLongOpt("directory").hasArg() .withDescription("Directory to annotate").create("d"); Option owl = OptionBuilder.withArgName("owl").withLongOpt("owl").hasArg() .withDescription("OWL file to use in annotation").create("o"); Option plain = OptionBuilder.withLongOpt("plain").withDescription("Plain text file format").create("p"); Option tei = OptionBuilder.withLongOpt("tei").withDescription("TEI file format").create("t"); Option mode = OptionBuilder.withArgName("extract|minimal|maximal|prosody").withLongOpt("mode").hasArg() .withDescription("Mode to operate in").create("m"); Option clean = OptionBuilder.withArgName("T0,T1,T3").withLongOpt("clean").hasArg() .withDescription("Remove gives types, MUST START UPPERCASE").create("c"); Options options = new Options(); options.addOption(file); options.addOption(directory); options.addOption(owl); options.addOption(plain); options.addOption(tei); options.addOption(mode); options.addOption(clean); CommandLineParser parser = new GnuParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmdline = null; try { cmdline = parser.parse(options, args); } catch (ParseException e) { e.printStackTrace(); System.exit(-1); } BertieStandalone standalone = new BertieStandalone(); String documentPath = null; // Check for custom OWL if (cmdline.hasOption("owl")) { owlPath = cmdline.getOptionValue("owl"); } // Check for clean if (cmdline.hasOption("clean")) { typesToRemove = cmdline.getOptionValue("clean"); } // Check for mode if (cmdline.hasOption("mode")) { String currentMode = cmdline.getOptionValue("mode"); if (currentMode.equals("extract")) { extractMode = true; } else if (currentMode.equals("poetry")) { poetryMode = true; } analysisMode = currentMode; } // Check for directory option if (cmdline.hasOption("directory")) { // We support TEI directorys only if (!cmdline.hasOption("tei")) { logger.log(Level.WARNING, "TEI file format must be selected with directory argument"); System.exit(-1); } String directoryPath = cmdline.getOptionValue("directory"); if (extractMode) { try { standalone.extractWithCollectionReader(directoryPath); } catch (Exception e) { } System.exit(0); } try { standalone.processWithCollectionReader(directoryPath); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } System.exit(0); } // Check for file option if (cmdline.hasOption("file")) { // TODO: clean this up documentPath = cmdline.getOptionValue("file"); filePath = cmdline.getOptionValue("file"); // TEI if (cmdline.hasOption("tei")) { try { processWithFile(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } System.exit(0); } // Check for plain option if (!cmdline.hasOption("plain")) { logger.log(Level.WARNING, "Plain text format must be selected with file argument"); System.exit(-1); } } else { logger.log(Level.WARNING, "No file argument given. Quitting."); formatter.printHelp("bertie", options); System.exit(-1); } // Make sure we have a document path if (documentPath == null) { logger.log(Level.WARNING, "Document path is empty. Quitting."); System.exit(-1); } // Read the document try { String encodingType = "UTF-8"; BufferedReader fileReader = new BufferedReader( new InputStreamReader(new FileInputStream(documentPath), encodingType)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = fileReader.readLine()) != null) { sb.append(line + newLine); } String input = sb.toString(); fileReader.close(); String output = standalone.process(input); if (output == null) { logger.log(Level.WARNING, "Empty processing result."); System.exit(-1); } PrintWriter fileWriter = new PrintWriter(documentPath, encodingType); fileWriter.write(output); fileWriter.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:it.unibas.spicybenchmark.Main.java
public static void main(String[] args) { try {//from w ww. j a v a2s . com String propertiesFile = args[0]; StringBuilder executionTimes = new StringBuilder("--- Execution times: ---\n"); Configuration configuration = DAOConfiguration.loadConfigurationFile(propertiesFile); IDataSourceProxy dataSource = new DAOXsd().loadSchema(configuration.getSchemaAbsolutePath()); LoadXMLFile xmlLoader = new LoadXMLFile(); Date beforeLoadingExpected = new Date(); INode expectedInstanceNode = xmlLoader.loadInstance(dataSource, configuration.getExpectedInstanceAbsolutePath()); Date afterLoadingExpected = new Date(); long loadingExpected = afterLoadingExpected.getTime() - beforeLoadingExpected.getTime(); executionTimes.append("Expected Instance loaded: ").append(loadingExpected).append(" ms\n"); INode translatedInstanceNode = xmlLoader.loadInstance(dataSource, configuration.getTranslatedInstanceAbsolutePath()); Date afterLoadingTranslated = new Date(); long loadingTranslated = afterLoadingTranslated.getTime() - afterLoadingExpected.getTime(); executionTimes.append("Translated Instance loaded: ").append(loadingTranslated).append(" ms\n"); List<String> exclusionList = new DAOExclusionList().loadExclusionList(dataSource, configuration.getExclusionsFileAbsolutePath()); Date startSpicyTime = new Date(); FeatureCollectionGenerator featureCollectionGenerator = new FeatureCollectionGenerator(); FeatureCollection featureCollection = featureCollectionGenerator.generate(expectedInstanceNode, translatedInstanceNode, exclusionList, dataSource, configuration); EvaluateSimilarity evaluator = new EvaluateSimilarity(); SimilarityResult similarityResult = evaluator.getSimilarityResult(featureCollection); similarityResult .setNumberOfNodesInExpectedInstance(new CalculateSize().getNumberOfNodes(expectedInstanceNode)); similarityResult.setNumberOfNodesInTranslatedInstance( new CalculateSize().getNumberOfNodes(translatedInstanceNode)); Date endSpicyTime = new Date(); long spicyExecTime = endSpicyTime.getTime() - startSpicyTime.getTime(); executionTimes.append("Spicy execution time: ").append(spicyExecTime).append(" ms\n"); if (configuration.isTreeEditDistanceValiente()) { Date startValiente = new Date(); similarityResult .setTreeEditDistanceValiente(new TreeEditDistanceGeneratorSimPack().compute(configuration)); Date stopValiente = new Date(); long valienteExecTime = stopValiente.getTime() - startValiente.getTime(); executionTimes.append("Valiente execution time: ").append(valienteExecTime).append(" ms\n"); } if (configuration.isTreeEditDistanceShasha()) { Date startShasha = new Date(); similarityResult.setTreeEditDistanceShasha( new TreeEditDistanceGenerator().computeTreeEditDistance(featureCollection)); Date stopShasha = new Date(); long shashaExecTime = stopShasha.getTime() - startShasha.getTime(); executionTimes.append("Shasha execution time: ").append(shashaExecTime).append(" ms\n"); } // similarityResult.setTopDownOrderedMaximumSubtree(new TopDownOrderedMaximumSubtreeGenerator().compute(configuration)); // similarityResult.setBottomUpMaximumSubtree(new BottomUpMaximumSubtreeGenerator().compute(configuration)); // similarityResult.setJaccard(new JaccardGenerator().compute(expectedInstanceNode, translatedInstanceNode)); Utility.printFinalLog(similarityResult, configuration, executionTimes.toString()); } catch (DAOException ex) { logger.error(ex); } }
From source file:net.modelbased.proasense.storage.reader.StorageReaderMongoServiceRestBenchmark.java
public static void main(String[] args) { // Get benchmark properties StorageReaderMongoServiceRestBenchmark benchmark = new StorageReaderMongoServiceRestBenchmark(); benchmark.loadClientProperties();/*from w w w.j ava 2 s. c o m*/ // ProaSense Storage Reader Service configuration properties String STORAGE_READER_SERVICE_URL = benchmark.clientProperties .getProperty("proasense.storage.reader.service.url"); String QUERY_SIMPLE_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.simple.collectionid"); String NO_QUERY_SIMPLE_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.simple.starttime"); String NO_QUERY_SIMPLE_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.simple.endtime"); String QUERY_DERIVED_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.derived.collectionid"); String NO_QUERY_DERIVED_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.derived.starttime"); String NO_QUERY_DERIVED_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.derived.endtime"); String QUERY_PREDICTED_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.predicted.collectionid"); String NO_QUERY_PREDICTED_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.predicted.starttime"); String NO_QUERY_PREDICTED_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.predicted.endtime"); String QUERY_ANOMALY_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.anomaly.collectionid"); String NO_QUERY_ANOMALY_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.anomaly.starttime"); String NO_QUERY_ANOMALY_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.anomaly.endtime"); String QUERY_RECOMMENDATION_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.recommendation.collectionid"); String NO_QUERY_RECOMMENDATION_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.recommendation.starttime"); String NO_QUERY_RECOMMENDATION_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.recommendation.endtime"); String QUERY_FEEDBACK_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.feedback.collectionid"); String NO_QUERY_FEEDBACK_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.feedback.starttime"); String NO_QUERY_FEEDBACK_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.feedback.endtime"); String propertyKey = "value"; // Default HTTP client and common property variables for requests HttpClient client = new DefaultHttpClient(); StringBuilder requestUrl = null; List<NameValuePair> params = null; String queryString = null; StatusLine status = null; // Default query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/default"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_COLLECTIONID)); params.add(new BasicNameValuePair("startTime", NO_QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", NO_QUERY_SIMPLE_ENDTIME)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); HttpGet query11 = new HttpGet(requestUrl.toString()); query11.setHeader("Content-type", "application/json"); try { status = client.execute(query11).getStatusLine(); System.out.println("SIMPLE.DEFAULT:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/value"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_COLLECTIONID)); params.add(new BasicNameValuePair("startTime", NO_QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", NO_QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", "value")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); HttpGet query12 = new HttpGet(STORAGE_READER_SERVICE_URL); query12.setHeader("Content-type", "application/json"); try { status = client.execute(query12).getStatusLine(); System.out.println("SIMPLE.AVERAGE:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for simple events HttpGet query13 = new HttpGet(STORAGE_READER_SERVICE_URL); query13.setHeader("Content-type", "application/json"); try { status = client.execute(query13).getStatusLine(); System.out.println("SIMPLE.MAXIMUM:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for simple events HttpGet query14 = new HttpGet(STORAGE_READER_SERVICE_URL); query14.setHeader("Content-type", "application/json"); try { status = client.execute(query14).getStatusLine(); System.out.println("SIMPLE.MINUMUM:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for derived events HttpGet query21 = new HttpGet(STORAGE_READER_SERVICE_URL); query21.setHeader("Content-type", "application/json"); try { status = client.execute(query21).getStatusLine(); System.out.println("DERIVED.DEFAULT:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for derived events HttpGet query22 = new HttpGet(STORAGE_READER_SERVICE_URL); query22.setHeader("Content-type", "application/json"); try { status = client.execute(query22).getStatusLine(); System.out.println("DERIVED.AVERAGE:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for derived events HttpGet query23 = new HttpGet(STORAGE_READER_SERVICE_URL); query23.setHeader("Content-type", "application/json"); try { status = client.execute(query23).getStatusLine(); System.out.println("DERIVED.MAXIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for derived events HttpGet query24 = new HttpGet(STORAGE_READER_SERVICE_URL); query24.setHeader("Content-type", "application/json"); try { status = client.execute(query24).getStatusLine(); System.out.println("DERIVED.MINIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for predicted events HttpGet query31 = new HttpGet(STORAGE_READER_SERVICE_URL); query31.setHeader("Content-type", "application/json"); try { status = client.execute(query31).getStatusLine(); System.out.println("PREDICTED.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for predicted events HttpGet query32 = new HttpGet(STORAGE_READER_SERVICE_URL); query32.setHeader("Content-type", "application/json"); try { status = client.execute(query32).getStatusLine(); System.out.println("PREDICTED.AVERAGE: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for predicted events HttpGet query33 = new HttpGet(STORAGE_READER_SERVICE_URL); query33.setHeader("Content-type", "application/json"); try { status = client.execute(query33).getStatusLine(); System.out.println("PREDICTED.MAXIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for derived events HttpGet query34 = new HttpGet(STORAGE_READER_SERVICE_URL); query34.setHeader("Content-type", "application/json"); try { status = client.execute(query34).getStatusLine(); System.out.println("PREDICTED.MINIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for anomaly events HttpGet query41 = new HttpGet(STORAGE_READER_SERVICE_URL); query41.setHeader("Content-type", "application/json"); try { status = client.execute(query41).getStatusLine(); System.out.println("ANOMALY.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for recommendation events HttpGet query51 = new HttpGet(STORAGE_READER_SERVICE_URL); query51.setHeader("Content-type", "application/json"); try { status = client.execute(query51).getStatusLine(); System.out.println("RECOMMENDATION.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for recommendation events HttpGet query52 = new HttpGet(STORAGE_READER_SERVICE_URL); query52.setHeader("Content-type", "application/json"); try { status = client.execute(query52).getStatusLine(); System.out.println("RECOMMENDATION.AVERAGE: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for derived events HttpGet query53 = new HttpGet(STORAGE_READER_SERVICE_URL); query53.setHeader("Content-type", "application/json"); try { status = client.execute(query53).getStatusLine(); System.out.println("RECOMMENDATION.MAXIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for derived events HttpGet query54 = new HttpGet(STORAGE_READER_SERVICE_URL); query54.setHeader("Content-type", "application/json"); try { status = client.execute(query54).getStatusLine(); System.out.println("RECOMMENDATION.MINIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for feedback events HttpGet query61 = new HttpGet(STORAGE_READER_SERVICE_URL); query54.setHeader("Content-type", "application/json"); try { status = client.execute(query54).getStatusLine(); System.out.println("FEEDBACK.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:com.music.Generator.java
public static void main(String[] args) throws Exception { Score score1 = new Score(); Read.midi(score1, "c:/tmp/gen.midi"); for (Part part : score1.getPartArray()) { System.out.println(part.getInstrument()); }//from w ww .jav a 2 s . com new StartupListener().contextInitialized(null); Generator generator = new Generator(); generator.configLocation = "c:/config/music"; generator.maxConcurrentGenerations = 5; generator.init(); UserPreferences prefs = new UserPreferences(); prefs.setElectronic(Ternary.YES); //prefs.setSimpleMotif(Ternary.YES); //prefs.setMood(Mood.MAJOR); //prefs.setDrums(Ternary.YES); //prefs.setClassical(true); prefs.setAccompaniment(Ternary.YES); prefs.setElectronic(Ternary.YES); final ScoreContext ctx = generator.generatePiece(); Score score = ctx.getScore(); for (Part part : score.getPartArray()) { System.out.println(part.getTitle() + ": " + part.getInstrument()); } System.out.println("Metre: " + ctx.getMetre()[0] + "/" + ctx.getMetre()[1]); System.out.println(ctx); Write.midi(score, "c:/tmp/gen.midi"); new Thread(new Runnable() { @Override public void run() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(0, 0, 500, 500); frame.setVisible(true); Part part = ctx.getParts().get(PartType.MAIN); Note[] notes = part.getPhrase(0).getNoteArray(); List<Integer> pitches = new ArrayList<Integer>(); for (Note note : notes) { if (!note.isRest()) { pitches.add(note.getPitch()); } } GraphicsPanel gp = new GraphicsPanel(pitches); frame.setContentPane(gp); } }).start(); DecimalFormat df = new DecimalFormat("#.##"); for (Part part : score.getPartArray()) { StringBuilder sb = new StringBuilder(); printStatistics(ctx, part); System.out.println("------------ " + part.getTitle() + "-----------------"); Phrase[] phrases = part.getPhraseArray(); for (Phrase phr : phrases) { if (phr instanceof ExtendedPhrase) { sb.append("Contour=" + ((ExtendedPhrase) phr).getContour() + " "); } double measureSize = 0; int measures = 0; double totalLength = 0; List<String> pitches = new ArrayList<String>(); List<String> lengths = new ArrayList<String>(); System.out.println("((Phrase notes: " + phr.getNoteArray().length + ")"); for (Note note : phr.getNoteArray()) { if (!note.isRest()) { int degree = 0; if (phr instanceof ExtendedPhrase) { degree = Arrays.binarySearch(((ExtendedPhrase) phr).getScale().getDefinition(), note.getPitch() % 12); } pitches.add(String.valueOf(note.getPitch() + " (" + degree + ") ")); } else { pitches.add(" R "); } lengths.add(df.format(note.getRhythmValue())); measureSize += note.getRhythmValue(); totalLength += note.getRhythmValue(); ; if (measureSize >= ctx.getNormalizedMeasureSize()) { pitches.add(" || "); lengths.add(" || " + (measureSize > ctx.getNormalizedMeasureSize() ? "!" : "")); measureSize = 0; measures++; } } sb.append(pitches.toString() + "\r\n"); sb.append(lengths.toString() + "\r\n"); if (part.getTitle().equals(PartType.MAIN.getTitle())) { sb.append("\r\n"); } System.out.println("Phrase measures: " + measures); System.out.println("Phrase length: " + totalLength); } System.out.println(sb.toString()); } MutingPrintStream.ignore.set(true); Write.midi(score, "c:/tmp/gen.midi"); MutingPrintStream.ignore.set(null); Play.midi(score); generator.toMp3(FileUtils.readFileToByteArray(new File("c:/tmp/gen.midi"))); }
From source file:com.util.finalProy.java
/** * @param args the command line arguments *//*w w w . j a va2s .c o m*/ public static void main(String[] args) throws JSONException { // TODO code application logic her System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON"); String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json"; System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null; try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); } if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } String jsonResult = sb.toString(); System.out.println(sb.toString()); System.out.println( "\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n"); JSONObject objJason = new JSONObject(jsonResult); JSONArray dataJson = new JSONArray(); dataJson = objJason.getJSONArray("data"); System.out.println("objeto normal 1 " + dataJson.toString()); // // System.out.println( "\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n"); String jsonString2 = dataJson.toString(); String temp = dataJson.toString(); temp = jsonString2.replace("[", ""); jsonString2 = temp.replace("]", ""); System.out.println("new json string" + jsonString2); JSONObject objJson2 = new JSONObject(jsonString2); System.out.println("el objeto simple json es " + objJson2.toString()); System.out.println( "\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n"); String account1 = objJson2.optString("account"); System.out.println(account1); JSONObject objJson3 = new JSONObject(account1); System.out.println("el ULTIMO OBJETO SIMPLE ES " + objJson3.toString()); System.out.println( "\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n"); String firstName = objJson3.getString("first_name"); System.out.println(firstName); System.out.println(objJson3.get("id")); System.out.println( "\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n"); Gson gson = new Gson(); Account account = gson.fromJson(objJson3.toString(), Account.class); System.out.println(account.getFirst_name()); System.out.println(account.getCreation()); }
From source file:com.era7.bioinfo.annotation.AutomaticQualityControl.java
public static void main(String[] args) { if (args.length != 4) { System.out.println("This program expects four parameters: \n" + "1. Gene annotation XML filename \n" + "2. Reference protein set (.fasta)\n" + "3. Output TXT filename\n" + "4. Initial Blast XML results filename (the one used at the very beginning of the semiautomatic annotation process)\n"); } else {// w w w .ja va 2s. com BufferedWriter outBuff = null; try { File inFile = new File(args[0]); File fastaFile = new File(args[1]); File outFile = new File(args[2]); File blastFile = new File(args[3]); //Primero cargo todos los datos del archivo xml del blast BufferedReader buffReader = new BufferedReader(new FileReader(blastFile)); StringBuilder stBuilder = new StringBuilder(); String line = null; while ((line = buffReader.readLine()) != null) { stBuilder.append(line); } buffReader.close(); System.out.println("Creating blastoutput..."); BlastOutput blastOutput = new BlastOutput(stBuilder.toString()); System.out.println("BlastOutput created! :)"); stBuilder.delete(0, stBuilder.length()); HashMap<String, String> blastProteinsMap = new HashMap<String, String>(); ArrayList<Iteration> iterations = blastOutput.getBlastOutputIterations(); for (Iteration iteration : iterations) { blastProteinsMap.put(iteration.getQueryDef().split("\\|")[1].trim(), iteration.toString()); } //freeing some memory blastOutput = null; //------------------------------------------------------------------------ //Initializing writer for output file outBuff = new BufferedWriter(new FileWriter(outFile)); //reading gene annotation xml file..... buffReader = new BufferedReader(new FileReader(inFile)); stBuilder = new StringBuilder(); line = null; while ((line = buffReader.readLine()) != null) { stBuilder.append(line); } buffReader.close(); XMLElement genesXML = new XMLElement(stBuilder.toString()); //freeing some memory I don't need anymore stBuilder.delete(0, stBuilder.length()); //reading file with the reference proteins set ArrayList<String> proteinsReferenceSet = new ArrayList<String>(); buffReader = new BufferedReader(new FileReader(fastaFile)); while ((line = buffReader.readLine()) != null) { if (line.charAt(0) == '>') { proteinsReferenceSet.add(line.split("\\|")[1]); } } buffReader.close(); Element pGenes = genesXML.asJDomElement().getChild(PredictedGenes.TAG_NAME); List<Element> contigs = pGenes.getChildren(ContigXML.TAG_NAME); System.out.println("There are " + contigs.size() + " contigs to be checked... "); outBuff.write("There are " + contigs.size() + " contigs to be checked... \n"); outBuff.write("Proteins reference set: \n"); for (String st : proteinsReferenceSet) { outBuff.write(st + ","); } outBuff.write("\n"); for (Element elem : contigs) { ContigXML contig = new ContigXML(elem); //escribo el id del contig en el que estoy outBuff.write("Checking contig: " + contig.getId() + "\n"); outBuff.flush(); List<XMLElement> geneList = contig.getChildrenWith(PredictedGene.TAG_NAME); System.out.println("geneList.size() = " + geneList.size()); int numeroDeGenesParaAnalizar = geneList.size() / FACTOR; if (numeroDeGenesParaAnalizar == 0) { numeroDeGenesParaAnalizar++; } ArrayList<Integer> indicesUtilizados = new ArrayList<Integer>(); outBuff.write("\nThe contig has " + geneList.size() + " predicted genes, let's analyze: " + numeroDeGenesParaAnalizar + "\n"); for (int j = 0; j < numeroDeGenesParaAnalizar; j++) { int geneIndex; boolean geneIsDismissed = false; do { geneIsDismissed = false; geneIndex = (int) Math.round(Math.floor(Math.random() * geneList.size())); PredictedGene tempGene = new PredictedGene(geneList.get(geneIndex).asJDomElement()); if (tempGene.getStatus().equals(PredictedGene.STATUS_DISMISSED)) { geneIsDismissed = true; } } while (indicesUtilizados.contains(new Integer(geneIndex)) && geneIsDismissed); indicesUtilizados.add(geneIndex); System.out.println("geneIndex = " + geneIndex); //Ahora hay que sacar el gen correspondiente al indice y hacer el control de calidad PredictedGene gene = new PredictedGene(geneList.get(geneIndex).asJDomElement()); outBuff.write("\nAnalyzing gene with id: " + gene.getId() + " , annotation uniprot id: " + gene.getAnnotationUniprotId() + "\n"); outBuff.write("eValue: " + gene.getEvalue() + "\n"); //--------------PETICION POST HTTP BLAST---------------------- PostMethod post = new PostMethod(BLAST_URL); post.addParameter("program", "blastx"); post.addParameter("sequence", gene.getSequence()); post.addParameter("database", "uniprotkb"); post.addParameter("email", "ppareja@era7.com"); post.addParameter("exp", "1e-10"); post.addParameter("stype", "dna"); // execute the POST HttpClient client = new HttpClient(); int status = client.executeMethod(post); System.out.println("status post = " + status); InputStream inStream = post.getResponseBodyAsStream(); String fileName = "jobid.txt"; FileOutputStream outStream = new FileOutputStream(new File(fileName)); byte[] buffer = new byte[1024]; int len; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); //Once the file is created I just have to read one line in order to extract the job id buffReader = new BufferedReader(new FileReader(new File(fileName))); String jobId = buffReader.readLine(); buffReader.close(); System.out.println("jobId = " + jobId); //--------------HTTP CHECK JOB STATUS REQUEST---------------------- GetMethod get = new GetMethod(CHECK_JOB_STATUS_URL + jobId); String jobStatus = ""; do { try { Thread.sleep(1000);//sleep for 1000 ms } catch (InterruptedException ie) { //If this thread was intrrupted by nother thread } status = client.executeMethod(get); //System.out.println("status get = " + status); inStream = get.getResponseBodyAsStream(); fileName = "jobStatus.txt"; outStream = new FileOutputStream(new File(fileName)); while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); //Once the file is created I just have to read one line in order to extract the job id buffReader = new BufferedReader(new FileReader(new File(fileName))); jobStatus = buffReader.readLine(); //System.out.println("jobStatus = " + jobStatus); buffReader.close(); } while (!jobStatus.equals(FINISHED_JOB_STATUS)); //Once I'm here the blast should've already finished //--------------JOB RESULTS HTTP REQUEST---------------------- get = new GetMethod(JOB_RESULT_URL + jobId + "/out"); status = client.executeMethod(get); System.out.println("status get = " + status); inStream = get.getResponseBodyAsStream(); fileName = "jobResults.txt"; outStream = new FileOutputStream(new File(fileName)); while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); //--------parsing the blast results file----- TreeSet<GeneEValuePair> featuresBlast = new TreeSet<GeneEValuePair>(); buffReader = new BufferedReader(new FileReader(new File(fileName))); while ((line = buffReader.readLine()) != null) { if (line.length() > 3) { String prefix = line.substring(0, 3); if (prefix.equals("TR:") || prefix.equals("SP:")) { String[] columns = line.split(" "); String id = columns[1]; //System.out.println("id = " + id); String e = ""; String[] arraySt = line.split("\\.\\.\\."); if (arraySt.length > 1) { arraySt = arraySt[1].trim().split(" "); int contador = 0; for (int k = 0; k < arraySt.length && contador <= 2; k++) { String string = arraySt[k]; if (!string.equals("")) { contador++; if (contador == 2) { e = string; } } } } else { //Number before e- String[] arr = arraySt[0].split("e-")[0].split(" "); String numeroAntesE = arr[arr.length - 1]; String numeroDespuesE = arraySt[0].split("e-")[1].split(" ")[0]; e = numeroAntesE + "e-" + numeroDespuesE; } double eValue = Double.parseDouble(e); //System.out.println("eValue = " + eValue); GeneEValuePair g = new GeneEValuePair(id, eValue); featuresBlast.add(g); } } } GeneEValuePair currentGeneEValuePair = new GeneEValuePair(gene.getAnnotationUniprotId(), gene.getEvalue()); System.out.println("currentGeneEValuePair.id = " + currentGeneEValuePair.id); System.out.println("currentGeneEValuePair.eValue = " + currentGeneEValuePair.eValue); boolean blastContainsGene = false; for (GeneEValuePair geneEValuePair : featuresBlast) { if (geneEValuePair.id.equals(currentGeneEValuePair.id)) { blastContainsGene = true; //le pongo la e que tiene en el wu-blast para poder comparar currentGeneEValuePair.eValue = geneEValuePair.eValue; break; } } if (blastContainsGene) { outBuff.write("The protein was found in the WU-BLAST result.. \n"); //Una vez que se que esta en el blast tengo que ver que sea la mejor GeneEValuePair first = featuresBlast.first(); outBuff.write("Protein with best eValue according to the WU-BLAST result: " + first.id + " , " + first.eValue + "\n"); if (first.id.equals(currentGeneEValuePair.id)) { outBuff.write("Proteins with best eValue match up \n"); } else { if (first.eValue == currentGeneEValuePair.eValue) { outBuff.write( "The one with best eValue is not the same protein but has the same eValue \n"); } else if (first.eValue > currentGeneEValuePair.eValue) { outBuff.write( "The one with best eValue is not the same protein but has a worse eValue :) \n"); } else { outBuff.write( "The best protein from BLAST has an eValue smaller than ours, checking if it's part of the reference set...\n"); //System.exit(-1); if (proteinsReferenceSet.contains(first.id)) { //The protein is in the reference set and that shouldn't happen outBuff.write( "The protein was found on the reference set, checking if it belongs to the same contig...\n"); String iterationSt = blastProteinsMap.get(gene.getAnnotationUniprotId()); if (iterationSt != null) { outBuff.write( "The protein was found in the BLAST used at the beginning of the annotation process.\n"); Iteration iteration = new Iteration(iterationSt); ArrayList<Hit> hits = iteration.getIterationHits(); boolean contigFound = false; Hit errorHit = null; for (Hit hit : hits) { if (hit.getHitDef().indexOf(contig.getId()) >= 0) { contigFound = true; errorHit = hit; break; } } if (contigFound) { outBuff.write( "ERROR: A hit from the same contig was find in the Blast file: \n" + errorHit.toString() + "\n"); } else { outBuff.write("There is no hit with the same contig! :)\n"); } } else { outBuff.write( "The protein is NOT in the BLAST used at the beginning of the annotation process.\n"); } } else { //The protein was not found on the reference set so everything's ok outBuff.write( "The protein was not found on the reference, everything's ok :)\n"); } } } } else { outBuff.write("The protein was NOT found on the WU-BLAST !! :( \n"); //System.exit(-1); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { try { //closing outputfile outBuff.close(); } catch (IOException ex) { Logger.getLogger(AutomaticQualityControl.class.getName()).log(Level.SEVERE, null, ex); } } } }
From source file:fi.iki.elonen.SimpleWebServer.java
/** * Starts as a standalone file server and waits for Enter. *//*from w ww . j a va 2s . c om*/ public static void main(String[] args) { // Defaults int port = 8080; String host = null; // bind to all interfaces by default List<File> rootDirs = new ArrayList<File>(); boolean quiet = false; String cors = null; Map<String, String> options = new HashMap<String, String>(); // Parse command-line, with short and long versions of the options. for (int i = 0; i < args.length; ++i) { if ("-h".equalsIgnoreCase(args[i]) || "--host".equalsIgnoreCase(args[i])) { host = args[i + 1]; } else if ("-p".equalsIgnoreCase(args[i]) || "--port".equalsIgnoreCase(args[i])) { if (args[i + 1].equals("public")) { port = PUBLIC; } else if (args[i + 1].equals("private")) { port = PRIVATE; } else { port = Integer.parseInt(args[i + 1]); } } else if ("-q".equalsIgnoreCase(args[i]) || "--quiet".equalsIgnoreCase(args[i])) { quiet = true; } else if ("-d".equalsIgnoreCase(args[i]) || "--dir".equalsIgnoreCase(args[i])) { rootDirs.add(new File(args[i + 1]).getAbsoluteFile()); } else if (args[i].startsWith("--cors")) { cors = "*"; int equalIdx = args[i].indexOf('='); if (equalIdx > 0) { cors = args[i].substring(equalIdx + 1); } } else if ("--licence".equalsIgnoreCase(args[i])) { System.out.println(SimpleWebServer.LICENCE + "\n"); } else if (args[i].startsWith("-X:")) { int dot = args[i].indexOf('='); if (dot > 0) { String name = args[i].substring(0, dot); String value = args[i].substring(dot + 1, args[i].length()); options.put(name, value); } } } if (rootDirs.isEmpty()) { rootDirs.add(new File(".").getAbsoluteFile()); } options.put("host", host); options.put("port", "" + port); options.put("quiet", String.valueOf(quiet)); StringBuilder sb = new StringBuilder(); for (File dir : rootDirs) { if (sb.length() > 0) { sb.append(":"); } try { sb.append(dir.getCanonicalPath()); } catch (IOException ignored) { } } options.put("home", sb.toString()); ServiceLoader<WebServerPluginInfo> serviceLoader = ServiceLoader.load(WebServerPluginInfo.class); for (WebServerPluginInfo info : serviceLoader) { String[] mimeTypes = info.getMimeTypes(); for (String mime : mimeTypes) { String[] indexFiles = info.getIndexFilesForMimeType(mime); if (!quiet) { System.out.print("# Found plugin for Mime type: \"" + mime + "\""); if (indexFiles != null) { System.out.print(" (serving index files: "); for (String indexFile : indexFiles) { System.out.print(indexFile + " "); } } System.out.println(")."); } registerPluginForMimeType(indexFiles, mime, info.getWebServerPlugin(mime), options); } } ServerRunner.executeInstance(new SimpleWebServer(host, port, rootDirs, quiet, cors)); }
From source file:is.idega.idegaweb.egov.gumbo.bpm.violation.ViolationDataProviderRealWebservice.java
public static void main(String[] arguments) { try {/*from w ww . j av a2s .c o m*/ FSWebserviceBROTAMAL_Service locator = new FSWebserviceBROTAMAL_ServiceLocator(); FSWebserviceBROTAMAL_PortType port = locator.getFSWebserviceBROTAMALSoap12HttpPort( new URL(GumboConstants.WEB_SERVICE_URL + "FSWebserviceBROTAMALSoap12HttpPort")); StringBuilder ret = new StringBuilder(); GetVigtunarleyfiByKtElement parameters = new GetVigtunarleyfiByKtElement("5411850389"); VigtunarleyfiTypeUser res[] = port.getVigtunarleyfiByKt(parameters); int len = res.length; for (int i = 0; i < len; i++) { ret.append(res[i].getHeitiLeyfis()); if (i < (len - 1)) { ret.append(", "); } } } catch (ServiceException se) { se.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } }
From source file:com.ctriposs.rest4j.tools.snapshot.check.Rest4JSnapshotCompatibilityChecker.java
public static void main(String[] args) { final Options options = new Options(); options.addOption("h", "help", false, "Print help"); options.addOption(OptionBuilder.withArgName("compatibility_level").withLongOpt("compat").hasArg() .withDescription("Compatibility level " + listCompatLevelOptions()).create('c')); final String cmdLineSyntax = Rest4JSnapshotCompatibilityChecker.class.getCanonicalName() + " [pairs of <prevRestspecPath currRestspecPath>]"; final CommandLineParser parser = new PosixParser(); final CommandLine cmd; try {/*from w w w.ja va 2 s . com*/ cmd = parser.parse(options, args); } catch (ParseException e) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(1); return; // to suppress IDE warning } final String[] targets = cmd.getArgs(); if (cmd.hasOption('h') || targets.length < 2 || targets.length % 2 != 0) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(1); } final String compatValue; if (cmd.hasOption('c')) { compatValue = cmd.getOptionValue('c'); } else { compatValue = CompatibilityLevel.DEFAULT.name(); } final CompatibilityLevel compat; try { compat = CompatibilityLevel.valueOf(compatValue.toUpperCase()); } catch (IllegalArgumentException e) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(1); return; } final StringBuilder allSummaries = new StringBuilder(); boolean result = true; final String resolverPath = System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH); final Rest4JSnapshotCompatibilityChecker checker = new Rest4JSnapshotCompatibilityChecker(); checker.setResolverPath(resolverPath); for (int i = 1; i < targets.length; i += 2) { String prevTarget = targets[i - 1]; String currTarget = targets[i]; CompatibilityInfoMap infoMap = checker.check(prevTarget, currTarget, compat); result &= infoMap.isCompatible(compat); allSummaries.append(infoMap.createSummary(prevTarget, currTarget)); } if (compat != CompatibilityLevel.OFF && allSummaries.length() > 0) { System.out.println(allSummaries); } System.exit(result ? 0 : 1); }