List of usage examples for java.io InputStream read
public int read(byte b[]) throws IOException
b
. From source file:com.hsbc.frc.SevenHero.ClientProxyAuthentication.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try {/*from w ww. j av a 2 s .c o m*/ httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080), new UsernamePasswordCredentials("43668069", "wf^O^2013")); HttpHost targetHost = new HttpHost("pt.3g.qq.com"); HttpHost proxy = new HttpHost("133.13.162.149", 8080); BasicClientCookie netscapeCookie = null; httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); // httpclient.getCookieStore().addCookie(netscapeCookie); httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); HttpGet httpget = new HttpGet("/"); httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"); System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("via proxy: " + proxy); System.out.println("to target: " + targetHost); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } InputStream is = entity.getContent(); StringBuffer sb = new StringBuffer(200); byte data[] = new byte[65536]; int n = 1; do { n = is.read(data); if (n > 0) { sb.append(new String(data)); } } while (n > 0); // System.out.println(sb); EntityUtils.consume(entity); System.out.println("----------------------------------------"); Header[] headerlist = response.getAllHeaders(); for (int i = 0; i < headerlist.length; i++) { Header header = headerlist[i]; if (header.getName().equals("Set-Cookie")) { String setCookie = header.getValue(); String cookies[] = setCookie.split(";"); for (int j = 0; j < cookies.length; j++) { String cookie[] = cookies[j].split("="); CookieManager.cookie.put(cookie[0], cookie[1]); } } System.out.println(header.getName() + ":" + header.getValue()); } String sid = getSid(sb.toString(), "&"); System.out.println("sid: " + sid); httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080), new UsernamePasswordCredentials("43668069", "wf^O^2013")); String url = Constant.openUrl + "&" + sid; targetHost = new HttpHost(url); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); httpget = new HttpGet("/"); httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"); Iterator it = CookieManager.cookie.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); Object key = entry.getKey(); Object value = entry.getValue(); netscapeCookie = new BasicClientCookie((String) (key), (String) (value)); netscapeCookie.setVersion(0); netscapeCookie.setDomain(".qq.com"); netscapeCookie.setPath("/"); // httpclient.getCookieStore().addCookie(netscapeCookie); } response = httpclient.execute(targetHost, httpget); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:airnowgrib2tojson.AirNowGRIB2toJSON.java
/** * @param args the command line arguments */// ww w . j a v a2s .c o m public static void main(String[] args) { SimpleDateFormat GMT = new SimpleDateFormat("yyMMddHH"); GMT.setTimeZone(TimeZone.getTimeZone("GMT-2")); System.out.println(GMT.format(new Date())); FTPClient ftpClient = new FTPClient(); FileOutputStream fos = null; try { //Connecting to AirNow FTP server to get the fresh AQI data ftpClient.connect("ftp.airnowapi.org"); ftpClient.login("pixelshade", "GZDN8uqduwvk"); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //downloading .grib2 file File of = new File("US-" + GMT.format(new Date()) + "_combined.grib2"); OutputStream outstr = new BufferedOutputStream(new FileOutputStream(of)); InputStream instr = ftpClient .retrieveFileStream("GRIB2/US-" + GMT.format(new Date()) + "_combined.grib2"); byte[] bytesArray = new byte[4096]; int bytesRead = -1; while ((bytesRead = instr.read(bytesArray)) != -1) { outstr.write(bytesArray, 0, bytesRead); } //Close used resources ftpClient.completePendingCommand(); outstr.close(); instr.close(); // logout the user ftpClient.logout(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { //disconnect from AirNow server ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } try { //Open .grib2 file final File AQIfile = new File("US-" + GMT.format(new Date()) + "_combined.grib2"); final GridDataset gridDS = GridDataset.open(AQIfile.getAbsolutePath()); //The data type needed - AQI; since it isn't defined in GRIB2 standard, //Aerosol type is used instead; look AirNow API documentation for details. GridDatatype AQI = gridDS.findGridDatatype("Aerosol_type_msl"); //Get the coordinate system for selected data type; //cut the rectangle to work with - time and height axes aren't present in these files //and latitude/longitude go "-1", which means all the data provided. GridCoordSystem AQIGCS = AQI.getCoordinateSystem(); List<CoordinateAxis> AQI_XY = AQIGCS.getCoordinateAxes(); Array AQIslice = AQI.readDataSlice(0, 0, -1, -1); //Variables for iterating through coordinates VariableDS var = AQI.getVariable(); Index index = AQIslice.getIndex(); //Variables for counting lat/long from the indices provided double stepX = (AQI_XY.get(2).getMaxValue() - AQI_XY.get(2).getMinValue()) / index.getShape(1); double stepY = (AQI_XY.get(1).getMaxValue() - AQI_XY.get(1).getMinValue()) / index.getShape(0); double curX = AQI_XY.get(2).getMinValue(); double curY = AQI_XY.get(1).getMinValue(); //Output details OutputStream ValLog = new FileOutputStream("USA_AQI.json"); Writer ValWriter = new OutputStreamWriter(ValLog); for (int j = 0; j < index.getShape(0); j++) { for (int i = 0; i < index.getShape(1); i++) { float val = AQIslice.getFloat(index.set(j, i)); //Write the AQI value and its coordinates if it's present by i/j indices if (!Float.isNaN(val)) ValWriter.write("{\r\n\"lat\":" + curX + ",\r\n\"lng\":" + curY + ",\r\n\"AQI\":" + val + ",\r\n},\r\n"); curX += stepX; } curY += stepY; curX = AQI_XY.get(2).getMinValue(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.shvet.poi.util.HexDump.java
public static void main(String[] args) throws Exception { File file = new File(args[0]); InputStream in = new BufferedInputStream(new FileInputStream(file)); byte[] b = new byte[(int) file.length()]; in.read(b); System.out.println(HexDump.dump(b, 0, 0)); in.close();//from ww w.j a v a 2 s.c o m }
From source file:luisjosediez.Ejercicio2.java
/** * @param args the command line arguments */// www . j av a 2 s. c o m public static void main(String[] args) { // TODO code application logic here System.out.println("Introduce la direccin de un servidor ftp: "); FTPClient cliente = new FTPClient(); String servFTP = cadena(); String clave = ""; System.out.println("Introduce usuario (vaco para conexin annima): "); String usuario = cadena(); String opcion; if (usuario.equals("")) { clave = ""; } else { System.out.println("Introduce contrasea: "); clave = cadena(); } try { cliente.setPassiveNatWorkaround(false); cliente.connect(servFTP, 21); boolean login = cliente.login(usuario, clave); if (login) { System.out.println("Conexin ok"); } else { System.out.println("Login incorrecto"); cliente.disconnect(); System.exit(1); } do { System.out.println("Orden [exit para salir]: "); opcion = cadena(); if (opcion.equals("ls")) { FTPFile[] files = cliente.listFiles(); String tipos[] = { "Fichero", "Directorio", "Enlace" }; for (int i = 0; i < files.length; i++) { System.out.println("\t" + files[i].getName() + "\t=> " + tipos[files[i].getType()]); } } else if (opcion.startsWith("cd ")) { try { cliente.changeWorkingDirectory(opcion.substring(3)); } catch (IOException e) { } } else if (opcion.equals("help")) { System.out.println( "Puede ejecutar los comandos 'exit', 'ls', 'cd', 'get' y 'upload'. Para ms detalles utilice 'help <comando>'."); } else if (opcion.startsWith("help ")) { if (opcion.endsWith(" get")) { System.out.println( "Permite descargar un archivo concreto. Uso: 'get <rutaArchivoADescargar>'."); } else if (opcion.endsWith(" ls")) { System.out.println("Lista los ficheros y directorios en la ubicacin actual. Uso: 'ls'."); } else if (opcion.endsWith(" cd")) { System.out.println("Permite cambiar la ubicacin actual. Uso: 'cd <rutaDestino>'."); } else if (opcion.endsWith(" put")) { System.out.println( "Permite subir un archivo al directorio actual. Uso: 'put <rutaArchivoASubir>'."); } } else if (opcion.startsWith("get ")) { try { System.out.println("Indique la carpeta de descarga: "); try (FileOutputStream fos = new FileOutputStream(cadena() + opcion.substring(4))) { cliente.retrieveFile(opcion.substring(4), fos); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } } else if (opcion.startsWith("put ")) { try { try { System.out.println(opcion.substring(4)); File local = new File(opcion.substring(4)); System.out.println(local.getName()); InputStream is = new FileInputStream(opcion.substring(4)); OutputStream os = cliente.storeFileStream(local.getName()); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = is.read(bytesIn)) != -1) { os.write(bytesIn, 0, read); } is.close(); os.close(); boolean completed = cliente.completePendingCommand(); if (completed) { System.out.println("The file is uploaded successfully."); } } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } } } while (!(opcion.equals("exit"))); boolean logout = cliente.logout(); if (logout) System.out.println("Logout..."); else System.out.println("Logout incorrecto"); cliente.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.archive.modules.recrawl.wbm.WbmPersistLoadProcessor.java
/** * main entry point for quick test./*from w w w . j av a2 s . com*/ * @param args */ public static void main(String[] args) throws Exception { String url = args[0]; String cookie = args.length > 1 ? args[1] : null; WbmPersistLoadProcessor wp = new WbmPersistLoadProcessor(); if (cookie != null) { wp.setRequestHeaders(Collections.singletonMap("Cookie", cookie)); } InputStream is = wp.getCDX(url); byte[] b = new byte[1024]; int n; while ((n = is.read(b)) > 0) { System.out.write(b, 0, n); } is.close(); }
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. j a v a 2 s.c o m*/ 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:copi.ScalaEntryPoint.java
public static void main(String[] args) { /*// w w w.j av a 2 s . c o m * Set lwjgl library path so that LWJGL finds the natives depending on * the OS. */ File libDir = new File(path); if (!libDir.exists()) { // create native lib folder libDir.mkdir(); // retrieve os type String osName = System.getProperty("os.name"); // try to determine if the system is 64 bit boolean is64bit = false; if (System.getProperty("os.name").contains("Windows")) { is64bit = (System.getenv("ProgramFiles(x86)") != null); } else { is64bit = (System.getProperty("os.arch").indexOf("64") != -1); } // construct name of native lib file String natLibLWJGL = ""; if (osName.startsWith("Windows")) { natLibLWJGL += "lwjgl"; if (is64bit) natLibLWJGL += "64"; natLibLWJGL += ".dll"; } else if (osName.startsWith("Linux")) { natLibLWJGL += "liblwjgl"; if (is64bit) natLibLWJGL += "64"; natLibLWJGL += ".so"; } else if (osName.startsWith("Mac OS X")) { natLibLWJGL += "liblwjgl"; natLibLWJGL += ".jnilib"; } else { System.out.println("Unsupported OS: " + osName + ". Exiting."); System.exit(-1); } // try to establish an input stream on the native lib inside the jar InputStream fis = ScalaEntryPoint.class.getResourceAsStream("/" + natLibLWJGL); if (fis == null) { System.out.println("Native library file " + natLibLWJGL + " was not found inside JAR."); System.exit(-1); } // establish an output stream on the target file File fOut = new File(path + "/" + natLibLWJGL); try (FileOutputStream fos = new FileOutputStream(fOut)) { // create file at destination if not already existing if (!fOut.exists()) fOut.createNewFile(); // making buffer for copy operation byte[] buffer = new byte[1024]; int readBytes; // Open output stream and copy data between source file in JAR and the temporary file try { while ((readBytes = fis.read(buffer)) != -1) { fos.write(buffer, 0, readBytes); } } finally { fos.close(); fis.close(); } } catch (IOException e) { System.out.println(e.getMessage()); System.exit(-1); } // register shutdown hook JVMShutdownHook jvmShutdownHook = new JVMShutdownHook(); Runtime.getRuntime().addShutdownHook(jvmShutdownHook); } // set lwjgl native library path System.setProperty("org.lwjgl.librarypath", libDir.getAbsolutePath()); // start COPI System.out.println("Starting COPI ..."); (new SICApplicationLogic()).render(); }
From source file:com.app.server.Main.java
/** * This is the start of the all the services in web server * @param args/*w w w. j ava2 s . com*/ * @throws IOException * @throws SAXException */ public static void main(String[] args) throws IOException, SAXException { long startTime = System.currentTimeMillis(); Hashtable urlClassLoaderMap = new Hashtable(); Hashtable executorServicesMap = new Hashtable(); Hashtable ataMap = new Hashtable<String, ATAConfig>(); Hashtable messagingClassMap = new Hashtable(); ConcurrentHashMap servletMapping = new ConcurrentHashMap(); Vector deployerList = new Vector(), serviceList = new Vector(); DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() { protected void loadRules() { // TODO Auto-generated method stub try { loadXMLRules(new InputSource(new FileInputStream("./config/serverconfig-rules.xml"))); } catch (FileNotFoundException e) { log.error("Error in loading the xml rules ./config/serverconfig-rules.xml", e); // TODO Auto-generated catch block //e.printStackTrace(); } } }); Digester serverdigester = serverdigesterLoader.newDigester(); final ServerConfig serverconfig = (ServerConfig) serverdigester .parse(new InputSource(new FileInputStream("./config/serverconfig.xml"))); //log.info(messagingconfig); ////log.info(serverconfig.getDeploydirectory()); PropertyConfigurator.configure("log4j.properties"); /*MemcachedClient cache=new MemcachedClient( new InetSocketAddress("localhost", 1000));*/ // Store a value (async) for one hour //c.set("someKey", 36, new String("arun")); // Retrieve a value. System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory"); System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming"); ExecutorService executor = java.util.concurrent.Executors.newCachedThreadPool(); MBeanServer mbs = MBeanServerFactory.createMBeanServer("singham"); ObjectName name = null; try { mbs.registerMBean(serverconfig, new ObjectName("com.app.server:type=serverinfo")); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } /*try { name = new ObjectName("com.app.server:type=WarDeployer"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } WarDeployer warDeployer=new WarDeployer(serverconfig.getDeploydirectory(),serverconfig.getFarmWarDir(),serverconfig.getClustergroup(),urlClassLoaderMap,executorServicesMap,messagingClassMap,servletMapping,messagingconfig,sessionObjects); warDeployer.setPriority(MIN_PRIORITY); try { mbs.registerMBean(warDeployer, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //warDeployer.start(); executor.execute(warDeployer);*/ final byte[] shutdownBt = new byte[50]; /*WebServerRequestProcessor webserverRequestProcessor=new WebServer().new WebServerRequestProcessor(servletMapping,urlClassLoaderMap,serverSocketChannel,serverconfig.getDeploydirectory(),Integer.parseInt(serverconfig.getShutdownport()),1); webserverRequestProcessor.setPriority(MIN_PRIORITY); try { name = new ObjectName("com.app.server:type=WebServerRequestProcessor"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(webserverRequestProcessor, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //webserverRequestProcessor.start(); executor.execute(webserverRequestProcessor); for(int i=0;i<10;i++){ WebServerRequestProcessor webserverRequestProcessor1=new WebServer().new WebServerRequestProcessor(servletMapping,urlClassLoaderMap,serverSocketChannel,serverconfig.getDeploydirectory(),Integer.parseInt(serverconfig.getShutdownport()),2); webserverRequestProcessor1.setPriority(MIN_PRIORITY); try { name = new ObjectName("com.app.server:type=WebServerRequestProcessor"+(i+1)); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(webserverRequestProcessor1, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } executor.execute(webserverRequestProcessor1); }*/ /*ExecutorServiceThread executorService=new ExecutorServiceThread(serverSocketChannelServices,executorServicesMap,Integer.parseInt(serverconfig.getShutdownport()),ataMap,urlClassLoaderMap,serverconfig.getDeploydirectory(),serverconfig.getServicesdirectory(),serverconfig.getEarservicesdirectory(),serverconfig.getNodesport()); try { name = new ObjectName("com.app.services:type=ExecutorServiceThread"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(executorService, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //executorService.start(); executor.execute(executorService); for(int i=0;i<10;i++){ ExecutorServiceThread executorService1=new ExecutorServiceThread(serverSocketChannelServices,executorServicesMap,Integer.parseInt(serverconfig.getShutdownport()),ataMap,urlClassLoaderMap,serverconfig.getDeploydirectory(),serverconfig.getServicesdirectory(),serverconfig.getEarservicesdirectory(),serverconfig.getNodesport()); try { name = new ObjectName("com.app.services:type=ExecutorServiceThread"+(i+1)); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(executorService1, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } executor.execute(executorService1); }*/ /*WebServerHttpsRequestProcessor webserverHttpsRequestProcessor=new WebServer().new WebServerHttpsRequestProcessor(servletMapping,urlClassLoaderMap,Integer.parseInt(serverconfig.getHttpsport()),serverconfig.getDeploydirectory(),Integer.parseInt(serverconfig.getShutdownport()),serverconfig.getHttpscertificatepath(),serverconfig.getHttpscertificatepasscode(),1); try { name = new ObjectName("com.app.server:type=WebServerHttpsRequestProcessor"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(webserverHttpsRequestProcessor, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } webserverHttpsRequestProcessor.setPriority(MAX_PRIORITY); //webserverRequestProcessor.start(); executor.execute(webserverHttpsRequestProcessor);*/ /* for(int i=0;i<2;i++){ webserverHttpsRequestProcessor=new WebServer().new WebServerHttpsRequestProcessor(urlClassLoaderMap,Integer.parseInt(serverconfig.getHttpsport())+(i+1),serverconfig.getDeploydirectory(),Integer.parseInt(serverconfig.getShutdownport()),serverconfig.getHttpscertificatepath(),serverconfig.getHttpscertificatepasscode(),1); try { name = new ObjectName("com.app.server:type=WebServerHttpsRequestProcessor"+(i+1)); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(webserverHttpsRequestProcessor, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } executor.execute(webserverHttpsRequestProcessor); }*/ /*ATAServer ataServer=new ATAServer(serverconfig.getAtaaddress(),serverconfig.getAtaport(),ataMap); try { name = new ObjectName("com.app.services:type=ATAServer"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(ataServer, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ataServer.start();*/ /*ATAConfigClient ataClient=new ATAConfigClient(serverconfig.getAtaaddress(),serverconfig.getAtaport(),serverconfig.getServicesport(),executorServicesMap); try { name = new ObjectName("com.app.services:type=ATAConfigClient"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(ataClient, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ataClient.start();*/ /*MessagingServer messageServer=new MessagingServer(serverconfig.getMessageport(),messagingClassMap); try { name = new ObjectName("com.app.messaging:type=MessagingServer"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(messageServer, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //messageServer.start(); executor.execute(messageServer);*/ /*RandomQueueMessagePicker randomqueuemessagepicker=new RandomQueueMessagePicker(messagingClassMap); try { name = new ObjectName("com.app.messaging:type=RandomQueueMessagePicker"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(randomqueuemessagepicker, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //randomqueuemessagepicker.start(); executor.execute(randomqueuemessagepicker);*/ /*RoundRobinQueueMessagePicker roundrobinqueuemessagepicker=new RoundRobinQueueMessagePicker(messagingClassMap); try { name = new ObjectName("com.app.messaging:type=RoundRobinQueueMessagePicker"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(roundrobinqueuemessagepicker, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //roundrobinqueuemessagepicker.start(); executor.execute(roundrobinqueuemessagepicker);*/ /*TopicMessagePicker topicpicker= new TopicMessagePicker(messagingClassMap); try { name = new ObjectName("com.app.messaging:type=TopicMessagePicker"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(topicpicker, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //topicpicker.start(); executor.execute(topicpicker);*/ try { name = new ObjectName(SARDeployer.OBJECT_NAME); } catch (Exception e) { log.error("Error in creating the object name " + SARDeployer.OBJECT_NAME, e); // TODO Auto-generated catch block //e1.printStackTrace(); } log.info(System.getProperty("user.dir")); try { mbs.createMBean("com.app.server.SARDeployer", name); mbs.invoke(name, "init", new Object[] { deployerList }, new String[] { Vector.class.getName() }); mbs.invoke(name, "init", new Object[] { serviceList, serverconfig, mbs }, new String[] { Vector.class.getName(), ServerConfig.class.getName(), MBeanServer.class.getName() }); mbs.invoke(name, "start", null, null); mbs.invoke(name, "deploy", new Object[] { new URL("file:///" + new File("").getAbsolutePath() + "/config/mbean-service.xml") }, new String[] { URL.class.getName() }); /*name=new ObjectName("com.app.server:type=deployer,service=WARDeployer"); mbs.invoke(name, "deploy", new Object[]{new URL("file:///"+serverconfig.getDeploydirectory()+"/TestDollar2.war")}, new String[]{URL.class.getName()}); mbs.invoke(name, "deploy", new Object[]{new URL("file:///"+serverconfig.getDeploydirectory()+"/StrutsProj.war")}, new String[]{URL.class.getName()});*/ //mbs.registerMBean("", name); } catch (Exception ex) { log.error("Error in SAR DEPLOYER ", ex); // TODO Auto-generated catch block //e1.printStackTrace(); } //scanner.deployPackages(new File[]{new File(serverconfig.getDeploydirectory()+"/AppServer.war")}); try { new NodeResourceReceiver(mbs).start(); } catch (Exception ex) { log.error("Node Receiver start", ex); //e2.printStackTrace(); } long endTime = System.currentTimeMillis(); log.info("Server started in " + ((endTime - startTime) / 1000) + " seconds"); /*try { mbs.invoke(name, "startDeployer", null, null); } catch (InstanceNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (ReflectionException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (MBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } */ /*JarDeployer jarDeployer=new JarDeployer(registry,serverconfig.getServicesdirectory(), serverconfig.getServiceslibdirectory(),serverconfig.getCachedir(),executorServicesMap, urlClassLoaderMap); try { name = new ObjectName("com.app.server:type=JarDeployer"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(jarDeployer, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //jarDeployer.start(); executor.execute(jarDeployer);*/ /*EARDeployer earDeployer=new EARDeployer(registry,serverconfig.getEarservicesdirectory(),serverconfig.getDeploydirectory(),executorServicesMap, urlClassLoaderMap,serverconfig.getCachedir(),warDeployer); try { name = new ObjectName("com.app.server:type=EARDeployer"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(earDeployer, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //earDeployer.start(); executor.execute(earDeployer);*/ /*JVMConsole jvmConsole=new JVMConsole(Integer.parseInt(serverconfig.getJvmConsolePort())); try { name = new ObjectName("com.app.server:type=JVMConsole"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(jvmConsole, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } executor.execute(jvmConsole);*/ /*ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); XMLDeploymentScanner xmlDeploymentScanner =new XMLDeploymentScanner(serverconfig.getDeploydirectory(),serverconfig.getServiceslibdirectory()); exec.scheduleAtFixedRate(xmlDeploymentScanner, 0, 1000, TimeUnit.MILLISECONDS);*/ /*EmbeddedJMS embeddedJMS=null; try { embeddedJMS=new EmbeddedJMS(); embeddedJMS.start(); } catch (Exception ex) { // TODO Auto-generated catch block ex.printStackTrace(); } EJBDeployer ejbDeployer=new EJBDeployer(serverconfig.getServicesdirectory(),registry,Integer.parseInt(serverconfig.getServicesregistryport()),embeddedJMS); try { name = new ObjectName("com.app.server:type=EJBDeployer"); } catch (MalformedObjectNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { mbs.registerMBean(ejbDeployer, name); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //jarDeployer.start(); executor.execute(ejbDeployer);*/ new Thread() { public void run() { try { ServerSocket serverSocket = new ServerSocket(Integer.parseInt(serverconfig.getShutdownport())); while (true) { Socket sock = serverSocket.accept(); InputStream istream = sock.getInputStream(); istream.read(shutdownBt); String shutdownStr = new String(shutdownBt); String[] shutdownToken = shutdownStr.split("\r\n\r\n"); //log.info(shutdownStr); if (shutdownToken[0].startsWith("shutdown WebServer")) { synchronized (shutDownObject) { shutDownObject.notifyAll(); } } } } catch (Exception e) { log.error("Shutdown error", e); // TODO Auto-generated catch block //e.printStackTrace(); } } }.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { log.info("IN shutdown Hook"); synchronized (shutDownObject) { shutDownObject.notifyAll(); } } })); try { synchronized (shutDownObject) { shutDownObject.wait(); } //executor.shutdownNow(); //serverSocketChannelServices.close(); //embeddedJMS.stop(); } catch (Exception e) { log.error("Error in object wait ", e); // TODO Auto-generated catch block //e1.printStackTrace(); } try { mbs.invoke(name, "stop", null, null); mbs.invoke(name, "destroy", null, null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } log.info("Halting JVM"); log.info("Exiting JVM"); /*try{ Thread.sleep(10000); } catch(Exception ex){ }*/ //webserverRequestProcessor.stop(); //webserverRequestProcessor1.stop(); /*warDeployer.stop(); executorService.stop(); //ataServer.stop(); //ataClient.stop(); messageServer.stop(); randomqueuemessagepicker.stop(); roundrobinqueuemessagepicker.stop(); topicpicker.stop();*/ /*try { mbs.invoke(new ObjectName("com.app.server:type=SARDeployer"), "destroyDeployer", null, null); } catch (InstanceNotFoundException | MalformedObjectNameException | ReflectionException | MBeanException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ //earDeployer.stop(); System.exit(0); }
From source file:com.zimbra.cs.mime.Mime.java
public static void main(String[] args) throws MessagingException, IOException { String s = URLDecoder//from ww w.j ava 2 s . c om .decode("Zimbra%20日本語化の考慮点.txt", "utf-8"); System.out.println(s); System.out.println(expandNumericCharacterReferences( "Zimbra%20日本語化の考慮点.txt@&;&#;&#x;&#༤7")); MimeMessage mm = new FixedMimeMessage(JMSession.getSession(), new SharedFileInputStream("C:\\Temp\\mail\\24245")); InputStream is = new RawContentMultipartDataSource(mm, new ContentType(mm.getContentType())) .getInputStream(); int num; byte buf[] = new byte[1024]; while ((num = is.read(buf)) != -1) { System.out.write(buf, 0, num); } }
From source file:com.google.oacurl.Fetch.java
public static void main(String[] args) throws Exception { FetchOptions options = new FetchOptions(); CommandLine line = options.parse(args); args = line.getArgs();//from ww w .j ava2 s .co m if (options.isHelp()) { new HelpFormatter().printHelp("url", options.getOptions()); System.exit(0); } if (args.length != 1) { new HelpFormatter().printHelp("url", options.getOptions()); System.exit(-1); } if (options.isInsecure()) { SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier()); } LoggingConfig.init(options.isVerbose()); if (options.isVerbose()) { LoggingConfig.enableWireLog(); } String url = args[0]; ServiceProviderDao serviceProviderDao = new ServiceProviderDao(); ConsumerDao consumerDao = new ConsumerDao(); AccessorDao accessorDao = new AccessorDao(); Properties loginProperties = null; try { loginProperties = new PropertiesProvider(options.getLoginFileName()).get(); } catch (FileNotFoundException e) { System.err.println(".oacurl.properties file not found in homedir"); System.err.println("Make sure you've run oacurl-login first!"); System.exit(-1); } OAuthServiceProvider serviceProvider = serviceProviderDao.nullServiceProvider(); OAuthConsumer consumer = consumerDao.loadConsumer(loginProperties, serviceProvider); OAuthAccessor accessor = accessorDao.loadAccessor(loginProperties, consumer); OAuthClient client = new OAuthClient(new HttpClient4(SingleClient.HTTP_CLIENT_POOL)); OAuthVersion version = (loginProperties.containsKey("oauthVersion")) ? OAuthVersion.valueOf(loginProperties.getProperty("oauthVersion")) : OAuthVersion.V1; OAuthEngine engine; switch (version) { case V1: engine = new V1OAuthEngine(); break; case V2: engine = new V2OAuthEngine(); break; case WRAP: engine = new WrapOAuthEngine(); break; default: throw new IllegalArgumentException("Unknown version: " + version); } try { OAuthMessage request; List<Entry<String, String>> related = options.getRelated(); Method method = options.getMethod(); if (method == Method.POST || method == Method.PUT) { InputStream bodyStream; if (related != null) { bodyStream = new MultipartRelatedInputStream(related); } else if (options.getFile() != null) { bodyStream = new FileInputStream(options.getFile()); } else { bodyStream = System.in; } request = newRequestMessage(accessor, method, url, bodyStream, engine); request.getHeaders().add(new OAuth.Parameter("Content-Type", options.getContentType())); } else { request = newRequestMessage(accessor, method, url, null, engine); } List<Parameter> headers = options.getHeaders(); addHeadersToRequest(request, headers); HttpResponseMessage httpResponse; if (version == OAuthVersion.V1) { OAuthResponseMessage response; response = client.access(request, ParameterStyle.AUTHORIZATION_HEADER); httpResponse = response.getHttpResponse(); } else { HttpMessage httpRequest = new HttpMessage(request.method, new URL(request.URL), request.getBodyAsStream()); httpRequest.headers.addAll(request.getHeaders()); httpResponse = client.getHttpClient().execute(httpRequest, client.getHttpParameters()); httpResponse = HttpMessageDecoder.decode(httpResponse); } System.err.flush(); if (options.isInclude()) { Map<String, Object> dump = new HashMap<String, Object>(); httpResponse.dump(dump); System.out.print(dump.get(HttpMessage.RESPONSE)); } // Dump the bytes in the response's encoding. InputStream bodyStream = httpResponse.getBody(); byte[] buf = new byte[1024]; int count; while ((count = bodyStream.read(buf)) > -1) { System.out.write(buf, 0, count); } } catch (OAuthProblemException e) { OAuthUtil.printOAuthProblemException(e); } }