List of usage examples for java.lang String length
public int length()
From source file:org.jfree.chart.demo.Display.java
/** * Launch the application./*ww w . ja v a 2 s . com*/ */ public static void main(String[] args) throws IOException { EventQueue.invokeLater(new Runnable() { public void run() { try { Display window = new Display(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } //////////// } }); try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s; File dataFile = new File("data.txt"); FileWriter fw = new FileWriter(dataFile); BufferedWriter bw = new BufferedWriter(fw); DataParser datIn = new DataParser(effectiveX, effectiveY); //while(!enabled){}//spin until enabled while ((s = in.readLine()) != null && s.length() != 0 && enabled) { // System.out.println(s); if (datIn.parseString(s)) { bw.write(s); bw.write('\n'); bw.flush(); panel_1.plotCoords(datIn.getX(), datIn.getFlippedY()); TimeElapsed.setText(Double.toString(datIn.getTime())); } } bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:net.itransformers.idiscover.discoverylisteners.XmlTopologyDeviceLogger.java
public static void main(String[] args) throws IOException, JAXBException { String path = "devices_and_models\\lab\\undirected"; File dir = new File(path); String[] files = dir.list(new FilenameFilter() { public boolean accept(File dir, String name) { return (name.endsWith(".hml")); }//from w w w . j a v a 2 s. c o m }); Map<String, String> params = new HashMap<String, String>(); params.put("path", path); params.put("conf/xslt", "iDiscover\\conf\\xslt\\transformator3.xslt"); XmlTopologyDeviceLogger logger = new XmlTopologyDeviceLogger(params, null, null); for (String fileName : files) { FileInputStream is = new FileInputStream(path + File.separator + fileName); DiscoveredDeviceData discoveredDeviceData; try { discoveredDeviceData = JaxbMarshalar.unmarshal(DiscoveredDeviceData.class, is); } finally { is.close(); } String deviceName = fileName.substring("device-".length(), fileName.length() - ".xml".length()); logger.handleDevice(deviceName, null, discoveredDeviceData, null); } }
From source file:edu.msu.cme.rdp.kmer.cli.FastKmerFilter.java
public static void main(String[] args) throws Exception { final KmerSet<Set<RefKmer>> kmerSet; final SeqReader queryReader; final SequenceType querySeqType; final File queryFile; final KmerStartsWriter out; final boolean translQuery; final int wordSize; final int translTable; final boolean alignedSeqs; final List<String> refLabels = new ArrayList(); final int maxThreads; final int trieWordSize; try {//from ww w. ja v a 2s . co m CommandLine cmdLine = new PosixParser().parse(options, args); args = cmdLine.getArgs(); if (args.length < 3) { throw new Exception("Unexpected number of arguments"); } if (cmdLine.hasOption("out")) { out = new KmerStartsWriter(cmdLine.getOptionValue("out")); } else { out = new KmerStartsWriter(System.out); } if (cmdLine.hasOption("aligned")) { alignedSeqs = true; } else { alignedSeqs = false; } if (cmdLine.hasOption("transl-table")) { translTable = Integer.valueOf(cmdLine.getOptionValue("transl-table")); } else { translTable = 11; } if (cmdLine.hasOption("threads")) { maxThreads = Integer.valueOf(cmdLine.getOptionValue("threads")); } else { maxThreads = Runtime.getRuntime().availableProcessors(); } queryFile = new File(args[1]); wordSize = Integer.valueOf(args[0]); SequenceType refSeqType = null; querySeqType = SeqUtils.guessSequenceType(queryFile); queryReader = new SequenceReader(queryFile); if (querySeqType == SequenceType.Protein) { throw new Exception("Expected nucl query sequences"); } refSeqType = SeqUtils .guessSequenceType(new File(args[2].contains("=") ? args[2].split("=")[1] : args[2])); translQuery = refSeqType == SequenceType.Protein; if (translQuery && wordSize % 3 != 0) { throw new Exception("Word size must be a multiple of 3 for nucl ref seqs"); } if (translQuery) { trieWordSize = wordSize / 3; } else { trieWordSize = wordSize; } kmerSet = new KmerSet<Set<RefKmer>>();//new KmerTrie(trieWordSize, translQuery); for (int index = 2; index < args.length; index++) { String refName; String refFileName = args[index]; if (refFileName.contains("=")) { String[] lexemes = refFileName.split("="); refName = lexemes[0]; refFileName = lexemes[1]; } else { String tmpName = new File(refFileName).getName(); if (tmpName.contains(".")) { refName = tmpName.substring(0, tmpName.lastIndexOf(".")); } else { refName = tmpName; } } File refFile = new File(refFileName); if (refSeqType != SeqUtils.guessSequenceType(refFile)) { throw new Exception( "Reference file " + refFile + " contains " + SeqUtils.guessFileFormat(refFile) + " sequences but expected " + refSeqType + " sequences"); } SequenceReader seqReader = new SequenceReader(refFile); Sequence seq; while ((seq = seqReader.readNextSequence()) != null) { if (seq.getSeqName().startsWith("#")) { continue; } KmerGenerator kmers; try { if (translQuery) { //protein ref kmers = new ProtKmerGenerator(seq.getSeqString(), trieWordSize, alignedSeqs); } else { kmers = new NuclKmerGenerator(seq.getSeqString(), trieWordSize, alignedSeqs); } while (kmers.hasNext()) { Kmer temp = kmers.next(); long[] next = temp.getLongKmers(); Set<RefKmer> refKmers = kmerSet.get(next); if (refKmers == null) { refKmers = new HashSet(); kmerSet.add(next, refKmers); } RefKmer kmerRef = new RefKmer(); kmerRef.modelPos = kmers.getPosition(); kmerRef.refFileIndex = refLabels.size(); kmerRef.refSeqid = seq.getSeqName(); refKmers.add(kmerRef); } } catch (IllegalArgumentException ex) { //System.err.println(seq.getSeqName()+ " " + ex.getMessage()); } } seqReader.close(); refLabels.add(refName); } } catch (Exception e) { new HelpFormatter().printHelp( "KmerSearch <kmerSize> <query_file> [name=]<ref_file> ...\nkmerSize should be multiple of 3, (recommend 45, minimum 30, maximum 63) ", options); e.printStackTrace(); System.exit(1); throw new RuntimeException("Stupid jvm"); //While this will never get thrown it is required to make sure javac doesn't get confused about uninitialized variables } long startTime = System.currentTimeMillis(); long seqCount = 0; final int maxTasks = 25000; System.err.println("Starting kmer mapping at " + new Date()); System.err.println("* Number of threads: " + maxThreads); System.err.println("* References: " + refLabels); System.err.println("* Reads file: " + queryFile); System.err.println("* Kmer length: " + trieWordSize); System.err.println("* Kmer Refset Size: " + kmerSet.size()); final AtomicInteger processed = new AtomicInteger(); final AtomicInteger outstandingTasks = new AtomicInteger(); ExecutorService service = Executors.newFixedThreadPool(maxThreads); Sequence querySeq; while ((querySeq = queryReader.readNextSequence()) != null) { seqCount++; String seqString = querySeq.getSeqString(); if ((!translQuery && seqString.length() < wordSize) || (translQuery && seqString.length() < wordSize + 2)) { //System.err.println(querySeq.getSeqName() + "\t" + seqString.length()); continue; } final Sequence threadSeq = querySeq; Runnable r = new Runnable() { public void run() { try { processSeq(threadSeq, refLabels, kmerSet, out, wordSize, translQuery, translTable, false); processSeq(threadSeq, refLabels, kmerSet, out, wordSize, translQuery, translTable, true); processed.incrementAndGet(); outstandingTasks.decrementAndGet(); } catch (Exception e) { e.printStackTrace(); } } }; outstandingTasks.incrementAndGet(); service.submit(r); while (outstandingTasks.get() >= maxTasks) ; if ((processed.get() + 1) % 1000000 == 0) { System.err.println("Processed " + processed + " sequences in " + (System.currentTimeMillis() - startTime) + " ms"); } } service.shutdown(); service.awaitTermination(1, TimeUnit.DAYS); System.err.println("Finished Processed " + processed + " sequences in " + (System.currentTimeMillis() - startTime) + " ms"); out.close(); }
From source file:name.livitski.databag.cli.Syntax.java
/** * Diagnostic entry point for the build process to check that all * usage strings that describe the application's syntax are present * in <code>usage.resources</code>. * Absent resources cause a <code>System.err</code> message * and a non-zero exit code./*from w ww .j ava 2 s .c o m*/ * @param args this method ignores its argument */ @SuppressWarnings("unchecked") public static void main(String[] args) { PrintStream out = System.err; Resources resources = new Resources(); final Class<Syntax> clazz = Syntax.class; String id = null; String legend = null; for (Option option : (Collection<Option>) OPTIONS.getOptions()) { try { id = getOptionId(option); legend = resources.getString(USAGE_BUNDLE, clazz, id).trim(); if (legend.indexOf('.') < legend.length() - 1) { out.printf( "Description of option %s must be a single sentence ending with a period. Got:%n\"%s\"%n", id, legend); System.exit(5); } if (option.hasArg()) resources.getString(USAGE_BUNDLE, clazz, "arg" + id); legend = null; } catch (MissingResourceException missing) { if (null == legend) { out.printf("Option \"%s\" does not have a description string in the resource bundle \"%s\"%n", id, USAGE_BUNDLE); missing.printStackTrace(out); System.exit(1); } out.printf("Required argument spec \"%s\" is missing from the resource bundle \"%s\"%n", getArgumentId(option), USAGE_BUNDLE); missing.printStackTrace(out); System.exit(2); } catch (Exception problem) { out.printf("Error while verifying option \"%s\" in the resource bundle \"%s\"%n", id, USAGE_BUNDLE); problem.printStackTrace(out); System.exit(-1); } } }
From source file:examples.mail.IMAPExportMbox.java
public static void main(String[] args) throws IOException { int connect_timeout = CONNECT_TIMEOUT; int read_timeout = READ_TIMEOUT; int argIdx = 0; String eol = EOL_DEFAULT;//from www. j a va 2s . c o m boolean printHash = false; boolean printMarker = false; int retryWaitSecs = 0; for (argIdx = 0; argIdx < args.length; argIdx++) { if (args[argIdx].equals("-c")) { connect_timeout = Integer.parseInt(args[++argIdx]); } else if (args[argIdx].equals("-r")) { read_timeout = Integer.parseInt(args[++argIdx]); } else if (args[argIdx].equals("-R")) { retryWaitSecs = Integer.parseInt(args[++argIdx]); } else if (args[argIdx].equals("-LF")) { eol = LF; } else if (args[argIdx].equals("-CRLF")) { eol = CRLF; } else if (args[argIdx].equals("-.")) { printHash = true; } else if (args[argIdx].equals("-X")) { printMarker = true; } else { break; } } final int argCount = args.length - argIdx; if (argCount < 2) { System.err.println("Usage: IMAPExportMbox [-LF|-CRLF] [-c n] [-r n] [-R n] [-.] [-X]" + " imap[s]://user:password@host[:port]/folder/path [+|-]<mboxfile> [sequence-set] [itemnames]"); System.err.println( "\t-LF | -CRLF set end-of-line to LF or CRLF (default is the line.separator system property)"); System.err.println("\t-c connect timeout in seconds (default 10)"); System.err.println("\t-r read timeout in seconds (default 10)"); System.err.println("\t-R temporary failure retry wait in seconds (default 0; i.e. disabled)"); System.err.println("\t-. print a . for each complete message received"); System.err.println("\t-X print the X-IMAP line for each complete message received"); System.err.println( "\tthe mboxfile is where the messages are stored; use '-' to write to standard output."); System.err.println( "\tPrefix filename with '+' to append to the file. Prefix with '-' to allow overwrite."); System.err.println( "\ta sequence-set is a list of numbers/number ranges e.g. 1,2,3-10,20:* - default 1:*"); System.err .println("\titemnames are the message data item name(s) e.g. BODY.PEEK[HEADER.FIELDS (SUBJECT)]" + " or a macro e.g. ALL - default (INTERNALDATE BODY.PEEK[])"); System.exit(1); } final URI uri = URI.create(args[argIdx++]); final String file = args[argIdx++]; String sequenceSet = argCount > 2 ? args[argIdx++] : "1:*"; final String itemNames; // Handle 0, 1 or multiple item names if (argCount > 3) { if (argCount > 4) { StringBuilder sb = new StringBuilder(); sb.append("("); for (int i = 4; i <= argCount; i++) { if (i > 4) { sb.append(" "); } sb.append(args[argIdx++]); } sb.append(")"); itemNames = sb.toString(); } else { itemNames = args[argIdx++]; } } else { itemNames = "(INTERNALDATE BODY.PEEK[])"; } final boolean checkSequence = sequenceSet.matches("\\d+:(\\d+|\\*)"); // are we expecting a sequence? final MboxListener chunkListener; if (file.equals("-")) { chunkListener = null; } else if (file.startsWith("+")) { final File mbox = new File(file.substring(1)); System.out.println("Appending to file " + mbox); chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, true)), eol, printHash, printMarker, checkSequence); } else if (file.startsWith("-")) { final File mbox = new File(file.substring(1)); System.out.println("Writing to file " + mbox); chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, false)), eol, printHash, printMarker, checkSequence); } else { final File mbox = new File(file); if (mbox.exists()) { throw new IOException("mailbox file: " + mbox + " already exists!"); } System.out.println("Creating file " + mbox); chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox)), eol, printHash, printMarker, checkSequence); } String path = uri.getPath(); if (path == null || path.length() < 1) { throw new IllegalArgumentException("Invalid folderPath: '" + path + "'"); } String folder = path.substring(1); // skip the leading / // suppress login details final PrintCommandListener listener = new PrintCommandListener(System.out, true) { @Override public void protocolReplyReceived(ProtocolCommandEvent event) { if (event.getReplyCode() != IMAPReply.PARTIAL) { // This is dealt with by the chunk listener super.protocolReplyReceived(event); } } }; // Connect and login final IMAPClient imap = IMAPUtils.imapLogin(uri, connect_timeout * 1000, listener); String maxIndexInFolder = null; try { imap.setSoTimeout(read_timeout * 1000); if (!imap.select(folder)) { throw new IOException("Could not select folder: " + folder); } for (String line : imap.getReplyStrings()) { maxIndexInFolder = matches(line, PATEXISTS, 1); if (maxIndexInFolder != null) { break; } } if (chunkListener != null) { imap.setChunkListener(chunkListener); } // else the command listener displays the full output without processing while (true) { boolean ok = imap.fetch(sequenceSet, itemNames); // If the fetch failed, can we retry? if (!ok && retryWaitSecs > 0 && chunkListener != null && checkSequence) { final String replyString = imap.getReplyString(); //includes EOL if (startsWith(replyString, PATTEMPFAIL)) { System.err.println("Temporary error detected, will retry in " + retryWaitSecs + "seconds"); sequenceSet = (chunkListener.lastSeq + 1) + ":*"; try { Thread.sleep(retryWaitSecs * 1000); } catch (InterruptedException e) { // ignored } } else { throw new IOException( "FETCH " + sequenceSet + " " + itemNames + " failed with " + replyString); } } else { break; } } } catch (IOException ioe) { String count = chunkListener == null ? "?" : Integer.toString(chunkListener.total); System.err.println("FETCH " + sequenceSet + " " + itemNames + " failed after processing " + count + " complete messages "); if (chunkListener != null) { System.err.println("Last complete response seen: " + chunkListener.lastFetched); } throw ioe; } finally { if (printHash) { System.err.println(); } if (chunkListener != null) { chunkListener.close(); final Iterator<String> missingIds = chunkListener.missingIds.iterator(); if (missingIds.hasNext()) { StringBuilder sb = new StringBuilder(); for (;;) { sb.append(missingIds.next()); if (!missingIds.hasNext()) { break; } sb.append(","); } System.err.println("*** Missing ids: " + sb.toString()); } } imap.logout(); imap.disconnect(); } if (chunkListener != null) { System.out.println("Processed " + chunkListener.total + " messages."); } if (maxIndexInFolder != null) { System.out.println("Folder contained " + maxIndexInFolder + " messages."); } }
From source file:ValidateLicenseHeaders.java
/** * ValidateLicenseHeaders jboss-src-root * /*from w w w . j a v a 2 s .co m*/ * @param args */ public static void main(String[] args) throws Exception { if (args.length == 0 || args[0].startsWith("-h")) { log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root"); System.exit(1); } int rootArg = 0; if (args.length == 2) { if (args[0].startsWith("-add")) addDefaultHeader = true; else { log.severe("Uknown argument: " + args[0]); log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root"); System.exit(1); } rootArg = 1; } File jbossSrcRoot = new File(args[rootArg]); if (jbossSrcRoot.exists() == false) { log.info("Src root does not exist, check " + jbossSrcRoot.getAbsolutePath()); System.exit(1); } URL u = Thread.currentThread().getContextClassLoader() .getResource("META-INF/services/javax.xml.parsers.DocumentBuilderFactory"); System.err.println(u); // Load the valid copyright statements for the licenses File licenseInfo = new File(jbossSrcRoot, "varia/src/etc/license-info.xml"); if (licenseInfo.exists() == false) { log.severe("Failed to find the varia/src/etc/license-info.xml under the src root"); System.exit(1); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = factory.newDocumentBuilder(); Document doc = db.parse(licenseInfo); NodeList licenses = doc.getElementsByTagName("license"); for (int i = 0; i < licenses.getLength(); i++) { Element license = (Element) licenses.item(i); String key = license.getAttribute("id"); ArrayList headers = new ArrayList(); licenseHeaders.put(key, headers); NodeList copyrights = license.getElementsByTagName("terms-header"); for (int j = 0; j < copyrights.getLength(); j++) { Element copyright = (Element) copyrights.item(j); copyright.normalize(); String id = copyright.getAttribute("id"); // The id will be blank if there is no id attribute if (id.length() == 0) continue; String text = getElementContent(copyright); if (text == null) continue; // Replace all duplicate whitespace and '*' with a single space text = text.replaceAll("[\\s*]+", " "); if (text.length() == 1) continue; text = text.toLowerCase().trim(); // Replace any copyright date0-date1,date2 with copyright ... text = text.replaceAll(COPYRIGHT_REGEX, "..."); LicenseHeader lh = new LicenseHeader(id, text); headers.add(lh); } } log.fine(licenseHeaders.toString()); File[] files = jbossSrcRoot.listFiles(dotJavaFilter); log.info("Root files count: " + files.length); processSourceFiles(files, 0); log.info("Processed " + totalCount); log.info("Updated jboss headers: " + jbossCount); // Files with no headers details log.info("Files with no headers: " + noheaders.size()); FileWriter fw = new FileWriter("NoHeaders.txt"); for (Iterator iter = noheaders.iterator(); iter.hasNext();) { File f = (File) iter.next(); fw.write(f.getAbsolutePath()); fw.write('\n'); } fw.close(); // Files with unknown headers details log.info("Files with invalid headers: " + invalidheaders.size()); fw = new FileWriter("InvalidHeaders.txt"); for (Iterator iter = invalidheaders.iterator(); iter.hasNext();) { File f = (File) iter.next(); fw.write(f.getAbsolutePath()); fw.write('\n'); } fw.close(); // License usage summary log.info("Creating HeadersSummary.txt"); fw = new FileWriter("HeadersSummary.txt"); for (Iterator iter = licenseHeaders.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); fw.write("+++ License type=" + key); fw.write('\n'); List list = (List) entry.getValue(); Iterator jiter = list.iterator(); while (jiter.hasNext()) { LicenseHeader lh = (LicenseHeader) jiter.next(); fw.write('\t'); fw.write(lh.id); fw.write(", count="); fw.write("" + lh.count); fw.write('\n'); } } fw.close(); }
From source file:eu.planets_project.tb.gui.backing.admin.wsclient.util.WSClient.java
/** * Invokes an operation using SAAJ/*from w w w. j a va 2 s. com*/ * * @param operation The operation to invoke */ public static void main(String[] args) { try { /*OperationInfo operation = new OperationInfo(); operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/"); operation.setInputMessageName("HelloWorld_sayHello"); operation.setInputMessageText("<urn:sayHello xmlns:urn='urn:jbosstest'><arg0>Markus</arg0></urn:sayHello>"); operation.setNamespaceURI("urn:jbosstest"); operation.setOutputMessageName("HelloWorld_sayHelloResponse"); operation.setOutputMessageText("<sayHello><return>0</return></sayHello>"); operation.setSoapActionURI(""); operation.setStyle("document"); operation.setTargetMethodName("sayHello"); operation.setTargetObjectURI(null); operation.setTargetURL("http://localhost:8080/HelloWorld/HelloWorld");*/ OperationInfo operation = new OperationInfo(); operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/"); operation.setInputMessageName("ConversionRateSoapIn"); operation.setInputMessageText( "<ns5:ConversionRate xmlns:ns5='http://www.webserviceX.NET/'><ns5:FromCurrency>EUR</ns5:FromCurrency><ns5:ToCurrency>SKK</ns5:ToCurrency></ns5:ConversionRate>"); operation.setNamespaceURI("http://www.webserviceX.NET/"); operation.setOutputMessageName("ConversionRateSoapOut"); operation.setOutputMessageText( "<ConversionRate><ConversionRateResult>0</ConversionRateResult></ConversionRate>"); operation.setSoapActionURI("http://www.webserviceX.NET/ConversionRate"); operation.setStyle("document"); operation.setTargetMethodName("ConversionRate"); operation.setTargetObjectURI(null); operation.setTargetURL("http://www.webservicex.net/CurrencyConvertor.asmx"); // Determine if the operation style is RPC boolean isRPC = operation.getStyle().equalsIgnoreCase("rpc"); // All connections are created by using a connection factory SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance(); // Now we can create a SOAPConnection object using the connection factory SOAPConnection connection = conFactory.createConnection(); // All SOAP messages are created by using a message factory MessageFactory msgFactory = MessageFactory.newInstance(); // Now we can create the SOAP message object SOAPMessage msg = msgFactory.createMessage(); // Get the SOAP part from the SOAP message object SOAPPart soapPart = msg.getSOAPPart(); // The SOAP part object will automatically contain the SOAP envelope SOAPEnvelope envelope = soapPart.getEnvelope(); //envelope.addNamespaceDeclaration("", operation.getNamespaceURI()); if (isRPC) { // Add namespace declarations to the envelope, usually only required for RPC/encoded envelope.addNamespaceDeclaration(XSI_NAMESPACE_PREFIX, XSI_NAMESPACE_URI); envelope.addNamespaceDeclaration(XSD_NAMESPACE_PREFIX, XSD_NAMESPACE_URI); } // Get the SOAP header from the envelope SOAPHeader header = envelope.getHeader(); // The client does not yet support SOAP headers header.detachNode(); // Get the SOAP body from the envelope and populate it SOAPBody body = envelope.getBody(); // Create the default namespace for the SOAP body //body.addNamespaceDeclaration("", operation.getNamespaceURI()); // Add the service information String targetObjectURI = operation.getTargetObjectURI(); if (targetObjectURI == null) { // The target object URI should not be null targetObjectURI = ""; } // Add the service information //Name svcInfo = envelope.createName(operation.getTargetMethodName(), "", targetObjectURI); Name svcInfo = envelope.createName(operation.getTargetMethodName(), "ns2", operation.getNamespaceURI()); SOAPElement svcElem = body.addChildElement(svcInfo); if (isRPC) { // Set the encoding style of the service element svcElem.setEncodingStyle(operation.getEncodingStyle()); } // Add the message contents to the SOAP body Document doc = XMLSupport.readXML(operation.getInputMessageText()); if (doc.hasRootElement()) { // Begin building content buildSoapElement(envelope, svcElem, doc.getRootElement(), isRPC); } //svcElem.addTextNode(operation.getInputMessageText()); //svcElem. // Check for a SOAPAction String soapActionURI = operation.getSoapActionURI(); if (soapActionURI != null && soapActionURI.length() > 0) { // Add the SOAPAction value as a MIME header MimeHeaders mimeHeaders = msg.getMimeHeaders(); mimeHeaders.setHeader("SOAPAction", "\"" + operation.getSoapActionURI() + "\""); } // Save changes to the message we just populated msg.saveChanges(); // Get ready for the invocation URLEndpoint endpoint = new URLEndpoint(operation.getTargetURL()); // Show the URL endpoint message in the log ByteArrayOutputStream msgStream = new ByteArrayOutputStream(); msg.writeTo(msgStream); log.debug("SOAP Message MeasurementTarget URL: " + endpoint.getURL()); log.debug("SOAP Request: " + msgStream.toString()); // Make the call SOAPMessage response = connection.call(msg, endpoint); // Close the connection, we are done with it connection.close(); // Get the content of the SOAP response Source responseContent = response.getSOAPPart().getContent(); // Convert the SOAP response into a JDOM TransformerFactory tFact = TransformerFactory.newInstance(); Transformer transformer = tFact.newTransformer(); JDOMResult jdomResult = new JDOMResult(); transformer.transform(responseContent, jdomResult); // Get the document created by the transform operation Document responseDoc = jdomResult.getDocument(); // Send the response to the Log String strResponse = XMLSupport.outputString(responseDoc); log.debug("SOAP Response from: " + operation.getTargetMethodName() + ": " + strResponse); // Set the response as the output message operation.setOutputMessageText(strResponse); // Return the response generated //return strResponse; } catch (Throwable ex) { log.error("Error invoking operation:"); log.error(ex.getMessage()); } //return ""; }
From source file:org.kuali.student.git.importer.ApplyManualBranchCleanup.java
/** * @param args//from w w w.j a v a 2 s . co m */ public static void main(String[] args) { if (args.length < 4 || args.length > 7) { usage(); } File inputFile = new File(args[0]); if (!inputFile.exists()) usage(); boolean bare = false; if (args[2].trim().equals("1")) { bare = true; } String remoteName = args[3].trim(); String refPrefix = Constants.R_HEADS; if (args.length == 5) refPrefix = args[4].trim(); String userName = null; String password = null; if (args.length == 6) userName = args[5].trim(); if (args.length == 7) password = args[6].trim(); try { Repository repo = GitRepositoryUtils.buildFileRepository(new File(args[1]).getAbsoluteFile(), false, bare); Git git = new Git(repo); RevWalk rw = new RevWalk(repo); ObjectInserter objectInserter = repo.newObjectInserter(); BufferedReader fileReader = new BufferedReader(new FileReader(inputFile)); String line = fileReader.readLine(); int lineNumber = 1; BatchRefUpdate batch = repo.getRefDatabase().newBatchUpdate(); List<RefSpec> branchesToDelete = new ArrayList<>(); while (line != null) { if (line.startsWith("#") || line.length() == 0) { // skip over comments and blank lines line = fileReader.readLine(); lineNumber++; continue; } String parts[] = line.trim().split(":"); String branchName = parts[0]; Ref branchRef = repo.getRef(refPrefix + "/" + branchName); if (branchRef == null) { log.warn("line: {}, No branch matching {} exists, skipping.", lineNumber, branchName); line = fileReader.readLine(); lineNumber++; continue; } String tagName = null; if (parts.length > 1) tagName = parts[1]; if (tagName != null) { if (tagName.equals("keep")) { log.info("keeping existing branch for {}", branchName); line = fileReader.readLine(); lineNumber++; continue; } if (tagName.equals("tag")) { /* * Shortcut to say make the tag start with the same name as the branch. */ tagName = branchName; } // create a tag RevCommit commit = rw.parseCommit(branchRef.getObjectId()); ObjectId tag = GitRefUtils.insertTag(tagName, commit, objectInserter); batch.addCommand(new ReceiveCommand(null, tag, Constants.R_TAGS + tagName, Type.CREATE)); log.info("converting branch {} into a tag {}", branchName, tagName); } if (remoteName.equals("local")) { batch.addCommand( new ReceiveCommand(branchRef.getObjectId(), null, branchRef.getName(), Type.DELETE)); } else { // if the branch is remote then remember its name so we can batch delete after we have the full list. branchesToDelete.add(new RefSpec(":" + Constants.R_HEADS + branchName)); } line = fileReader.readLine(); lineNumber++; } fileReader.close(); // run the batch update batch.execute(rw, new TextProgressMonitor()); if (!remoteName.equals("local")) { // push the tag to the remote right now log.info("pushing tags to {}", remoteName); PushCommand pushCommand = git.push().setRemote(remoteName).setPushTags() .setProgressMonitor(new TextProgressMonitor()); if (userName != null) pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, password)); Iterable<PushResult> results = pushCommand.call(); for (PushResult pushResult : results) { if (!pushResult.equals(Result.NEW)) { log.warn("failed to push tag " + pushResult.getMessages()); } } // delete the branches from the remote log.info("pushing branch deletes to remote: {}", remoteName); results = git.push().setRemote(remoteName).setRefSpecs(branchesToDelete) .setProgressMonitor(new TextProgressMonitor()).call(); } objectInserter.release(); rw.release(); } catch (Exception e) { log.error("unexpected Exception ", e); } }
From source file:io.alicorn.device.client.DeviceClient.java
public static void main(String[] args) { logger.info("Starting Alicorn Client System"); // Prepare Display Color. transform3xWrite(DisplayTools.commandForColor(0, 204, 255)); // Setup text information. // transform3xWrite(DisplayTools.commandForText("Sup Fam")); class StringWrapper { public String string = ""; }/*from ww w .j av a2 s .co m*/ final StringWrapper string = new StringWrapper(); // Text Handler. Thread thread = new Thread(new Runnable() { @Override public void run() { String latestString = ""; String outputStringLine1Complete = ""; long outputStringLine1Cursor = 1; int outputStringLine1Mask = 0; String outputStringLine2 = ""; while (true) { if (!latestString.equals(string.string)) { latestString = string.string; String[] latestStrings = latestString.split("::"); outputStringLine1Complete = latestStrings[0]; outputStringLine1Mask = outputStringLine1Complete.length(); outputStringLine1Cursor = 0; // Trim second line to a length of sixteen. outputStringLine2 = latestStrings.length > 1 ? latestStrings[1] : ""; if (outputStringLine2.length() > 16) { outputStringLine2 = outputStringLine2.substring(0, 16); } } StringBuilder outputStringLine1 = new StringBuilder(); if (outputStringLine1Complete.length() > 0) { long cursor = outputStringLine1Cursor; for (int i = 0; i < 16; i++) { outputStringLine1.append( outputStringLine1Complete.charAt((int) (cursor % outputStringLine1Mask))); cursor += 1; } outputStringLine1Cursor += 1; } else { outputStringLine1.append(" "); } try { transform3xWrite( DisplayTools.commandForText(outputStringLine1.toString() + outputStringLine2)); Thread.sleep(400); } catch (Exception e) { e.printStackTrace(); } } } }); thread.start(); // Event Handler while (true) { try { String url = "http://169.254.90.174:9789/api/iot/narwhalText"; HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); string.string = apacheHttpEntityToString(response.getEntity()); Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } } }
From source file:bmsi.util.UnaryPredicate.java
public static void main(String[] argv) throws IOException { String filea = argv[argv.length - 2]; String fileb = argv[argv.length - 1]; String[] a = slurp(filea);/*from w w w.j a v a 2s . c om*/ String[] b = slurp(fileb); Diff d = new Diff(a, b); char style = 'n'; d.heuristic = false; for (int i = 0; i < argv.length - 2; ++i) { String f = argv[i]; if (f.startsWith("-")) { for (int j = 1; j < f.length(); ++j) { switch (f.charAt(j)) { case 'H': // heuristic on d.heuristic = true; break; case 'e': // Ed style style = 'e'; break; case 'c': // Context diff style = 'c'; break; case 'u': style = 'u'; break; } } } } boolean reverse = style == 'e'; Diff.Change script = d.diff_2(reverse); if (script == null) System.err.println("No differences"); else { Base p; switch (style) { case 'e': p = new EdPrint(a, b); break; case 'c': p = new ContextPrint(a, b); break; case 'u': p = new UnifiedPrint(a, b); break; default: p = new NormalPrint(a, b); } p.print_header(filea, fileb); p.print_script(script); } }