label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: protected String getLibJSCode() throws IOException { if (cachedLibJSCode == null) { InputStream is = getClass().getResourceAsStream(JS_LIB_FILE); StringWriter output = new StringWriter(); IOUtils.copy(is, output); cachedLibJSCode = output.toString(); } return cachedLibJSCode; } Code Sample 2: private void gerarComissao() { int opt = Funcoes.mensagemConfirma(null, "Confirma gerar comiss�es para o vendedor " + txtNomeVend.getVlrString().trim() + "?"); if (opt == JOptionPane.OK_OPTION) { StringBuilder insert = new StringBuilder(); insert.append("INSERT INTO RPCOMISSAO "); insert.append("(CODEMP, CODFILIAL, CODPED, CODITPED, "); insert.append("CODEMPVD, CODFILIALVD, CODVEND, VLRCOMISS ) "); insert.append("VALUES "); insert.append("(?,?,?,?,?,?,?,?)"); PreparedStatement ps; int parameterIndex; boolean gerou = false; try { for (int i = 0; i < tab.getNumLinhas(); i++) { if (((BigDecimal) tab.getValor(i, 8)).floatValue() > 0) { parameterIndex = 1; ps = con.prepareStatement(insert.toString()); ps.setInt(parameterIndex++, AplicativoRep.iCodEmp); ps.setInt(parameterIndex++, ListaCampos.getMasterFilial("RPCOMISSAO")); ps.setInt(parameterIndex++, txtCodPed.getVlrInteger()); ps.setInt(parameterIndex++, (Integer) tab.getValor(i, ETabNota.ITEM.ordinal())); ps.setInt(parameterIndex++, AplicativoRep.iCodEmp); ps.setInt(parameterIndex++, ListaCampos.getMasterFilial("RPVENDEDOR")); ps.setInt(parameterIndex++, txtCodVend.getVlrInteger()); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.VLRCOMIS.ordinal())); ps.executeUpdate(); gerou = true; } } if (gerou) { Funcoes.mensagemInforma(null, "Comiss�o gerada para " + txtNomeVend.getVlrString().trim()); txtCodPed.setText("0"); lcPedido.carregaDados(); carregaTabela(); con.commit(); } else { Funcoes.mensagemInforma(null, "N�o foi possiv�l gerar comiss�o!\nVerifique os valores das comiss�es dos itens."); } } catch (Exception e) { e.printStackTrace(); Funcoes.mensagemErro(this, "Erro ao gerar comiss�o!\n" + e.getMessage()); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } } }
00
Code Sample 1: public static String getWebPage(URL urlObj) { try { String content = ""; InputStreamReader is = new InputStreamReader(urlObj.openStream()); BufferedReader reader = new BufferedReader(is); String line; while ((line = reader.readLine()) != null) { content += line; } return content; } catch (IOException e) { throw new Error("The page " + quote(urlObj.toString()) + "could not be retrieved." + "\nThis is could be caused by a number of things:" + "\n" + "\n - the computer hosting the web page you want is down, or has returned an error" + "\n - your computer does not have Internet access" + "\n - the heat death of the universe has occurred, taking down all web servers with it"); } } Code Sample 2: public static long[] getUids(String myUid) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpGet get = new HttpGet(UIDS_URI); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); JSONArray result = new JSONArray(res); long[] friends = new long[result.length()]; long uid = Long.parseLong(myUid); for (int i = 0; i < result.length(); i++) { if (uid != result.getLong(i)) { friends[i] = result.getLong(i); } } return friends; } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); }
00
Code Sample 1: private void validateODFDoc(String url, String ver, ValidationReport commentary) throws IOException, MalformedURLException { logger.debug("Beginning document validation ..."); synchronized (ODFValidationSession.class) { PropertyMapBuilder builder = new PropertyMapBuilder(); String[] segments = url.split("/"); CommentatingErrorHandler h = new CommentatingErrorHandler(commentary, segments[segments.length - 1]); ValidateProperty.ERROR_HANDLER.put(builder, h); ValidationDriver driver = new ValidationDriver(builder.toPropertyMap()); InputStream candidateStream = null; try { logger.debug("Loading schema version " + ver); byte[] schemaBytes = getSchemaForVersion(ver); driver.loadSchema(new InputSource(new ByteArrayInputStream(schemaBytes))); URLConnection conn = new URL(url).openConnection(); candidateStream = conn.getInputStream(); logger.debug("Calling validate()"); commentary.incIndent(); boolean isValid = driver.validate(new InputSource(candidateStream)); logger.debug("Errors in instance:" + h.getInstanceErrCount()); if (h.getInstanceErrCount() > CommentatingErrorHandler.THRESHOLD) { commentary.addComment("(<i>" + (h.getInstanceErrCount() - CommentatingErrorHandler.THRESHOLD) + " error(s) omitted for the sake of brevity</i>)"); } commentary.decIndent(); if (isValid) { commentary.addComment("The document is valid"); } else { commentary.addComment("ERROR", "The document is invalid"); } } catch (SAXException e) { commentary.addComment("FATAL", "The resource is not conformant XML: " + e.getMessage()); logger.error(e.getMessage()); } finally { Utils.streamClose(candidateStream); } } } Code Sample 2: public static void main(String[] arg) throws IOException { XmlPullParserFactory PULL_PARSER_FACTORY; try { PULL_PARSER_FACTORY = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); PULL_PARSER_FACTORY.setNamespaceAware(true); DasParser dp = new DasParser(PULL_PARSER_FACTORY); URL url = new URL("http://www.ebi.ac.uk/das-srv/uniprot/das/uniprot/features?segment=P05067"); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String aLine, xml = ""; while ((aLine = br.readLine()) != null) { xml += aLine; } WritebackDocument wbd = dp.parse(xml); System.out.println("FIN" + wbd); } catch (XmlPullParserException xppe) { throw new IllegalStateException("Fatal Exception thrown at initialisation. Cannot initialise the PullParserFactory required to allow generation of the DAS XML.", xppe); } }
11
Code Sample 1: public void testCreate() throws Exception { File f = File.createTempFile("DiskCacheItemTest", "tmp"); f.deleteOnExit(); try { DiskCacheItem i = new DiskCacheItem(f); i.setLastModified(200005L); i.setTranslationCount(11); i.setEncoding("GB2312"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] chineseText = new byte[] { -42, -48, -46, -30, 87, 101, 98, 46, 99, 111, 109, 32, -54, -57, -46, -69, -72, -10, -61, -26, -49, -14, -42, -48, -50, -60, -45, -61, -69, -89, -95, -94, -67, -23, -55, -36, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -42, -48, -50, -60, -51, -8, -43, -66, -93, -84, -54, -57, -46, -69, -68, -36, -51, -88, -49, -14, -74, -85, -73, -67, -75, -60, -51, -8, -62, -25, -57, -59, -63, -70, -93, -84, -53, -4, -75, -60, -60, -65, -75, -60, -44, -38, -45, -38, -80, -17, -42, -6, -78, -69, -74, -49, -73, -94, -43, -71, -41, -77, -76, -13, -75, -60, -58, -13, -46, -75, -68, -28, -67, -8, -48, -48, -49, -32, -69, -91, -63, -86, -49, -75, -67, -45, -76, -91, -95, -93, -50, -46, -61, -57, -49, -32, -48, -59, -93, -84, -42, -48, -50, -60, -45, -61, -69, -89, -67, -85, -69, -31, -51, -88, -71, -3, -79, -66, -51, -8, -43, -66, -93, -84, -43, -46, -75, -67, -45, -48, -71, -40, -46, -47, -45, -21, -42, -48, -71, -6, -58, -13, -46, -75, -67, -88, -63, -94, -70, -49, -41, -9, -67, -69, -51, -7, -71, -40, -49, -75, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -93, -84, -69, -14, -45, -48, -46, -30, -45, -21, -42, -48, -71, -6, 32, -58, -13, -46, -75, -67, -8, -48, -48, -70, -49, -41, -9, -67, -69, -51, -7, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -45, -48, -45, -61, -48, -59, -49, -94, -41, -54, -63, -49, -95, -93 }; { InputStream input = new ByteArrayInputStream(chineseText); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("GB2312", i.getEncoding()); assertEquals(200005L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[279]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } { FileInputStream input = new FileInputStream(f); StringWriter w = new StringWriter(); try { IOUtils.copy(input, w, "GB2312"); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); } assertEquals(new String(chineseText, "GB2312"), w.toString()); } { FileInputStream input = new FileInputStream(f); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } assertTrue(Arrays.equals(chineseText, output.toByteArray())); } } finally { f.delete(); } } Code Sample 2: private boolean enregistreToi() { PrintWriter lEcrivain; String laDest = "./img_types/" + sonImage; if (!new File("./img_types").exists()) { new File("./img_types").mkdirs(); } try { FileChannel leFicSource = new FileInputStream(sonFichier).getChannel(); FileChannel leFicDest = new FileOutputStream(laDest).getChannel(); leFicSource.transferTo(0, leFicSource.size(), leFicDest); leFicSource.close(); leFicDest.close(); lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true)); lEcrivain.println(sonNom); lEcrivain.println(sonImage); if (sonOptionRadio1.isSelected()) { lEcrivain.println("0:?"); } if (sonOptionRadio2.isSelected()) { lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE)); } if (sonOptionRadio3.isSelected()) { lEcrivain.println("2:?"); } lEcrivain.close(); return true; } catch (Exception lException) { return false; } }
11
Code Sample 1: public MemoryTextBody(InputStream is, String mimeCharset) throws IOException { this.mimeCharset = mimeCharset; TempPath tempPath = TempStorage.getInstance().getRootTempPath(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); out.close(); tempFile = out.toByteArray(); } Code Sample 2: private File getTempFile(DigitalObject object, String pid) throws Exception { File directory = new File(tmpDir, object.getId()); File target = new File(directory, pid); if (!target.exists()) { target.getParentFile().mkdirs(); target.createNewFile(); } Payload payload = object.getPayload(pid); InputStream in = payload.open(); FileOutputStream out = null; try { out = new FileOutputStream(target); IOUtils.copyLarge(in, out); } catch (Exception ex) { close(out); target.delete(); payload.close(); throw ex; } close(out); payload.close(); return target; }
11
Code Sample 1: public String buscaSAIKU() { URL url; Properties prop = new CargaProperties().Carga(); BufferedReader in; String inputLine; String miLinea = null; try { url = new URL(prop.getProperty("SAIKU")); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = in.readLine()) != null) { if (inputLine.contains("lastSuccessfulBuild/artifact/saiku-bi-platform-plugin/target")) { miLinea = inputLine; log.debug(miLinea); miLinea = miLinea.substring(miLinea.indexOf("lastSuccessfulBuild/artifact/saiku-bi-platform-plugin/target")); miLinea = miLinea.substring(0, miLinea.indexOf("\">")); miLinea = url + miLinea; } } } catch (Throwable t) { } log.debug("Detetectado last build SAIKU: " + miLinea); return miLinea; } Code Sample 2: @SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { PositionParser pp; Database.init("XIDResult"); pp = new PositionParser("01:33:50.904+30:39:35.79"); String url = "http://simbad.u-strasbg.fr/simbad/sim-script?submit=submit+script&script="; String script = "format object \"%IDLIST[%-30*]|-%COO(A)|%COO(D)|%OTYPELIST(S)\"\n"; String tmp = ""; script += pp.getPosition() + " radius=1m"; url += URLEncoder.encode(script, "ISO-8859-1"); URL simurl = new URL(url); BufferedReader in = new BufferedReader(new InputStreamReader(simurl.openStream())); String boeuf; boolean data_found = false; JSONObject retour = new JSONObject(); JSONArray dataarray = new JSONArray(); JSONArray colarray = new JSONArray(); JSONObject jsloc = new JSONObject(); jsloc.put("sTitle", "ID"); colarray.add(jsloc); jsloc = new JSONObject(); jsloc.put("sTitle", "Position"); colarray.add(jsloc); jsloc = new JSONObject(); jsloc.put("sTitle", "Type"); colarray.add(jsloc); retour.put("aoColumns", colarray); int datasize = 0; while ((boeuf = in.readLine()) != null) { if (data_found) { String[] fields = boeuf.trim().split("\\|", -1); int pos = fields.length - 1; if (pos >= 3) { String type = fields[pos]; pos--; String dec = fields[pos]; pos--; String ra = fields[pos]; String id = ""; for (int i = 0; i < pos; i++) { id += fields[i]; if (i < (pos - 1)) { id += "|"; } } if (id.length() <= 30) { JSONArray darray = new JSONArray(); darray.add(id.trim()); darray.add(ra + " " + dec); darray.add(type.trim()); dataarray.add(darray); datasize++; } } } else if (boeuf.startsWith("::data")) { data_found = true; } } retour.put("aaData", dataarray); retour.put("iTotalRecords", datasize); retour.put("iTotalDisplayRecords", datasize); System.out.println(retour.toJSONString()); in.close(); }
00
Code Sample 1: public void compressImage(InputStream input, String output, DjatokaEncodeParam params) throws DjatokaException { if (params == null) params = new DjatokaEncodeParam(); File inputFile; try { inputFile = File.createTempFile("tmp", ".tif"); inputFile.deleteOnExit(); IOUtils.copyStream(input, new FileOutputStream(inputFile)); if (params.getLevels() == 0) { ImageRecord dim = ImageRecordUtils.getImageDimensions(inputFile.getAbsolutePath()); params.setLevels(ImageProcessingUtils.getLevelCount(dim.getWidth(), dim.getHeight())); dim = null; } } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } compressImage(inputFile.getAbsolutePath(), output, params); if (inputFile != null) inputFile.delete(); } Code Sample 2: public String getProxy(String userName, String password) throws Exception { URL url = new URL(httpURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); ObjectOutputStream outputToServlet = new ObjectOutputStream(conn.getOutputStream()); outputToServlet.writeObject(userName); outputToServlet.writeObject(password); outputToServlet.flush(); outputToServlet.close(); ObjectInputStream inputFromServlet = new ObjectInputStream(conn.getInputStream()); return inputFromServlet.readObject() + ""; }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: private File copyFile(String fileInClassPath, String systemPath) throws Exception { InputStream is = getClass().getResourceAsStream(fileInClassPath); OutputStream os = new FileOutputStream(systemPath); IOUtils.copy(is, os); is.close(); os.close(); return new File(systemPath); }
00
Code Sample 1: public int fileUpload(File pFile, String uploadName, Hashtable pValue) throws Exception { int res = 0; MultipartEntity reqEntity = new MultipartEntity(); if (uploadName != null) { FileBody bin = new FileBody(pFile); reqEntity.addPart(uploadName, bin); } Enumeration<String> enm = pValue.keys(); String key; while (enm.hasMoreElements()) { key = enm.nextElement(); reqEntity.addPart(key, new StringBody("" + pValue.get(key))); } httpPost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpPost); HttpEntity resEntity = response.getEntity(); res = response.getStatusLine().getStatusCode(); close(); return res; } Code Sample 2: @BeforeClass public static void setUpOnce() throws OWLOntologyCreationException { dbManager = (OWLDBOntologyManager) OWLDBManager.createOWLOntologyManager(OWLDataFactoryImpl.getInstance()); dbIRI = IRI.create(ontoUri); System.out.println("copying ontology to work folder..."); try { final File directory = new File("./resources/LUBM10-DB-forUpdate/"); final File[] filesToDelete = directory.listFiles(); if (filesToDelete != null && filesToDelete.length > 0) { for (final File file : filesToDelete) { if (!file.getName().endsWith(".svn")) Assert.assertTrue(file.delete()); } } final File original = new File("./resources/LUBM10-DB/LUBM10.h2.db"); final File copy = new File("./resources/LUBM10-DB-forUpdate/LUBM10.h2.db"); final FileChannel inChannel = new FileInputStream(original).getChannel(); final FileChannel outChannel = new FileOutputStream(copy).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException ioe) { System.err.println(ioe.getMessage()); Assert.fail(); } onto = (OWLMutableOntology) dbManager.loadOntology(dbIRI); factory = dbManager.getOWLDataFactory(); }
11
Code Sample 1: private synchronized File gzipTempFile(File tempFile) throws BlogunityException { try { File gzippedFile = new File(BlogunityManager.getSystemConfiguration().getTempDir(), tempFile.getName() + ".gz"); GZIPOutputStream zos = new GZIPOutputStream(new FileOutputStream(gzippedFile)); byte[] readBuffer = new byte[2156]; int bytesIn = 0; FileInputStream fis = new FileInputStream(tempFile); while ((bytesIn = fis.read(readBuffer)) != -1) { zos.write(readBuffer, 0, bytesIn); } fis.close(); zos.close(); return gzippedFile; } catch (Exception e) { throw new BlogunityException(I18NStatusFactory.create(I18N.ERRORS.FEED_GZIP_FAILED, e)); } } Code Sample 2: private static void zip(File d) throws FileNotFoundException, IOException { String[] entries = d.list(); byte[] buffer = new byte[4096]; int bytesRead; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(new File(d.getParent() + File.separator + "dist.zip"))); for (int i = 0; i < entries.length; i++) { File f = new File(d, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); int skipl = d.getCanonicalPath().length(); ZipEntry entry = new ZipEntry(f.getPath().substring(skipl)); out.putNextEntry(entry); while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); FileUtils.moveFile(new File(d.getParent() + File.separator + "dist.zip"), new File(d + File.separator + "dist.zip")); }
11
Code Sample 1: public void covertFile(File file) throws IOException { if (!file.isFile()) { return; } Reader reader = null; OutputStream os = null; File newfile = null; String filename = file.getName(); boolean succeed = false; try { newfile = new File(file.getParentFile(), filename + ".bak"); reader = new InputStreamReader(new FileInputStream(file), fromEncoding); os = new FileOutputStream(newfile); IOUtils.copy(reader, os, toEncoding); } catch (Exception e) { e.printStackTrace(); throw new IOException("Encoding error for file [" + file.getAbsolutePath() + "]"); } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (Exception e) { e.printStackTrace(); } } } try { file.delete(); succeed = newfile.renameTo(file); } catch (Exception e) { throw new IOException("Clear bak error for file [" + file.getAbsolutePath() + "]"); } if (succeed) { System.out.println("Changed encoding for file [" + file.getAbsolutePath() + "]"); } } Code Sample 2: protected static IFile createTempFile(CodeFile codeFile) { IPath path = Util.getAbsolutePathFromCodeFile(codeFile); File file = new File(path.toOSString()); String[] parts = codeFile.getName().split("\\."); String extension = parts[parts.length - 1]; IPath ext = path.addFileExtension(extension); File tempFile = new File(ext.toOSString()); if (tempFile.exists()) { boolean deleted = tempFile.delete(); System.out.println("deleted: " + deleted); } try { boolean created = tempFile.createNewFile(); if (created) { FileOutputStream fos = new FileOutputStream(tempFile); FileInputStream fis = new FileInputStream(file); while (fis.available() > 0) { fos.write(fis.read()); } fis.close(); fos.close(); IFile iFile = Util.getFileFromPath(ext); return iFile; } } catch (IOException e) { e.printStackTrace(); } return null; }
00
Code Sample 1: public static void main(String[] args) { FTPClient client = new FTPClient(); try { File l_file = new File("C:/temp/testLoribel.html"); String l_url = "http://www.loribel.com/index.html"; GB_HttpTools.loadUrlToFile(l_url, l_file, ENCODING.ISO_8859_1); System.out.println("Try to connect..."); client.connect("ftp://ftp.phpnet.org"); System.out.println("Connected to server"); System.out.println("Try to connect..."); boolean b = client.login("fff", "ddd"); System.out.println("Login: " + b); String[] l_names = client.listNames(); GB_DebugTools.debugArray(GB_FtpDemo2.class, "names", l_names); b = client.makeDirectory("test02/toto"); System.out.println("Mkdir: " + b); String l_remote = "test02/test.xml"; InputStream l_local = new StringInputStream("Test111111111111111"); b = client.storeFile(l_remote, l_local); System.out.println("Copy file: " + b); } catch (Exception ex) { ex.printStackTrace(); } } Code Sample 2: public static void main(String[] args) { if (args.length <= 0) { System.out.println(" *** SQL script generator and executor ***"); System.out.println(" You must specify name of the file with SQL script data"); System.out.println(" Fisrt rows of this file must be:"); System.out.println(" 1) JDBC driver class for your DBMS"); System.out.println(" 2) URL for your database instance"); System.out.println(" 3) user in that database (with administrator priviliges)"); System.out.println(" 4) password of that user"); System.out.println(" Next rows can have: '@' before schema to create,"); System.out.println(" '#' before table to create, '&' before table to insert,"); System.out.println(" '$' before trigger (inverse 'FK on delete cascade') to create,"); System.out.println(" '>' before table to drop, '<' before schema to drop."); System.out.println(" Other rows contain parameters of these actions:"); System.out.println(" for & action each parameter is a list of values,"); System.out.println(" for @ -//- is # acrion, for # -//- is column/constraint "); System.out.println(" definition or $ action. $ syntax to delete from table:"); System.out.println(" fullNameOfTable:itsColInWhereClause=matchingColOfThisTable"); System.out.println(" '!' before row means that it is a comment."); System.out.println(" If some exception is occured, all script is rolled back."); System.out.println(" If you specify 2nd command line argument - file name too -"); System.out.println(" connection will be established but all statements will"); System.out.println(" be saved in that output file and not transmitted to DB"); System.out.println(" If you specify 3nd command line argument - connect_string -"); System.out.println(" connect information will be added to output file"); System.out.println(" in the form 'connect user/password@connect_string'"); System.exit(0); } try { String[] info = new String[4]; BufferedReader reader = new BufferedReader(new FileReader(new File(args[0]))); Writer writer = null; try { for (int i = 0; i < 4; i++) info[i] = reader.readLine(); try { Class.forName(info[0]); Connection connection = DriverManager.getConnection(info[1], info[2], info[3]); SQLScript script = new SQLScript(connection); if (args.length > 1) { writer = new FileWriter(args[1]); if (args.length > 2) writer.write("connect " + info[2] + "/" + info[3] + "@" + args[2] + script.statementTerminator); } try { System.out.println(script.executeScript(reader, writer) + " updates has been performed during script execution"); } catch (SQLException e4) { reader.close(); if (writer != null) writer.close(); System.out.println(" Script execution error: " + e4); } connection.close(); } catch (Exception e3) { reader.close(); if (writer != null) writer.close(); System.out.println(" Connection error: " + e3); } } catch (IOException e2) { System.out.println("Error in file " + args[0]); } } catch (FileNotFoundException e1) { System.out.println("File " + args[0] + " not found"); } }
00
Code Sample 1: public void run() { saveWLHome(); for (final TabControl control : tabControls) { control.performOk(WLPropertyPage.this.getProject(), WLPropertyPage.this); } if (isEnabledJCLCopy()) { final File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File log4jLibrary = new File(lib, "log4j-1.2.13.jar"); if (!log4jLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jcl/log4j-1.2.13.jar")); fos = new FileOutputStream(log4jLibrary); IOUtils.copy(srcFile, fos); srcFile.close(); fos.flush(); fos.close(); srcFile = toInputStream(new Path("/jcl/commons-logging-1.0.4.jar")); File jcl = new File(lib, "commons-logging-1.0.4.jar"); fos = new FileOutputStream(jcl); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy JCL jars file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } } if (isEnabledJSTLCopy()) { File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File jstlLibrary = new File(lib, "jstl.jar"); if (!jstlLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jstl/jstl.jar")); fos = new FileOutputStream(jstlLibrary); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy the JSTL 1.1 jar file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (final IOException e) { Logger.getLog().debug("I/O exception closing resources", e); } } } } } Code Sample 2: public String login() { String authSuccess = "false"; try { String errorMesg = ""; int error; if ((error = utils.stringIsNull(passwd)) != -1) { errorMesg += rb.getString("passwdField") + ": " + utils.errors[error] + " "; } else if ((error = utils.stringIsEmpty(passwd)) != -1) { errorMesg += rb.getString("passwdField") + ": " + utils.errors[error] + " "; } if ((error = utils.stringIsNull(login)) != -1) { errorMesg += rb.getString("loginField") + ": " + utils.errors[error] + " "; } else if ((error = utils.stringIsEmpty(login)) != -1) { errorMesg += rb.getString("loginField") + ": " + utils.errors[error] + " "; } String[] admins = conf.getProperty("admin").split("\\s"); boolean admin = false; for (int i = 0; i < admins.length; i++) { if (admins[i].equals(login)) { admin = true; } } if (!admin) { errorMesg += rb.getString("noAdmin"); session.invalidate(); } else { session.setAttribute("conf", conf); } if (errorMesg.length() > 0) { status = errorMesg; System.out.println(status); FacesContext context = FacesContext.getCurrentInstance(); context.renderResponse(); } else { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(passwd.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { String hex = Integer.toHexString(0xFF & result[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } authSuccess = (sqlManager.getPassword(login).equals(hexString.toString())) ? "true" : "false"; if (authSuccess.equals("false")) session.invalidate(); } } catch (NoSuchAlgorithmException nsae) { utils.catchExp(nsae); status = utils.getStatus(); if (stacktrace) { stackTrace = utils.getStackTrace(); } FacesContext.getCurrentInstance().renderResponse(); } catch (SQLException sqle) { utils.catchExp(sqle); status = utils.getStatus(); if (stacktrace) { stackTrace = utils.getStackTrace(); } FacesContext.getCurrentInstance().renderResponse(); } return authSuccess; }
11
Code Sample 1: public void run() { FileInputStream src; try { src = new FileInputStream(srcName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileOutputStream dest; FileChannel srcC = src.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(BUFFER_SIZE); try { int i = 1; int fileNo = 0; long maxByte = this.maxSize << 10; long nbByte = srcC.size(); long nbFile = (nbByte / maxByte) + 1; for (fileNo = 0; fileNo < nbFile; fileNo++) { long fileByte = 0; String destName = srcName + "_" + fileNo; dest = new FileOutputStream(destName); FileChannel destC = dest.getChannel(); while ((i > 0) && fileByte < maxByte) { i = srcC.read(buf); buf.flip(); fileByte += i; destC.write(buf); buf.compact(); } destC.close(); dest.close(); } } catch (IOException e1) { e1.printStackTrace(); return; } } Code Sample 2: public static void copy(String srcFileName, String destFileName) throws IOException { if (srcFileName == null) { throw new IllegalArgumentException("srcFileName is null"); } if (destFileName == null) { throw new IllegalArgumentException("destFileName is null"); } FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(srcFileName).getChannel(); dest = new FileOutputStream(destFileName).getChannel(); long n = src.size(); MappedByteBuffer buf = src.map(FileChannel.MapMode.READ_ONLY, 0, n); dest.write(buf); } finally { if (dest != null) { try { dest.close(); } catch (IOException e1) { } } if (src != null) { try { src.close(); } catch (IOException e1) { } } } }
11
Code Sample 1: public static boolean copy(InputStream is, File file) { try { IOUtils.copy(is, new FileOutputStream(file)); return true; } catch (Exception e) { logger.severe(e.getMessage()); return false; } } Code Sample 2: public void processExplicitSchemaAndWSDL(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { HashMap services = configContext.getAxisConfiguration().getServices(); String filePart = req.getRequestURL().toString(); String schema = filePart.substring(filePart.lastIndexOf("/") + 1, filePart.length()); if ((services != null) && !services.isEmpty()) { Iterator i = services.values().iterator(); while (i.hasNext()) { AxisService service = (AxisService) i.next(); InputStream stream = service.getClassLoader().getResourceAsStream("META-INF/" + schema); if (stream != null) { OutputStream out = res.getOutputStream(); res.setContentType("text/xml"); IOUtils.copy(stream, out, true); return; } } } }
11
Code Sample 1: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } } Code Sample 2: private static void copyFile(File f) { try { String baseName = baseDir.getCanonicalPath(); String fullPath = f.getCanonicalPath(); String nameSufix = fullPath.substring(baseName.length() + 1); File destFile = new File(FileDestDir, nameSufix); destFile.getParentFile().mkdirs(); destFile.createNewFile(); FileChannel fromChannel = new FileInputStream(f).getChannel(); FileChannel toChannel = new FileOutputStream(destFile).getChannel(); fromChannel.transferTo(0, fromChannel.size(), toChannel); fromChannel.close(); toChannel.close(); destFile.setLastModified(f.lastModified()); } catch (Exception e) { System.err.println(e.getMessage()); } }
00
Code Sample 1: public static InputStream getResourceRelativeAsStream(final String name, final Class context) { final URL url = getResourceRelative(name, context); if (url == null) { return null; } try { return url.openStream(); } catch (IOException e) { return null; } } Code Sample 2: public static String MD5Encrypt(String OriginalString) { String encryptedString = new String(""); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(OriginalString.getBytes()); byte b[] = md.digest(); for (int i = 0; i < b.length; i++) { char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; char[] ob = new char[2]; ob[0] = digit[(b[i] >>> 4) & 0X0F]; ob[1] = digit[b[i] & 0X0F]; encryptedString += new String(ob); } } catch (NoSuchAlgorithmException nsae) { System.out.println("the algorithm doesn't exist"); } return encryptedString; }
11
Code Sample 1: public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private void trainDepParser(byte flag, JarArchiveOutputStream zout) throws Exception { AbstractDepParser parser = null; OneVsAllDecoder decoder = null; if (flag == ShiftPopParser.FLAG_TRAIN_LEXICON) { System.out.println("\n* Save lexica"); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, s_featureXml); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, s_featureXml); } else if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE) { System.out.println("\n* Print training instances"); System.out.println("- loading lexica"); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, t_xml, ENTRY_LEXICA); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, t_xml, ENTRY_LEXICA); } else if (flag == ShiftPopParser.FLAG_TRAIN_BOOST) { System.out.println("\n* Train conditional"); decoder = new OneVsAllDecoder(m_model); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, t_xml, t_map, decoder); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, t_xml, t_map, decoder); } AbstractReader<DepNode, DepTree> reader = null; DepTree tree; int n; if (s_format.equals(AbstractReader.FORMAT_DEP)) reader = new DepReader(s_trainFile, true); else if (s_format.equals(AbstractReader.FORMAT_CONLLX)) reader = new CoNLLXReader(s_trainFile, true); parser.setLanguage(s_language); reader.setLanguage(s_language); for (n = 0; (tree = reader.nextTree()) != null; n++) { parser.parse(tree); if (n % 1000 == 0) System.out.printf("\r- parsing: %dK", n / 1000); } System.out.println("\r- parsing: " + n); if (flag == ShiftPopParser.FLAG_TRAIN_LEXICON) { System.out.println("- saving"); parser.saveTags(ENTRY_LEXICA); t_xml = parser.getDepFtrXml(); } else if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE || flag == ShiftPopParser.FLAG_TRAIN_BOOST) { a_yx = parser.a_trans; zout.putArchiveEntry(new JarArchiveEntry(ENTRY_PARSER)); PrintStream fout = new PrintStream(zout); fout.print(s_depParser); fout.flush(); zout.closeArchiveEntry(); zout.putArchiveEntry(new JarArchiveEntry(ENTRY_FEATURE)); IOUtils.copy(new FileInputStream(s_featureXml), zout); zout.closeArchiveEntry(); zout.putArchiveEntry(new JarArchiveEntry(ENTRY_LEXICA)); IOUtils.copy(new FileInputStream(ENTRY_LEXICA), zout); zout.closeArchiveEntry(); if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE) t_map = parser.getDepFtrMap(); } }
11
Code Sample 1: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: private String getMD5(String data) { try { MessageDigest md5Algorithm = MessageDigest.getInstance("MD5"); md5Algorithm.update(data.getBytes(), 0, data.length()); byte[] digest = md5Algorithm.digest(); StringBuffer hexString = new StringBuffer(); String hexDigit = null; for (int i = 0; i < digest.length; i++) { hexDigit = Integer.toHexString(0xFF & digest[i]); if (hexDigit.length() < 2) { hexDigit = "0" + hexDigit; } hexString.append(hexDigit); } return hexString.toString(); } catch (NoSuchAlgorithmException ne) { return data; } }
11
Code Sample 1: private void initUserExtensions(SeleniumConfiguration seleniumConfiguration) throws IOException { StringBuilder contents = new StringBuilder(); StringOutputStream s = new StringOutputStream(); IOUtils.copy(SeleniumConfiguration.class.getResourceAsStream("default-user-extensions.js"), s); contents.append(s.toString()); File providedUserExtensions = seleniumConfiguration.getFile(ConfigurationPropertyKeys.SELENIUM_USER_EXTENSIONS, seleniumConfiguration.getDirectoryConfiguration().getInput(), false); if (providedUserExtensions != null) { contents.append(FileUtils.readFileToString(providedUserExtensions, null)); } seleniumUserExtensions = new File(seleniumConfiguration.getDirectoryConfiguration().getInput(), "user-extensions.js"); FileUtils.forceMkdir(seleniumUserExtensions.getParentFile()); FileUtils.writeStringToFile(seleniumUserExtensions, contents.toString(), null); } Code Sample 2: public static boolean copyFile(File src, File des) { try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(des)); int b; while ((b = in.read()) != -1) out.write(b); out.flush(); out.close(); in.close(); return true; } catch (IOException ie) { m_logCat.error("Copy file + " + src + " to " + des + " failed!", ie); return false; } }
11
Code Sample 1: public int update(BusinessObject o) throws DAOException { int update = 0; Account acc = (Account) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("UPDATE_ACCOUNT")); pst.setString(1, acc.getName()); pst.setString(2, acc.getAddress()); pst.setInt(3, acc.getCurrency()); pst.setInt(4, acc.getMainContact()); pst.setBoolean(5, acc.isArchived()); pst.setInt(6, acc.getId()); update = pst.executeUpdate(); if (update <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (update > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return update; } Code Sample 2: private void populateAPI(API api) { try { if (api.isPopulated()) { log.traceln("Skipping API " + api.getName() + " (already populated)"); return; } api.setPopulated(true); String sql = "update API set populated=1 where name=?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, api.getName()); pstmt.executeUpdate(); pstmt.close(); storePackagesAndClasses(api); conn.commit(); } catch (SQLException ex) { log.error("Store (api: " + api.getName() + ") failed!"); DBUtils.logSQLException(ex); log.error("Rolling back.."); try { conn.rollback(); } catch (SQLException inner_ex) { log.error("rollback failed!"); } } }
11
Code Sample 1: public static void main(String[] args) throws Throwable { Options options = new Options(); options.addOption(new CommandLineOptionBuilder("cas", "cas file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("o", "output directory").longName("outputDir").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("tempDir", "temp directory").build()); options.addOption(new CommandLineOptionBuilder("prefix", "file prefix for all generated files ( default " + DEFAULT_PREFIX + " )").build()); options.addOption(new CommandLineOptionBuilder("trim", "trim file in sfffile's tab delimmed trim format").build()); options.addOption(new CommandLineOptionBuilder("trimMap", "trim map file containing tab delimited trimmed fastX file to untrimmed counterpart").build()); options.addOption(new CommandLineOptionBuilder("chromat_dir", "directory of chromatograms to be converted into phd " + "(it is assumed the read data for these chromatograms are in a fasta file which the .cas file knows about").build()); options.addOption(new CommandLineOptionBuilder("s", "cache size ( default " + DEFAULT_CACHE_SIZE + " )").longName("cache_size").build()); options.addOption(new CommandLineOptionBuilder("useIllumina", "any FASTQ files in this assembly are encoded in Illumina 1.3+ format (default is Sanger)").isFlag(true).build()); options.addOption(new CommandLineOptionBuilder("useClosureTrimming", "apply additional contig trimming based on JCVI Closure rules").isFlag(true).build()); CommandLine commandLine; try { commandLine = CommandLineUtils.parseCommandLine(options, args); int cacheSize = commandLine.hasOption("s") ? Integer.parseInt(commandLine.getOptionValue("s")) : DEFAULT_CACHE_SIZE; File casFile = new File(commandLine.getOptionValue("cas")); File casWorkingDirectory = casFile.getParentFile(); ReadWriteDirectoryFileServer outputDir = DirectoryFileServer.createReadWriteDirectoryFileServer(commandLine.getOptionValue("o")); String prefix = commandLine.hasOption("prefix") ? commandLine.getOptionValue("prefix") : DEFAULT_PREFIX; TrimDataStore trimDatastore; if (commandLine.hasOption("trim")) { List<TrimDataStore> dataStores = new ArrayList<TrimDataStore>(); final String trimFiles = commandLine.getOptionValue("trim"); for (String trimFile : trimFiles.split(",")) { System.out.println("adding trim file " + trimFile); dataStores.add(new DefaultTrimFileDataStore(new File(trimFile))); } trimDatastore = MultipleDataStoreWrapper.createMultipleDataStoreWrapper(TrimDataStore.class, dataStores); } else { trimDatastore = TrimDataStoreUtil.EMPTY_DATASTORE; } CasTrimMap trimToUntrimmedMap; if (commandLine.hasOption("trimMap")) { trimToUntrimmedMap = new DefaultTrimFileCasTrimMap(new File(commandLine.getOptionValue("trimMap"))); } else { trimToUntrimmedMap = new UnTrimmedExtensionTrimMap(); } boolean useClosureTrimming = commandLine.hasOption("useClosureTrimming"); TraceDataStore<FileSangerTrace> sangerTraceDataStore = null; Map<String, File> sangerFileMap = null; ReadOnlyDirectoryFileServer sourceChromatogramFileServer = null; if (commandLine.hasOption("chromat_dir")) { sourceChromatogramFileServer = DirectoryFileServer.createReadOnlyDirectoryFileServer(new File(commandLine.getOptionValue("chromat_dir"))); sangerTraceDataStore = new SingleSangerTraceDirectoryFileDataStore(sourceChromatogramFileServer, ".scf"); sangerFileMap = new HashMap<String, File>(); Iterator<String> iter = sangerTraceDataStore.getIds(); while (iter.hasNext()) { String id = iter.next(); sangerFileMap.put(id, sangerTraceDataStore.get(id).getFile()); } } PrintWriter logOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".log")), true); PrintWriter consensusOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".consensus.fasta")), true); PrintWriter traceFilesOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".traceFiles.txt")), true); PrintWriter referenceFilesOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".referenceFiles.txt")), true); long startTime = System.currentTimeMillis(); logOut.println(System.getProperty("user.dir")); final ReadWriteDirectoryFileServer tempDir; if (!commandLine.hasOption("tempDir")) { tempDir = DirectoryFileServer.createTemporaryDirectoryFileServer(DEFAULT_TEMP_DIR); } else { File t = new File(commandLine.getOptionValue("tempDir")); IOUtil.mkdirs(t); tempDir = DirectoryFileServer.createTemporaryDirectoryFileServer(t); } try { if (!outputDir.contains("chromat_dir")) { outputDir.createNewDir("chromat_dir"); } if (sourceChromatogramFileServer != null) { for (File f : sourceChromatogramFileServer) { String name = f.getName(); OutputStream out = new FileOutputStream(outputDir.createNewFile("chromat_dir/" + name)); final FileInputStream fileInputStream = new FileInputStream(f); try { IOUtils.copy(fileInputStream, out); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(fileInputStream); } } } FastQQualityCodec qualityCodec = commandLine.hasOption("useIllumina") ? FastQQualityCodec.ILLUMINA : FastQQualityCodec.SANGER; CasDataStoreFactory casDataStoreFactory = new MultiCasDataStoreFactory(new H2SffCasDataStoreFactory(casWorkingDirectory, tempDir, EmptyDataStoreFilter.INSTANCE), new H2FastQCasDataStoreFactory(casWorkingDirectory, trimToUntrimmedMap, qualityCodec, tempDir.getRootDir()), new FastaCasDataStoreFactory(casWorkingDirectory, trimToUntrimmedMap, cacheSize)); final SliceMapFactory sliceMapFactory = new LargeNoQualitySliceMapFactory(); CasAssembly casAssembly = new DefaultCasAssembly.Builder(casFile, casDataStoreFactory, trimDatastore, trimToUntrimmedMap, casWorkingDirectory).build(); System.out.println("finished making casAssemblies"); for (File traceFile : casAssembly.getNuceotideFiles()) { traceFilesOut.println(traceFile.getAbsolutePath()); final String name = traceFile.getName(); String extension = FilenameUtils.getExtension(name); if (name.contains("fastq")) { if (!outputDir.contains("solexa_dir")) { outputDir.createNewDir("solexa_dir"); } if (outputDir.contains("solexa_dir/" + name)) { IOUtil.delete(outputDir.getFile("solexa_dir/" + name)); } outputDir.createNewSymLink(traceFile.getAbsolutePath(), "solexa_dir/" + name); } else if ("sff".equals(extension)) { if (!outputDir.contains("sff_dir")) { outputDir.createNewDir("sff_dir"); } if (outputDir.contains("sff_dir/" + name)) { IOUtil.delete(outputDir.getFile("sff_dir/" + name)); } outputDir.createNewSymLink(traceFile.getAbsolutePath(), "sff_dir/" + name); } } for (File traceFile : casAssembly.getReferenceFiles()) { referenceFilesOut.println(traceFile.getAbsolutePath()); } DataStore<CasContig> contigDatastore = casAssembly.getContigDataStore(); Map<String, AceContig> aceContigs = new HashMap<String, AceContig>(); CasIdLookup readIdLookup = sangerFileMap == null ? casAssembly.getReadIdLookup() : new DifferentFileCasIdLookupAdapter(casAssembly.getReadIdLookup(), sangerFileMap); Date phdDate = new Date(startTime); NextGenClosureAceContigTrimmer closureContigTrimmer = null; if (useClosureTrimming) { closureContigTrimmer = new NextGenClosureAceContigTrimmer(2, 5, 10); } for (CasContig casContig : contigDatastore) { final AceContigAdapter adpatedCasContig = new AceContigAdapter(casContig, phdDate, readIdLookup); CoverageMap<CoverageRegion<AcePlacedRead>> coverageMap = DefaultCoverageMap.buildCoverageMap(adpatedCasContig); for (AceContig aceContig : ConsedUtil.split0xContig(adpatedCasContig, coverageMap)) { if (useClosureTrimming) { AceContig trimmedAceContig = closureContigTrimmer.trimContig(aceContig); if (trimmedAceContig == null) { System.out.printf("%s was completely trimmed... skipping%n", aceContig.getId()); continue; } aceContig = trimmedAceContig; } aceContigs.put(aceContig.getId(), aceContig); consensusOut.print(new DefaultNucleotideEncodedSequenceFastaRecord(aceContig.getId(), NucleotideGlyph.convertToString(NucleotideGlyph.convertToUngapped(aceContig.getConsensus().decode())))); } } System.out.printf("finished adapting %d casAssemblies into %d ace contigs%n", contigDatastore.size(), aceContigs.size()); QualityDataStore qualityDataStore = sangerTraceDataStore == null ? casAssembly.getQualityDataStore() : MultipleDataStoreWrapper.createMultipleDataStoreWrapper(QualityDataStore.class, TraceQualityDataStoreAdapter.adapt(sangerTraceDataStore), casAssembly.getQualityDataStore()); final DateTime phdDateTime = new DateTime(phdDate); final PhdDataStore casPhdDataStore = CachedDataStore.createCachedDataStore(PhdDataStore.class, new ArtificalPhdDataStore(casAssembly.getNucleotideDataStore(), qualityDataStore, phdDateTime), cacheSize); final PhdDataStore phdDataStore = sangerTraceDataStore == null ? casPhdDataStore : MultipleDataStoreWrapper.createMultipleDataStoreWrapper(PhdDataStore.class, new PhdSangerTraceDataStoreAdapter<FileSangerTrace>(sangerTraceDataStore, phdDateTime), casPhdDataStore); WholeAssemblyAceTag pathToPhd = new DefaultWholeAssemblyAceTag("phdball", "cas2consed", new Date(DateTimeUtils.currentTimeMillis()), "../phd_dir/" + prefix + ".phd.ball"); AceAssembly aceAssembly = new DefaultAceAssembly<AceContig>(new SimpleDataStore<AceContig>(aceContigs), phdDataStore, Collections.<File>emptyList(), new DefaultAceTagMap(Collections.<ConsensusAceTag>emptyList(), Collections.<ReadAceTag>emptyList(), Arrays.asList(pathToPhd))); System.out.println("writing consed package..."); ConsedWriter.writeConsedPackage(aceAssembly, sliceMapFactory, outputDir.getRootDir(), prefix, false); } catch (Throwable t) { t.printStackTrace(logOut); throw t; } finally { long endTime = System.currentTimeMillis(); logOut.printf("took %s%n", new Period(endTime - startTime)); logOut.flush(); logOut.close(); outputDir.close(); consensusOut.close(); traceFilesOut.close(); referenceFilesOut.close(); trimDatastore.close(); } } catch (ParseException e) { printHelp(options); System.exit(1); } } Code Sample 2: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.close(output); } } finally { IOUtils.close(input); } }
00
Code Sample 1: @Override protected void doFetch(HttpServletRequest request, HttpServletResponse response) throws IOException, GadgetException { if (request.getHeader("If-Modified-Since") != null) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } String host = request.getHeader("Host"); if (!lockedDomainService.isSafeForOpenProxy(host)) { String msg = "Embed request for url " + getParameter(request, URL_PARAM, "") + " made to wrong domain " + host; logger.info(msg); throw new GadgetException(GadgetException.Code.INVALID_PARAMETER, msg); } HttpRequest rcr = buildHttpRequest(request, URL_PARAM); HttpResponse results = requestPipeline.execute(rcr); if (results.isError()) { HttpRequest fallbackRcr = buildHttpRequest(request, FALLBACK_URL_PARAM); if (fallbackRcr != null) { results = requestPipeline.execute(fallbackRcr); } } if (contentRewriterRegistry != null) { try { results = contentRewriterRegistry.rewriteHttpResponse(rcr, results); } catch (RewritingException e) { throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e); } } for (Map.Entry<String, String> entry : results.getHeaders().entries()) { String name = entry.getKey(); if (!DISALLOWED_RESPONSE_HEADERS.contains(name.toLowerCase())) { response.addHeader(name, entry.getValue()); } } String responseType = results.getHeader("Content-Type"); if (!StringUtils.isEmpty(rcr.getRewriteMimeType())) { String requiredType = rcr.getRewriteMimeType(); if (requiredType.endsWith("/*") && !StringUtils.isEmpty(responseType)) { requiredType = requiredType.substring(0, requiredType.length() - 2); if (!responseType.toLowerCase().startsWith(requiredType.toLowerCase())) { response.setContentType(requiredType); responseType = requiredType; } } else { response.setContentType(requiredType); responseType = requiredType; } } setResponseHeaders(request, response, results); if (results.getHttpStatusCode() != HttpResponse.SC_OK) { response.sendError(results.getHttpStatusCode()); } IOUtils.copy(results.getResponse(), response.getOutputStream()); } Code Sample 2: protected String getManualDownloadURL() { if (_newestVersionString.indexOf("weekly") > 0) { return "http://www.cs.rice.edu/~javaplt/drjavarice/weekly/"; } final String DRJAVA_FILES_PAGE = "http://sourceforge.net/project/showfiles.php?group_id=44253"; final String LINK_PREFIX = "<a href=\"/project/showfiles.php?group_id=44253"; final String LINK_SUFFIX = "\">"; BufferedReader br = null; try { URL url = new URL(DRJAVA_FILES_PAGE); InputStream urls = url.openStream(); InputStreamReader is = new InputStreamReader(urls); br = new BufferedReader(is); String line; int pos; while ((line = br.readLine()) != null) { if ((pos = line.indexOf(_newestVersionString)) >= 0) { int prePos = line.indexOf(LINK_PREFIX); if ((prePos >= 0) && (prePos < pos)) { int suffixPos = line.indexOf(LINK_SUFFIX, prePos); if ((suffixPos >= 0) && (suffixPos + LINK_SUFFIX.length() == pos)) { String versionLink = edu.rice.cs.plt.text.TextUtil.xmlUnescape(line.substring(prePos + LINK_PREFIX.length(), suffixPos)); return DRJAVA_FILES_PAGE + versionLink; } } } } ; } catch (IOException e) { return DRJAVA_FILES_PAGE; } finally { try { if (br != null) br.close(); } catch (IOException e) { } } return DRJAVA_FILES_PAGE; }
00
Code Sample 1: private void createPropertyName(String objectID, String value, String propertyName, Long userID) throws JspTagException { rObject object = new rObject(new Long(objectID), userID); ClassProperty classProperty = new ClassProperty(propertyName, object.getClassName()); String newValue = value; if (classProperty.getName().equals("Password")) { try { MessageDigest crypt = MessageDigest.getInstance("MD5"); crypt.update(value.getBytes()); byte digest[] = crypt.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { hexString.append(hexDigit(digest[i])); } newValue = hexString.toString(); crypt.reset(); } catch (NoSuchAlgorithmException e) { System.err.println("jspShop: Could not get instance of MD5 algorithm. Please fix this!" + e.getMessage()); e.printStackTrace(); throw new JspTagException("Error crypting password!: " + e.getMessage()); } } Properties properties = new Properties(new Long(objectID), userID); try { Property property = properties.create(classProperty.getID(), newValue); pageContext.setAttribute(getId(), property); } catch (CreateException e) { throw new JspTagException("Could not create PropertyValue, CreateException: " + e.getMessage()); } } Code Sample 2: public DataRecord addRecord(InputStream input) throws DataStoreException { File temporary = null; try { temporary = newTemporaryFile(); DataIdentifier tempId = new DataIdentifier(temporary.getName()); usesIdentifier(tempId); long length = 0; MessageDigest digest = MessageDigest.getInstance(DIGEST); OutputStream output = new DigestOutputStream(new FileOutputStream(temporary), digest); try { length = IOUtils.copyLarge(input, output); } finally { output.close(); } DataIdentifier identifier = new DataIdentifier(digest.digest()); File file; synchronized (this) { usesIdentifier(identifier); file = getFile(identifier); System.out.println("new file name: " + file.getName()); File parent = file.getParentFile(); System.out.println("parent file: " + file.getParentFile().getName()); if (!parent.isDirectory()) { parent.mkdirs(); } if (!file.exists()) { temporary.renameTo(file); if (!file.exists()) { throw new IOException("Can not rename " + temporary.getAbsolutePath() + " to " + file.getAbsolutePath() + " (media read only?)"); } } else { long now = System.currentTimeMillis(); if (file.lastModified() < now) { file.setLastModified(now); } } if (!file.isFile()) { throw new IOException("Not a file: " + file); } if (file.length() != length) { throw new IOException(DIGEST + " collision: " + file); } } inUse.remove(tempId); return new FileDataRecord(identifier, file); } catch (NoSuchAlgorithmException e) { throw new DataStoreException(DIGEST + " not available", e); } catch (IOException e) { throw new DataStoreException("Could not add record", e); } finally { if (temporary != null) { temporary.delete(); } } }
00
Code Sample 1: public static void main(String[] args) { CookieManager cm = new CookieManager(); try { URL url = new URL("http://www.hccp.org/test/cookieTest.jsp"); URLConnection conn = url.openConnection(); conn.connect(); cm.storeCookies(conn); cm.setCookies(url.openConnection()); } catch (IOException ioe) { ioe.printStackTrace(); } } Code Sample 2: public static void unZip(String unZipfileName, String outputDirectory) throws IOException, FileNotFoundException { FileOutputStream fileOut; File file; ZipEntry zipEntry; ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(unZipfileName)), encoder); while ((zipEntry = zipIn.getNextEntry()) != null) { file = new File(outputDirectory + File.separator + zipEntry.getName()); if (zipEntry.isDirectory()) { createDirectory(file.getPath(), ""); } else { File parent = file.getParentFile(); if (!parent.exists()) { createDirectory(parent.getPath(), ""); } fileOut = new FileOutputStream(file); int readedBytes; while ((readedBytes = zipIn.read(buf)) > 0) { fileOut.write(buf, 0, readedBytes); } fileOut.close(); } zipIn.closeEntry(); } }
11
Code Sample 1: public boolean copyTo(String targetFilePath) { try { FileInputStream srcFile = new FileInputStream(filePath); FileOutputStream target = new FileOutputStream(targetFilePath); byte[] buff = new byte[1024]; int readed = -1; while ((readed = srcFile.read(buff)) > 0) target.write(buff, 0, readed); srcFile.close(); target.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } Code Sample 2: public static void copyFile(File source, File destination) throws IOException { if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (destination == null) { String message = Logging.getMessage("nullValue.DestinationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fic, foc; try { fis = new FileInputStream(source); fic = fis.getChannel(); fos = new FileOutputStream(destination); foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size()); fos.flush(); fis.close(); fos.close(); } finally { WWIO.closeStream(fis, source.getPath()); WWIO.closeStream(fos, destination.getPath()); } }
00
Code Sample 1: public static void copy(String a, String b) throws IOException { File inputFile = new File(a); File outputFile = new File(b); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public synchronized FTPClient getFTPClient(String User, String Password) throws IOException { if (logger.isDebugEnabled()) { logger.debug("getFTPClient(String, String) - start"); } while ((counter >= maxClients)) { try { wait(); } catch (InterruptedException e) { logger.error("getFTPClient(String, String)", e); e.printStackTrace(); } } FTPClient result = null; String key = User.concat(Password); logger.debug("versuche vorhandenen FTPClient aus Liste zu lesen"); if (Clients != null) { if (Clients.containsKey(key)) { LinkedList ClientList = (LinkedList) Clients.get(key); if (!ClientList.isEmpty()) do { result = (FTPClient) ClientList.getLast(); logger.debug("-- hole einen Client aus der Liste: " + result.toString()); ClientList.removeLast(); if (!result.isConnected()) { logger.debug("---- nicht mehr verbunden."); result = null; } else { try { result.changeWorkingDirectory("/"); } catch (IOException e) { logger.debug("---- schmei�t Exception bei Zugriff."); result = null; } } } while (result == null && !ClientList.isEmpty()); if (ClientList.isEmpty()) { Clients.remove(key); } } else { } } else logger.debug("-- keine Liste vorhanden."); if (result == null) { logger.debug("Kein FTPCLient verf�gbar, erstelle einen neuen."); result = new FTPClient(); logger.debug("-- Versuche Connect"); result.connect(Host); logger.debug("-- Versuche Login"); result.login(User, Password); result.setFileType(FTPClient.BINARY_FILE_TYPE); if (counter == maxClients - 1) { RemoveBufferedClient(); } } logger.debug("OK: neuer FTPClient ist " + result.toString()); ; counter++; if (logger.isDebugEnabled()) { logger.debug("getFTPClient(String, String) - end"); } return result; }
00
Code Sample 1: public Component loadComponent(URI uri, URI origuri) throws ComponentException { try { Component comp = null; InputStream is = null; java.net.URL url = null; try { url = uri.getJavaURL(); } catch (java.net.MalformedURLException e) { throw new ComponentException("Invalid URL " + uri + " for component " + origuri + ":\n " + e.getMessage()); } try { if (url.getProtocol().equals("ftp")) is = ftpHandler.getInputStream(url); else { java.net.URLConnection conn = url.openConnection(); conn.connect(); is = conn.getInputStream(); } } catch (IOException e) { if (is != null) is.close(); throw new ComponentException("IO error loading URL " + url + " for component " + origuri + ":\n " + e.getMessage()); } try { comp = componentIO.loadComponent(origuri, uri, is, isSavable(uri)); } catch (ComponentException e) { if (is != null) is.close(); throw new ComponentException("Error loading component " + origuri + " from " + url + ":\n " + e.getMessage()); } is.close(); return comp; } catch (IOException ioe) { Tracer.debug("didn't manage to close inputstream...."); return null; } } Code Sample 2: public static URL getIconURLForUser(String id) { try { URL url = new URL("http://profiles.yahoo.com/" + id); BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream())); String input = null; while ((input = r.readLine()) != null) { if (input.indexOf("<a href=\"") < 0) continue; if (input.indexOf("<img src=\"") < 0) continue; if (input.indexOf("<a href=\"") > input.indexOf("<img src=\"")) continue; String href = input.substring(input.indexOf("<a href=\"") + 9); String src = input.substring(input.indexOf("<img src=\"") + 10); if (href.indexOf("\"") < 0) continue; if (src.indexOf("\"") < 0) continue; href = href.substring(0, href.indexOf("\"")); src = src.substring(0, src.indexOf("\"")); if (href.equals(src)) { return new URL(href); } } } catch (IOException e) { } URL toReturn = null; try { toReturn = new URL("http://us.i1.yimg.com/us.yimg.com/i/ppl/no_photo.gif"); } catch (MalformedURLException e) { Debug.assrt(false); } return toReturn; }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { BufferedInputStream is = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[1024]; int count = 0; while ((count = is.read(buf, 0, 1024)) != -1) os.write(buf, 0, count); is.close(); os.close(); } Code Sample 2: public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\testTDESENC.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESDEC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.decrypt(reader, writer, key, mode); }
00
Code Sample 1: @org.junit.Test public void simpleRead() throws Exception { final InputStream istream = StatsInputStreamTest.class.getResourceAsStream("/testFile.txt"); final StatsInputStream ris = new StatsInputStream(istream); assertEquals("read size", 0, ris.getSize()); IOUtils.copy(ris, new NullOutputStream()); assertEquals("in the end", 30, ris.getSize()); } Code Sample 2: private String calculateMD5(String input) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); digest.update(input.getBytes()); byte[] md5 = digest.digest(); String tmp = ""; String res = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } return res; }
11
Code Sample 1: public void copy(String pathFileIn, String pathFileOut) { try { File inputFile = new File(pathFileIn); File outputFile = new File(pathFileOut); FileReader in = new FileReader(inputFile); File outDir = new File(DirOut); if (!outDir.exists()) outDir.mkdirs(); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); this.printColumn(inputFile.getName(), outputFile.getPath()); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static void copyFile(final File source, final File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
11
Code Sample 1: private String generateStorageDir(String stringToBeHashed) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(stringToBeHashed.getBytes()); byte[] hashedKey = digest.digest(); return Util.encodeArrayToHexadecimalString(hashedKey); } Code Sample 2: private String generateFilename() { byte[] hash = null; try { MessageDigest digest = MessageDigest.getInstance("MD5"); try { digest.update(InetAddress.getLocalHost().toString().getBytes()); } catch (UnknownHostException e) { } digest.update(String.valueOf(System.currentTimeMillis()).getBytes()); digest.update(String.valueOf(Runtime.getRuntime().freeMemory()).getBytes()); byte[] foo = new byte[128]; new SecureRandom().nextBytes(foo); digest.update(foo); hash = digest.digest(); } catch (NoSuchAlgorithmException e) { Debug.assrt(false); } return hexEncode(hash); }
00
Code Sample 1: protected Object insertSingle(Object name, Object fact) throws SQLException { DFAgentDescription dfd = (DFAgentDescription) fact; AID agentAID = dfd.getName(); String agentName = agentAID.getName(); DFAgentDescription dfdToReturn = null; String batchErrMsg = ""; Connection conn = getConnectionWrapper().getConnection(); PreparedStatements pss = getPreparedStatements(); try { dfdToReturn = (DFAgentDescription) removeSingle(dfd.getName()); Date leaseTime = dfd.getLeaseTime(); long lt = (leaseTime != null ? leaseTime.getTime() : -1); String descrId = getGUID(); pss.stm_insAgentDescr.setString(1, descrId); pss.stm_insAgentDescr.setString(2, agentName); pss.stm_insAgentDescr.setString(3, String.valueOf(lt)); pss.stm_insAgentDescr.executeUpdate(); saveAID(agentAID); Iterator iter = dfd.getAllLanguages(); if (iter.hasNext()) { pss.stm_insLanguage.clearBatch(); while (iter.hasNext()) { pss.stm_insLanguage.setString(1, descrId); pss.stm_insLanguage.setString(2, (String) iter.next()); pss.stm_insLanguage.addBatch(); } pss.stm_insLanguage.executeBatch(); } iter = dfd.getAllOntologies(); if (iter.hasNext()) { pss.stm_insOntology.clearBatch(); while (iter.hasNext()) { pss.stm_insOntology.setString(1, descrId); pss.stm_insOntology.setString(2, (String) iter.next()); pss.stm_insOntology.addBatch(); } pss.stm_insOntology.executeBatch(); } iter = dfd.getAllProtocols(); if (iter.hasNext()) { pss.stm_insProtocol.clearBatch(); while (iter.hasNext()) { pss.stm_insProtocol.setString(1, descrId); pss.stm_insProtocol.setString(2, (String) iter.next()); pss.stm_insProtocol.addBatch(); } pss.stm_insProtocol.executeBatch(); } saveServices(descrId, dfd.getAllServices()); regsCnt++; if (regsCnt > MAX_REGISTER_WITHOUT_CLEAN) { regsCnt = 0; clean(); } conn.commit(); } catch (SQLException sqle) { try { conn.rollback(); } catch (SQLException se) { logger.log(Logger.SEVERE, "Rollback for incomplete insertion of DFD for agent " + dfd.getName() + " failed.", se); } throw sqle; } return dfdToReturn; } Code Sample 2: private void writeData(IBaseType dataType, Writer writer) throws XMLStreamException { InputStream isData; DataType data = (DataType) baseType; if (data.isSetInputStream()) { isData = data.getInputStream(); try { IOUtils.copy(isData, writer); } catch (IOException e) { throw new XMLStreamException("DataType fail writing streaming data ", e); } } else if (data.isSetOutputStream()) { throw new XMLStreamException("DataType only can write streaming input, its an output stream (only for reading) "); } else { new CharactersEventImpl(startElement.getLocation(), String.valueOf(baseType.asData()), false).writeAsEncodedUnicode(writer); } }
00
Code Sample 1: public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) h = "0" + h; hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { } return ""; } Code Sample 2: public InputStream doRemoteCall(NamedList<String> params) throws IOException { String protocol = "http"; String host = getHost(); int port = Integer.parseInt(getPort()); StringBuilder sb = new StringBuilder(); for (Map.Entry entry : params) { Object key = entry.getKey(); Object value = entry.getValue(); sb.append(key).append("=").append(value).append("&"); } sb.setLength(sb.length() - 1); String file = "/" + getUrl() + "/?" + sb.toString(); URL url = new URL(protocol, host, port, file); logger.debug(url.toString()); InputStream stream; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); try { stream = conn.getInputStream(); } catch (IOException ioe) { InputStream is = conn.getErrorStream(); if (is != null) { String msg = getStringFromInputStream(conn.getErrorStream()); throw new IOException(msg); } else { throw ioe; } } return stream; }
11
Code Sample 1: public static final boolean checkForUpdate(final String currentVersion, final String updateURL, boolean noLock) throws Exception { try { final String parentFDTConfDirName = System.getProperty("user.home") + File.separator + ".fdt"; final String fdtUpdateConfFileName = "update.properties"; final File confFile = createOrGetRWFile(parentFDTConfDirName, fdtUpdateConfFileName); if (confFile != null) { long lastCheck = 0; Properties updateProperties = new Properties(); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(confFile); updateProperties.load(fis); final String lastCheckProp = (String) updateProperties.get("LastCheck"); lastCheck = 0; if (lastCheckProp != null) { try { lastCheck = Long.parseLong(lastCheckProp); } catch (Throwable t) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Got exception parsing LastCheck param", t); } lastCheck = 0; } } } catch (Throwable t) { logger.log(Level.WARNING, "Cannot load update properties file: " + confFile, t); } finally { closeIgnoringExceptions(fos); closeIgnoringExceptions(fis); } final long now = System.currentTimeMillis(); boolean bHaveUpdates = false; checkAndSetInstanceID(updateProperties); if (lastCheck + FDT.UPDATE_PERIOD < now) { lastCheck = now; try { logger.log("\n\nChecking for remote updates ... This may be disabled using -noupdates flag."); bHaveUpdates = updateFDT(currentVersion, updateURL, false, noLock); if (bHaveUpdates) { logger.log("FDT may be updated using: java -jar fdt.jar -update"); } else { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "No updates available"); } } } catch (Throwable t) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.WARNING, "Got exception", t); } } updateProperties.put("LastCheck", "" + now); try { fos = new FileOutputStream(confFile); updateProperties.store(fos, null); } catch (Throwable t1) { logger.log(Level.WARNING, "Cannot store update properties file", t1); } finally { closeIgnoringExceptions(fos); } return bHaveUpdates; } } else { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, " [ checkForUpdate ] Cannot read or write the update conf file: " + parentFDTConfDirName + File.separator + fdtUpdateConfFileName); } return false; } } catch (Throwable t) { logger.log(Level.WARNING, "Got exception checking for updates", t); } return false; } Code Sample 2: public void actionPerformed(ActionEvent e) { int returnVal = chooser.showSaveDialog(jd); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); String fileName = file.getPath(); String ext = StringUtil.getLowerExtension(fileName); if (!"png".equals(ext)) { fileName += ".png"; file = new File(fileName); } boolean doIt = true; if (file.exists()) { int i = JOptionPane.showConfirmDialog(jd, getMessage("warn_file_exist")); if (i != JOptionPane.YES_OPTION) doIt = false; } else if (!file.getParentFile().exists()) { doIt = file.getParentFile().mkdirs(); } if (doIt) { FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(imageURL.getPath()).getChannel(); dest = new FileOutputStream(fileName).getChannel(); src.transferTo(0, src.size(), dest); } catch (FileNotFoundException e1) { warn(jd, getMessage("err_no_source_file")); } catch (IOException e2) { warn(jd, getMessage("err_output_target")); } finally { try { if (src != null) src.close(); } catch (IOException e1) { } try { if (dest != null) dest.close(); } catch (IOException e1) { } src = null; dest = null; } } } }
00
Code Sample 1: public static void concatFiles(final String as_base_file_name) throws IOException, FileNotFoundException { new File(as_base_file_name).createNewFile(); final OutputStream lo_out = new FileOutputStream(as_base_file_name, true); int ln_part = 1, ln_readed = -1; final byte[] lh_buffer = new byte[32768]; File lo_file = new File(as_base_file_name + "part1"); while (lo_file.exists() && lo_file.isFile()) { final InputStream lo_input = new FileInputStream(lo_file); while ((ln_readed = lo_input.read(lh_buffer)) != -1) { lo_out.write(lh_buffer, 0, ln_readed); } ln_part++; lo_file = new File(as_base_file_name + "part" + ln_part); } lo_out.flush(); lo_out.close(); } Code Sample 2: public static Image getImage(URL url) throws IOException { InputStream is = null; try { is = url.openStream(); Image img = getImage(is); img.setUrl(url); return img; } finally { if (is != null) { is.close(); } } }
11
Code Sample 1: public static void readFile(FOUserAgent ua, String uri, Writer output, String encoding) throws IOException { InputStream in = getURLInputStream(ua, uri); try { StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, encoding); } finally { IOUtils.closeQuietly(in); } } Code Sample 2: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
00
Code Sample 1: public static String BaiKe(String unknown) { String encodeurl = ""; long sTime = System.currentTimeMillis(); long eTime; try { String regEx = "\\#(.+)\\#"; String searchText = ""; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(unknown); if (m.find()) { searchText = m.group(1); } System.out.println("searchText : " + searchText); encodeurl = URLEncoder.encode(searchText, "UTF-8"); String url = "http://www.hudong.com/wiki/" + encodeurl; HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection(); conn.setConnectTimeout(10000); Parser parser = new Parser(conn); parser.setEncoding(parser.getEncoding()); NodeFilter filtera = new TagNameFilter("DIV"); NodeList nodes = parser.extractAllNodesThatMatch(filtera); String textInPage = ""; if (nodes != null) { for (int i = 0; i < nodes.size(); i++) { Node textnode = (Node) nodes.elementAt(i); if ("div class=\"summary\"".equals(textnode.getText())) { String temp = textnode.toPlainTextString(); textInPage += temp + "\n"; } } } String s = Replace(textInPage, searchText); eTime = System.currentTimeMillis(); String time = "搜索[" + searchText + "]用时:" + (eTime - sTime) / 1000.0 + "s"; System.out.println(s); return time + "\r\n" + s; } catch (Exception e) { e.printStackTrace(); return "大姨妈来了"; } } Code Sample 2: public static final void copyFile(String srcFilename, String dstFilename) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; FileChannel ifc = null; FileChannel ofc = null; Util.copyBuffer.clear(); try { fis = new FileInputStream(srcFilename); ifc = fis.getChannel(); fos = new FileOutputStream(dstFilename); ofc = fos.getChannel(); int sz = (int) ifc.size(); int n = 0; while (n < sz) { if (ifc.read(Util.copyBuffer) < 0) { break; } Util.copyBuffer.flip(); n += ofc.write(Util.copyBuffer); Util.copyBuffer.compact(); } } finally { try { if (ifc != null) { ifc.close(); } else if (fis != null) { fis.close(); } } catch (IOException exc) { } try { if (ofc != null) { ofc.close(); } else if (fos != null) { fos.close(); } } catch (IOException exc) { } } }
11
Code Sample 1: public static void encrypt(File plain, File symKey, File ciphered, String algorithm) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { Key key = null; try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(symKey)); key = (Key) in.readObject(); } catch (IOException ioe) { KeyGenerator generator = KeyGenerator.getInstance(algorithm); key = generator.generateKey(); ObjectOutputStream out = new ObjectOutputStream(new java.io.FileOutputStream(symKey)); out.writeObject(key); out.close(); } Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getEncoded(), algorithm)); FileInputStream in = new FileInputStream(plain); CipherOutputStream out = new CipherOutputStream(new FileOutputStream(ciphered), cipher); byte[] buffer = new byte[4096]; for (int read = in.read(buffer); read > -1; read = in.read(buffer)) { out.write(buffer, 0, read); } out.close(); } Code Sample 2: public void setContentAsStream(final InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { output.close(); } this.content = output.toByteArray(); }
11
Code Sample 1: public boolean isPasswordCorrect(String attempt) { try { MessageDigest digest = MessageDigest.getInstance(attempt); digest.update(salt); digest.update(attempt.getBytes("UTF-8")); byte[] attemptHash = digest.digest(); return attemptHash.equals(hash); } catch (UnsupportedEncodingException ex) { Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex); return false; } } Code Sample 2: private String hashPassword(String password) { if (password != null && password.trim().length() > 0) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.trim().getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } } return null; }
00
Code Sample 1: public final String encrypt(String input) throws Exception { try { MessageDigest messageDigest = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); messageDigest.reset(); messageDigest.update(input.getBytes()); String output = convert(messageDigest.digest()); return output; } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Fatal Error while digesting input string", ex); } } return input; } Code Sample 2: @Override public List<SheetFullName> importSheets(INetxiliaSystem workbookProcessor, WorkbookId workbookName, URL url, IProcessingConsole console) throws ImportException { try { return importSheets(workbookProcessor, workbookName, url.openStream(), console); } catch (IOException e) { throw new ImportException(url, "Cannot open workbook:" + e, e); } }
00
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public static void copieFichier(File fichier1, File fichier2) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(fichier1).getChannel(); out = new FileOutputStream(fichier2).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
11
Code Sample 1: private static File copyFileTo(File file, File directory) throws IOException { File newFile = new File(directory, file.getName()); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(file); fos = new FileOutputStream(newFile); byte buff[] = new byte[1024]; int val; while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val); } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } return newFile; } Code Sample 2: public void copieFichier(String fileIn, String fileOut) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(fileIn).getChannel(); out = new FileOutputStream(fileOut).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
00
Code Sample 1: @Override public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { if ((baseName == null) || (locale == null) || (format == null) || (loader == null)) { throw new NullPointerException(); } ResourceBundle bundle = null; if (format.equals(XML)) { String bundleName = toBundleName(baseName, locale); String resourceName = toResourceName(bundleName, format); URL url = loader.getResource(resourceName); if (url != null) { URLConnection connection = url.openConnection(); if (connection != null) { if (reload) { connection.setUseCaches(false); } InputStream stream = connection.getInputStream(); if (stream != null) { BufferedInputStream bis = new BufferedInputStream(stream); bundle = new XMLResourceBundle(bis); bis.close(); } } } } return bundle; } Code Sample 2: public static String calculatesMD5(String plainText) throws NoSuchAlgorithmException { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(plainText.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { plainText = Integer.toHexString(0xFF & digest[i]); if (plainText.length() < 2) { plainText = "0" + plainText; } hexString.append(plainText); } return hexString.toString(); }
11
Code Sample 1: public static void main(String[] args) throws IOException, DataFormatException { byte in_buf[] = new byte[20000]; if (args.length < 2) { System.out.println("too few arguments"); System.exit(0); } String inputName = args[0]; InputStream in = new FileInputStream(inputName); int index = 0; for (int i = 1; i < args.length; i++) { int size = Integer.parseInt(args[i]); boolean copy = size >= 0; if (size < 0) { size = -size; } OutputStream out = null; if (copy) { index++; out = new FileOutputStream(inputName + "." + index + ".dat"); } while (size > 0) { int read = in.read(in_buf, 0, Math.min(in_buf.length, size)); if (read < 0) { break; } size -= read; if (copy) { out.write(in_buf, 0, read); } } if (copy) { out.close(); } } index++; OutputStream out = new FileOutputStream(inputName + "." + index + ".dat"); while (true) { int read = in.read(in_buf); if (read < 0) { break; } out.write(in_buf, 0, read); } out.close(); in.close(); } Code Sample 2: public static long copyFile(File source, File target) throws IOException { FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); fileOutputStream = new FileOutputStream(target); FileChannel in = fileInputStream.getChannel(); FileChannel out = fileOutputStream.getChannel(); return out.transferFrom(in, 0, source.length()); } finally { if (fileInputStream != null) fileInputStream.close(); if (fileOutputStream != null) fileOutputStream.close(); } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: private static void ensure(File pFile) throws IOException { if (!pFile.exists()) { FileOutputStream fos = new FileOutputStream(pFile); String resourceName = "/" + pFile.getName(); InputStream is = BaseTest.class.getResourceAsStream(resourceName); Assert.assertNotNull(String.format("Could not find resource [%s].", resourceName), is); IOUtils.copy(is, fos); fos.close(); } }
00
Code Sample 1: public static void initialize(Monitor monitor, final JETEmitter jetEmitter) throws JETException { IProgressMonitor progressMonitor = BasicMonitor.toIProgressMonitor(monitor); progressMonitor.beginTask("", 10); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_GeneratingJETEmitterFor_message", new Object[] { jetEmitter.templateURI })); final IWorkspace workspace = ResourcesPlugin.getWorkspace(); IJavaModel javaModel = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); try { final JETCompiler jetCompiler = jetEmitter.templateURIPath == null ? new MyBaseJETCompiler(jetEmitter.templateURI, jetEmitter.encoding, jetEmitter.classLoader) : new MyBaseJETCompiler(jetEmitter.templateURIPath, jetEmitter.templateURI, jetEmitter.encoding, jetEmitter.classLoader); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETParsing_message", new Object[] { jetCompiler.getResolvedTemplateURI() })); jetCompiler.parse(); progressMonitor.worked(1); String packageName = jetCompiler.getSkeleton().getPackageName(); if (jetEmitter.templateURIPath != null) { URI templateURI = URI.createURI(jetEmitter.templateURIPath[0]); URLClassLoader theClassLoader = null; if (templateURI.isPlatformResource()) { IProject project = workspace.getRoot().getProject(templateURI.segment(1)); if (JETNature.getRuntime(project) != null) { List<URL> urls = new ArrayList<URL>(); IJavaProject javaProject = JavaCore.create(project); urls.add(new File(project.getLocation() + "/" + javaProject.getOutputLocation().removeFirstSegments(1) + "/").toURL()); for (IClasspathEntry classpathEntry : javaProject.getResolvedClasspath(true)) { if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { IPath projectPath = classpathEntry.getPath(); IProject otherProject = workspace.getRoot().getProject(projectPath.segment(0)); IJavaProject otherJavaProject = JavaCore.create(otherProject); urls.add(new File(otherProject.getLocation() + "/" + otherJavaProject.getOutputLocation().removeFirstSegments(1) + "/").toURL()); } } theClassLoader = new URLClassLoader(urls.toArray(new URL[0])) { @Override public Class<?> loadClass(String className) throws ClassNotFoundException { try { return super.loadClass(className); } catch (ClassNotFoundException classNotFoundException) { return jetEmitter.classLoader.loadClass(className); } } }; } } else if (templateURI.isPlatformPlugin()) { final Bundle bundle = Platform.getBundle(templateURI.segment(1)); if (bundle != null) { theClassLoader = new URLClassLoader(new URL[0], jetEmitter.classLoader) { @Override public Class<?> loadClass(String className) throws ClassNotFoundException { try { return bundle.loadClass(className); } catch (ClassNotFoundException classNotFoundException) { return super.loadClass(className); } } }; } } if (theClassLoader != null) { String className = (packageName.length() == 0 ? "" : packageName + ".") + jetCompiler.getSkeleton().getClassName(); if (className.endsWith("_")) { className = className.substring(0, className.length() - 1); } try { Class<?> theClass = theClassLoader.loadClass(className); Class<?> theOtherClass = null; try { theOtherClass = jetEmitter.classLoader.loadClass(className); } catch (ClassNotFoundException exception) { } if (theClass != theOtherClass) { String methodName = jetCompiler.getSkeleton().getMethodName(); Method[] methods = theClass.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (methods[i].getName().equals(methodName)) { jetEmitter.setMethod(methods[i]); break; } } return; } } catch (ClassNotFoundException exception) { } } } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); jetCompiler.generate(outputStream); final InputStream contents = new ByteArrayInputStream(outputStream.toByteArray()); if (!javaModel.isOpen()) { javaModel.open(new SubProgressMonitor(progressMonitor, 1)); } else { progressMonitor.worked(1); } final IProject project = workspace.getRoot().getProject(jetEmitter.getProjectName()); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETPreparingProject_message", new Object[] { project.getName() })); IJavaProject javaProject; if (!project.exists()) { progressMonitor.subTask("JET creating project " + project.getName()); project.create(new SubProgressMonitor(progressMonitor, 1)); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETCreatingProject_message", new Object[] { project.getName() })); IProjectDescription description = workspace.newProjectDescription(project.getName()); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); description.setLocation(null); project.open(new SubProgressMonitor(progressMonitor, 1)); project.setDescription(description, new SubProgressMonitor(progressMonitor, 1)); javaProject = JavaCore.create(project); for (Map.Entry<String, String> option : jetEmitter.getJavaOptions().entrySet()) { javaProject.setOption(option.getKey(), option.getValue()); } } else { project.open(new SubProgressMonitor(progressMonitor, 5)); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); project.setDescription(description, new SubProgressMonitor(progressMonitor, 1)); javaProject = JavaCore.create(project); } List<IClasspathEntry> classpath = new UniqueEList<IClasspathEntry>(Arrays.asList(javaProject.getRawClasspath())); for (int i = 0, len = classpath.size(); i < len; i++) { IClasspathEntry entry = classpath.get(i); if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE && ("/" + project.getName()).equals(entry.getPath().toString())) { classpath.remove(i); } } progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETInitializingProject_message", new Object[] { project.getName() })); IClasspathEntry classpathEntry = JavaCore.newSourceEntry(new Path("/" + project.getName() + "/src")); IClasspathEntry jreClasspathEntry = JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")); classpath.add(classpathEntry); classpath.add(jreClasspathEntry); classpath.addAll(jetEmitter.classpathEntries); IFolder sourceFolder = project.getFolder(new Path("src")); if (!sourceFolder.exists()) { sourceFolder.create(false, true, new SubProgressMonitor(progressMonitor, 1)); } IFolder runtimeFolder = project.getFolder(new Path("bin")); if (!runtimeFolder.exists()) { runtimeFolder.create(false, true, new SubProgressMonitor(progressMonitor, 1)); } javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[classpath.size()]), new SubProgressMonitor(progressMonitor, 1)); javaProject.setOutputLocation(new Path("/" + project.getName() + "/bin"), new SubProgressMonitor(progressMonitor, 1)); javaProject.close(); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETOpeningJavaProject_message", new Object[] { project.getName() })); javaProject.open(new SubProgressMonitor(progressMonitor, 1)); IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots(); IPackageFragmentRoot sourcePackageFragmentRoot = null; for (int j = 0; j < packageFragmentRoots.length; ++j) { IPackageFragmentRoot packageFragmentRoot = packageFragmentRoots[j]; if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) { sourcePackageFragmentRoot = packageFragmentRoot; break; } } StringTokenizer stringTokenizer = new StringTokenizer(packageName, "."); IProgressMonitor subProgressMonitor = new SubProgressMonitor(progressMonitor, 1); subProgressMonitor.beginTask("", stringTokenizer.countTokens() + 4); subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_CreateTargetFile_message")); IContainer sourceContainer = sourcePackageFragmentRoot == null ? project : (IContainer) sourcePackageFragmentRoot.getCorrespondingResource(); while (stringTokenizer.hasMoreElements()) { String folderName = stringTokenizer.nextToken(); sourceContainer = sourceContainer.getFolder(new Path(folderName)); if (!sourceContainer.exists()) { ((IFolder) sourceContainer).create(false, true, new SubProgressMonitor(subProgressMonitor, 1)); } } IFile targetFile = sourceContainer.getFile(new Path(jetCompiler.getSkeleton().getClassName() + ".java")); if (!targetFile.exists()) { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETCreating_message", new Object[] { targetFile.getFullPath() })); targetFile.create(contents, true, new SubProgressMonitor(subProgressMonitor, 1)); } else { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETUpdating_message", new Object[] { targetFile.getFullPath() })); targetFile.setContents(contents, true, true, new SubProgressMonitor(subProgressMonitor, 1)); } subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETBuilding_message", new Object[] { project.getName() })); project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, new SubProgressMonitor(subProgressMonitor, 1)); IMarker[] markers = targetFile.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE); boolean errors = false; for (int i = 0; i < markers.length; ++i) { IMarker marker = markers[i]; if (marker.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO) == IMarker.SEVERITY_ERROR) { errors = true; subProgressMonitor.subTask(marker.getAttribute(IMarker.MESSAGE) + " : " + (CodeGenPlugin.getPlugin().getString("jet.mark.file.line", new Object[] { targetFile.getLocation(), marker.getAttribute(IMarker.LINE_NUMBER) }))); } } if (!errors) { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETLoadingClass_message", new Object[] { jetCompiler.getSkeleton().getClassName() + ".class" })); List<URL> urls = new ArrayList<URL>(); urls.add(new File(project.getLocation() + "/" + javaProject.getOutputLocation().removeFirstSegments(1) + "/").toURL()); final Set<Bundle> bundles = new HashSet<Bundle>(); LOOP: for (IClasspathEntry jetEmitterClasspathEntry : jetEmitter.getClasspathEntries()) { IClasspathAttribute[] classpathAttributes = jetEmitterClasspathEntry.getExtraAttributes(); if (classpathAttributes != null) { for (IClasspathAttribute classpathAttribute : classpathAttributes) { if (classpathAttribute.getName().equals(CodeGenUtil.EclipseUtil.PLUGIN_ID_CLASSPATH_ATTRIBUTE_NAME)) { Bundle bundle = Platform.getBundle(classpathAttribute.getValue()); if (bundle != null) { bundles.add(bundle); continue LOOP; } } } } urls.add(new URL("platform:/resource" + jetEmitterClasspathEntry.getPath() + "/")); } URLClassLoader theClassLoader = new URLClassLoader(urls.toArray(new URL[0]), jetEmitter.classLoader) { @Override public Class<?> loadClass(String className) throws ClassNotFoundException { try { return super.loadClass(className); } catch (ClassNotFoundException exception) { for (Bundle bundle : bundles) { try { return bundle.loadClass(className); } catch (ClassNotFoundException exception2) { } } throw exception; } } }; Class<?> theClass = theClassLoader.loadClass((packageName.length() == 0 ? "" : packageName + ".") + jetCompiler.getSkeleton().getClassName()); String methodName = jetCompiler.getSkeleton().getMethodName(); Method[] methods = theClass.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (methods[i].getName().equals(methodName)) { jetEmitter.setMethod(methods[i]); break; } } } subProgressMonitor.done(); } catch (CoreException exception) { throw new JETException(exception); } catch (Exception exception) { throw new JETException(exception); } finally { progressMonitor.done(); } } Code Sample 2: @Override public List<SheetFullName> importSheets(INetxiliaSystem workbookProcessor, WorkbookId workbookName, URL url, IProcessingConsole console) throws ImportException { try { return importSheets(workbookProcessor, workbookName, url.openStream(), console); } catch (IOException e) { throw new ImportException(url, "Cannot open workbook:" + e, e); } }
00
Code Sample 1: public void loadProfilefromConfig(String filename, P xslProfileClass, String profileTag) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { if (Val.chkStr(profileTag).equals("")) { profileTag = "Profile"; } String configuration_folder_path = this.getConfigurationFolderPath(); if (configuration_folder_path == null || configuration_folder_path.length() == 0) { Properties properties = new Properties(); final URL url = CswProfiles.class.getResource("CswCommon.properties"); properties.load(url.openStream()); configuration_folder_path = properties.getProperty("DEFAULT_CONFIGURATION_FOLDER_PATH"); } DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); ResourcePath rscPath = new ResourcePath(); InputSource configFile = rscPath.makeInputSource(configuration_folder_path + filename); if (configFile == null) { configFile = rscPath.makeInputSource("/" + configuration_folder_path + filename); } Document doc = builder.parse(configFile); NodeList profileNodes = doc.getElementsByTagName(profileTag); for (int i = 0; i < profileNodes.getLength(); i++) { Node currProfile = profileNodes.item(i); XPath xpath = XPathFactory.newInstance().newXPath(); String id = Val.chkStr(xpath.evaluate("ID", currProfile)); String name = Val.chkStr(xpath.evaluate("Name", currProfile)); String description = Val.chkStr(xpath.evaluate("Description", currProfile)); String requestXslt = Val.chkStr(xpath.evaluate("GetRecords/XSLTransformations/Request", currProfile)); String expectedGptXmlOutput = Val.chkStr(xpath.evaluate("GetRecords/XSLTransformations/Request/@expectedGptXmlOutput", currProfile)); if (expectedGptXmlOutput.equals("")) { expectedGptXmlOutput = FORMAT_SEARCH_TO_XSL.MINIMAL_LEGACY_CSWCLIENT.toString(); } String responseXslt = Val.chkStr(xpath.evaluate("GetRecords/XSLTransformations/Response", currProfile)); String requestKVPs = Val.chkStr(xpath.evaluate("GetRecordByID/RequestKVPs", currProfile)); String metadataXslt = Val.chkStr(xpath.evaluate("GetRecordByID/XSLTransformations/Response", currProfile)); boolean extentSearch = Boolean.parseBoolean(Val.chkStr(xpath.evaluate("SupportSpatialQuery", currProfile))); boolean liveDataMaps = Boolean.parseBoolean(Val.chkStr(xpath.evaluate("SupportContentTypeQuery", currProfile))); boolean extentDisplay = Boolean.parseBoolean(Val.chkStr(xpath.evaluate("SupportSpatialBoundary", currProfile))); boolean harvestable = Boolean.parseBoolean(Val.chkStr(xpath.evaluate("Harvestable", currProfile))); requestXslt = configuration_folder_path + requestXslt; responseXslt = configuration_folder_path + responseXslt; metadataXslt = configuration_folder_path + metadataXslt; SearchXslProfile profile = null; try { profile = xslProfileClass.getClass().newInstance(); profile.setId(id); profile.setName(name); profile.setDescription(description); profile.setRequestxslt(requestXslt); profile.setResponsexslt(responseXslt); profile.setMetadataxslt(metadataXslt); profile.setSupportsContentTypeQuery(liveDataMaps); profile.setSupportsSpatialBoundary(extentDisplay); profile.setSupportsSpatialQuery(extentSearch); profile.setKvp(requestKVPs); profile.setHarvestable(harvestable); profile.setFormatRequestToXsl(SearchXslProfile.FORMAT_SEARCH_TO_XSL.valueOf(expectedGptXmlOutput)); profile.setFilter_extentsearch(extentSearch); profile.setFilter_livedatamap(liveDataMaps); addProfile((P) profile); } catch (InstantiationException e) { throw new IOException("Could not instantiate profile class" + e.getMessage()); } catch (IllegalAccessException e) { throw new IOException("Could not instantiate profile class" + e.getMessage()); } } } Code Sample 2: public static void main(String[] args) { try { String user = "techbeherca"; String targetUrl = "http://api.fanfou.com/statuses/user_timeline.xml?id=" + user; URL url = new URL(targetUrl); InputStream in = url.openStream(); ArrayList<MessageObj> list; if (in != null) { MessageListDOMParser parser = new MessageListDOMParser(); list = (ArrayList<MessageObj>) parser.parseXML(in); TransactionDAO dao = new TransactionDAO(); dao.insert(list); } } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: @Test public void test_lookupResourceType_FullSearch_TwoWords() throws Exception { URL url = new URL(baseUrl + "/lookupResourceType/alloyed+tritanium"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("[{\"itemTypeID\":25595,\"itemCategoryID\":4,\"name\":\"Alloyed Tritanium Bar\",\"icon\":\"69_11\"}]")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/json; charset=utf-8")); } Code Sample 2: public synchronized List<AnidbSearchResult> getAnimeTitles() throws Exception { URL url = new URL("http", host, "/api/animetitles.dat.gz"); ResultCache cache = getCache(); @SuppressWarnings("unchecked") List<AnidbSearchResult> anime = (List) cache.getSearchResult(null, Locale.ROOT); if (anime != null) { return anime; } Pattern pattern = Pattern.compile("^(?!#)(\\d+)[|](\\d)[|]([\\w-]+)[|](.+)$"); Map<Integer, String> primaryTitleMap = new HashMap<Integer, String>(); Map<Integer, Map<String, String>> officialTitleMap = new HashMap<Integer, Map<String, String>>(); Map<Integer, Map<String, String>> synonymsTitleMap = new HashMap<Integer, Map<String, String>>(); Scanner scanner = new Scanner(new GZIPInputStream(url.openStream()), "UTF-8"); try { while (scanner.hasNextLine()) { Matcher matcher = pattern.matcher(scanner.nextLine()); if (matcher.matches()) { int aid = Integer.parseInt(matcher.group(1)); String type = matcher.group(2); String language = matcher.group(3); String title = matcher.group(4); if (type.equals("1")) { primaryTitleMap.put(aid, title); } else if (type.equals("2") || type.equals("4")) { Map<Integer, Map<String, String>> titleMap = (type.equals("4") ? officialTitleMap : synonymsTitleMap); Map<String, String> languageTitleMap = titleMap.get(aid); if (languageTitleMap == null) { languageTitleMap = new HashMap<String, String>(); titleMap.put(aid, languageTitleMap); } languageTitleMap.put(language, title); } } } } finally { scanner.close(); } anime = new ArrayList<AnidbSearchResult>(primaryTitleMap.size()); for (Entry<Integer, String> entry : primaryTitleMap.entrySet()) { Map<String, String> localizedTitles = new HashMap<String, String>(); if (synonymsTitleMap.containsKey(entry.getKey())) { localizedTitles.putAll(synonymsTitleMap.get(entry.getKey())); } if (officialTitleMap.containsKey(entry.getKey())) { localizedTitles.putAll(officialTitleMap.get(entry.getKey())); } anime.add(new AnidbSearchResult(entry.getKey(), entry.getValue(), localizedTitles)); } return cache.putSearchResult(null, Locale.ROOT, anime); }
11
Code Sample 1: public void run() { StringBuffer xml; String tabName; Element guiElement; setBold(monitor.getReading()); setBold(monitor.getReadingStatus()); monitor.getReadingStatus().setText(" Working"); HttpMethod method = null; xml = new StringBuffer(); File tempfile = new File(url); if (tempfile.exists()) { try { InputStream in = new FileInputStream(tempfile); int temp; while ((temp = in.read()) != -1) { xml.append((char) temp); } in.close(); } catch (IOException e) { System.out.println("Loading Monitor Failed, error while reading XML file from local file"); e.printStackTrace(System.err); return; } } else { try { HttpClient client = new HttpClient(); method = new GetMethod(url); int response = client.executeMethod(method); if (response == 200) { InputStream in = method.getResponseBodyAsStream(); int temp; while ((temp = in.read()) != -1) { xml.append((char) temp); } in.close(); } else { if (method != null) { method.releaseConnection(); } System.out.println("Loading Monitor Failed. Incorrect response from HTTP Server " + response); return; } } catch (IOException e) { if (method != null) { method.releaseConnection(); } System.out.println("Loading Monitor Failed, error while reading XML file from HTTP Server"); e.printStackTrace(System.err); return; } } setPlain(monitor.getReading()); setPlain(monitor.getReadingStatus()); monitor.getReadingStatus().setText(" Done"); setBold(monitor.getValidating()); setBold(monitor.getValidatingStatus()); monitor.getValidatingStatus().setText(" Working"); DocumentBuilderFactoryImpl factory = new DocumentBuilderFactoryImpl(); try { DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.parse(new ByteArrayInputStream(xml.toString().getBytes())); if (method != null) { method.releaseConnection(); } Element root = document.getDocumentElement(); NodeList temp = root.getElementsByTagName("resource"); for (int j = 0; j < temp.getLength(); j++) { Element resource = (Element) temp.item(j); resources.add(new URL(resource.getAttribute("url"))); } NodeList connections = root.getElementsByTagName("jmxserver"); for (int j = 0; j < connections.getLength(); j++) { Element connection = (Element) connections.item(j); String name = connection.getAttribute("name"); String tempUrl = connection.getAttribute("url"); String auth = connection.getAttribute("auth"); if (tempUrl.indexOf("${host}") != -1) { HostDialog dialog = new HostDialog(Config.getHosts()); String host = dialog.showDialog(); if (host == null) { System.out.println("Host can not be null, unable to create panel."); return; } tempUrl = tempUrl.replaceAll("\\$\\{host\\}", host); Config.addHost(host); } JMXServiceURL jmxUrl = new JMXServiceURL(tempUrl); JmxServerGraph server = new JmxServerGraph(name, jmxUrl, new JmxWorker(false)); if (auth != null && auth.equalsIgnoreCase("true")) { LoginTrueService loginService = new LoginTrueService(); JXLoginPanel.Status status = JXLoginPanel.showLoginDialog(null, loginService); if (status != JXLoginPanel.Status.SUCCEEDED) { return; } server.setUsername(loginService.getName()); server.setPassword(loginService.getPassword()); } servers.put(name, server); NodeList listeners = connection.getElementsByTagName("listener"); for (int i = 0; i < listeners.getLength(); i++) { Element attribute = (Element) listeners.item(i); String taskname = attribute.getAttribute("taskname"); MBean mbean = new MBean(attribute.getAttribute("mbean"), null); String filtertype = attribute.getAttribute("filterType"); TaskNotificationListener listener = new TaskNotificationListener(); NotificationFilterSupport filter = new NotificationFilterSupport(); if (filtertype == null || "".equals(filtertype)) { filter = null; } else { filter.enableType(filtertype); } Task task = new Task(-1, Task.LISTEN, server); task.setMbean(mbean); task.setListener(listener); task.setFilter(filter); server.getWorker().addTask(task); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); tasks.put(taskname, hashTempList); } NodeList attributes = connection.getElementsByTagName("attribute"); for (int i = 0; i < attributes.getLength(); i++) { Element attribute = (Element) attributes.item(i); String taskname = attribute.getAttribute("taskname"); MBean mbean = new MBean(attribute.getAttribute("mbean"), null); String attributename = attribute.getAttribute("attributename"); String frequency = attribute.getAttribute("frequency"); String onEvent = attribute.getAttribute("onEvent"); if (frequency.equalsIgnoreCase("onchange")) { TaskNotificationListener listener = new TaskNotificationListener(); AttributeChangeNotificationFilter filter = new AttributeChangeNotificationFilter(); filter.enableAttribute(attributename); Task task = new Task(-1, Task.LISTEN, server); MBeanAttribute att = new MBeanAttribute(mbean, attributename); task.setAttribute(att); task.setMbean(mbean); task.setListener(listener); task.setFilter(filter); server.getWorker().addTask(task); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } Task task2 = new Task(-1, Task.GET_ATTRIBUTE, server); task2.setAttribute(att); task2.setMbean(mbean); server.getWorker().addTask(task2); List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); hashTempList.add(task2); tasks.put(taskname, hashTempList); } else { int frequency2 = Integer.parseInt(frequency); Task task = new Task(frequency2, Task.GET_ATTRIBUTE, server); MBeanAttribute att = new MBeanAttribute(mbean, attributename); task.setAttribute(att); task.setMbean(mbean); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); tasks.put(taskname, hashTempList); TaskNotificationListener listener = null; if (onEvent != null && !"".equals(onEvent)) { Task tempTask = tasks.get(onEvent).get(0); if (tempTask == null) { System.out.println(onEvent + " was not found."); return; } else { listener = (TaskNotificationListener) tempTask.getListener(); } } if (listener == null) { server.getWorker().addTask(task); } else { listener.addTask(task); } } } } NodeList guiTemp = root.getElementsByTagName("gui"); guiElement = (Element) guiTemp.item(0); tabName = guiElement.getAttribute("name"); if (MonitorServer.contains(tabName)) { JOptionPane.showMessageDialog(null, "This panel is already open, stoping creating of panel.", "Panel already exists", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < monitor.getTab().getTabCount(); i++) { if (monitor.getTab().getComponent(i).equals(monitor)) { monitor.getTab().setTitleAt(i, tabName); break; } } NodeList tempBindings = root.getElementsByTagName("binding"); for (int i = 0; i < tempBindings.getLength(); i++) { Element binding = (Element) tempBindings.item(i); String guiname = binding.getAttribute("guiname"); String tmethod = binding.getAttribute("method"); String taskname = binding.getAttribute("taskname"); String formater = binding.getAttribute("formater"); BindingContainer tempBinding; if (formater == null || (formater != null && formater.equals(""))) { tempBinding = new BindingContainer(guiname, tmethod, taskname); } else { tempBinding = new BindingContainer(guiname, tmethod, taskname, formater); } bindings.add(tempBinding); } } catch (Exception e) { System.err.println("Exception message: " + e.getMessage()); System.out.println("Loading Monitor Failed, couldnt parse XML file."); e.printStackTrace(System.err); return; } setPlain(monitor.getValidating()); setPlain(monitor.getValidatingStatus()); monitor.getValidatingStatus().setText(" Done"); setBold(monitor.getDownload()); setBold(monitor.getDownloadStatus()); monitor.getDownloadStatus().setText(" Working"); List<File> jarFiles = new ArrayList<File>(); File cacheDir = new File(Config.getCacheDir()); if (!cacheDir.exists()) { cacheDir.mkdir(); } for (URL resUrl : resources) { try { HttpClient client = new HttpClient(); HttpMethod methodRes = new GetMethod(resUrl.toString()); int response = client.executeMethod(methodRes); if (response == 200) { int index = resUrl.toString().lastIndexOf("/") + 1; File file = new File(Config.getCacheDir() + resUrl.toString().substring(index)); FileOutputStream out = new FileOutputStream(file); InputStream in = methodRes.getResponseBodyAsStream(); int readTemp = 0; while ((readTemp = in.read()) != -1) { out.write(readTemp); } System.out.println(file.getName() + " downloaded."); methodRes.releaseConnection(); if (file.getName().endsWith(".jar")) { jarFiles.add(file); } } else { methodRes.releaseConnection(); System.out.println("Loading Monitor Failed. Unable to get resource " + url); return; } } catch (IOException e) { System.out.println("Loading Monitor Failed, error while reading resource file " + "from HTTP Server"); e.printStackTrace(System.err); return; } } URL[] urls = new URL[jarFiles.size()]; try { for (int i = 0; i < jarFiles.size(); i++) { File file = jarFiles.get(i); File newFile = new File(Config.getCacheDir() + "/" + System.currentTimeMillis() + file.getName()); FileInputStream in = new FileInputStream(file); FileOutputStream out = new FileOutputStream(newFile); int n = 0; byte[] buf = new byte[1024]; while ((n = in.read(buf, 0, 1024)) > -1) { out.write(buf, 0, n); } out.close(); out.close(); in.close(); urls[i] = new URL("file:" + newFile.getAbsolutePath()); } } catch (Exception e1) { System.out.println("Unable to load jar files."); e1.printStackTrace(); } URLClassLoader loader = new URLClassLoader(urls); engine.setClassLoader(loader); setPlain(monitor.getDownload()); setPlain(monitor.getDownloadStatus()); monitor.getDownloadStatus().setText(" Done"); setBold(monitor.getGui()); setBold(monitor.getGuiStatus()); monitor.getGuiStatus().setText(" Working"); Container container; try { String tempXml = xml.toString(); int start = tempXml.indexOf("<gui"); start = tempXml.indexOf('>', start) + 1; int end = tempXml.indexOf("</gui>"); container = engine.render(new StringReader(tempXml.substring(start, end))); } catch (Exception e) { e.printStackTrace(System.err); System.err.println("Exception msg: " + e.getMessage()); System.out.println("Loading Monitor Failed, error creating gui."); return; } for (BindingContainer bcon : bindings) { List<Task> temp = tasks.get(bcon.getTask()); if (temp == null) { System.out.println("Task with name " + bcon.getTask() + " doesnt exist."); } else { for (Task task : temp) { if (task != null) { Object comp = engine.find(bcon.getComponent()); if (comp != null) { if (task.getTaskType() == Task.LISTEN && task.getFilter() instanceof AttributeChangeNotificationFilter) { TaskNotificationListener listener = (TaskNotificationListener) task.getListener(); if (bcon.getFormater() == null) { listener.addResultListener(new Binding(comp, bcon.getMethod())); } else { listener.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader)); } } else { if (bcon.getFormater() == null) { task.addResultListener(new Binding(comp, bcon.getMethod())); } else { task.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader)); } } } else { System.out.println("Refering to gui name, " + bcon.getComponent() + ", that doesnt exist. Unable to create monitor."); return; } } else { System.out.println("Refering to task name, " + bcon.getTask() + ", that doesnt exist. Unable to create monitor."); return; } } } } for (int i = 0; i < monitor.getTab().getTabCount(); i++) { if (monitor.getTab().getComponent(i).equals(monitor)) { monitor.getTab().setComponentAt(i, new MonitorContainerPanel(container, this)); break; } } System.out.println("Connecting to server(s)."); Enumeration e = servers.keys(); List<JmxWorker> list = new ArrayList<JmxWorker>(); while (e.hasMoreElements()) { JmxWorker worker = servers.get(e.nextElement()).getWorker(); worker.setRunning(true); worker.start(); list.add(worker); } MonitorServer.add(tabName, list); Config.addUrl(url); } Code Sample 2: public boolean backupFile(File oldFile, File newFile) { boolean isBkupFileOK = false; FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(oldFile).getChannel(); targetChannel = new FileOutputStream(newFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException e) { logger.log(Level.SEVERE, "IO exception occurred while copying file", e); } finally { if ((newFile != null) && (newFile.exists()) && (newFile.length() > 0)) { isBkupFileOK = true; } try { if (sourceChannel != null) { sourceChannel.close(); } if (targetChannel != null) { targetChannel.close(); } } catch (IOException e) { logger.info("closing channels failed"); } } return isBkupFileOK; }
00
Code Sample 1: private boolean goToForum() { URL url = null; URLConnection urlConn = null; int code = 0; boolean gotNumReplies = false; boolean gotMsgNum = false; try { url = new URL("http://" + m_host + "/forums/index.php?topic=" + m_gameId + ".new"); } catch (MalformedURLException e) { e.printStackTrace(); return false; } try { urlConn = url.openConnection(); ((HttpURLConnection) urlConn).setRequestMethod("GET"); ((HttpURLConnection) urlConn).setInstanceFollowRedirects(false); urlConn.setDoOutput(false); urlConn.setDoInput(true); urlConn.setRequestProperty("Host", m_host); urlConn.setRequestProperty("Accept", "*/*"); urlConn.setRequestProperty("Connection", "Keep-Alive"); urlConn.setRequestProperty("Cache-Control", "no-cache"); if (m_referer != null) urlConn.setRequestProperty("Referer", m_referer); if (m_cookies != null) urlConn.setRequestProperty("Cookie", m_cookies); m_referer = url.toString(); readCookies(urlConn); code = ((HttpURLConnection) urlConn).getResponseCode(); if (code != 200) { String msg = ((HttpURLConnection) urlConn).getResponseMessage(); m_turnSummaryRef = String.valueOf(code) + ": " + msg; return false; } BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line = ""; Pattern p_numReplies = Pattern.compile(".*?;num_replies=(\\d+)\".*"); Pattern p_msgNum = Pattern.compile(".*?<a name=\"msg(\\d+)\"></a><a name=\"new\"></a>.*"); Pattern p_attachId = Pattern.compile(".*?action=dlattach;topic=" + m_gameId + ".0;attach=(\\d+)\">.*"); while ((line = in.readLine()) != null) { if (!gotNumReplies) { Matcher match_numReplies = p_numReplies.matcher(line); if (match_numReplies.matches()) { m_numReplies = match_numReplies.group(1); gotNumReplies = true; continue; } } if (!gotMsgNum) { Matcher match_msgNum = p_msgNum.matcher(line); if (match_msgNum.matches()) { m_msgNum = match_msgNum.group(1); gotMsgNum = true; continue; } } Matcher match_attachId = p_attachId.matcher(line); if (match_attachId.matches()) m_attachId = match_attachId.group(1); } in.close(); } catch (Exception e) { e.printStackTrace(); return false; } if (!gotNumReplies || !gotMsgNum) { m_turnSummaryRef = "Error: "; if (!gotNumReplies) m_turnSummaryRef += "No num_replies found in A&A.org forum topic. "; if (!gotMsgNum) m_turnSummaryRef += "No msgXXXXXX found in A&A.org forum topic. "; return false; } return true; } Code Sample 2: public static Dictionary loadManifestFrom(BaseData bundledata) throws BundleException { URL url = bundledata.getEntry(Constants.OSGI_BUNDLE_MANIFEST); if (url == null) return null; try { return Headers.parseManifest(url.openStream()); } catch (IOException e) { throw new BundleException(NLS.bind(EclipseAdaptorMsg.ECLIPSE_DATA_ERROR_READING_MANIFEST, bundledata.getLocation()), e); } }
00
Code Sample 1: public void run() { int requestCount = 0; long i0 = System.currentTimeMillis(); while (requestCount != maxRequests) { long r0 = System.currentTimeMillis(); try { url = new URL(requestedUrl); logger.debug("Requesting Url, " + url.toString()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((httpResponse = in.readLine()) != null) { logger.trace("Http Response = " + httpResponse); } } catch (Exception e) { logger.fatal("Exception thrown retrievng Url = " + requestedUrl + ", " + e); notification.setNotification(e.toString()); } long r1 = System.currentTimeMillis(); requestedElapsedTime = r1 - r0; logger.debug("Request(" + this.getName() + "/" + this.getId() + ") #" + requestCount + " processed, took " + requestedElapsedTime + "ms"); requestCount++; } long i1 = System.currentTimeMillis(); iterationElapsedTime = i1 - i0; logger.trace("Iteration elapsed time is " + iterationElapsedTime + "ms for thread ID " + this.getId()); status.incrementIterationsComplete(); logger.info("Iteration for Url = " + requestedUrl + ", (" + this.getName() + "/" + this.getId() + ") took " + iterationElapsedTime + "ms"); try { logger.debug("Joining thread(" + this.getId() + ")"); this.join(100); } catch (Exception e) { logger.fatal(e); notification.setNotification(e.toString()); } } Code Sample 2: public Location getLocation(String ip) throws Exception { URL url = new URL("http://api.hostip.info/?ip=" + ip); SAXReader reader = new SAXReader(); Document doc = reader.read(url.openStream()); System.out.println(doc.asXML()); Location location = new Location(doc); return location; }
00
Code Sample 1: public String getLastVersion() { try { String server = icescrum2Properties.get("check.url").toString(); Boolean useProxy = new Boolean(icescrum2Properties.get("proxy.active").toString()); Boolean authProxy = new Boolean(icescrum2Properties.get("proxy.auth.active").toString()); URL url = new URL(server); if (useProxy) { String proxy = icescrum2Properties.get("proxy.url").toString(); String port = icescrum2Properties.get("proxy.port").toString(); Properties systemProperties = System.getProperties(); systemProperties.setProperty("http.proxyHost", proxy); systemProperties.setProperty("http.proxyPort", port); } URLConnection connection = url.openConnection(); if (authProxy) { String username = icescrum2Properties.get("proxy.auth.username").toString(); String password = icescrum2Properties.get("proxy.auth.password").toString(); String login = username + ":" + password; String encodedLogin = Base64.base64Encode(login); connection.setRequestProperty("Proxy-Authorization", "Basic " + encodedLogin); } connection.setConnectTimeout(Integer.parseInt(icescrum2Properties.get("check.timeout").toString())); InputStream input = connection.getInputStream(); StringWriter writer = new StringWriter(); InputStreamReader streamReader = new InputStreamReader(input); BufferedReader buffer = new BufferedReader(streamReader); String value = ""; while (null != (value = buffer.readLine())) { writer.write(value); } return writer.toString(); } catch (IOException e) { } return null; } Code Sample 2: public static String SHA1(String string) throws XLWrapException { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new XLWrapException("SHA-1 message digest is not available."); } byte[] data = new byte[40]; md.update(string.getBytes()); data = md.digest(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); }
00
Code Sample 1: public void backup(File source) throws BackupException { try { int index = source.getAbsolutePath().lastIndexOf("."); if (index == -1) return; File dest = new File(source.getAbsolutePath().substring(0, index) + ".bak"); FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception ex) { throw new BackupException(ex.getMessage(), ex, source); } } Code Sample 2: @Override public byte[] getAvatar() throws IOException { HttpUriRequest request; try { request = new HttpGet(mUrl); } catch (IllegalArgumentException e) { IOException ioe = new IOException("Invalid url " + mUrl); ioe.initCause(e); throw ioe; } HttpResponse response = mClient.execute(request); HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { byte[] data = new byte[1024]; int nbread; while ((nbread = in.read(data)) != -1) { os.write(data, 0, nbread); } } finally { in.close(); os.close(); } return os.toByteArray(); }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: private void putAlgosFromJar(File jarfile, AlgoDir dir, Model model) throws FileNotFoundException, IOException { URLClassLoader urlLoader = new URLClassLoader(new URL[] { jarfile.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(jarfile)); JarEntry entry = jis.getNextJarEntry(); String name = null; String tmpdir = System.getProperty("user.dir") + File.separator + Application.getProperty("dir.tmp") + File.separator; byte[] buffer = new byte[1000]; while (entry != null) { name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); try { Class<?> cls = urlLoader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && ((cls.getModifiers() & Modifier.ABSTRACT) == 0)) { dir.addAlgorithm(cls); model.putClass(cls.getName(), cls); } else if (ISerializable.class.isAssignableFrom(cls)) { model.putClass(cls.getName(), cls); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else if (Constants.isAllowedImageType(name)) { int lastSep = name.lastIndexOf("/"); if (lastSep != -1) { String dirs = tmpdir + name.substring(0, lastSep); File d = new File(dirs); if (!d.exists()) d.mkdirs(); } String filename = tmpdir + name; File f = new File(filename); if (!f.exists()) { f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); int read = -1; while ((read = jis.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.close(); } } entry = jis.getNextJarEntry(); } }
00
Code Sample 1: public void include(String href) throws ProteuException { try { if (href.toLowerCase().startsWith("http://")) { java.net.URLConnection urlConn = (new java.net.URL(href)).openConnection(); Download.sendInputStream(this, urlConn.getInputStream()); } else { requestHead.set("JCN_URL_INCLUDE", href); Url.build(this); } } catch (ProteuException pe) { throw pe; } catch (Throwable t) { logger.error("Include", t); throw new ProteuException(t.getMessage(), t); } } Code Sample 2: private boolean importPKC(String keystoreLocation, String pw, String pkcFile, String alias) { boolean imported = false; KeyStore ks = null; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new BufferedInputStream(new FileInputStream(keystoreLocation)), pw.toCharArray()); } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading keystore file when exporting PKC: " + e.getMessage()); } return false; } Certificate cert = null; try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pkcFile)); CertificateFactory cf = CertificateFactory.getInstance("X.509"); while (bis.available() > 0) { cert = cf.generateCertificate(bis); } } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading certificate from file when importing PKC: " + e.getMessage()); } return false; } BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(new File(keystoreLocation))); } catch (FileNotFoundException e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error accessing key store file when importing certificate: " + e.getMessage()); } return false; } try { if (alias.equals("rootca")) { ks.setCertificateEntry(alias, cert); } else { KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias, new KeyStore.PasswordProtection(pw.toCharArray())); ks.setKeyEntry(alias, pkEntry.getPrivateKey(), pw.toCharArray(), new Certificate[] { cert }); } ks.store(bos, pw.toCharArray()); imported = true; } catch (Exception e) { e.printStackTrace(); if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error writing keystore to file when importing key store: " + e.getMessage()); } return false; } return imported; }
11
Code Sample 1: public static synchronized String encrypt(String plaintextPassword) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new Exception(e); } try { md.update(plaintextPassword.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: public static String hash(String plainText) throws Exception { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(plainText.getBytes(), 0, plainText.length()); String hash = new BigInteger(1, m.digest()).toString(16); if (hash.length() == 31) { hash = "0" + hash; } return hash; }
00
Code Sample 1: private void downloadPage(final URL url, final File file) { try { long size = 0; final byte[] buffer = new byte[BotUtil.BUFFER_SIZE]; final File tempFile = new File(file.getParentFile(), "temp.tmp"); int length; int lastUpdate = 0; FileOutputStream fos = new FileOutputStream(tempFile); final InputStream is = url.openStream(); do { length = is.read(buffer); if (length >= 0) { fos.write(buffer, 0, length); size += length; } if (lastUpdate > UPDATE_TIME) { report(0, (int) (size / Format.MEMORY_MEG), "Downloading... " + Format.formatMemory(size)); lastUpdate = 0; } lastUpdate++; } while (length >= 0); fos.close(); if (url.toString().toLowerCase().endsWith(".gz")) { final FileInputStream fis = new FileInputStream(tempFile); final GZIPInputStream gis = new GZIPInputStream(fis); fos = new FileOutputStream(file); size = 0; lastUpdate = 0; do { length = gis.read(buffer); if (length >= 0) { fos.write(buffer, 0, length); size += length; } if (lastUpdate > UPDATE_TIME) { report(0, (int) (size / Format.MEMORY_MEG), "Uncompressing... " + Format.formatMemory(size)); lastUpdate = 0; } lastUpdate++; } while (length >= 0); fos.close(); fis.close(); gis.close(); tempFile.delete(); } else { file.delete(); tempFile.renameTo(file); } } catch (final IOException e) { throw new AnalystError(e); } } Code Sample 2: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
11
Code Sample 1: public boolean loadResource(String resourcePath) { try { URL url = Thread.currentThread().getContextClassLoader().getResource(resourcePath); if (url == null) { logger.error("Cannot find the resource named: '" + resourcePath + "'. Failed to load the keyword list."); return false; } InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String ligne = br.readLine(); while (ligne != null) { if (!contains(ligne.toUpperCase())) { addLast(ligne.toUpperCase()); } ligne = br.readLine(); } return true; } catch (IOException ioe) { logger.log(Level.ERROR, "Cannot load default SQL keywords file.", ioe); } return false; } Code Sample 2: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String cacheName = req.getParameter("cacheName"); if (cacheName == null || cacheName.equals("")) { resp.getWriter().println("parameter cacheName required"); return; } else { StringBuffer urlStr = new StringBuffer(); urlStr.append(BASE_URL); urlStr.append("?"); urlStr.append("cacheName="); urlStr.append("rpcwc.bo.cache."); urlStr.append(cacheName); URL url = new URL(urlStr.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; StringBuffer output = new StringBuffer(); while ((line = reader.readLine()) != null) { output.append(line); output.append(System.getProperty("line.separator")); } reader.close(); resp.getWriter().println(output.toString()); } }
00
Code Sample 1: @Override void retrieveSupplementalInfo() throws IOException, InterruptedException { String encodedProductID = URLEncoder.encode(productID, "UTF-8"); String uri = BASE_PRODUCT_URI + encodedProductID; HttpUriRequest head = new HttpGet(uri); AndroidHttpClient client = AndroidHttpClient.newInstance(null); HttpResponse response = client.execute(head); int status = response.getStatusLine().getStatusCode(); if (status != 200) { return; } String content = consume(response.getEntity()); Matcher matcher = PRODUCT_NAME_PRICE_PATTERN.matcher(content); if (matcher.find()) { append(matcher.group(1)); append(matcher.group(2)); } setLink(uri); } Code Sample 2: public static int deleteExecution(String likePatten) { Connection conn = null; PreparedStatement psmt = null; StringBuffer SQL = new StringBuffer(200); int deleted = 0; SQL.append(" DELETE FROM JHF_EXCEPTION ").append(" WHERE ORDER_ID LIKE ? "); try { conn = JdbcConnectionPool.mainConnection(); conn.setAutoCommit(false); conn.setReadOnly(false); psmt = conn.prepareStatement(SQL.toString()); psmt.setString(1, "%" + likePatten + "%"); deleted = psmt.executeUpdate(); conn.commit(); } catch (SQLException e) { if (null != conn) { try { conn.rollback(); } catch (SQLException e1) { System.out.println(" error when roll back !"); } } } finally { try { if (null != psmt) { psmt.close(); psmt = null; } if (null != conn) { conn.close(); conn = null; } } catch (SQLException e) { System.out.println(" error when psmt close or conn close ."); } } return deleted; }
00
Code Sample 1: private static void generateTIFF(Connection con, String category, String area_code, String topic_code, String timeseries, String diff_timeseries, Calendar time, String area_label, String raster_label, String image_label, String note, Rectangle2D bounds, Rectangle2D raster_bounds, String source_filename, String diff_filename, String legend_filename, String output_filename, int output_maximum_size) throws SQLException, IOException { Debug.println("ImageCropper.generateTIFF begin"); MapContext map_context = new MapContext("test", new Configuration()); try { Map map = new Map(map_context, area_label, new Configuration()); map.setCoordSys(ProjectionCategories.default_coordinate_system); map.setPatternOutline(new XPatternOutline(new XPatternPaint(Color.white))); String type = null; RasterLayer rlayer = getRasterLayer(map, raster_label, getLinuxPathEquivalent(source_filename), getLinuxPathEquivalent(diff_filename), type, getLinuxPathEquivalent(legend_filename)); map.addLayer(rlayer, true); map.setBounds2DImage(bounds, true); Dimension image_dim = null; image_dim = new Dimension((int) rlayer.raster.getDeviceBounds().getWidth() + 1, (int) rlayer.raster.getDeviceBounds().getHeight() + 1); if (output_maximum_size > 0) { double width_factor = image_dim.getWidth() / output_maximum_size; double height_factor = image_dim.getHeight() / output_maximum_size; double factor = Math.max(width_factor, height_factor); if (factor > 1.0) { image_dim.setSize(image_dim.getWidth() / factor, image_dim.getHeight() / factor); } } map.setImageDimension(image_dim); map.scale(); image_dim = new Dimension((int) map.getBounds2DImage().getWidth(), (int) map.getBounds2DImage().getHeight()); Image image = null; Graphics gr = null; image = ImageCreator.getImage(image_dim); gr = image.getGraphics(); try { map.paint(gr); } catch (Exception e) { Debug.println("map.paint error: " + e.getMessage()); } String tiff_filename = ""; try { tiff_filename = formatPath(category, timeseries, output_filename); new File(new_filename).mkdirs(); Debug.println("tiff_filename: " + tiff_filename); BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_BYTE_INDEXED); bi.createGraphics().drawImage(image, 0, 0, null); File f = new File(tiff_filename); FileOutputStream out = new FileOutputStream(f); TIFFEncodeParam param = new TIFFEncodeParam(); param.setCompression(TIFFEncodeParam.COMPRESSION_PACKBITS); TIFFImageEncoder encoder = (TIFFImageEncoder) TIFFCodec.createImageEncoder("tiff", out, param); encoder.encode(bi); out.close(); } catch (IOException e) { Debug.println("ImageCropper.generateTIFF TIFFCodec e: " + e.getMessage()); throw new IOException("GenerateTIFF.IOException: " + e); } PreparedStatement pstmt = null; try { String query = "select Proj_ID, AccessType_Code from project " + "where Proj_Code= '" + area_code.trim() + "'"; Statement stmt = null; ResultSet rs = null; int proj_id = -1; int access_code = -1; stmt = con.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { proj_id = rs.getInt(1); access_code = rs.getInt(2); } rs.close(); stmt.close(); String delete_raster = "delete from rasterlayer where " + "Raster_Name='" + tiff_name.trim() + "' and Group_Code='" + category.trim() + "' and Proj_ID =" + proj_id; Debug.println("***** delete_raster: " + delete_raster); pstmt = con.prepareStatement(delete_raster); boolean del = pstmt.execute(); pstmt.close(); String insert_raster = "insert into rasterlayer(Raster_Name, " + "Group_Code, Proj_ID, Raster_TimeCode, Raster_Xmin, " + "Raster_Ymin, Raster_Area_Xmin, Raster_Area_Ymin, " + "Raster_Visibility, Raster_Order, Raster_Path, " + "AccessType_Code, Raster_TimePeriod) values(?,?,?,?, " + "?,?,?,?,?,?,?,?,?)"; pstmt = con.prepareStatement(insert_raster); pstmt.setString(1, tiff_name); pstmt.setString(2, category); pstmt.setInt(3, proj_id); pstmt.setString(4, timeseries); pstmt.setDouble(5, raster_bounds.getX()); pstmt.setDouble(6, raster_bounds.getY()); pstmt.setDouble(7, raster_bounds.getWidth()); pstmt.setDouble(8, raster_bounds.getHeight()); pstmt.setString(9, "false"); int sequence = 0; if (tiff_name.endsWith("DP")) { sequence = 1; } else if (tiff_name.endsWith("DY")) { sequence = 2; } else if (tiff_name.endsWith("DA")) { sequence = 3; } pstmt.setInt(10, sequence); pstmt.setString(11, tiff_filename); pstmt.setInt(12, access_code); if (time == null) { pstmt.setNull(13, java.sql.Types.DATE); } else { pstmt.setDate(13, new java.sql.Date(time.getTimeInMillis())); } pstmt.executeUpdate(); } catch (SQLException e) { Debug.println("SQLException occurred e: " + e.getMessage()); con.rollback(); throw new SQLException("GenerateTIFF.SQLException: " + e); } finally { pstmt.close(); } } catch (Exception e) { Debug.println("ImageCropper.generateTIFF e: " + e.getMessage()); } Debug.println("ImageCropper.generateTIFF end"); } Code Sample 2: public String loadURLString(java.net.URL url) { try { BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String s = ""; while (br.ready() && s != null) { s = br.readLine(); if (s != null) { buf.append(s); buf.append("\n"); } } return buf.toString(); } catch (IOException ex) { return ""; } catch (NullPointerException npe) { return ""; } }
00
Code Sample 1: public void connect() throws IOException { if (log.isDebugEnabled()) log.debug("Connecting to: " + HOST); ftpClient.connect(HOST); if (log.isDebugEnabled()) log.debug("\tReply: " + ftpClient.getReplyString()); if (log.isDebugEnabled()) log.debug("Login as anonymous"); ftpClient.login("anonymous", ""); if (log.isDebugEnabled()) log.debug("\tReply: " + ftpClient.getReplyString()); folder = INTACT_FOLDER; } Code Sample 2: private static String md5(String digest, String data) throws IOException { MessageDigest messagedigest; try { messagedigest = MessageDigest.getInstance(digest); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } messagedigest.update(data.getBytes("ISO-8859-1")); byte[] bytes = messagedigest.digest(); StringBuilder stringbuffer = new StringBuilder(bytes.length * 2); for (int j = 0; j < bytes.length; j++) { int k = bytes[j] >>> 4 & 0x0f; stringbuffer.append(hexChars[k]); k = bytes[j] & 0x0f; stringbuffer.append(hexChars[k]); } return stringbuffer.toString(); }
11
Code Sample 1: private void unpackBundle() throws IOException { File useJarPath = null; if (DownloadManager.isWindowsVista()) { useJarPath = lowJarPath; File jarDir = useJarPath.getParentFile(); if (jarDir != null) { jarDir.mkdirs(); } } else { useJarPath = jarPath; } DownloadManager.log("Unpacking " + this + " to " + useJarPath); InputStream rawStream = new FileInputStream(localPath); JarInputStream in = new JarInputStream(rawStream) { public void close() throws IOException { } }; try { File jarTmp = null; JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { String entryName = entry.getName(); if (entryName.equals("classes.pack")) { File packTmp = new File(useJarPath + ".pack"); packTmp.getParentFile().mkdirs(); DownloadManager.log("Writing temporary .pack file " + packTmp); OutputStream tmpOut = new FileOutputStream(packTmp); try { DownloadManager.send(in, tmpOut); } finally { tmpOut.close(); } jarTmp = new File(useJarPath + ".tmp"); DownloadManager.log("Writing temporary .jar file " + jarTmp); unpack(packTmp, jarTmp); packTmp.delete(); } else if (!entryName.startsWith("META-INF")) { File dest; if (DownloadManager.isWindowsVista()) { dest = new File(lowJavaPath, entryName.replace('/', File.separatorChar)); } else { dest = new File(DownloadManager.JAVA_HOME, entryName.replace('/', File.separatorChar)); } if (entryName.equals(BUNDLE_JAR_ENTRY_NAME)) dest = useJarPath; File destTmp = new File(dest + ".tmp"); boolean exists = dest.exists(); if (!exists) { DownloadManager.log(dest + ".mkdirs()"); dest.getParentFile().mkdirs(); } try { DownloadManager.log("Using temporary file " + destTmp); FileOutputStream out = new FileOutputStream(destTmp); try { byte[] buffer = new byte[2048]; int c; while ((c = in.read(buffer)) > 0) out.write(buffer, 0, c); } finally { out.close(); } if (exists) dest.delete(); DownloadManager.log("Renaming from " + destTmp + " to " + dest); if (!destTmp.renameTo(dest)) { throw new IOException("unable to rename " + destTmp + " to " + dest); } } catch (IOException e) { if (!exists) throw e; } } } if (jarTmp != null) { if (useJarPath.exists()) jarTmp.delete(); else if (!jarTmp.renameTo(useJarPath)) { throw new IOException("unable to rename " + jarTmp + " to " + useJarPath); } } if (DownloadManager.isWindowsVista()) { DownloadManager.log("Using broker to move " + name); if (!DownloadManager.moveDirWithBroker(DownloadManager.getKernelJREDir() + name)) { throw new IOException("unable to create " + name); } DownloadManager.log("Broker finished " + name); } DownloadManager.log("Finished unpacking " + this); } finally { rawStream.close(); } if (deleteOnInstall) { localPath.delete(); } } Code Sample 2: public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { log.fatal("not a http request"); return; } HttpServletRequest httpRequest = (HttpServletRequest) request; String uri = httpRequest.getRequestURI(); int pathStartIdx = 0; String resourceName = null; pathStartIdx = uri.indexOf(path); if (pathStartIdx <= -1) { log.fatal("the url pattern must match: " + path + " found uri: " + uri); return; } resourceName = uri.substring(pathStartIdx + path.length()); int suffixIdx = uri.lastIndexOf('.'); if (suffixIdx <= -1) { log.fatal("no file suffix found for resource: " + uri); return; } String suffix = uri.substring(suffixIdx + 1).toLowerCase(); String mimeType = (String) mimeTypes.get(suffix); if (mimeType == null) { log.fatal("no mimeType found for resource: " + uri); log.fatal("valid mimeTypes are: " + mimeTypes.keySet()); return; } String themeName = getThemeName(); if (themeName == null) { themeName = this.themeName; } if (!themeName.startsWith("/")) { themeName = "/" + themeName; } InputStream is = null; is = ResourceFilter.class.getResourceAsStream(themeName + resourceName); if (is != null) { IOUtils.copy(is, response.getOutputStream()); response.setContentType(mimeType); response.flushBuffer(); IOUtils.closeQuietly(response.getOutputStream()); IOUtils.closeQuietly(is); } else { log.fatal("error loading resource: " + resourceName); } }
11
Code Sample 1: public RobotList<Float> sort_incr_Float(RobotList<Float> list, String field) { int length = list.size(); Index_value[] distri = new Index_value[length]; for (int i = 0; i < length; i++) { distri[i] = new Index_value(i, list.get(i)); } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (distri[i].value > distri[i + 1].value) { Index_value a = distri[i]; distri[i] = distri[i + 1]; distri[i + 1] = a; permut = true; } } } while (permut); RobotList<Float> sol = new RobotList<Float>(Float.class); for (int i = 0; i < length; i++) { sol.addLast(new Float(distri[i].value)); } return sol; } Code Sample 2: public static void main(String args[]) { int i, j, l; short NUMNUMBERS = 256; short numbers[] = new short[NUMNUMBERS]; Darjeeling.print("START"); for (l = 0; l < 100; l++) { for (i = 0; i < NUMNUMBERS; i++) numbers[i] = (short) (NUMNUMBERS - 1 - i); for (i = 0; i < NUMNUMBERS; i++) { for (j = 0; j < NUMNUMBERS - i - 1; j++) if (numbers[j] > numbers[j + 1]) { short temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } Darjeeling.print("END"); }
11
Code Sample 1: public static void copy(File src, File dest) throws IOException { log.info("Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath()); if (!src.exists()) throw new IOException("File not found: " + src.getAbsolutePath()); if (!src.canRead()) throw new IOException("Source not readable: " + src.getAbsolutePath()); if (src.isDirectory()) { if (!dest.exists()) if (!dest.mkdirs()) throw new IOException("Could not create direcotry: " + dest.getAbsolutePath()); String children[] = src.list(); for (String child : children) { File src1 = new File(src, child); File dst1 = new File(dest, child); copy(src1, dst1); } } else { FileInputStream fin = null; FileOutputStream fout = null; byte[] buffer = new byte[4096]; int bytesRead; fin = new FileInputStream(src); fout = new FileOutputStream(dest); while ((bytesRead = fin.read(buffer)) >= 0) fout.write(buffer, 0, bytesRead); if (fin != null) { fin.close(); } if (fout != null) { fout.close(); } } } Code Sample 2: private void copyFileToPhotoFolder(File photo, String personId) { try { FileChannel in = new FileInputStream(photo).getChannel(); File dirServer = new File(Constants.PHOTO_DIR); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.PHOTO_DIR + personId + ".jpg"); if (!fileServer.exists()) { fileServer.createNewFile(); } in.transferTo(0, in.size(), new FileOutputStream(fileServer).getChannel()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: boolean copyFileStructure(File oldFile, File newFile) { if (oldFile == null || newFile == null) return false; File searchFile = newFile; do { if (oldFile.equals(searchFile)) return false; searchFile = searchFile.getParentFile(); } while (searchFile != null); if (oldFile.isDirectory()) { if (progressDialog != null) { progressDialog.setDetailFile(oldFile, ProgressDialog.COPY); } if (simulateOnly) { } else { if (!newFile.mkdirs()) return false; } File[] subFiles = oldFile.listFiles(); if (subFiles != null) { if (progressDialog != null) { progressDialog.addWorkUnits(subFiles.length); } for (int i = 0; i < subFiles.length; i++) { File oldSubFile = subFiles[i]; File newSubFile = new File(newFile, oldSubFile.getName()); if (!copyFileStructure(oldSubFile, newSubFile)) return false; if (progressDialog != null) { progressDialog.addProgress(1); if (progressDialog.isCancelled()) return false; } } } } else { if (simulateOnly) { } else { FileReader in = null; FileWriter out = null; try { in = new FileReader(oldFile); out = new FileWriter(newFile); int count; while ((count = in.read()) != -1) out.write(count); } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { return false; } } } } return true; } Code Sample 2: public static void unzipModel(String filename, String tempdir) throws Exception { try { BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(filename); int BUFFER = 2048; ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { int count; byte data[] = new byte[BUFFER]; FileOutputStream fos = new FileOutputStream(tempdir + entry.getName()); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); } zis.close(); } catch (Exception e) { e.printStackTrace(); throw new Exception("Can not expand model in \"" + tempdir + "\" because:\n" + e.getMessage()); } }
11
Code Sample 1: public byte[] exportCommunityData(String communityId) throws RepositoryException, IOException { Community community; try { community = getCommunityById(communityId); } catch (CommunityNotFoundException e1) { throw new GroupwareRuntimeException("Community to export not found"); } String contentPath = JCRUtil.getNodeById(communityId, community.getWorkspace()).getPath(); try { File zipOutFilename = File.createTempFile("exported-community", ".zip.tmp"); TemporaryFilesHandler.register(null, zipOutFilename); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipOutFilename)); File file = File.createTempFile("exported-community", null); TemporaryFilesHandler.register(null, file); FileOutputStream fos = new FileOutputStream(file); exportCommunitySystemView(community, contentPath, fos); fos.close(); File propertiesFile = File.createTempFile("exported-community-properties", null); TemporaryFilesHandler.register(null, propertiesFile); FileOutputStream fosProperties = new FileOutputStream(propertiesFile); fosProperties.write(("communityId=" + communityId).getBytes()); fosProperties.write(";".getBytes()); fosProperties.write(("externalId=" + community.getExternalId()).getBytes()); fosProperties.write(";".getBytes()); fosProperties.write(("title=" + I18NUtils.localize(community.getTitle())).getBytes()); fosProperties.write(";".getBytes()); fosProperties.write(("communityType=" + community.getType()).getBytes()); fosProperties.write(";".getBytes()); fosProperties.write(("communityName=" + community.getName()).getBytes()); fosProperties.close(); FileInputStream finProperties = new FileInputStream(propertiesFile); byte[] bufferProperties = new byte[4096]; out.putNextEntry(new ZipEntry("properties")); int readProperties = 0; while ((readProperties = finProperties.read(bufferProperties)) > 0) { out.write(bufferProperties, 0, readProperties); } finProperties.close(); FileInputStream fin = new FileInputStream(file); byte[] buffer = new byte[4096]; out.putNextEntry(new ZipEntry("xmlData")); int read = 0; while ((read = fin.read(buffer)) > 0) { out.write(buffer, 0, read); } fin.close(); out.close(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileInputStream fisZipped = new FileInputStream(zipOutFilename); byte[] bufferOut = new byte[4096]; int readOut = 0; while ((readOut = fisZipped.read(bufferOut)) > 0) { baos.write(bufferOut, 0, readOut); } return baos.toByteArray(); } catch (Exception e) { String errorMessage = "Error exporting backup data, for comunnity with id " + communityId; log.error(errorMessage, e); throw new CMSRuntimeException(errorMessage, e); } } Code Sample 2: static void copy(String scr, String dest) throws IOException { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(scr); out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { closeIgnoringException(in); closeIgnoringException(out); } }
00
Code Sample 1: void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } } Code Sample 2: @Test public final void testImportODScontentXml() throws Exception { URL url = ODSTableImporterTest.class.getResource("/Messages.ods_FILES/content.xml"); String systemId = url.getPath(); InputStream in = url.openStream(); ODSTableImporter b = new ODSTableImporter(); b.importODSContentXml(systemId, in, null); assertMessagesOds(b); }
00
Code Sample 1: @SuppressWarnings({ "ProhibitedExceptionDeclared" }) public int run(@NotNull final List<String> args) throws Exception { int returnCode = 0; if (args.size() == 0) { log(Level.SEVERE, "noarguments"); returnCode++; } final byte[] buf = new byte[BUF_SIZE]; for (final String arg : args) { try { final URL url = new URL(arg); final URLConnection con = url.openConnection(); final InputStream in = con.getInputStream(); try { final String location = con.getHeaderField("Content-Location"); final String outputFilename = new File((location != null ? new URL(url, location) : url).getFile()).getName(); log(Level.INFO, "writing", arg, outputFilename); final OutputStream out = new FileOutputStream(outputFilename); try { for (int bytesRead; (bytesRead = in.read(buf)) != -1; ) { out.write(buf, 0, bytesRead); } } finally { out.close(); } } finally { in.close(); } } catch (final IOException e) { log(Level.WARNING, "cannotopen", arg, e); returnCode++; } } return returnCode; } Code Sample 2: public APIResponse delete(String id) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/item/delete/" + id).openConnection(); connection.setRequestMethod("DELETE"); connection.setConnectTimeout(TIMEOUT); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { response.setDone(true); response.setMessage("Item Deleted!"); } else { response.setDone(false); response.setMessage("Delete Item Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; }
11
Code Sample 1: public void extractSong(Song s, File dir) { FileInputStream fin = null; FileOutputStream fout = null; File dest = new File(dir, s.file.getName()); if (dest.equals(s.file)) return; byte[] buf = new byte[COPY_BLOCKSIZE]; try { fin = new FileInputStream(s.file); fout = new FileOutputStream(dest); int read = 0; do { read = fin.read(buf); if (read > 0) fout.write(buf, 0, read); } while (read > 0); } catch (IOException ex) { ex.printStackTrace(); Dialogs.showErrorDialog("xtract.error"); } finally { try { fin.close(); fout.close(); } catch (Exception ex) { } } } Code Sample 2: public static void write(File file, InputStream source) throws IOException { OutputStream outputStream = null; assert file != null : "file must not be null."; assert file.isFile() : "file must be a file."; assert file.canWrite() : "file must be writable."; assert source != null : "source must not be null."; try { outputStream = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(source, outputStream); outputStream.flush(); } finally { IOUtils.closeQuietly(outputStream); } }
00
Code Sample 1: private int saveToTempTable(ArrayList cons, String tempTableName, boolean truncateFirst) throws SQLException { if (truncateFirst) { this.executeUpdate("TRUNCATE TABLE " + tempTableName); Categories.dataDb().debug("TABLE " + tempTableName + " TRUNCATED."); } PreparedStatement ps = null; int rows = 0; try { String insert = "INSERT INTO " + tempTableName + " VALUES (?)"; ps = this.conn.prepareStatement(insert); for (int i = 0; i < cons.size(); i++) { ps.setLong(1, ((Long) cons.get(i)).longValue()); rows = ps.executeUpdate(); if ((i % 500) == 0) { this.conn.commit(); } } this.conn.commit(); } catch (SQLException sqle) { this.conn.rollback(); throw sqle; } finally { if (ps != null) { ps.close(); } } return rows; } Code Sample 2: public String output(final ComponentParameter compParameter) { InputStream inputStream; try { final URL url = new URL("http://xml.weather.yahoo.com/forecastrss?p=" + getPagelet().getOptionProperty("_weather_code") + "&u=c"); inputStream = url.openStream(); } catch (final IOException e) { return e.getMessage(); } final StringBuilder sb = new StringBuilder(); new AbstractXmlDocument(inputStream) { @Override protected void init() throws Exception { final Element root = getRoot(); final Namespace ns = root.getNamespaceForPrefix("yweather"); final Element channel = root.element("channel"); final String link = channel.elementText("link"); final Element item = channel.element("item"); Element ele = item.element(QName.get("condition", ns)); if (ele == null) { sb.append("ERROR"); return; } final String imgPath = getPagelet().getColumnBean().getPortalBean().getCssResourceHomePath(compParameter) + "/images/yahoo/"; String text, image; Date date = new SimpleDateFormat(YahooWeatherUtils.RFC822_MASKS[1], Locale.US).parse(ele.attributeValue("date")); final int temp = Integer.parseInt(ele.attributeValue("temp")); int code = Integer.valueOf(ele.attributeValue("code")).intValue(); if (code == 3200) { text = YahooWeatherUtils.yahooTexts[YahooWeatherUtils.yahooTexts.length - 1]; image = imgPath + "3200.gif"; } else { text = YahooWeatherUtils.yahooTexts[code]; image = imgPath + code + ".gif"; } sb.append("<div style=\"line-height: normal;\"><a target=\"_blank\" href=\"").append(link).append("\"><img src=\""); sb.append(image).append("\" /></a>"); sb.append(YahooWeatherUtils.formatHour(date)).append(" - "); sb.append(text).append(" - ").append(temp).append("℃").append("<br>"); final Iterator<?> it = item.elementIterator(QName.get("forecast", ns)); while (it.hasNext()) { ele = (Element) it.next(); date = new SimpleDateFormat("dd MMM yyyy", Locale.US).parse(ele.attributeValue("date")); final int low = Integer.parseInt(ele.attributeValue("low")); final int high = Integer.parseInt(ele.attributeValue("high")); code = Integer.valueOf(ele.attributeValue("code")).intValue(); if (code == 3200) { text = YahooWeatherUtils.yahooTexts[YahooWeatherUtils.yahooTexts.length - 1]; image = imgPath + "3200.gif"; } else { text = YahooWeatherUtils.yahooTexts[code]; image = imgPath + code + ".gif"; } sb.append(YahooWeatherUtils.formatWeek(date)).append(" ( "); sb.append(text).append(". "); sb.append(low).append("℃~").append(high).append("℃"); sb.append(" )<br>"); } sb.append("</div>"); } }; return sb.toString(); }
11
Code Sample 1: void copyFile(String from, String to) throws IOException { File destFile = new File(to); if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(from).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public void xtest12() throws Exception { PDFManager manager = new ITextManager(); InputStream pdf = new FileInputStream("/tmp/090237098008f637.pdf"); InputStream page1 = manager.cut(pdf, 36, 36); OutputStream outputStream = new FileOutputStream("/tmp/090237098008f637-1.pdf"); IOUtils.copy(page1, outputStream); outputStream.close(); pdf.close(); }
11
Code Sample 1: private void moveFile(File orig, File target) throws IOException { byte buffer[] = new byte[1000]; int bread = 0; FileInputStream fis = new FileInputStream(orig); FileOutputStream fos = new FileOutputStream(target); while (bread != -1) { bread = fis.read(buffer); if (bread != -1) fos.write(buffer, 0, bread); } fis.close(); fos.close(); orig.delete(); } Code Sample 2: public SWORDEntry ingestDepost(final DepositCollection pDeposit, final ServiceDocument pServiceDocument) throws SWORDException { try { ZipFileAccess tZipFile = new ZipFileAccess(super.getTempDir()); LOG.debug("copying file"); String tZipTempFileName = super.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tZipTempFileName)); Datastream tDatastream = new LocalDatastream(super.getGenericFileName(pDeposit), this.getContentType(), tZipTempFileName); _datastreamList.add(tDatastream); _datastreamList.addAll(tZipFile.getFiles(tZipTempFileName)); int i = 0; boolean found = false; for (i = 0; i < _datastreamList.size(); i++) { if (_datastreamList.get(i).getId().equalsIgnoreCase("mets")) { found = true; break; } } if (found) { SAXBuilder tBuilder = new SAXBuilder(); _mets = new METSObject(tBuilder.build(((LocalDatastream) _datastreamList.get(i)).getPath())); LocalDatastream tLocalMETSDS = (LocalDatastream) _datastreamList.remove(i); new File(tLocalMETSDS.getPath()).delete(); _datastreamList.add(_mets.getMETSDs()); _datastreamList.addAll(_mets.getMetadataDatastreams()); } else { throw new SWORDException("Couldn't find a METS document in the zip file, ensure it is named mets.xml or METS.xml"); } SWORDEntry tEntry = super.ingestDepost(pDeposit, pServiceDocument); tZipFile.removeLocalFiles(); return tEntry; } catch (IOException tIOExcpt) { String tMessage = "Couldn't retrieve METS from deposit: " + tIOExcpt.toString(); LOG.error(tMessage); tIOExcpt.printStackTrace(); throw new SWORDException(tMessage, tIOExcpt); } catch (JDOMException tJDOMExcpt) { String tMessage = "Couldn't build METS from deposit: " + tJDOMExcpt.toString(); LOG.error(tMessage); tJDOMExcpt.printStackTrace(); throw new SWORDException(tMessage, tJDOMExcpt); } }
00
Code Sample 1: private static String getWebPage(String urlString) throws Exception { URL url; HttpURLConnection conn; BufferedReader rd; String line; StringBuilder result = new StringBuilder(); try { url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { result.append(line); } rd.close(); } catch (Exception e) { e.printStackTrace(); } return result.toString(); } Code Sample 2: private void transferFile(String fileName) throws SocketException, IOException, Exception { FTPClient client = new FTPClient(); client.connect(server.getExternalName(), server.getPort()); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new Exception("Failed connecting to server"); } client.login(server.getDefaultUserName(), server.getDefaultUserPassword()); reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new Exception("Failed connecting to server"); } InputStream stream = getClass().getClassLoader().getResourceAsStream("res/conf/ftpd.properties"); client.storeFile(fileName, stream); File transfferedFile = new File(server.getServerRootDirectory(), fileName); assertTrue(transfferedFile.exists()); assertTrue(transfferedFile.delete()); }
00
Code Sample 1: @Override public void exec() { if (fileURI == null) return; InputStream is = null; try { if (fileURI.toLowerCase().startsWith("dbgp://")) { String uri = fileURI.substring(7); if (uri.toLowerCase().startsWith("file/")) { uri = fileURI.substring(5); is = new FileInputStream(new File(uri)); } else { XmldbURI pathUri = XmldbURI.create(URLDecoder.decode(fileURI.substring(15), "UTF-8")); Database db = getJoint().getContext().getDatabase(); DBBroker broker = null; try { broker = db.getBroker(); DocumentImpl resource = broker.getXMLResource(pathUri, Lock.READ_LOCK); if (resource.getResourceType() == DocumentImpl.BINARY_FILE) { is = broker.getBinaryResource((BinaryDocument) resource); } else { return; } } catch (EXistException e) { exception = e; } finally { db.release(broker); } } } else { URL url = new URL(fileURI); URLConnection conn = url.openConnection(); is = conn.getInputStream(); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[256]; int c; while ((c = is.read(buf)) > -1) { baos.write(buf, 0, c); } source = baos.toByteArray(); success = true; } catch (MalformedURLException e) { exception = e; } catch (IOException e) { exception = e; } catch (PermissionDeniedException e) { exception = e; } finally { if (is != null) try { is.close(); } catch (IOException e) { if (exception == null) exception = e; } } } Code Sample 2: public static String replace(URL url, Replacer replacer) throws Exception { URLConnection con = url.openConnection(); InputStreamReader reader = new InputStreamReader(con.getInputStream()); StringWriter wr = new StringWriter(); int c; StringBuffer token = null; while ((c = reader.read()) != -1) { if (c == '@') { if (token == null) { token = new StringBuffer(); } else { String val = replacer.replace(token.toString()); if (val != null) { wr.write(val); token = null; } else { wr.write('@'); wr.write(token.toString()); token.delete(0, token.length()); } } } else { if (token == null) { wr.write((char) c); } else { token.append((char) c); } } } if (token != null) { wr.write('@'); wr.write(token.toString()); } return wr.toString(); }
11
Code Sample 1: private ArrayList<Stock> fetchStockData(Stock[] stocks) throws IOException { Log.d(TAG, "Fetching stock data from Yahoo"); ArrayList<Stock> newStocks = new ArrayList<Stock>(stocks.length); if (stocks.length > 0) { StringBuilder sb = new StringBuilder(); for (Stock stock : stocks) { sb.append(stock.getSymbol()); sb.append('+'); } sb.deleteCharAt(sb.length() - 1); String urlStr = "http://finance.yahoo.com/d/quotes.csv?f=sb2n&s=" + sb.toString(); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(urlStr.toString()); HttpResponse response = client.execute(request); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = reader.readLine(); int i = 0; Log.d(TAG, "Parsing stock data from Yahoo"); while (line != null) { Log.d(TAG, "Parsing: " + line); String[] values = line.split(","); Stock stock = new Stock(stocks[i], stocks[i].getId()); stock.setCurrentPrice(Double.parseDouble(values[1])); stock.setName(values[2]); Log.d(TAG, "Parsed Stock: " + stock); newStocks.add(stock); line = reader.readLine(); i++; } } return newStocks; } Code Sample 2: void loadSVG(String svgFileURL) { try { URL url = new URL(svgFileURL); URLConnection c = url.openConnection(); c.setRequestProperty("Accept-Encoding", "gzip"); InputStream is = c.getInputStream(); String encoding = c.getContentEncoding(); if ("gzip".equals(encoding) || "x-gzip".equals(encoding) || svgFileURL.toLowerCase().endsWith(".svgz")) { is = new GZIPInputStream(is); } is = new BufferedInputStream(is); Document svgDoc = AppletUtils.parse(is, false); if (svgDoc != null) { if (grMngr.mainView.isBlank() == null) { grMngr.mainView.setBlank(cfgMngr.backgroundColor); } SVGReader.load(svgDoc, grMngr.mSpace, true, svgFileURL); grMngr.seekBoundingBox(); grMngr.buildLogicalStructure(); ConfigManager.defaultFont = VText.getMainFont(); grMngr.reveal(); if (grMngr.previousLocations.size() == 1) { grMngr.previousLocations.removeElementAt(0); } if (grMngr.rView != null) { grMngr.rView.getGlobalView(grMngr.mSpace.getCamera(1), 100); } grMngr.cameraMoved(null, null, 0); } else { System.err.println("An error occured while loading file " + svgFileURL); } } catch (Exception ex) { grMngr.reveal(); ex.printStackTrace(); } }
11
Code Sample 1: public void resumereceive(HttpServletRequest req, HttpServletResponse resp, SessionCommand command) { setHeader(resp); try { logger.debug("ResRec: Resume a 'receive' session with session id " + command.getSession() + " this client already received " + command.getLen() + " bytes"); File tempFile = new File(this.getSyncWorkDirectory(req), command.getSession() + ".smodif"); if (!tempFile.exists()) { logger.debug("ResRec: the file doesn't exist, so we created it by serializing the entities"); try { OutputStream fos = new FileOutputStream(tempFile); syncServer.getServerModifications(command.getSession(), fos); fos.close(); } catch (ImogSerializationException mse) { logger.error(mse.getMessage(), mse); } } InputStream fis = new FileInputStream(tempFile); fis.skip(command.getLen()); resp.setContentLength(fis.available()); while (fis.available() > 0) { resp.getOutputStream().write(fis.read()); } resp.getOutputStream().flush(); resp.flushBuffer(); fis.close(); } catch (IOException ioe) { logger.error(ioe.getMessage()); } } Code Sample 2: public void testAddFiles() throws Exception { File original = ZipPlugin.getFileInPlugin(new Path("testresources/test.zip")); File copy = new File(original.getParentFile(), "1test.zip"); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(original); out = new FileOutputStream(copy); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } ArchiveFile archive = new ArchiveFile(ZipPlugin.createArchive(copy.getPath())); archive.addFiles(new String[] { ZipPlugin.getFileInPlugin(new Path("testresources/add.txt")).getPath() }, new NullProgressMonitor()); IArchive[] children = archive.getChildren(); boolean found = false; for (IArchive child : children) { if (child.getLabel(IArchive.NAME).equals("add.txt")) found = true; } assertTrue(found); copy.delete(); }
00
Code Sample 1: @Override public RoleItem addUserRole(RoleItem role, long userId) throws DatabaseException { if (role == null) throw new NullPointerException("role"); if (role.getName() == null || "".equals(role.getName())) throw new NullPointerException("role.getName()"); if (hasRole(role.getName(), userId)) { return new RoleItem(role.getName(), "", "exist"); } RoleItem defaultRole = new RoleItem(role.getName(), "", "exist"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } String retID = "exist"; String roleDesc = ""; PreparedStatement seqSt = null, roleDescSt = null; try { int modified = 0; PreparedStatement insSt = getConnection().prepareStatement(INSERT_USER_IN_ROLE_STATEMENT); insSt.setLong(1, userId); insSt.setString(2, role.getName()); modified = insSt.executeUpdate(); seqSt = getConnection().prepareStatement(USER_ROLE_VALUE); ResultSet rs = seqSt.executeQuery(); while (rs.next()) { retID = rs.getString(1); } roleDescSt = getConnection().prepareStatement(SELECT_ROLE_DESCRIPTION); roleDescSt.setString(1, role.getName()); ResultSet rs2 = roleDescSt.executeQuery(); while (rs2.next()) { roleDesc = rs2.getString(1); } if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + seqSt + "\" and \"" + roleDescSt + "\""); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback! Queries: \"" + seqSt + "\" and \"" + roleDescSt + "\""); retID = "error"; } } catch (SQLException e) { LOGGER.error(e); retID = "error"; } finally { closeConnection(); } defaultRole.setId(retID); defaultRole.setDescription(roleDesc); return defaultRole; } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: @Override public byte[] read(String path) throws PersistenceException { InputStream reader = null; ByteArrayOutputStream sw = new ByteArrayOutputStream(); try { reader = new FileInputStream(path); IOUtils.copy(reader, sw); } catch (Exception e) { LOGGER.error("fail to read file - " + path, e); throw new PersistenceException(e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { LOGGER.error("fail to close reader", e); } } } return sw.toByteArray(); } Code Sample 2: private ByteBuffer getByteBuffer(String resource) throws IOException { ClassLoader classLoader = this.getClass().getClassLoader(); InputStream in = classLoader.getResourceAsStream(resource); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); return ByteBuffer.wrap(out.toByteArray()); }
11
Code Sample 1: public static java.io.ByteArrayOutputStream getFileByteStream(URL _url) { java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream(); try { InputStream input = _url.openStream(); IOUtils.copy(input, buffer); IOUtils.closeQuietly(input); } catch (Exception err) { throw new RuntimeException(err); } return buffer; } Code Sample 2: public void xtestGetThread() throws Exception { GMSearchOptions options = new GMSearchOptions(); options.setFrom(loginInfo.getUsername() + "*"); options.setSubject("message*"); GMSearchResponse mail = client.getMail(options); for (Iterator it = mail.getThreadSnapshots().iterator(); it.hasNext(); ) { GMThreadSnapshot threadSnapshot = (GMThreadSnapshot) it.next(); GMThread thread = client.getThread(threadSnapshot.getThreadID()); log.info("Most Recent Thread: " + thread); for (Iterator iter = thread.getMessages().iterator(); iter.hasNext(); ) { GMMessage message = (GMMessage) iter.next(); log.info("Message: " + message); Iterable<GMAttachment> attachments = message.getAttachments(); for (Iterator iterator = attachments.iterator(); iterator.hasNext(); ) { GMAttachment attachment = (GMAttachment) iterator.next(); String ext = FilenameUtils.getExtension(attachment.getFilename()); if (ext.trim().length() > 0) ext = "." + ext; String base = FilenameUtils.getBaseName(attachment.getFilename()); File file = File.createTempFile(base, ext, new File(System.getProperty("user.home"))); log.info("Saving attachment: " + file.getPath()); InputStream attStream = client.getAttachmentAsStream(attachment.getId(), message.getMessageID()); IOUtils.copy(attStream, new FileOutputStream(file)); attStream.close(); assertEquals(file.length(), attachment.getSize()); log.info("Done. Successfully saved: " + file.getPath()); file.delete(); } } } }
00
Code Sample 1: private static synchronized InputStream tryFailoverServer(String url, String currentlyActiveServer, int status, IOException e) throws MalformedURLException, IOException { logger.log(Level.WARNING, "problems connecting to geonames server " + currentlyActiveServer, e); if (geoNamesServerFailover == null || currentlyActiveServer.equals(geoNamesServerFailover)) { if (currentlyActiveServer.equals(geoNamesServerFailover)) { timeOfLastFailureMainServer = 0; } throw e; } timeOfLastFailureMainServer = System.currentTimeMillis(); logger.info("trying to connect to failover server " + geoNamesServerFailover); URLConnection conn = new URL(geoNamesServerFailover + url).openConnection(); String userAgent = USER_AGENT + " failover from " + geoNamesServer; if (status != 0) { userAgent += " " + status; } conn.setRequestProperty("User-Agent", userAgent); InputStream in = conn.getInputStream(); return in; } Code Sample 2: public static InputStream download(String endereco, ProxyConfig proxy) { if (proxy != null) { System.getProperties().put("proxySet", "true"); System.getProperties().put("proxyPort", proxy.getPorta()); System.getProperties().put("proxyHost", proxy.getHost()); Authenticator.setDefault(new ProxyAuthenticator(proxy.getUsuario(), proxy.getSenha())); } try { URL url = new URL(endereco); ; URLConnection connection = url.openConnection(); InputStream bis = new BufferedInputStream(connection.getInputStream()); return bis; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
00
Code Sample 1: public RobotList<Location> sort_decr_Location(RobotList<Location> list, String field) { int length = list.size(); Index_value[] enemy_dist = new Index_value[length]; if (field.equals("") || field.equals("location")) { Location cur_loc = this.getLocation(); for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, distance(cur_loc, list.get(i))); } } else if (field.equals("x")) { for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, list.get(i).x); } } else if (field.equals("y")) { for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, list.get(i).y); } } else { say("impossible to sort list - nothing modified"); return list; } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (enemy_dist[i].value < enemy_dist[i + 1].value) { Index_value a = enemy_dist[i]; enemy_dist[i] = enemy_dist[i + 1]; enemy_dist[i + 1] = a; permut = true; } } } while (permut); RobotList<Location> new_location_list = new RobotList<Location>(Location.class); for (int i = 0; i < length; i++) { new_location_list.addLast(list.get(enemy_dist[i].index)); } return new_location_list; } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
00
Code Sample 1: public static final String crypt(final String password, String salt, final String magic) { if (password == null) throw new IllegalArgumentException("Null password!"); if (salt == null) throw new IllegalArgumentException("Null salt!"); if (magic == null) throw new IllegalArgumentException("Null salt!"); byte finalState[]; long l; MessageDigest ctx, ctx1; try { ctx = MessageDigest.getInstance("md5"); ctx1 = MessageDigest.getInstance("md5"); } catch (final NoSuchAlgorithmException ex) { System.err.println(ex); return null; } if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } if (salt.indexOf('$') != -1) { salt = salt.substring(0, salt.indexOf('$')); } if (salt.length() > 8) { salt = salt.substring(0, 8); } ctx.update(password.getBytes()); ctx.update(magic.getBytes()); ctx.update(salt.getBytes()); ctx1.update(password.getBytes()); ctx1.update(salt.getBytes()); ctx1.update(password.getBytes()); finalState = ctx1.digest(); for (int pl = password.length(); pl > 0; pl -= 16) { ctx.update(finalState, 0, pl > 16 ? 16 : pl); } clearbits(finalState); for (int i = password.length(); i != 0; i >>>= 1) { if ((i & 1) != 0) { ctx.update(finalState, 0, 1); } else { ctx.update(password.getBytes(), 0, 1); } } finalState = ctx.digest(); for (int i = 0; i < 1000; i++) { try { ctx1 = MessageDigest.getInstance("md5"); } catch (final NoSuchAlgorithmException e0) { return null; } if ((i & 1) != 0) { ctx1.update(password.getBytes()); } else { ctx1.update(finalState, 0, 16); } if ((i % 3) != 0) { ctx1.update(salt.getBytes()); } if ((i % 7) != 0) { ctx1.update(password.getBytes()); } if ((i & 1) != 0) { ctx1.update(finalState, 0, 16); } else { ctx1.update(password.getBytes()); } finalState = ctx1.digest(); } final StringBuffer result = new StringBuffer(); result.append(magic); result.append(salt); result.append("$"); l = (bytes2u(finalState[0]) << 16) | (bytes2u(finalState[6]) << 8) | bytes2u(finalState[12]); result.append(to64(l, 4)); l = (bytes2u(finalState[1]) << 16) | (bytes2u(finalState[7]) << 8) | bytes2u(finalState[13]); result.append(to64(l, 4)); l = (bytes2u(finalState[2]) << 16) | (bytes2u(finalState[8]) << 8) | bytes2u(finalState[14]); result.append(to64(l, 4)); l = (bytes2u(finalState[3]) << 16) | (bytes2u(finalState[9]) << 8) | bytes2u(finalState[15]); result.append(to64(l, 4)); l = (bytes2u(finalState[4]) << 16) | (bytes2u(finalState[10]) << 8) | bytes2u(finalState[5]); result.append(to64(l, 4)); l = bytes2u(finalState[11]); result.append(to64(l, 2)); clearbits(finalState); return result.toString(); } Code Sample 2: public static Image getPluginImage(Object plugin, String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; }
00
Code Sample 1: public static String getStringResponse(String urlString) throws Exception { URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; StringBuilder buffer = new StringBuilder(); while ((inputLine = in.readLine()) != null) { buffer.append(inputLine); } in.close(); return buffer.toString(); } Code Sample 2: public static boolean verify(String password, String encryptedPassword) { MessageDigest digest = null; int size = 0; String base64 = null; if (encryptedPassword.regionMatches(true, 0, "{CRYPT}", 0, 7)) { throw new InternalError("Not implemented"); } else if (encryptedPassword.regionMatches(true, 0, "{SHA}", 0, 5)) { size = 20; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SSHA}", 0, 6)) { size = 20; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{MD5}", 0, 5)) { size = 16; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SMD5}", 0, 6)) { size = 16; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else { return false; } byte[] data = Base64.decode(base64.toCharArray()); byte[] orig = new byte[size]; System.arraycopy(data, 0, orig, 0, size); digest.reset(); digest.update(password.getBytes()); if (data.length > size) { digest.update(data, size, data.length - size); } return MessageDigest.isEqual(digest.digest(), orig); }
00
Code Sample 1: private void bokActionPerformed(java.awt.event.ActionEvent evt) { Vector vret = this.uniformtitlepanel.getEnteredValuesKeys(); String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds(); String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveUniformTitleSH("2", vret, patlib); System.out.println(xmlreq); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "UniformTitleSubjectHeadingServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); if (rootelement.getChild("Error") == null) { this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase")); } else { this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor")); } } catch (Exception e) { System.out.println(e); } } Code Sample 2: public static void copyFile(String hostname, String url, String username, String password, File targetFile) throws Exception { org.apache.commons.httpclient.HttpClient client = WebDavUtility.initClient("files-cert.rxhub.net", username, password); HttpMethod method = new GetMethod(url); client.executeMethod(method); BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(targetFile)); IOUtils.copyLarge(method.getResponseBodyAsStream(), output); }
11
Code Sample 1: private void btnOkActionPerformed(java.awt.event.ActionEvent evt) { if (validateData()) { LoginUser me = AdministrationPanelView.getMe(); Connection dbConnection = null; try { DriverManager.registerDriver(new com.mysql.jdbc.Driver()); dbConnection = DriverManager.getConnection(me.getSqlReportsURL(), me.getSqlReportsUser(), me.getSqlReportsPassword()); dbConnection.setAutoCommit(false); dbConnection.setSavepoint(); String sql = "INSERT INTO campaigns (type, name, dateCreated, createdBy) VALUES (?, ?, ?, ?)"; PreparedStatement statement = dbConnection.prepareStatement(sql); statement.setByte(1, (optTypeAgents.isSelected()) ? CampaignStatics.CAMP_TYPE_AGENT : CampaignStatics.CAMP_TYPE_IVR); statement.setString(2, txtCampaignName.getText()); statement.setTimestamp(3, new Timestamp(Calendar.getInstance().getTime().getTime())); statement.setLong(4, me.getId()); statement.executeUpdate(); ResultSet rs = statement.getGeneratedKeys(); rs.next(); long campaignId = rs.getLong(1); sql = "INSERT INTO usercampaigns (userid, campaignid, role) VALUES (?, ?, ?)"; statement = dbConnection.prepareStatement(sql); statement.setLong(1, me.getId()); statement.setLong(2, campaignId); statement.setString(3, "admin"); statement.executeUpdate(); dbConnection.commit(); dbConnection.close(); CampaignAdmin ca = new CampaignAdmin(); ca.setCampaign(txtCampaignName.getText()); ca.setVisible(true); dispose(); } catch (SQLException ex) { try { dbConnection.rollback(); } catch (SQLException ex1) { Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex1); } JOptionPane.showMessageDialog(this.getRootPane(), ex.getLocalizedMessage(), "Error", JOptionPane.ERROR_MESSAGE); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex); } } } Code Sample 2: @Override public void backup() { Connection connection = null; PreparedStatement prestm = null; try { if (logger.isInfoEnabled()) logger.info("backup table " + getOrigin() + " start..."); Class.forName(driver); connection = DriverManager.getConnection(url, username, password); String tableExistsResult = ""; prestm = connection.prepareStatement("show tables from " + schema + " like '" + getDestination() + "';"); ResultSet rs = prestm.executeQuery(); if (rs.next()) tableExistsResult = rs.getString(1); rs.close(); prestm.close(); if (StringUtils.isBlank(tableExistsResult)) { String createTableSql = ""; prestm = connection.prepareStatement("show create table " + getOrigin() + ";"); rs = prestm.executeQuery(); if (rs.next()) createTableSql = rs.getString(2); rs.close(); prestm.close(); createTableSql = createTableSql.replaceAll("`" + getOrigin() + "`", "`" + getDestination() + "`"); createTableSql = createTableSql.replaceAll("auto_increment", ""); createTableSql = createTableSql.replaceAll("AUTO_INCREMENT", ""); Matcher matcher = stripRelationTablePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll(""); matcher = normalizePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll("\n )"); Statement stm = connection.createStatement(); stm.execute(createTableSql); if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' created!"); } else if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' already exists"); Date date = new Date(); date.setTime(TimeUtil.addHours(date, -getHours()).getTimeInMillis()); date.setTime(TimeUtil.getTodayAtMidnight().getTimeInMillis()); if (logger.isInfoEnabled()) logger.info("backuping records before: " + date); long currentRows = 0L; prestm = connection.prepareStatement("select count(*) from " + getOrigin() + " where " + getCondition() + ""); java.sql.Date sqlDate = new java.sql.Date(date.getTime()); prestm.setDate(1, sqlDate); rs = prestm.executeQuery(); if (rs.next()) currentRows = rs.getLong(1); rs.close(); prestm.close(); if (currentRows > 0) { connection.setAutoCommit(false); prestm = connection.prepareStatement("INSERT INTO " + getDestination() + " SELECT * FROM " + getOrigin() + " WHERE " + getCondition()); prestm.setDate(1, sqlDate); int rows = prestm.executeUpdate(); prestm.close(); if (logger.isInfoEnabled()) logger.info(rows + " rows backupped"); prestm = connection.prepareStatement("DELETE FROM " + getOrigin() + " WHERE " + getCondition()); prestm.setDate(1, sqlDate); rows = prestm.executeUpdate(); prestm.close(); connection.commit(); if (logger.isInfoEnabled()) logger.info(rows + " rows deleted"); } else if (logger.isInfoEnabled()) logger.info("no backup need"); if (logger.isInfoEnabled()) logger.info("backup table " + getOrigin() + " end"); } catch (SQLException e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "dbcon", "Errore SQL durante il backup dei dati della tabella " + getOrigin(), e)); try { connection.rollback(); } catch (SQLException e1) { } } catch (Throwable e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "generic", "Errore generico durante il backup dei dati della tabella " + getOrigin(), e)); try { connection.rollback(); } catch (SQLException e1) { } } finally { try { if (prestm != null) prestm.close(); } catch (SQLException e) { } try { if (connection != null) connection.close(); } catch (SQLException e) { } } }
11
Code Sample 1: private void createSoundbank(String testSoundbankFileName) throws Exception { System.out.println("Create soundbank"); File packageDir = new File("testsoundbank"); if (packageDir.exists()) { for (File file : packageDir.listFiles()) assertTrue(file.delete()); assertTrue(packageDir.delete()); } packageDir.mkdir(); String sourceFileName = "testsoundbank/TestSoundBank.java"; File sourceFile = new File(sourceFileName); FileWriter writer = new FileWriter(sourceFile); writer.write("package testsoundbank;\n" + "public class TestSoundBank extends com.sun.media.sound.ModelAbstractOscillator { \n" + " @Override public int read(float[][] buffers, int offset, int len) throws java.io.IOException { \n" + " return 0;\n" + " }\n" + " @Override public String getVersion() {\n" + " return \"" + (soundbankRevision++) + "\";\n" + " }\n" + "}\n"); writer.close(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File("."))); compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile))).call(); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testSoundbankFileName)); ZipEntry ze = new ZipEntry("META-INF/services/javax.sound.midi.Soundbank"); zos.putNextEntry(ze); zos.write("testsoundbank.TestSoundBank".getBytes()); ze = new ZipEntry("testsoundbank/TestSoundBank.class"); zos.putNextEntry(ze); FileInputStream fis = new FileInputStream("testsoundbank/TestSoundBank.class"); int b = fis.read(); while (b != -1) { zos.write(b); b = fis.read(); } zos.close(); } Code Sample 2: public void guardarCantidad() { try { String can = String.valueOf(cantidadArchivos); File archivo = new File("cantidadArchivos.txt"); FileWriter fw = new FileWriter(archivo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter salida = new PrintWriter(bw); salida.print(can); salida.close(); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("cantidadArchivos.zip"); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[buffer]; File f = new File("cantidadArchivos.txt"); FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, buffer); ZipEntry entry = new ZipEntry("cantidadArchivos.txt"); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, buffer)) != -1) out.write(data, 0, count); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
00
Code Sample 1: public long copyDirAllFilesToDirectory(String baseDirStr, String destDirStr) throws Exception { long plussQuotaSize = 0; if (baseDirStr.endsWith(sep)) { baseDirStr = baseDirStr.substring(0, baseDirStr.length() - 1); } if (destDirStr.endsWith(sep)) { destDirStr = destDirStr.substring(0, destDirStr.length() - 1); } FileUtils.getInstance().createDirectory(destDirStr); BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File baseDir = new File(baseDirStr); baseDir.mkdirs(); if (!baseDir.exists()) { createDirectory(baseDirStr); } if ((baseDir.exists()) && (baseDir.isDirectory())) { String[] entryList = baseDir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String oldPathFileName = baseDirStr + sep + entryName; File entryFile = new File(oldPathFileName); if (entryFile.isFile()) { String newPathFileName = destDirStr + sep + entryName; File newFile = new File(newPathFileName); if (newFile.exists()) { plussQuotaSize -= newFile.length(); newFile.delete(); } in = new BufferedInputStream(new FileInputStream(oldPathFileName), bufferSize); out = new BufferedOutputStream(new FileOutputStream(newPathFileName), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } } } } else { throw new Exception("Base dir not exist ! baseDirStr = (" + baseDirStr + ")"); } return plussQuotaSize; } Code Sample 2: public Properties load() { Properties lvProperties = new Properties(); try { InputStream lvInputStream = url.openStream(); lvProperties.load(lvInputStream); } catch (Exception e) { throw new PropertiesLoadException("Error in load-method:", e); } return lvProperties; }
11
Code Sample 1: public void constructAssociationView() { String className; String methodName; String field; boolean foundRead = false; boolean foundWrite = false; boolean classWritten = false; try { AssocView = new BufferedWriter(new FileWriter("InfoFiles/AssociationView.txt")); FileInputStream fstreamPC = new FileInputStream("InfoFiles/PrincipleClassGroup.txt"); DataInputStream inPC = new DataInputStream(fstreamPC); BufferedReader PC = new BufferedReader(new InputStreamReader(inPC)); while ((field = PC.readLine()) != null) { className = field; AssocView.write(className); AssocView.newLine(); classWritten = true; while ((methodName = PC.readLine()) != null) { if (methodName.contentEquals("EndOfClass")) break; AssocView.write("StartOfMethod"); AssocView.newLine(); AssocView.write(methodName); AssocView.newLine(); for (int i = 0; i < readFileCount && foundRead == false; i++) { if (methodName.compareTo(readArray[i]) == 0) { foundRead = true; for (int j = 1; readArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (readArray[i + j].indexOf(".") > 0) { field = readArray[i + j].substring(0, readArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(readArray[i + j]); AssocView.newLine(); } } } } } for (int i = 0; i < writeFileCount && foundWrite == false; i++) { if (methodName.compareTo(writeArray[i]) == 0) { foundWrite = true; for (int j = 1; writeArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (writeArray[i + j].indexOf(".") > 0) { field = writeArray[i + j].substring(0, writeArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(writeArray[i + j]); AssocView.newLine(); } } } } } AssocView.write("EndOfMethod"); AssocView.newLine(); foundRead = false; foundWrite = false; } if (classWritten == true) { AssocView.write("EndOfClass"); AssocView.newLine(); classWritten = false; } } PC.close(); AssocView.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static boolean copyFileChannel(final File _fileFrom, final File _fileTo, final boolean _append) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(_fileFrom).getChannel(); dstChannel = new FileOutputStream(_fileTo, _append).getChannel(); if (_append) { dstChannel.transferFrom(srcChannel, dstChannel.size(), srcChannel.size()); } else { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } srcChannel.close(); dstChannel.close(); } catch (final IOException e) { return false; } finally { try { if (srcChannel != null) { srcChannel.close(); } } catch (final IOException _evt) { FuLog.error(_evt); } try { if (dstChannel != null) { dstChannel.close(); } } catch (final IOException _evt) { FuLog.error(_evt); } } return true; }
00
Code Sample 1: private String extractFileFromZip(ZipFile zip, String fileName) throws IOException { String contents = null; ZipEntry entry = zip.getEntry(fileName); if (entry != null) { InputStream input = zip.getInputStream(entry); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copyAndClose(input, buffer); contents = buffer.toString(); } return contents; } Code Sample 2: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); }
00
Code Sample 1: public void run() { try { int id = getID() - 1; String file = id + ".dem"; String data = URLEncoder.encode("file", "UTF-8") + "=" + URLEncoder.encode(file, "UTF-8"); data += "&" + URLEncoder.encode("hash", "UTF-8") + "=" + URLEncoder.encode(getMD5Digest("tf2invite" + file), "UTF-8"); URL url = new URL("http://94.23.189.99/ftp.php"); final URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); String line; BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { System.out.println(line); if (line.startsWith("demo=")) msg("2The last gather demo has been uploaded successfully: " + line.split("=")[1]); } rd.close(); wr.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public void displayItems() throws IOException { URL url = new URL(SNIPPETS_FEED + "?bq=" + URLEncoder.encode(QUERY, "UTF-8") + "&key=" + DEVELOPER_KEY); HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); InputStream inputStream = httpConnection.getInputStream(); int ch; while ((ch = inputStream.read()) > 0) { System.out.print((char) ch); } }
11
Code Sample 1: public static void loadPoFile(URL url) { states state = states.IDLE; String msgCtxt = ""; String msgId = ""; String msgStr = ""; try { if (url == null) return; InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF8")); String strLine; while ((strLine = br.readLine()) != null) { if (strLine.startsWith("msgctxt")) { if (state != states.MSGCTXT) msgCtxt = ""; state = states.MSGCTXT; strLine = strLine.substring(7).trim(); } if (strLine.startsWith("msgid")) { if (state != states.MSGID) msgId = ""; state = states.MSGID; strLine = strLine.substring(5).trim(); } if (strLine.startsWith("msgstr")) { if (state != states.MSGSTR) msgStr = ""; state = states.MSGSTR; strLine = strLine.substring(6).trim(); } if (!strLine.startsWith("\"")) { state = states.IDLE; msgCtxt = ""; msgId = ""; msgStr = ""; } else { if (state == states.MSGCTXT) { msgCtxt += format(strLine); } if (state == states.MSGID) { if (msgId.isEmpty()) { if (!msgCtxt.isEmpty()) { msgId = msgCtxt + "|"; msgCtxt = ""; } } msgId += format(strLine); } if (state == states.MSGSTR) { msgCtxt = ""; msgStr += format(strLine); if (!msgId.isEmpty()) messages.setProperty(msgId, msgStr); } } } in.close(); } catch (IOException e) { Logger.logError(e, "Error loading message.po."); } } Code Sample 2: public static boolean processUrl(String urlPath, UrlLineHandler handler) { boolean ret = true; URL url; InputStream in = null; BufferedReader bin = null; try { url = new URL(urlPath); in = url.openStream(); bin = new BufferedReader(new InputStreamReader(in)); String line; while ((line = bin.readLine()) != null) { if (!handler.process(line)) break; } } catch (IOException e) { ret = false; } finally { safelyClose(bin, in); } return ret; }
00
Code Sample 1: public static String move_tags(String sessionid, String absolutePathForTheMovedTags, String absolutePathForTheDestinationTag) { String resultJsonString = "some problem existed inside the create_new_tag() function if you see this string"; try { Log.d("current running function name:", "move_tags"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "move_tag")); nameValuePairs.add(new BasicNameValuePair("absolute_new_parent_tag", absolutePathForTheDestinationTag)); nameValuePairs.add(new BasicNameValuePair("absolute_tags", absolutePathForTheMovedTags)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); resultJsonString = EntityUtils.toString(response.getEntity()); return resultJsonString; } catch (Exception e) { e.printStackTrace(); } return resultJsonString; } Code Sample 2: private boolean readRemoteFile() { InputStream inputstream; Concept concept = new Concept(); try { inputstream = url.openStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputStreamReader); String s4; while ((s4 = bufferedreader.readLine()) != null && s4.length() > 0) { if (!parseLine(s4, concept)) { return false; } } } catch (MalformedURLException e) { logger.fatal("malformed URL, trying to read local file"); return readLocalFile(); } catch (IOException e1) { logger.fatal("Error reading URL file, trying to read local file"); return readLocalFile(); } catch (Exception x) { logger.fatal("Failed to readRemoteFile " + x.getMessage() + ", trying to read local file"); return readLocalFile(); } return true; }
00
Code Sample 1: public int read(String name) { status = STATUS_OK; try { name = name.trim().toLowerCase(); if ((name.indexOf("file:") >= 0) || (name.indexOf(":/") > 0)) { URL url = new URL(name); in = new BufferedInputStream(url.openStream()); } else { in = new BufferedInputStream(new FileInputStream(name)); } status = read(in); } catch (IOException e) { status = STATUS_OPEN_ERROR; } return status; } Code Sample 2: public static final void copyFile(File argSource, File argDestination) throws IOException { FileChannel srcChannel = new FileInputStream(argSource).getChannel(); FileChannel dstChannel = new FileOutputStream(argDestination).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { srcChannel.close(); dstChannel.close(); } }
00
Code Sample 1: @SuppressWarnings({ "ProhibitedExceptionDeclared" }) public int run(@NotNull final List<String> args) throws Exception { int returnCode = 0; if (args.size() == 0) { log(Level.SEVERE, "noarguments"); returnCode++; } final byte[] buf = new byte[BUF_SIZE]; for (final String arg : args) { try { final URL url = new URL(arg); final URLConnection con = url.openConnection(); final InputStream in = con.getInputStream(); try { final String location = con.getHeaderField("Content-Location"); final String outputFilename = new File((location != null ? new URL(url, location) : url).getFile()).getName(); log(Level.INFO, "writing", arg, outputFilename); final OutputStream out = new FileOutputStream(outputFilename); try { for (int bytesRead; (bytesRead = in.read(buf)) != -1; ) { out.write(buf, 0, bytesRead); } } finally { out.close(); } } finally { in.close(); } } catch (final IOException e) { log(Level.WARNING, "cannotopen", arg, e); returnCode++; } } return returnCode; } Code Sample 2: String fetch_pls(String pls) { InputStream pstream = null; if (pls.startsWith("http://")) { try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), pls); else url = new URL(pls); URLConnection urlc = url.openConnection(); pstream = urlc.getInputStream(); } catch (Exception ee) { System.err.println(ee); return null; } } if (pstream == null && !running_as_applet) { try { pstream = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + pls); } catch (Exception ee) { System.err.println(ee); return null; } } String line = null; while (true) { try { line = readline(pstream); } catch (Exception e) { } if (line == null) break; if (line.startsWith("File1=")) { byte[] foo = line.getBytes(); int i = 6; for (; i < foo.length; i++) { if (foo[i] == 0x0d) break; } return line.substring(6, i); } } return null; }
00
Code Sample 1: public void echo(HttpRequest request, HttpResponse response) throws IOException { InputStream in = request.getInputStream(); if ("gzip".equals(request.getField("Content-Encoding"))) { in = new GZIPInputStream(in); } IOUtils.copy(in, response.getOutputStream()); } Code Sample 2: private static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); if (login) { postURL = "http://upload.badongo.com/mpu_upload.php"; } HttpPost httppost = new HttpPost(postURL); file = new File("g:/S2SClient.7z"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("Filename", new StringBody(file.getName())); if (login) { mpEntity.addPart("PHPSESSID", new StringBody(dataid)); } mpEntity.addPart("Filedata", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into badongo.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("Upload response : " + uploadresponse); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } System.out.println("res " + uploadresponse); httpclient.getConnectionManager().shutdown(); }
11
Code Sample 1: @Override public void setContentAsStream(InputStream input) throws IOException { BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(htmlFile)); try { IOUtils.copy(input, output); } finally { output.close(); } if (this.getLastModified() != -1) { htmlFile.setLastModified(this.getLastModified()); } } Code Sample 2: public static void streamCopyFile(File srcFile, File destFile) { try { FileInputStream fi = new FileInputStream(srcFile); FileOutputStream fo = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int readLength = 0; while (readLength != -1) { readLength = fi.read(buf); if (readLength != -1) { fo.write(buf, 0, readLength); } } fo.close(); fi.close(); } catch (Exception e) { } }
11
Code Sample 1: public static String getRandomUserAgent() { if (USER_AGENT_CACHE == null) { Collection<String> userAgentsCache = new ArrayList<String>(); try { URL url = Tools.getResource(UserAgent.class.getClassLoader(), "user-agents-browser.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { userAgentsCache.add(str); } in.close(); USER_AGENT_CACHE = userAgentsCache.toArray(new String[userAgentsCache.size()]); } catch (Exception e) { System.err.println("Can not read file; using default user-agent; error message: " + e.getMessage()); return DEFAULT_USER_AGENT; } } return USER_AGENT_CACHE[new Random().nextInt(USER_AGENT_CACHE.length)]; } Code Sample 2: public static String sendSoapMsg(String SOAPUrl, byte[] b, String SOAPAction) throws IOException { log.finest("HTTP REQUEST SIZE " + b.length); if (SOAPAction.startsWith("\"") == false) SOAPAction = "\"" + SOAPAction + "\""; URL url = new URL(SOAPUrl); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestProperty("SOAPAction", SOAPAction); httpConn.setRequestProperty("Content-Type", "text/xml; charset=\"utf-8\""); httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Cache-Control", "no-cache"); httpConn.setRequestProperty("Pragma", "no-cache"); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); OutputStream out = httpConn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); StringBuffer response = new StringBuffer(1024); String inputLine; while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); log.finest("HTTP RESPONSE SIZE: " + response.length()); return response.toString(); }
00
Code Sample 1: public static void exportDB(String input, String output) { try { Class.forName("org.sqlite.JDBC"); String fileName = input + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero DB", "Error", JOptionPane.ERROR_MESSAGE); } else { G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); HashMap<Integer, String> languageIDs = new HashMap<Integer, String>(); HashMap<Integer, String> typeIDs = new HashMap<Integer, String>(); long tiempoInicio = System.currentTimeMillis(); Element dataBaseXML = new Element("database"); Element languages = new Element("languages"); Statement stat = G.conn.createStatement(); ResultSet rs = stat.executeQuery("select * from language order by id"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); languageIDs.put(id, name); Element language = new Element("language"); language.setText(name); languages.addContent(language); } dataBaseXML.addContent(languages); rs = stat.executeQuery("select * from type order by id"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); typeIDs.put(id, name); } rs = stat.executeQuery("select distinct name from main order by name"); while (rs.next()) { String name = rs.getString("name"); Element image = new Element("image"); image.setAttribute("id", name); Statement stat2 = G.conn.createStatement(); ResultSet rs2 = stat2.executeQuery("select distinct idL from main where name = \"" + name + "\" order by idL"); while (rs2.next()) { int idL = rs2.getInt("idL"); Element language = new Element("language"); language.setAttribute("id", languageIDs.get(idL)); Statement stat3 = G.conn.createStatement(); ResultSet rs3 = stat3.executeQuery("select * from main where name = \"" + name + "\" and idL = " + idL + " order by idT"); while (rs3.next()) { int idT = rs3.getInt("idT"); String word = rs3.getString("word"); Element wordE = new Element("word"); wordE.setAttribute("type", typeIDs.get(idT)); wordE.setText(word); language.addContent(wordE); String pathSrc = input + File.separator + name.substring(0, 1).toUpperCase() + File.separator + name; String pathDst = output + File.separator + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } rs3.close(); stat3.close(); image.addContent(language); } rs2.close(); stat2.close(); dataBaseXML.addContent(image); } rs.close(); stat.close(); XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); FileOutputStream f = new FileOutputStream(output + File.separator + G.imagesName); out.output(dataBaseXML, f); f.flush(); f.close(); long totalTiempo = System.currentTimeMillis() - tiempoInicio; System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos"); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public String md5(String phrase) { MessageDigest m; String coded = new String(); try { m = MessageDigest.getInstance("MD5"); m.update(phrase.getBytes(), 0, phrase.length()); coded = (new BigInteger(1, m.digest()).toString(16)).toString(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return coded; }