label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: @Override public void run() { long timeout = 10 * 1000L; long start = (new Date()).getTime(); try { InputStream is = socket.getInputStream(); boolean available = false; while (!available && !socket.isClosed()) { try { if (is.available() != 0) { available = true; } else { Thread.sleep(100); } } catch (Exception e) { LOG.error("Error checking socket", e); } long curr = (new Date()).getTime(); if ((curr - start) >= timeout) { break; } } if (socket.isClosed()) { } else { tmpFile = File.createTempFile("ftp", "dat", new File("./tmp")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile)); IOUtils.copy(is, bos); bos.flush(); bos.close(); } String msg = FtpResponse.ReadComplete.asString() + ClientCommand.SP + "Read Complete" + ClientCommand.CRLF; List<String> list = new ArrayList<String>(); list.add(msg); ClientResponse response = new ClientResponse(list); ftpClient.notifyListeners(response); } catch (Exception e) { LOG.error("Error reading server response", e); } } Code Sample 2: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
00
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } Code Sample 2: public <T extends FetionResponse> T executeAction(FetionAction<T> fetionAction) throws IOException { URL url = new URL(fetionAction.getProtocol().name().toLowerCase() + "://" + fetionUrl + fetionAction.getRequestData()); URLConnection connection = url.openConnection(); InputStream in = connection.getInputStream(); byte[] buffer = new byte[10240]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); int read = 0; while ((read = in.read(buffer)) > 0) { bout.write(buffer, 0, read); } return fetionAction.processResponse(parseRawResponse(bout.toByteArray())); }
11
Code Sample 1: public static void copyFile(File fileIn, File fileOut) throws IOException { FileChannel chIn = new FileInputStream(fileIn).getChannel(); FileChannel chOut = new FileOutputStream(fileOut).getChannel(); try { chIn.transferTo(0, chIn.size(), chOut); } catch (IOException e) { throw e; } finally { if (chIn != null) chIn.close(); if (chOut != null) chOut.close(); } } Code Sample 2: public void checkFilesAndCopyValid(String filename) { downloadResults(); loadResults(); File tmpFolderF = new File(tmpFolder); deleteFileFromTMPFolder(tmpFolderF); ZipReader zr = new ZipReader(); zr.UnzipFile(filename); try { LogManager.getInstance().log("Ov��uji odevzdan� soubory a kop�ruji validovan�:"); LogManager.getInstance().log(""); JAXBElement<?> element = ElementJAXB.getJAXBElement(); Ppa1VysledkyCviceniType pvct = (Ppa1VysledkyCviceniType) element.getValue(); File zipFolder = new File(tmpFolder).listFiles()[0].listFiles()[0].listFiles()[0]; File[] zipFolderList = zipFolder.listFiles(); for (File studentDirectory : zipFolderList) { if (studentDirectory.isDirectory()) { String osobniCisloZeSlozky = studentDirectory.getName().split("-")[0]; LogManager.getInstance().changeLog("Prov��ov�n� soubor� studenta s ��slem: " + osobniCisloZeSlozky); List<StudentType> students = (List<StudentType>) pvct.getStudent(); for (StudentType student : students) { if (student.getOsobniCislo().equals(osobniCisloZeSlozky)) { int pzp = student.getDomaciUlohy().getPosledniZpracovanyPokus().getCislo().intValue(); DomaciUlohyType dut = student.getDomaciUlohy(); ChybneOdevzdaneType chot = dut.getChybneOdevzdane(); ObjectFactory of = new ObjectFactory(); File[] pokusyDirectories = studentDirectory.listFiles(); NodeList souboryNL = result.getElementsByTagName("soubor"); int start = souboryNL.getLength() - 1; boolean samostatnaPrace = false; for (int i = (pokusyDirectories.length - 1); i >= 0; i--) { if ((pokusyDirectories[i].isDirectory()) && (pzp < Integer.parseInt(pokusyDirectories[i].getName().split("_")[1].trim()))) { File testedFile = pokusyDirectories[i].listFiles()[0]; if ((testedFile.exists()) && (testedFile.isFile())) { String[] partsOfFilename = testedFile.getName().split("_"); String osobniCisloZeSouboru = "", priponaSouboru = ""; String[] posledniCastSouboru = null; if (partsOfFilename.length == 4) { posledniCastSouboru = partsOfFilename[3].split("[.]"); osobniCisloZeSouboru = posledniCastSouboru[0]; if (posledniCastSouboru.length <= 1) priponaSouboru = ""; else priponaSouboru = posledniCastSouboru[1]; } String samostatnaPraceNazev = Konfigurace.getInstance().getSamostatnaPraceNazev(); List<SouborType> lst = chot.getSoubor(); if (testedFile.getName().startsWith(samostatnaPraceNazev)) { samostatnaPrace = true; } else { samostatnaPrace = false; if (partsOfFilename.length != 4) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� struktura jm�na souboru."); lst.add(st); continue; } else if (!testedFile.getName().startsWith("Ppa1_cv")) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� za��tek jm�na souboru."); lst.add(st); continue; } else if (!priponaSouboru.equals("java")) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� p��pona souboru."); lst.add(st); continue; } else if (!osobniCisloZeSouboru.equals(osobniCisloZeSlozky)) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Nesouhlas� osobn� ��sla."); lst.add(st); continue; } else if (partsOfFilename[3].split("[.]").length > 2) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("V�ce p��pon souboru."); lst.add(st); continue; } else { long cisloCviceni, cisloUlohy; try { if (partsOfFilename[1].length() == 4) { String cisloS = partsOfFilename[1].substring(2); long cisloL = Long.parseLong(cisloS); cisloCviceni = cisloL; } else { throw new NumberFormatException(); } } catch (NumberFormatException e) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Chyb� (nebo je chybn�) ��slo cvi�en�"); lst.add(st); continue; } try { if (partsOfFilename[2].length() > 0) { String cisloS = partsOfFilename[2]; long cisloL = Long.parseLong(cisloS); cisloUlohy = cisloL; } else { throw new NumberFormatException(); } } catch (NumberFormatException e) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Chyb� (nebo je chybn�) ��slo �lohy"); lst.add(st); continue; } CislaUloh ci = new CislaUloh(); List<long[]> cviceni = ci.getSeznamCviceni(); boolean nalezenoCv = false, nalezenaUl = false; for (long[] c : cviceni) { if (c[0] == cisloCviceni) { for (int j = 1; j < c.length; j++) { if (c[j] == cisloUlohy) { nalezenaUl = true; break; } } nalezenoCv = true; break; } } if (!nalezenoCv) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Neplatn� ��slo cvi�en�"); lst.add(st); continue; } if (!nalezenaUl) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Neplatn� ��slo �lohy"); lst.add(st); continue; } } } } Calendar dateFromZipFile = null; File zipFile = new File(filename); if (zipFile.exists()) { String[] s = zipFile.getName().split("_"); if (s.length >= 3) { String[] date = s[1].split("-"), time = s[2].split("-"); dateFromZipFile = new GregorianCalendar(); dateFromZipFile.set(Integer.parseInt(date[0]), Integer.parseInt(date[1]) - 1, Integer.parseInt(date[2]), Integer.parseInt(time[0]), Integer.parseInt(time[1]), 0); } } boolean shodaJmenaSouboru = false; String vysledekValidaceSouboru = ""; for (int j = start; j >= 0; j--) { NodeList vlastnostiSouboruNL = souboryNL.item(j).getChildNodes(); for (int k = 0; k < vlastnostiSouboruNL.getLength(); k++) { if (vlastnostiSouboruNL.item(k).getNodeName().equals("cas")) { String[] obsahElementuCas = vlastnostiSouboruNL.item(k).getTextContent().split(" "); String[] datumZElementu = obsahElementuCas[0].split("-"), casZElementu = obsahElementuCas[1].split("-"); Calendar datumACasZElementu = new GregorianCalendar(); datumACasZElementu.set(Integer.parseInt(datumZElementu[0]), Integer.parseInt(datumZElementu[1]) - 1, Integer.parseInt(datumZElementu[2]), Integer.parseInt(casZElementu[0]), Integer.parseInt(casZElementu[1]), Integer.parseInt(casZElementu[2])); if ((dateFromZipFile != null) && (datumACasZElementu.compareTo(dateFromZipFile) > 0)) { shodaJmenaSouboru = false; break; } } if (vlastnostiSouboruNL.item(k).getNodeName().equals("nazev")) { shodaJmenaSouboru = vlastnostiSouboruNL.item(k).getTextContent().equals(testedFile.getName()); } if (vlastnostiSouboruNL.item(k).getNodeName().equals("vysledek")) { vysledekValidaceSouboru = vlastnostiSouboruNL.item(k).getTextContent(); } } if (shodaJmenaSouboru) { start = --j; break; } } if (shodaJmenaSouboru && !samostatnaPrace) { boolean odevzdanoVcas = false; String cisloCviceniS = testedFile.getName().split("_")[1].substring(2); int cisloCviceniI = Integer.parseInt(cisloCviceniS); String cisloUlohyS = testedFile.getName().split("_")[2]; int cisloUlohyI = Integer.parseInt(cisloUlohyS); List<CviceniType> lct = student.getDomaciUlohy().getCviceni(); for (CviceniType ct : lct) { if (ct.getCislo().intValue() == cisloCviceniI) { MezniTerminOdevzdaniVcasType mtovt = ct.getMezniTerminOdevzdaniVcas(); Calendar mtovGC = new GregorianCalendar(); mtovGC.set(mtovt.getDatum().getYear(), mtovt.getDatum().getMonth() - 1, mtovt.getDatum().getDay(), 23, 59, 59); Calendar fileTimeStamp = new GregorianCalendar(); fileTimeStamp.setTimeInMillis(testedFile.lastModified()); String[] datumSouboru = String.format("%tF", fileTimeStamp).split("-"); String[] casSouboru = String.format("%tT", fileTimeStamp).split(":"); XMLGregorianCalendar xmlGCDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(Integer.parseInt(datumSouboru[0]), Integer.parseInt(datumSouboru[1]), Integer.parseInt(datumSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); XMLGregorianCalendar xmlGCTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(Integer.parseInt(casSouboru[0]), Integer.parseInt(casSouboru[1]), Integer.parseInt(casSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); if (fileTimeStamp.compareTo(mtovGC) <= 0) odevzdanoVcas = true; else odevzdanoVcas = false; List<UlohaType> lut = ct.getUloha(); for (UlohaType ut : lut) { if (ut.getCislo().intValue() == cisloUlohyI) { List<OdevzdanoType> lot = ut.getOdevzdano(); OdevzdanoType ot = of.createOdevzdanoType(); ot.setDatum(xmlGCDate); ot.setCas(xmlGCTime); OdevzdanoVcasType ovt = of.createOdevzdanoVcasType(); ovt.setVysledek(odevzdanoVcas); ValidatorType vt = of.createValidatorType(); vt.setVysledek(vysledekValidaceSouboru.equals("true")); ot.setOdevzdanoVcas(ovt); ot.setValidator(vt); lot.add(ot); if (vt.isVysledek()) { String test = String.format("%s%s%02d", validovane, File.separator, ct.getCislo().intValue()); if (!(new File(test).exists())) { LogManager.getInstance().log("Nebyla provedena p��prava soubor�. Chyb� slo�ka " + test.substring(Ppa1Cviceni.USER_DIR.length()) + "."); return; } else { copyValidFile(testedFile, ct.getCislo().intValue()); } } break; } } break; } } } else if (shodaJmenaSouboru && samostatnaPrace) { String[] partsOfFilename = testedFile.getName().split("_"); String[] partsOfLastPartOfFilename = partsOfFilename[partsOfFilename.length - 1].split("[.]"); String osobniCisloZeSouboru = partsOfLastPartOfFilename[0]; String priponaZeSouboru = partsOfLastPartOfFilename[partsOfLastPartOfFilename.length - 1]; if ((partsOfLastPartOfFilename.length == 2) && (priponaZeSouboru.equals("java"))) { if (student.getOsobniCislo().equals(osobniCisloZeSouboru)) { Calendar fileTimeStamp = new GregorianCalendar(); fileTimeStamp.setTimeInMillis(testedFile.lastModified()); String[] datumSouboru = String.format("%tF", fileTimeStamp).split("-"); String[] casSouboru = String.format("%tT", fileTimeStamp).split(":"); XMLGregorianCalendar xmlGCDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(Integer.parseInt(datumSouboru[0]), Integer.parseInt(datumSouboru[1]), Integer.parseInt(datumSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); XMLGregorianCalendar xmlGCTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(Integer.parseInt(casSouboru[0]), Integer.parseInt(casSouboru[1]), Integer.parseInt(casSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); List<UlozenoType> lut = student.getSamostatnaPrace().getUlozeno(); if (lut.isEmpty()) { File samostatnaPraceNewFile = new File(sp + File.separator + testedFile.getName()); if (samostatnaPraceNewFile.exists()) { samostatnaPraceNewFile.delete(); samostatnaPraceNewFile.createNewFile(); } String EOL = "" + (char) 0x0D + (char) 0x0A; FileReader fr = new FileReader(testedFile); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(samostatnaPraceNewFile); String line; while ((line = br.readLine()) != null) fw.write(line + EOL); br.close(); fw.close(); samostatnaPraceNewFile.setLastModified(testedFile.lastModified()); } UlozenoType ut = of.createUlozenoType(); ut.setDatum(xmlGCDate); ut.setCas(xmlGCTime); lut.add(0, ut); } } } } } PosledniZpracovanyPokusType pzpt = new PosledniZpracovanyPokusType(); String[] slozkaPoslednihoPokusu = pokusyDirectories[pokusyDirectories.length - 1].getName().split("_"); int cisloPokusu = Integer.parseInt(slozkaPoslednihoPokusu[slozkaPoslednihoPokusu.length - 1].trim()); pzpt.setCislo(new BigInteger(String.valueOf(cisloPokusu))); student.getDomaciUlohy().setPosledniZpracovanyPokus(pzpt); break; } } } } ElementJAXB.setJAXBElement(element); LogManager.getInstance().log("Ov��ov�n� a kop�rov�n� odevzdan�ch soubor� dokon�eno."); } catch (FileNotFoundException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } catch (DatatypeConfigurationException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } catch (IOException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } LogManager.getInstance().log("Maz�n� rozbalen�ch soubor� ..."); deleteFileFromTMPFolder(tmpFolderF); LogManager.getInstance().changeLog("Maz�n� rozbalen�ch soubor� ... OK"); }
11
Code Sample 1: public void postProcess() throws StopWriterVisitorException { shpWriter.postProcess(); try { FileChannel fcinShp = new FileInputStream(fTemp).getChannel(); FileChannel fcoutShp = new FileOutputStream(fileShp).getChannel(); DriverUtilities.copy(fcinShp, fcoutShp); File shxFile = SHP.getShxFile(fTemp); FileChannel fcinShx = new FileInputStream(shxFile).getChannel(); FileChannel fcoutShx = new FileOutputStream(SHP.getShxFile(fileShp)).getChannel(); DriverUtilities.copy(fcinShx, fcoutShx); File dbfFile = getDataFile(fTemp); short originalEncoding = DbfEncodings.getInstance().getDbfIdForCharset(shpWriter.getCharset()); RandomAccessFile fo = new RandomAccessFile(dbfFile, "rw"); fo.seek(29); fo.writeByte(originalEncoding); fo.close(); FileChannel fcinDbf = new FileInputStream(dbfFile).getChannel(); FileChannel fcoutDbf = new FileOutputStream(getDataFile(fileShp)).getChannel(); DriverUtilities.copy(fcinDbf, fcoutDbf); fTemp.delete(); shxFile.delete(); dbfFile.delete(); reload(); } catch (FileNotFoundException e) { throw new StopWriterVisitorException(getName(), e); } catch (IOException e) { throw new StopWriterVisitorException(getName(), e); } catch (ReloadDriverException e) { throw new StopWriterVisitorException(getName(), e); } } Code Sample 2: 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()); } }
11
Code Sample 1: public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("DOWNLOAD - Send content: " + realFile.getAbsolutePath()); LOGGER.debug("Output stream: " + out.toString()); if (ServerConfiguration.isDynamicSEL()) { LOGGER.error("IS DINAMIC SEL????"); } else { } if (".tokens".equals(realFile.getName()) || ".response".equals(realFile.getName()) || ".request".equals(realFile.getName()) || isAllowedClient) { FileInputStream in = null; try { in = new FileInputStream(realFile); int bytes = IOUtils.copy(in, out); LOGGER.debug("System resource or Allowed Client wrote bytes: " + bytes); out.flush(); } catch (Exception e) { LOGGER.error("Error while downloading over encryption system " + realFile.getName() + " file", e); } finally { IOUtils.closeQuietly(in); } } else { } } Code Sample 2: public static boolean copy(File source, File dest) { 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); if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
00
Code Sample 1: private final void saveCopy(String source, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(source)); to = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " copying file"); } try { to.close(); from.close(); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " closing files"); } to = null; from = null; } Code Sample 2: private SpequlosResponse executeGet(String targetURL, String urlParameters) { URL url; HttpURLConnection connection = null; boolean succ = false; try { url = new URL(targetURL + "?" + urlParameters); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer log = new StringBuffer(); ArrayList<String> response = new ArrayList<String>(); while ((line = rd.readLine()) != null) { if (line.startsWith("<div class=\"qos\">")) { System.out.println("here is the line : " + line); String resp = line.split(">")[1].split("<")[0]; System.out.println("here is the splitted line : " + resp); if (!resp.startsWith("None")) { succ = true; String[] values = resp.split(" "); ArrayList<String> realvalues = new ArrayList<String>(); for (String s : values) { realvalues.add(s); } if (realvalues.size() == 5) { realvalues.add(2, realvalues.get(2) + " " + realvalues.get(3)); realvalues.remove(3); realvalues.remove(3); } for (String n : realvalues) { response.add(n); } } } else { log.append(line); log.append('\r'); } } rd.close(); SpequlosResponse speqresp = new SpequlosResponse(response, log.toString(), succ); return speqresp; } catch (Exception e) { e.printStackTrace(); String log = "Please check the availability of Spequlos server!<br />" + "URL:" + targetURL + "<br />" + "PARAMETERS:" + urlParameters + "<br />"; return new SpequlosResponse(null, log, succ); } finally { if (connection != null) connection.disconnect(); } }
00
Code Sample 1: public void testReleaseOnEntityWriteTo() throws Exception { HttpParams params = defaultParams.copy(); ConnManagerParams.setMaxTotalConnections(params, 1); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1)); ThreadSafeClientConnManager mgr = createTSCCM(params, null); assertEquals(0, mgr.getConnectionsInPool()); DefaultHttpClient client = new DefaultHttpClient(mgr, params); HttpGet httpget = new HttpGet("/random/20000"); HttpHost target = getServerHttp(); HttpResponse response = client.execute(target, httpget); ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null); try { connreq.getConnection(250, TimeUnit.MILLISECONDS); fail("ConnectionPoolTimeoutException should have been thrown"); } catch (ConnectionPoolTimeoutException expected) { } HttpEntity e = response.getEntity(); assertNotNull(e); ByteArrayOutputStream outsteam = new ByteArrayOutputStream(); e.writeTo(outsteam); assertEquals(1, mgr.getConnectionsInPool()); connreq = mgr.requestConnection(new HttpRoute(target), null); ManagedClientConnection conn = connreq.getConnection(250, TimeUnit.MILLISECONDS); mgr.releaseConnection(conn, -1, null); mgr.shutdown(); } Code Sample 2: public Document parse(Document document) { CSSCompilerBuilder compilerBuilder = new CSSCompilerBuilder(); StyleSheetCompilerFactory compilerFactory = getStyleSheetCompilerFactory(); compilerBuilder.setStyleSheetCompilerFactory(compilerFactory); CSSCompiler cssCompiler = compilerBuilder.getCSSCompiler(); CompiledStyleSheet defaultCompiledStyleSheet; try { URL url = getClass().getResource("/com/volantis/mcs/runtime/default.css"); InputStream stream = url.openStream(); defaultCompiledStyleSheet = cssCompiler.compile(new InputStreamReader(stream), null); } catch (IOException e) { throw new ExtendedRuntimeException(e); } StylingFactory stylingFactory = StylingFactory.getDefaultInstance(); StylingEngine stylingEngine = stylingFactory.createStylingEngine(new InlineStyleSheetCompilerFactory(StylingFunctions.getResolver())); stylingEngine.pushStyleSheet(defaultCompiledStyleSheet); DocumentStyler styler = new DocumentStyler(stylingEngine, XDIMESchemata.CDM_NAMESPACE); styler.style(document); DOMWalker walker = new DOMWalker(new WalkingDOMVisitorStub() { public void visit(Element element) { if (element.getStyles() == null) { throw new IllegalArgumentException("element " + element.getName() + " has no styles"); } } }); walker.walk(document); DOMTransformer transformer = new DeferredInheritTransformer(); document = transformer.transform(null, document); return document; }
11
Code Sample 1: 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(); } if (coded.length() < 32) { coded = "0" + coded; } return coded; } Code Sample 2: private byte[] md5Digest(String pPassword) { if (pPassword == null) { throw new NullPointerException("input null text for hashing"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pPassword.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Cannot find MD5 algorithm"); } }
11
Code Sample 1: public static void copyWithClose(InputStream is, OutputStream os) throws IOException { try { IOUtils.copy(is, os); } catch (IOException ioe) { try { if (os != null) os.close(); } catch (Exception e) { } try { if (is != null) is.close(); } catch (Exception e) { } } } Code Sample 2: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
00
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.B64InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public ISOMsg filter(ISOChannel channel, ISOMsg m, LogEvent evt) throws VetoException { if (key == null || fields == null) throw new VetoException("MD5Filter not configured"); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getKey()); int[] f = getFields(m); for (int i = 0; i < f.length; i++) { int fld = f[i]; if (m.hasField(fld)) { ISOComponent c = m.getComponent(fld); if (c instanceof ISOBinaryField) md.update((byte[]) c.getValue()); else md.update(((String) c.getValue()).getBytes()); } } byte[] digest = md.digest(); if (m.getDirection() == ISOMsg.OUTGOING) { m.set(new ISOBinaryField(64, digest, 0, 8)); m.set(new ISOBinaryField(128, digest, 8, 8)); } else { byte[] rxDigest = new byte[16]; if (m.hasField(64)) System.arraycopy((byte[]) m.getValue(64), 0, rxDigest, 0, 8); if (m.hasField(128)) System.arraycopy((byte[]) m.getValue(128), 0, rxDigest, 8, 8); if (!Arrays.equals(digest, rxDigest)) { evt.addMessage(m); evt.addMessage("MAC expected: " + ISOUtil.hexString(digest)); evt.addMessage("MAC received: " + ISOUtil.hexString(rxDigest)); throw new VetoException("invalid MAC"); } m.unset(64); m.unset(128); } } catch (NoSuchAlgorithmException e) { throw new VetoException(e); } catch (ISOException e) { throw new VetoException(e); } return m; }
00
Code Sample 1: private void handleSSI(HttpData data) throws HttpError, IOException { File tempFile = TempFileHandler.getTempFile(); FileOutputStream out = new FileOutputStream(tempFile); BufferedReader in = new BufferedReader(new FileReader(data.realPath)); String[] env = getEnvironmentVariables(data); if (ssi == null) { ssi = new BSssi(); } ssi.addEnvironment(env); if (data.resp == null) { SimpleResponse resp = new SimpleResponse(); resp.setHeader("Content-Type", "text/html"); moreHeaders(resp); resp.setHeader("Connection", "close"); data.resp = resp; resp.write(data.out); } String t; int start; Enumeration en; boolean anIfCondition = true; while ((t = in.readLine()) != null) { if ((start = t.indexOf("<!--#")) > -1) { if (anIfCondition) out.write(t.substring(0, start).getBytes()); try { en = ssi.parse(t.substring(start)).elements(); SSICommand command; while (en.hasMoreElements()) { command = (SSICommand) en.nextElement(); logger.fine("Command=" + command); switch(command.getCommand()) { case BSssi.CMD_IF_TRUE: anIfCondition = true; break; case BSssi.CMD_IF_FALSE: anIfCondition = false; break; case BSssi.CMD_CGI: out.flush(); if (command.getFileType() != null && command.getFileType().startsWith("shtm")) { HttpData d = newHttpData(data); d.out = out; d.realPath = HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()); new SsiHandler(d, ssi).perform(); } else { String application = getExtension(command.getFileType()); if (application == null) { writePaused(new FileInputStream(HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl())), out, pause); } else { String parameter = ""; if (command.getMessage().indexOf("php") >= 0) { parameter = "-f "; } Process p = Runtime.getRuntime().exec(application + " " + parameter + HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl())); BufferedReader pIn = new BufferedReader(new InputStreamReader(p.getInputStream())); String aLine; while ((aLine = pIn.readLine()) != null) out.write((aLine + "\n").getBytes()); pIn.close(); } } break; case BSssi.CMD_EXEC: Process p = Runtime.getRuntime().exec(command.getMessage()); BufferedReader pIn = new BufferedReader(new InputStreamReader(p.getInputStream())); String aLine; while ((aLine = pIn.readLine()) != null) out.write((aLine + "\n").getBytes()); BufferedReader pErr = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((aLine = pErr.readLine()) != null) out.write((aLine + "\n").getBytes()); pIn.close(); pErr.close(); p.destroy(); break; case BSssi.CMD_INCLUDE: File incFile = HttpThread.getMappedFilename(command.getMessage()); if (incFile.exists() && incFile.canRead()) { writePaused(new FileInputStream(incFile), out, pause); } break; case BSssi.CMD_FILESIZE: long sizeBytes = HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()).length(); double smartSize; String unit = "bytes"; if (command.getFileType().trim().equals("abbrev")) { if (sizeBytes > 1000000) { smartSize = sizeBytes / 1024000.0; unit = "M"; } else if (sizeBytes > 1000) { smartSize = sizeBytes / 1024.0; unit = "K"; } else { smartSize = sizeBytes; unit = "bytes"; } NumberFormat numberFormat = new DecimalFormat("#,##0", new DecimalFormatSymbols(Locale.ENGLISH)); out.write((numberFormat.format(smartSize) + "" + unit).getBytes()); } else { NumberFormat numberFormat = new DecimalFormat("#,###,##0", new DecimalFormatSymbols(Locale.ENGLISH)); out.write((numberFormat.format(sizeBytes) + " " + unit).getBytes()); } break; case BSssi.CMD_FLASTMOD: out.write(ssi.format(new Date(HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()).lastModified()), TimeZone.getTimeZone("GMT")).getBytes()); break; case BSssi.CMD_NOECHO: break; case BSssi.CMD_ECHO: default: out.write(command.getMessage().getBytes()); break; } } } catch (Exception e) { e.printStackTrace(); out.write((ssi.getErrorMessage() + " " + e.getMessage()).getBytes()); } if (anIfCondition) out.write("\n".getBytes()); } else { if (anIfCondition) out.write((t + "\n").getBytes()); } out.flush(); } in.close(); out.close(); data.fileData.setContentType("text/html"); data.fileData.setFile(tempFile); writePaused(new FileInputStream(tempFile), data.out, pause); logger.fine("HandleSSI done for " + data.resp); } Code Sample 2: public boolean check(Object credentials) { String password = (credentials instanceof String) ? (String) credentials : credentials.toString(); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] ha1; if (credentials instanceof Credential.MD5) { ha1 = ((Credential.MD5) credentials).getDigest(); } else { md.update(username.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(realm.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(password.getBytes(StringUtil.__ISO_8859_1)); ha1 = md.digest(); } md.reset(); md.update(method.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(uri.getBytes(StringUtil.__ISO_8859_1)); byte[] ha2 = md.digest(); md.update(TypeUtil.toString(ha1, 16).getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(nonce.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(nc.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(cnonce.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(qop.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(TypeUtil.toString(ha2, 16).getBytes(StringUtil.__ISO_8859_1)); byte[] digest = md.digest(); return (TypeUtil.toString(digest, 16).equalsIgnoreCase(response)); } catch (Exception e) { Log.warn(e); } return false; }
00
Code Sample 1: private PrecomputedAnimatedModel loadPrecomputedModel_(URL url) { if (precompCache.containsKey(url.toExternalForm())) { return (precompCache.get(url.toExternalForm()).copy()); } TextureLoader.getInstance().getTexture(""); List<SharedGroup> frames = new ArrayList<SharedGroup>(); Map<String, Animation> animations = new Hashtable<String, Animation>(); if (url.toExternalForm().endsWith(".amo")) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String objFileName = reader.readLine(); objFileName = url.toExternalForm().substring(0, url.toExternalForm().lastIndexOf("/")) + "/" + objFileName; frames = loadOBJFrames(objFileName); String line; while ((line = reader.readLine()) != null) { StringTokenizer tokenizer = new StringTokenizer(line); String animName = tokenizer.nextToken(); int from = Integer.valueOf(tokenizer.nextToken()); int to = Integer.valueOf(tokenizer.nextToken()); tokenizer.nextToken(); animations.put(animName, new Animation(animName, from, to)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { frames = loadOBJFrames(url.toExternalForm()); } PrecomputedAnimatedModel precompModel = new PrecomputedAnimatedModel(frames, animations); precompCache.put(url.toExternalForm(), precompModel); return (precompModel); } Code Sample 2: public static synchronized String Encrypt(String plaintextPassword) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (Exception error) { throw new Exception(error.getMessage()); } try { md.update(plaintextPassword.getBytes("UTF-8")); } catch (Exception e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
11
Code Sample 1: private void addAuditDatastream() throws ObjectIntegrityException, StreamIOException { if (m_obj.getAuditRecords().size() == 0) { return; } String dsId = m_pid.toURI() + "/AUDIT"; String dsvId = dsId + "/" + DateUtility.convertDateToString(m_obj.getCreateDate()); Entry dsEntry = m_feed.addEntry(); dsEntry.setId(dsId); dsEntry.setTitle("AUDIT"); dsEntry.setUpdated(m_obj.getCreateDate()); dsEntry.addCategory(MODEL.STATE.uri, "A", null); dsEntry.addCategory(MODEL.CONTROL_GROUP.uri, "X", null); dsEntry.addCategory(MODEL.VERSIONABLE.uri, "false", null); dsEntry.addLink(dsvId, Link.REL_ALTERNATE); Entry dsvEntry = m_feed.addEntry(); dsvEntry.setId(dsvId); dsvEntry.setTitle("AUDIT.0"); dsvEntry.setUpdated(m_obj.getCreateDate()); ThreadHelper.addInReplyTo(dsvEntry, m_pid.toURI() + "/AUDIT"); dsvEntry.addCategory(MODEL.FORMAT_URI.uri, AUDIT1_0.uri, null); dsvEntry.addCategory(MODEL.LABEL.uri, "Audit Trail for this object", null); if (m_format.equals(ATOM_ZIP1_1)) { String name = "AUDIT.0.xml"; try { m_zout.putNextEntry(new ZipEntry(name)); Reader r = new StringReader(DOTranslationUtility.getAuditTrail(m_obj)); IOUtils.copy(r, m_zout, m_encoding); m_zout.closeEntry(); r.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); dsvEntry.setSummary("AUDIT.0"); dsvEntry.setContent(iri, "text/xml"); } else { dsvEntry.setContent(DOTranslationUtility.getAuditTrail(m_obj), "text/xml"); } } Code Sample 2: public Bitmap getImage() throws IOException { int recordBegin = 78 + 8 * mCount; Bitmap result = null; FileChannel channel = new FileInputStream(mFile).getChannel(); channel.position(mRecodeOffset[mPage]); ByteBuffer bodyBuffer; if (mPage + 1 < mCount) { int length = mRecodeOffset[mPage + 1] - mRecodeOffset[mPage]; bodyBuffer = channel.map(MapMode.READ_ONLY, mRecodeOffset[mPage], length); byte[] tmpCache = new byte[bodyBuffer.capacity()]; bodyBuffer.get(tmpCache); FileOutputStream o = new FileOutputStream("/sdcard/test.bmp"); o.write(tmpCache); o.flush(); o.getFD().sync(); o.close(); result = BitmapFactory.decodeByteArray(tmpCache, 0, length); } else { } channel.close(); return result; }
11
Code Sample 1: private Document saveFile(Document document, File file) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { Preference preference = preferences.get(0); String repo = preference.getRepository(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(document.getLocation()); File folder = new File(sbRepo.append(sbFolder).toString()); log.info("Check in file ID [" + document.getId() + "] to " + folder.getAbsolutePath()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null, fcVersionDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append(".").append(document.getExt()); StringBuffer sbVersionFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append("_").append(document.getVersion().toString()).append(".").append(document.getExt()); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcVersionDest = new FileOutputStream(sbVersionFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); fcSource = new FileInputStream(file).getChannel(); fcVersionDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } if (fcVersionDest != null) { fcVersionDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } return document; } Code Sample 2: public static void copyFile(final String inFile, final String outFile) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(inFile).getChannel(); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } catch (final Exception e) { } finally { if (in != null) { try { in.close(); } catch (final Exception e) { } } if (out != null) { try { out.close(); } catch (final Exception e) { } } } }
00
Code Sample 1: public static IChemModel readInChI(URL url) throws CDKException { IChemModel chemModel = new ChemModel(); try { IMoleculeSet moleculeSet = new MoleculeSet(); chemModel.setMoleculeSet(moleculeSet); StdInChIParser parser = new StdInChIParser(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { if (line.toLowerCase().startsWith("inchi=")) { IAtomContainer atc = parser.parseInchi(line); moleculeSet.addAtomContainer(atc); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new CDKException(e.getMessage()); } return chemModel; } Code Sample 2: @SuppressWarnings("deprecation") private void loadClassFilesFromJar() { IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) getJavaElement(); File jarFile = packageFragmentRoot.getResource().getLocation().toFile(); try { URL url = jarFile.toURL(); URLConnection u = url.openConnection(); ZipInputStream inputStream = new ZipInputStream(u.getInputStream()); ZipEntry entry = inputStream.getNextEntry(); while (null != entry) { if (entry.getName().endsWith(".class")) { ClassParser parser = new ClassParser(inputStream, entry.getName()); Repository.addClass(parser.parse()); } entry = inputStream.getNextEntry(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public void fileCopy2(File inFile, File outFile) throws Exception { try { FileChannel srcChannel = new FileInputStream(inFile).getChannel(); FileChannel dstChannel = new FileOutputStream(outFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { throw new Exception("Could not copy file: " + inFile.getName()); } } Code Sample 2: public static ByteBuffer join(ByteBuffer buffer1, ByteBuffer buffer2) { if (buffer2 == null || buffer2.remaining() == 0) return NIOUtils.copy(buffer1); if (buffer1 == null || buffer1.remaining() == 0) return NIOUtils.copy(buffer2); ByteBuffer buffer = ByteBuffer.allocate(buffer1.remaining() + buffer2.remaining()); buffer.put(buffer1); buffer.put(buffer2); buffer.flip(); return buffer; }
11
Code Sample 1: private String load(URL url) { BufferedReader r = null; try { r = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); while (r.ready()) { buf.append(r.readLine()).append('\n'); } r.close(); return buf.toString(); } catch (IOException e) { e.printStackTrace(); return null; } } Code Sample 2: public String getScenarioData(String urlForSalesData) throws IOException, Exception { InputStream inputStream = null; BufferedReader bufferedReader = null; DataInputStream input = null; StringBuffer sBuf = new StringBuffer(); Proxy proxy; if (httpWebProxyServer != null && Integer.toString(httpWebProxyPort) != null) { SocketAddress address = new InetSocketAddress(httpWebProxyServer, httpWebProxyPort); proxy = new Proxy(Proxy.Type.HTTP, address); } else { proxy = null; } proxy = null; URL url; try { url = new URL(urlForSalesData); HttpURLConnection httpUrlConnection; if (proxy != null) httpUrlConnection = (HttpURLConnection) url.openConnection(proxy); else httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setDoInput(true); httpUrlConnection.setRequestMethod("GET"); String name = rb.getString("WRAP_NAME"); String password = rb.getString("WRAP_PASSWORD"); Credentials simpleAuthCrentials = new Credentials(TOKEN_TYPE.SimpleApiAuthToken, name, password); ACSTokenProvider tokenProvider = new ACSTokenProvider(httpWebProxyServer, httpWebProxyPort, simpleAuthCrentials); String requestUriStr1 = "https://" + solutionName + "." + acmHostName + "/" + serviceName; String appliesTo1 = rb.getString("SIMPLEAPI_APPLIES_TO"); String token = tokenProvider.getACSToken(requestUriStr1, appliesTo1); httpUrlConnection.addRequestProperty("token", "WRAPv0.9 " + token); httpUrlConnection.addRequestProperty("solutionName", solutionName); httpUrlConnection.connect(); if (httpUrlConnection.getResponseCode() == HttpServletResponse.SC_UNAUTHORIZED) { List<TestSalesOrderService> salesOrderServiceBean = new ArrayList<TestSalesOrderService>(); TestSalesOrderService response = new TestSalesOrderService(); response.setResponseCode(HttpServletResponse.SC_UNAUTHORIZED); response.setResponseMessage(httpUrlConnection.getResponseMessage()); salesOrderServiceBean.add(response); } inputStream = httpUrlConnection.getInputStream(); input = new DataInputStream(inputStream); bufferedReader = new BufferedReader(new InputStreamReader(input)); String str; while (null != ((str = bufferedReader.readLine()))) { sBuf.append(str); } String responseString = sBuf.toString(); return responseString; } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } }
00
Code Sample 1: public static boolean copyFile(File from, File to) { try { FileChannel fromChannel = new FileInputStream(from).getChannel(); FileChannel toChannel = new FileOutputStream(to).getChannel(); toChannel.transferFrom(fromChannel, 0, fromChannel.size()); fromChannel.close(); toChannel.close(); } catch (IOException e) { log.error("failed to copy " + from.getAbsolutePath() + " to " + to.getAbsolutePath() + ": caught exception", e); return false; } return true; } Code Sample 2: public static String createHash(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] digest = md.digest(); return toHexString(digest); } catch (NoSuchAlgorithmException nsae) { System.out.println(nsae.getMessage()); } return ""; }
00
Code Sample 1: private void btnOkActionPerformed(java.awt.event.ActionEvent evt) { try { int id = 0; String sql = "SELECT MAX(ID) as MAX_ID from CORE_USER_GROUPS"; PreparedStatement pStmt = Database.getMyConnection().prepareStatement(sql); ResultSet rs = pStmt.executeQuery(); if (rs.next()) { id = rs.getInt("MAX_ID") + 1; } else { id = 1; } Database.close(pStmt); sql = "INSERT INTO CORE_USER_GROUPS" + " (ID, GRP_NAME, GRP_DESC, DATE_INITIAL, DATE_FINAL, IND_STATUS)" + " VALUES (?, ?, ?, ?, ?, ?)"; pStmt = Database.getMyConnection().prepareStatement(sql); pStmt.setInt(1, id); pStmt.setString(2, txtGrpName.getText()); pStmt.setString(3, txtGrpDesc.getText()); pStmt.setDate(4, Utils.getTodaySql()); pStmt.setDate(5, Date.valueOf("9999-12-31")); pStmt.setString(6, "A"); pStmt.executeUpdate(); Database.getMyConnection().commit(); Database.close(pStmt); MessageBox.ok("New group added successfully", this); rs = getGroups(); tblGroups.setModel(new GroupsTableModel(rs)); Database.close(rs); } catch (SQLException e) { log.error("Failed with update operation \n" + e.getMessage()); MessageBox.ok("Failed to create the new group in the database", this); try { Database.getMyConnection().rollback(); } catch (Exception inner) { } ; } catch (IllegalArgumentException e) { log.error("Illegal argument for the DATE_FINAL \n" + e.getMessage()); MessageBox.ok("Failed to create the new group in the database", this); try { Database.getMyConnection().rollback(); } catch (Exception inner) { } ; } finally { txtGrpName.setEnabled(false); txtGrpDesc.setEnabled(false); btnOk.setEnabled(false); btnCancel.requestFocus(); } } Code Sample 2: public static void copyFile4(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copy(in, out); in.close(); out.close(); }
00
Code Sample 1: public void open(final String method, final java.net.URL url, boolean asyncFlag, final String userName, final String password) throws java.io.IOException { this.abort(); Proxy proxy = this.proxy; URLConnection c = proxy == null || proxy == Proxy.NO_PROXY ? url.openConnection() : url.openConnection(proxy); synchronized (this) { this.connection = c; this.isAsync = asyncFlag; this.requestMethod = method; this.requestURL = url; this.requestUserName = userName; this.requestPassword = password; } this.changeState(HttpRequest.STATE_LOADING, 0, null, null); } Code Sample 2: public void updatePortletName(PortletName portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "update WM_PORTAL_PORTLET_NAME " + "set TYPE=? " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); ps.setString(1, portletNameBean.getPortletName()); RsetTools.setLong(ps, 2, portletNameBean.getPortletId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
11
Code Sample 1: public static boolean copy(FileSystem srcFS, Path src, FileSystem dstFS, Path dst, boolean deleteSource, boolean overwrite, Configuration conf) throws IOException { LOG.debug("[sgkim] copy - start"); dst = checkDest(src.getName(), dstFS, dst, overwrite); if (srcFS.getFileStatus(src).isDir()) { checkDependencies(srcFS, src, dstFS, dst); if (!dstFS.mkdirs(dst)) { return false; } FileStatus contents[] = srcFS.listStatus(src); for (int i = 0; i < contents.length; i++) { copy(srcFS, contents[i].getPath(), dstFS, new Path(dst, contents[i].getPath().getName()), deleteSource, overwrite, conf); } } else if (srcFS.isFile(src)) { InputStream in = null; OutputStream out = null; try { LOG.debug("[sgkim] srcFS: " + srcFS + ", src: " + src); in = srcFS.open(src); LOG.debug("[sgkim] dstFS: " + dstFS + ", dst: " + dst); out = dstFS.create(dst, overwrite); LOG.debug("[sgkim] copyBytes - start"); IOUtils.copyBytes(in, out, conf, true); LOG.debug("[sgkim] copyBytes - end"); } catch (IOException e) { IOUtils.closeStream(out); IOUtils.closeStream(in); throw e; } } else { throw new IOException(src.toString() + ": No such file or directory"); } LOG.debug("[sgkim] copy - end"); if (deleteSource) { return srcFS.delete(src, true); } else { return true; } } Code Sample 2: private String getResourceAsString(final String name) throws IOException { final InputStream is = JiBXTestCase.class.getResourceAsStream(name); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyAndClose(is, baos); return baos.toString(); }
11
Code Sample 1: public long getMD5Hash(String str) { MessageDigest m = null; try { m = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(str.getBytes(), 0, str.length()); return new BigInteger(1, m.digest()).longValue(); } Code Sample 2: public static String generateHash(String msg) throws NoSuchAlgorithmException { if (msg == null) { throw new IllegalArgumentException("Input string can not be null"); } MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); m.update(msg.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1, digest); String hashText = bigInt.toString(16); while (hashText.length() < 32) { hashText = "0" + hashText; } return hashText; }
11
Code Sample 1: @Override public Document duplicate() { BinaryDocument b = new BinaryDocument(this.name, this.content.getContentType()); try { IOUtils.copy(this.getContent().getInputStream(), this.getContent().getOutputStream()); return b; } catch (IOException e) { throw ManagedIOException.manage(e); } } Code Sample 2: public void invoke(WorkflowContext arg0, ProgressMonitor arg1, Issues arg2) { File inputFile = new File(getInputFile()); File outputFile = new File(getOutputFile()); if (!getFileExtension(getInputFile()).equalsIgnoreCase(getFileExtension(getOutputFile())) || !getFileExtension(getInputFile()).equalsIgnoreCase(OO_CALC_EXTENSION)) { OpenOfficeConnection connection = new SocketOpenOfficeConnection(); OpenOfficeDocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(inputFile, outputFile); connection.disconnect(); } else { FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = new FileInputStream(inputFile).getChannel(); outputChannel = new FileOutputStream(outputFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } catch (FileNotFoundException e) { arg2.addError("File not found: " + e.getMessage()); } catch (IOException e) { arg2.addError("Could not copy file: " + e.getMessage()); } finally { if (inputChannel != null) { try { inputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } if (outputChannel != null) { try { outputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } } } }
00
Code Sample 1: private static void loadProperties(Properties props, String res, boolean warnIfNotFound) throws IOException { log.debug("Reading properties from resource " + res); URL url = ResourceFileStorageFactory.class.getResource(res); if (null == url) { if (warnIfNotFound) { log.warn("Resource " + res + " was not found"); } else { log.debug("Resource " + res + " was not found"); } } else { InputStream in = url.openStream(); try { props.load(in); } finally { in.close(); } } } Code Sample 2: public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_name); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
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: public void notifyIterationEnds(final IterationEndsEvent event) { log.info("moving files..."); File source = new File("deqsim.log"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("deqsim.log")); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move deqsim.log to its iteration directory."); } } int parallelCnt = 0; source = new File("deqsim.log." + parallelCnt); while (source.exists()) { File destination = new File(Controler.getIterationFilename("deqsim.log." + parallelCnt)); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move deqsim.log." + parallelCnt + " to its iteration directory."); } parallelCnt++; source = new File("deqsim.log." + parallelCnt); } source = new File("loads_out.txt"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("loads_out.txt")); try { IOUtils.copyFile(source, destination); } catch (FileNotFoundException e) { log.info("WARNING: Could not copy loads_out.txt to its iteration directory."); } catch (IOException e) { log.info("WARNING: Could not copy loads_out.txt to its iteration directory."); } destination = new File("loads_in.txt"); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move loads_out.txt to loads_in.txt."); } } source = new File("linkprocs.txt"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("linkprocs.txt")); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move linkprocs.txt to its iteration directory."); } } }
11
Code Sample 1: public void writeData(String name, int items, int mznum, int mzscale, long tstart, long tdelta, int[] peaks) { PrintWriter file = getWriter(name + ".txt"); file.println("999 9999"); file.println("Doe, John"); file.println("TEST Lab"); if (mzscale == 1) file.println("PALMS Positive Ion Data"); else if (mzscale == -1) file.println("PALMS Negative Ion Data"); else file.println("PALMS GJIFJIGJ Ion Data"); file.println("TEST Mission"); file.println("1 1"); file.println("1970 01 01 2008 07 09"); file.println("0"); file.println("TIME (UT SECONDS)"); file.println(mznum + 4); for (int i = 0; i < mznum + 4; i++) file.println("1.0"); for (int i = 0; i < mznum + 4; i++) file.println("9.9E29"); file.println("TOTION total MCP signal (electron units)"); file.println("HMASS high mass integral (fraction)"); file.println("UNLIST (unlisted low mass peaks (fraction)"); file.println("UFO unidentified peaks (fraction)"); for (int i = 1; i <= mznum; i++) file.println("MS" + i + " (fraction)"); int header2length = 13; file.println(header2length); for (int i = 0; i < header2length; i++) file.println("1.0"); for (int i = 0; i < header2length; i++) file.println("9.9E29"); file.println("AirCraftTime aircraft time (s)"); file.println("INDEX index ()"); file.println("SCAT scatter (V)"); file.println("JMETER joule meter ()"); file.println("ND neutral density (fraction)"); file.println("SCALEA Mass scale intercept (us)"); file.println("SCALEB mass scale slope (us)"); file.println("NUMPKS number of peaks ()"); file.println("CONF confidence (coded)"); file.println("CAT preliminary category ()"); file.println("AeroDiam aerodynamic diameter (um)"); file.println("AeroDiam1p7 aero diam if density=1.7 (um)"); file.println("TOTBACK total background subtracted (electron units)"); file.println("0"); file.println("0"); String nothing = "0.000000"; for (int i = 0; i < items; i++) { file.println(tstart + (tdelta * i)); file.println(tstart + (tdelta * i) - 3); file.println(i + 1); for (int j = 0; j < 15; j++) file.println(Math.random()); boolean peaked = false; for (int k = 1; k <= mznum; k++) { for (int j = 0; j < peaks.length && !peaked; j++) if (k == peaks[j]) { double randData = (int) (1000000 * (j + 1)); file.println(randData / 1000000); peaked = true; } if (!peaked) file.println(nothing); peaked = false; } } try { Scanner test = new Scanner(f); while (test.hasNext()) { System.out.println(test.nextLine()); } System.out.println("test"); } catch (Exception e) { } file.close(); } Code Sample 2: public void unzip(String zipFileName, String outputDirectory) throws Exception { ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName)); ZipEntry z; while ((z = in.getNextEntry()) != null) { System.out.println("unziping " + z.getName()); if (z.isDirectory()) { String name = z.getName(); name = name.substring(0, name.length() - 1); File f = new File(outputDirectory + File.separator + name); f.mkdir(); System.out.println("mkdir " + outputDirectory + File.separator + name); } else { File f = new File(outputDirectory + File.separator + z.getName()); f.createNewFile(); FileOutputStream out = new FileOutputStream(f); int b; while ((b = in.read()) != -1) out.write(b); out.close(); } } in.close(); }
00
Code Sample 1: public Item findById(String itemId) throws UnsupportedEncodingException, IOException { String sessionId = (String) RuntimeAccess.getInstance().getSession().getAttribute("SESSION_ID"); DefaultHttpClient httpclient = new DefaultHttpClient(); FindItemByIdRequest request = new FindItemByIdRequest(); request.setItemID(itemId); request.setSessionId(sessionId); XStream writer = new XStream(); writer.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); writer.alias("FindItemByIdRequest", FindItemByIdRequest.class); XStream reader = new XStream(); reader.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); reader.alias("FindItemByIdResponse", FindItemByIdResponse.class); String strRequest = URLEncoder.encode(reader.toXML(request), "UTF-8"); HttpGet httpget = new HttpGet(MewitProperties.getMewitUrl() + "/resources/findItemById?REQUEST=" + strRequest); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { String result = URLDecoder.decode(EntityUtils.toString(entity), "UTF-8"); FindItemByIdResponse fibiResponse = (FindItemByIdResponse) reader.fromXML(result); return fibiResponse.getItem(); } return null; } Code Sample 2: public Document retrieveDefinition(String uri) throws IOException, UnvalidResponseException { if (!isADbPediaURI(uri)) throw new IllegalArgumentException("Not a DbPedia Resource URI"); String rawDataUri = fromResourceToRawDataUri(uri); URL url = new URL(rawDataUri); URLConnection conn = url.openConnection(); logger.debug(".conn open"); conn.setDoOutput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); logger.debug(".resp obtained"); StringBuffer responseBuffer = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { responseBuffer.append(line); responseBuffer.append(NEWLINE); } rd.close(); logger.debug(".done"); try { return documentParser.parse(responseBuffer.toString()); } catch (SAXException e) { throw new UnvalidResponseException("Incorrect XML document", e); } }
00
Code Sample 1: public void atualizarLivro(LivroBean livro) { PreparedStatement pstmt = null; String sql = "update livro " + "set " + "isbn = ?, " + "autor = ?, " + "editora = ?, " + "edicao = ?, " + "titulo = ? " + "where " + "isbn = ?"; try { pstmt = connection.prepareStatement(sql); pstmt.setString(1, livro.getISBN()); pstmt.setString(2, livro.getAutor()); pstmt.setString(3, livro.getEditora()); pstmt.setString(4, livro.getEdicao()); pstmt.setString(5, livro.getTitulo()); pstmt.executeUpdate(); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (SQLException ex1) { throw new RuntimeException("Erro ao tentar atualizar livro.", ex1); } throw new RuntimeException("Erro ao tentar atualizar livro.", ex); } finally { try { if (pstmt != null) { pstmt.close(); } if (connection != null) { connection.close(); } } catch (SQLException ex) { throw new RuntimeException("Erro ao tentar atualizar livro.", ex); } } } Code Sample 2: private void _PostParser(Document document, AnnotationManager annoMan, Document htmldoc, String baseurl) { xformer = annoMan.getTransformer(); builder = annoMan.getBuilder(); String annohash = ""; if (document == null) return; NodeList ndlist = document.getElementsByTagNameNS(annoNS, "body"); if (ndlist.getLength() != 1) { System.out.println("Sorry Annotation Body was found " + ndlist.getLength() + " times"); return; } Element bodynode = (Element) ndlist.item(0); Node htmlNode = bodynode.getElementsByTagName("html").item(0); if (htmlNode == null) htmlNode = bodynode.getElementsByTagName("HTML").item(0); Document newdoc = builder.newDocument(); Element rootelem = newdoc.createElementNS(rdfNS, "r:RDF"); rootelem.setAttribute("xmlns:r", rdfNS); rootelem.setAttribute("xmlns:a", annoNS); rootelem.setAttribute("xmlns:d", dubNS); rootelem.setAttribute("xmlns:t", threadNS); newdoc.appendChild(rootelem); Element tmpelem; NodeList tmpndlist; Element annoElem = newdoc.createElementNS(annoNS, "a:Annotation"); rootelem.appendChild(annoElem); tmpelem = (Element) document.getElementsByTagNameNS(annoNS, "context").item(0); String context = tmpelem.getChildNodes().item(0).getNodeValue(); annoElem.setAttributeNS(annoNS, "a:context", context); NodeList elemcontl = tmpelem.getElementsByTagNameNS(alNS, "context-element"); Node ncontext_element = null; if (elemcontl.getLength() > 0) { Node old_context_element = elemcontl.item(0); ncontext_element = newdoc.importNode(old_context_element, true); } tmpndlist = document.getElementsByTagNameNS(dubNS, "title"); annoElem.setAttributeNS(dubNS, "d:title", tmpndlist.getLength() > 0 ? tmpndlist.item(0).getChildNodes().item(0).getNodeValue() : "Default"); tmpelem = (Element) document.getElementsByTagNameNS(dubNS, "creator").item(0); annoElem.setAttributeNS(dubNS, "d:creator", tmpelem.getChildNodes().item(0).getNodeValue()); tmpelem = (Element) document.getElementsByTagNameNS(annoNS, "created").item(0); annoElem.setAttributeNS(annoNS, "a:created", tmpelem.getChildNodes().item(0).getNodeValue()); tmpelem = (Element) document.getElementsByTagNameNS(dubNS, "date").item(0); annoElem.setAttributeNS(dubNS, "d:date", tmpelem.getChildNodes().item(0).getNodeValue()); tmpndlist = document.getElementsByTagNameNS(dubNS, "language"); String language = (tmpndlist.getLength() > 0 ? tmpndlist.item(0).getChildNodes().item(0).getNodeValue() : "en"); annoElem.setAttributeNS(dubNS, "d:language", language); Node typen = newdoc.importNode(document.getElementsByTagNameNS(rdfNS, "type").item(0), true); annoElem.appendChild(typen); Element contextn = newdoc.createElementNS(annoNS, "a:context"); contextn.setAttributeNS(rdfNS, "r:resource", context); annoElem.appendChild(contextn); Node annotatesn = newdoc.importNode(document.getElementsByTagNameNS(annoNS, "annotates").item(0), true); annoElem.appendChild(annotatesn); Element newbodynode = newdoc.createElementNS(annoNS, "a:body"); annoElem.appendChild(newbodynode); if (ncontext_element != null) { contextn.appendChild(ncontext_element); } else { System.out.println("No context element found, we create one..."); try { XPointer xptr = new XPointer(htmldoc); NodeRange xprange = xptr.getRange(context, htmldoc); Element context_elem = newdoc.createElementNS(alNS, "al:context-element"); context_elem.setAttributeNS(alNS, "al:text", xprange.getContentString()); context_elem.appendChild(newdoc.createTextNode(annoMan.generateContextString(xprange))); contextn.appendChild(context_elem); } catch (XPointerRangeException e2) { e2.printStackTrace(); } } WordFreq wf = new WordFreq(annoMan.extractTextFromNode(htmldoc)); Element docident = newdoc.createElementNS(alNS, "al:document-identifier"); annotatesn.appendChild(docident); docident.setAttributeNS(alNS, "al:orig-url", ((Element) annotatesn).getAttributeNS(rdfNS, "resource")); docident.setAttributeNS(alNS, "al:version", "1"); Iterator it = null; it = wf.getSortedWordlist(); Map.Entry ent; String word; int count; int i = 0; while (it.hasNext()) { ent = (Map.Entry) it.next(); word = ((String) ent.getKey()); count = ((Counter) ent.getValue()).count; if ((word.length() > 4) && (i < 10)) { Element wordelem = newdoc.createElementNS(alNS, "al:word"); wordelem.setAttributeNS(alNS, "al:freq", Integer.toString(count)); wordelem.appendChild(newdoc.createTextNode(word)); docident.appendChild(wordelem); i++; } } try { StringWriter strw = new StringWriter(); MessageDigest messagedigest = MessageDigest.getInstance("MD5"); xformer.transform(new DOMSource(newdoc), new StreamResult(strw)); messagedigest.update(strw.toString().getBytes()); byte[] md5bytes = messagedigest.digest(); annohash = ""; for (int b = 0; b < md5bytes.length; b++) { String s = Integer.toHexString(md5bytes[b] & 0xFF); annohash = annohash + ((s.length() == 1) ? "0" + s : s); } this.annohash = annohash; annoElem.setAttribute("xmlns:al", alNS); annoElem.setAttributeNS(alNS, "al:id", getAnnohash()); Location = (baseurl + "/annotation/" + getAnnohash()); annoElem.setAttributeNS(rdfNS, "r:about", Location); newbodynode.setAttributeNS(rdfNS, "r:resource", baseurl + "/annotation/body/" + getAnnohash()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } annoMan.store(newdoc.getDocumentElement()); annoMan.createAnnoResource(newdoc.getDocumentElement(), getAnnohash()); if (htmlNode != null) annoMan.createAnnoBody(htmlNode, getAnnohash()); Location = (this.baseurl + "/annotation/" + getAnnohash()); annoElem.setAttributeNS(rdfNS, "r:about", Location); this.responseDoc = newdoc; }
11
Code Sample 1: 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); } Code Sample 2: @Test(dependsOnMethods = { "getSize" }) public void download() throws IOException { FileObject typica = fsManager.resolveFile("s3://" + bucketName + "/jonny.zip"); File localCache = File.createTempFile("vfs.", ".s3-test"); FileOutputStream out = new FileOutputStream(localCache); IOUtils.copy(typica.getContent().getInputStream(), out); Assert.assertEquals(localCache.length(), typica.getContent().getSize()); localCache.delete(); }
11
Code Sample 1: private static MyCookieData parseCookie(Cookie cookie) throws CookieException { String value = cookie.getValue(); System.out.println("original cookie: " + value); value = value.replace("%3A", ":"); value = value.replace("%40", "@"); System.out.println("cookie after replacement: " + value); String[] parts = value.split(":"); if (parts.length < 4) throw new CookieException("only " + parts.length + " parts in the cookie! " + value); String email = parts[0]; String nickname = parts[1]; boolean admin = Boolean.getBoolean(parts[2].toLowerCase()); String hsh = parts[3]; boolean valid_cookie = true; String cookie_secret = System.getProperty("COOKIE_SECRET"); if (cookie_secret == "") throw new CookieException("cookie secret is not set"); if (email.equals("")) { System.out.println("email is empty!"); nickname = ""; admin = false; } else { try { MessageDigest sha = MessageDigest.getInstance("SHA"); sha.update((email + nickname + admin + cookie_secret).getBytes()); StringBuilder builder = new StringBuilder(); for (byte b : sha.digest()) { byte tmphigh = (byte) (b >> 4); tmphigh = (byte) (tmphigh & 0xf); builder.append(hextab.charAt(tmphigh)); byte tmplow = (byte) (b & 0xf); builder.append(hextab.charAt(tmplow)); } System.out.println(); String vhsh = builder.toString(); if (!vhsh.equals(hsh)) { System.out.println("hash not same!"); System.out.println("hash passed in: " + hsh); System.out.println("hash generated: " + vhsh); valid_cookie = false; } else System.out.println("cookie match!"); } catch (NoSuchAlgorithmException ex) { } } return new MyCookieData(email, admin, nickname, valid_cookie); } Code Sample 2: public static String getMD5(String s) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(s.toLowerCase().getBytes()); return HexString.bufferToHex(md5.digest()); } catch (NoSuchAlgorithmException e) { System.err.println("Error grave al inicializar MD5"); e.printStackTrace(); return "!!"; } }
00
Code Sample 1: private InputStream getSearchInputStream(String name) { URL url = null; try { url = new URL(TheMovieDBXmlPullFeedParser.SEARCH_FEED_URL + URLEncoder.encode(name)); Log.d(Constants.LOG_TAG, "Movie search URL: " + url); } catch (MalformedURLException e) { throw new RuntimeException(e); } try { return url.openConnection().getInputStream(); } catch (IOException e) { throw new RuntimeException(e); } } Code Sample 2: String extractTiffFile(String path) throws IOException { ZipInputStream in = new ZipInputStream(new FileInputStream(path)); OutputStream out = new FileOutputStream(dir + TEMP_NAME); byte[] buf = new byte[1024]; int len; ZipEntry entry = in.getNextEntry(); if (entry == null) return null; String name = entry.getName(); if (!name.endsWith(".tif")) throw new IOException("This ZIP archive does not appear to contain a TIFF file"); while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); return name; }
11
Code Sample 1: @Override public boolean copyFile(String srcRootPath, String srcDir, String srcFileName, String destRootPath, String destDir, String destFileName) { File srcPath = new File(srcRootPath + separator() + Database.getDomainName() + separator() + srcDir); if (!srcPath.exists()) { try { srcPath.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + srcPath); return false; } } File destPath = new File(destRootPath + separator() + Database.getDomainName() + separator() + destDir); if (!destPath.exists()) { try { destPath.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + destPath); return false; } } File from = new File(srcPath + separator() + srcFileName); File to = new File(destPath + separator() + destFileName); boolean res = true; FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(from).getChannel(); destChannel = new FileOutputStream(to).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (Exception ex) { logger.error("Exception", ex); res = false; } finally { if (destChannel != null) { try { destChannel.close(); } catch (IOException ex) { logger.error("Exception", ex); res = false; } } if (srcChannel != null) { try { srcChannel.close(); } catch (IOException ex) { logger.error("Exception", ex); res = false; } } } return res; } Code Sample 2: private void invokeTest(String queryfile, String target) { try { String query = IOUtils.toString(XPathMarkBenchmarkTest.class.getResourceAsStream(queryfile)).trim(); String args = EXEC_CMD + " \"" + query + "\" \"" + target + '"'; System.out.println("Invoke command: \n " + args); Process proc = Runtime.getRuntime().exec(args, null, benchmarkDir); InputStream is = proc.getInputStream(); File outFile = new File(outDir, queryfile + ".result"); IOUtils.copy(is, new FileOutputStream(outFile)); is.close(); int ret = proc.waitFor(); if (ret != 0) { System.out.println("process exited with value : " + ret); } } catch (IOException ioe) { throw new IllegalStateException(ioe); } catch (InterruptedException irre) { throw new IllegalStateException(irre); } }
00
Code Sample 1: protected Source getStylesheetSource(Resource stylesheetLocation) throws ApplicationContextException { if (logger.isDebugEnabled()) { logger.debug("Loading XSLT stylesheet from " + stylesheetLocation); } try { URL url = stylesheetLocation.getURL(); String urlPath = url.toString(); String systemId = urlPath.substring(0, urlPath.lastIndexOf('/') + 1); return new StreamSource(url.openStream(), systemId); } catch (IOException ex) { throw new ApplicationContextException("Can't load XSLT stylesheet from " + stylesheetLocation, ex); } } Code Sample 2: public static PortalConfig install(File xml, File dir) throws IOException, ConfigurationException { if (!dir.exists()) { log.info("Creating directory {}", dir); dir.mkdirs(); } if (!xml.exists()) { log.info("Installing default configuration to {}", xml); OutputStream output = new FileOutputStream(xml); try { InputStream input = ResourceLoader.open("res://" + PORTAL_CONFIG_XML); try { IOUtils.copy(input, output); } finally { input.close(); } } finally { output.close(); } } return create(xml, dir); }
00
Code Sample 1: private static void initMagicRules() { InputStream in = null; try { String fname = System.getProperty("magic-mime"); if (fname != null && fname.length() != 0) { in = new FileInputStream(fname); if (in != null) { parse("-Dmagic-mime=" + fname, new InputStreamReader(in)); } } } catch (Exception e) { log.error("Failed to parse custom magic mime file defined by system property -Dmagic-mime [" + System.getProperty("magic-mime") + "]. File will be ignored.", e); } finally { in = closeStream(in); } try { Enumeration en = MimeUtil.class.getClassLoader().getResources("magic.mime"); while (en.hasMoreElements()) { URL url = (URL) en.nextElement(); in = url.openStream(); if (in != null) { try { parse("classpath:[" + url + "]", new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse magic.mime rule file [" + url + "] on the classpath. File will be ignored.", ex); } } } } catch (Exception e) { log.error("Problem while processing magic.mime files from classpath. Files will be ignored.", e); } finally { in = closeStream(in); } try { File f = new File(System.getProperty("user.home") + File.separator + ".magic.mime"); if (f.exists()) { in = new FileInputStream(f); if (in != null) { try { parse(f.getAbsolutePath(), new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse .magic.mime file from the users home directory. File will be ignored.", ex); } } } } catch (Exception e) { log.error("Problem while processing .magic.mime file from the users home directory. File will be ignored.", e); } finally { in = closeStream(in); } try { String name = System.getProperty("MAGIC"); if (name != null && name.length() != 0) { if (name.indexOf('.') < 0) { name = name + ".mime"; } else { name = name.substring(0, name.indexOf('.') - 1) + "mime"; } File f = new File(name); if (f.exists()) { in = new FileInputStream(f); if (in != null) { try { parse(f.getAbsolutePath(), new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse magic.mime file from directory located by environment variable MAGIC. File will be ignored.", ex); } } } } } catch (Exception e) { log.error("Problem while processing magic.mime file from directory located by environment variable MAGIC. File will be ignored.", e); } finally { in = closeStream(in); } int mMagicMimeEntriesSizeBeforeReadingOS = mMagicMimeEntries.size(); Iterator it = magicMimeFileLocations.iterator(); while (it.hasNext()) { parseMagicMimeFileLocation((String) it.next()); } if (mMagicMimeEntriesSizeBeforeReadingOS == mMagicMimeEntries.size()) { try { String resource = "eu/medsea/mimeutil/magic.mime"; in = MimeUtil.class.getClassLoader().getResourceAsStream(resource); if (in != null) { try { parse("resource:" + resource, new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse internal magic.mime file.", ex); } } } catch (Exception e) { log.error("Problem while processing internal magic.mime file.", e); } finally { in = closeStream(in); } } } Code Sample 2: public static String digest(String ha1, String ha2, String nonce) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(ha1, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(nonce, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(ha2, ISO_8859_1)); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } }
11
Code Sample 1: public static String md5String(String string) { try { MessageDigest msgDigest = MessageDigest.getInstance("MD5"); msgDigest.update(string.getBytes("UTF-8")); byte[] digest = msgDigest.digest(); String result = ""; for (int i = 0; i < digest.length; i++) { int value = digest[i]; if (value < 0) value += 256; result += Integer.toHexString(value); } return result; } catch (UnsupportedEncodingException error) { throw new IllegalArgumentException(error); } catch (NoSuchAlgorithmException error) { throw new IllegalArgumentException(error); } } Code Sample 2: public String encryptToMD5(String info) { byte[] digesta = null; try { MessageDigest alga = MessageDigest.getInstance("MD5"); alga.update(info.getBytes()); digesta = alga.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } String rs = byte2hex(digesta); return rs; }
00
Code Sample 1: private static String getDigest(String srcStr, String alg) { Assert.notNull(srcStr); Assert.notNull(alg); try { MessageDigest alga = MessageDigest.getInstance(alg); alga.update(srcStr.getBytes()); byte[] digesta = alga.digest(); return byte2hex(digesta); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: public Message[] expunge() throws MessagingException { Statement oStmt = null; CallableStatement oCall = null; PreparedStatement oUpdt = null; ResultSet oRSet; if (DebugFile.trace) { DebugFile.writeln("Begin DBFolder.expunge()"); DebugFile.incIdent(); } if (0 == (iOpenMode & READ_WRITE)) { if (DebugFile.trace) DebugFile.decIdent(); throw new javax.mail.FolderClosedException(this, "Folder is not open is READ_WRITE mode"); } if ((0 == (iOpenMode & MODE_MBOX)) && (0 == (iOpenMode & MODE_BLOB))) { if (DebugFile.trace) DebugFile.decIdent(); throw new javax.mail.FolderClosedException(this, "Folder is not open in MBOX nor BLOB mode"); } MboxFile oMBox = null; DBSubset oDeleted = new DBSubset(DB.k_mime_msgs, DB.gu_mimemsg + "," + DB.pg_message, DB.bo_deleted + "=1 AND " + DB.gu_category + "='" + oCatg.getString(DB.gu_category) + "'", 100); try { int iDeleted = oDeleted.load(getConnection()); File oFile = getFile(); if (oFile.exists() && iDeleted > 0) { oMBox = new MboxFile(oFile, MboxFile.READ_WRITE); int[] msgnums = new int[iDeleted]; for (int m = 0; m < iDeleted; m++) msgnums[m] = oDeleted.getInt(1, m); oMBox.purge(msgnums); oMBox.close(); } oStmt = oConn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); oRSet = oStmt.executeQuery("SELECT p." + DB.file_name + " FROM " + DB.k_mime_parts + " p," + DB.k_mime_msgs + " m WHERE p." + DB.gu_mimemsg + "=m." + DB.gu_mimemsg + " AND m." + DB.id_disposition + "='reference' AND m." + DB.bo_deleted + "=1 AND m." + DB.gu_category + "='" + oCatg.getString(DB.gu_category) + "'"); while (oRSet.next()) { String sFileName = oRSet.getString(1); if (!oRSet.wasNull()) { try { File oRef = new File(sFileName); oRef.delete(); } catch (SecurityException se) { if (DebugFile.trace) DebugFile.writeln("SecurityException " + sFileName + " " + se.getMessage()); } } } oRSet.close(); oRSet = null; oStmt.close(); oStmt = null; oFile = getFile(); oStmt = oConn.createStatement(); oStmt.executeUpdate("UPDATE " + DB.k_categories + " SET " + DB.len_size + "=" + String.valueOf(oFile.length()) + " WHERE " + DB.gu_category + "='" + getCategory().getString(DB.gu_category) + "'"); oStmt.close(); oStmt = null; if (oConn.getDataBaseProduct() == JDCConnection.DBMS_POSTGRESQL) { oStmt = oConn.createStatement(); for (int d = 0; d < iDeleted; d++) oStmt.executeQuery("SELECT k_sp_del_mime_msg('" + oDeleted.getString(0, d) + "')"); oStmt.close(); oStmt = null; } else { oCall = oConn.prepareCall("{ call k_sp_del_mime_msg(?) }"); for (int d = 0; d < iDeleted; d++) { oCall.setString(1, oDeleted.getString(0, d)); oCall.execute(); } oCall.close(); oCall = null; } if (oFile.exists() && iDeleted > 0) { BigDecimal oUnit = new BigDecimal(1); oStmt = oConn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); oRSet = oStmt.executeQuery("SELECT MAX(" + DB.pg_message + ") FROM " + DB.k_mime_msgs + " WHERE " + DB.gu_category + "='getCategory().getString(DB.gu_category)'"); oRSet.next(); BigDecimal oMaxPg = oRSet.getBigDecimal(1); if (oRSet.wasNull()) oMaxPg = new BigDecimal(0); oRSet.close(); oRSet = null; oStmt.close(); oStmt = null; oMaxPg = oMaxPg.add(oUnit); oStmt = oConn.createStatement(); oStmt.executeUpdate("UPDATE " + DB.k_mime_msgs + " SET " + DB.pg_message + "=" + DB.pg_message + "+" + oMaxPg.toString() + " WHERE " + DB.gu_category + "='" + getCategory().getString(DB.gu_category) + "'"); oStmt.close(); oStmt = null; DBSubset oMsgSet = new DBSubset(DB.k_mime_msgs, DB.gu_mimemsg + "," + DB.pg_message, DB.gu_category + "='" + getCategory().getString(DB.gu_category) + "' ORDER BY " + DB.pg_message, 1000); int iMsgCount = oMsgSet.load(oConn); oMBox = new MboxFile(oFile, MboxFile.READ_ONLY); long[] aPositions = oMBox.getMessagePositions(); oMBox.close(); if (iMsgCount != aPositions.length) { throw new IOException("DBFolder.expunge() Message count of " + String.valueOf(aPositions.length) + " at MBOX file " + oFile.getName() + " does not match message count at database index of " + String.valueOf(iMsgCount)); } oMaxPg = new BigDecimal(0); oUpdt = oConn.prepareStatement("UPDATE " + DB.k_mime_msgs + " SET " + DB.pg_message + "=?," + DB.nu_position + "=? WHERE " + DB.gu_mimemsg + "=?"); for (int m = 0; m < iMsgCount; m++) { oUpdt.setBigDecimal(1, oMaxPg); oUpdt.setBigDecimal(2, new BigDecimal(aPositions[m])); oUpdt.setString(3, oMsgSet.getString(0, m)); oUpdt.executeUpdate(); oMaxPg = oMaxPg.add(oUnit); } oUpdt.close(); } oConn.commit(); } catch (SQLException sqle) { try { if (oMBox != null) oMBox.close(); } catch (Exception e) { } try { if (oStmt != null) oStmt.close(); } catch (Exception e) { } try { if (oCall != null) oCall.close(); } catch (Exception e) { } try { if (oConn != null) oConn.rollback(); } catch (Exception e) { } throw new MessagingException(sqle.getMessage(), sqle); } catch (IOException sqle) { try { if (oMBox != null) oMBox.close(); } catch (Exception e) { } try { if (oStmt != null) oStmt.close(); } catch (Exception e) { } try { if (oCall != null) oCall.close(); } catch (Exception e) { } try { if (oConn != null) oConn.rollback(); } catch (Exception e) { } throw new MessagingException(sqle.getMessage(), sqle); } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End DBFolder.expunge()"); } return null; }
11
Code Sample 1: private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).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 static void copy(File src, File dst) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); srcChannel = null; dstChannel.close(); dstChannel = null; } catch (IOException ex) { Tools.logException(Tools.class, ex, dst.getAbsolutePath()); } }
11
Code Sample 1: public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { logger.error(Logger.SECURITY_FAILURE, "Problem decoding file to file", exc); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
00
Code Sample 1: 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; } 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; }
11
Code Sample 1: private static boolean prepareQualifyingFile(String completePath, String outputFile) { try { File inFile = new File(completePath + fSep + "qualifying.txt"); FileChannel inC = new FileInputStream(inFile).getChannel(); BufferedReader br = new BufferedReader(new FileReader(inFile)); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + outputFile); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); boolean endOfFile = true; short movieName = 0; int customer = 0; while (endOfFile) { String line = br.readLine(); if (line != null) { if (line.indexOf(":") >= 0) { movieName = new Short(line.substring(0, line.length() - 1)).shortValue(); } else { customer = new Integer(line.substring(0, line.indexOf(","))).intValue(); ByteBuffer outBuf = ByteBuffer.allocate(6); outBuf.putShort(movieName); outBuf.putInt(customer); outBuf.flip(); outC.write(outBuf); } } else endOfFile = false; } br.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } } Code Sample 2: public static void decompressGZIP(File gzip, File to, long skip) throws IOException { GZIPInputStream gis = null; BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(to)); FileInputStream fis = new FileInputStream(gzip); fis.skip(skip); gis = new GZIPInputStream(fis); final byte[] buffer = new byte[IO_BUFFER]; int read = -1; while ((read = gis.read(buffer)) != -1) { bos.write(buffer, 0, read); } } finally { try { gis.close(); } catch (Exception nope) { } try { bos.flush(); } catch (Exception nope) { } try { bos.close(); } catch (Exception nope) { } } }
00
Code Sample 1: public static void downloadJars(IProject project, String repositoryUrl, String jarDirectory, String[] jars) { try { File tmpFile = null; for (String jar : jars) { try { tmpFile = File.createTempFile("tmpPlugin_", ".zip"); URL url = new URL(repositoryUrl + jarDirectory + jar); String destFilename = new File(url.getFile()).getName(); File destFile = new File(project.getLocation().append("lib").append(jarDirectory).toFile(), destFilename); InputStream inputStream = null; FileOutputStream outputStream = null; try { URLConnection urlConnection = url.openConnection(); inputStream = urlConnection.getInputStream(); outputStream = new FileOutputStream(tmpFile); IOUtils.copy(inputStream, outputStream); } finally { if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } } } catch (Exception ex) { ex.printStackTrace(); } } Code Sample 2: public RFC1345List(URL url) { if (url == null) return; try { BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(url.openStream()))); final String linePattern = " XX??????? HHHH X"; String line; mnemos = new HashMap(); nextline: while ((line = br.readLine()) != null) { if (line.length() < 9) continue nextline; if (line.charAt(7) == ' ' || line.charAt(8) != ' ') { line = line.substring(0, 8) + " " + line.substring(8); } if (line.length() < linePattern.length()) continue nextline; for (int i = 0; i < linePattern.length(); i++) { char c = line.charAt(i); switch(linePattern.charAt(i)) { case ' ': if (c != ' ') continue nextline; break; case 'X': if (c == ' ') continue nextline; break; case '?': break; case 'H': if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) ; else continue nextline; break; default: throw new RuntimeException("Pattern broken!"); } } char c = (char) Integer.parseInt(line.substring(16, 20), 16); String mnemo = line.substring(1, 16).trim(); if (mnemo.length() < 2) throw new RuntimeException(); mnemos.put(mnemo, new Character(c)); } br.close(); } catch (FileNotFoundException ex) { } catch (IOException ex) { ex.printStackTrace(); } }
11
Code Sample 1: private void buildBundle() { if (targetProject == null) { MessageDialog.openError(getShell(), "Error", "No target SPAB project selected!"); return; } if (projectProcessDirSelector.getText().trim().length() == 0) { MessageDialog.openError(getShell(), "Error", "No process directory selected for project " + targetProject.getName() + "!"); return; } deleteBundleFile(); try { File projectDir = targetProject.getLocation().toFile(); File projectProcessesDir = new File(projectDir, projectProcessDirSelector.getText()); boolean bpmoCopied = IOUtils.copyProcessFilesSecure(getBPMOFile(), projectProcessesDir); boolean sbpelCopied = IOUtils.copyProcessFilesSecure(getSBPELFile(), projectProcessesDir); boolean xmlCopied = IOUtils.copyProcessFilesSecure(getBPEL4SWSFile(), projectProcessesDir); bundleFile = IOUtils.archiveBundle(projectDir, Activator.getDefault().getStateLocation().toFile()); if (bpmoCopied) { new File(projectProcessesDir, getBPMOFile().getName()).delete(); } if (sbpelCopied) { new File(projectProcessesDir, getSBPELFile().getName()).delete(); } if (xmlCopied) { new File(projectProcessesDir, getBPEL4SWSFile().getName()).delete(); } } catch (Throwable anyError) { LogManager.logError(anyError); MessageDialog.openError(getShell(), "Error", "Error building SPAB :\n" + anyError.getMessage()); updateBundleUI(); return; } bpmoFile = getBPMOFile(); sbpelFile = getSBPELFile(); xmlFile = getBPEL4SWSFile(); updateBundleUI(); getWizard().getContainer().updateButtons(); } Code Sample 2: @HttpAction(name = "map.saveOrUpdate", method = { HttpAction.Method.post }, responseType = "text/plain") @HttpAuthentication(method = { HttpAuthentication.Method.WSSE }) public String saveOrUpdate(FileItem file, User user, MapOriginal map) throws HttpRpcException { File tmpFile; GenericDAO<MapOriginal> mapDao = DAOFactory.createDAO(MapOriginal.class); try { assert (file != null); String jobid = null; if (file.getContentType().startsWith("image/")) { tmpFile = File.createTempFile("gmap", "img"); OutputStream out = new FileOutputStream(tmpFile); IOUtils.copy(file.getInputStream(), out); out.flush(); out.close(); map.setState(MapOriginal.MapState.UPLOAD); map.setUser(user); map.setMapPath(tmpFile.getPath()); map.setThumbnailUrl("/map/inproc.gif"); map.setMimeType(file.getContentType()); mapDao.saveOrUpdate(map); jobid = PoolFactory.getClientPool().put(map, TaskState.STATE_MO_FINISH, MapOverrideStrategy.class); } return jobid; } catch (IOException e) { logger.error(e); throw ERROR_INTERNAL; } catch (DAOException e) { logger.error(e); throw ERROR_INTERNAL; } }
11
Code Sample 1: private void copyResourceToDir(String ondexDir, String resource) { InputStream inputStream = OndexGraphImpl.class.getClassLoader().getResourceAsStream(resource); try { FileWriter fileWriter = new FileWriter(new File(ondexDir, resource)); IOUtils.copy(inputStream, fileWriter); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { logger.error("Unable to copy '" + resource + "' file to " + ondexDir + "'"); } } Code Sample 2: private String loadSchemas() { StringWriter writer = new StringWriter(); try { IOUtils.copy(CoreOdfValidator.class.getResourceAsStream("schema_list.properties"), writer); } catch (IOException e) { e.printStackTrace(); } return writer.toString(); }
11
Code Sample 1: private static byte[] calcMd5(String pass) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(pass.getBytes(), 0, pass.length()); byte[] hash = digest.digest(); return hash; } catch (NoSuchAlgorithmException e) { System.err.println("No MD5 algorithm found"); System.exit(1); } return null; } Code Sample 2: public static String getHash(String text) { if (text == null) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); byte[] hashedTextBytes = md.digest(); BigInteger hashedTextBigInteger = new BigInteger(1, hashedTextBytes); String hashedTextString = hashedTextBigInteger.toString(16); return hashedTextString; } catch (NoSuchAlgorithmException e) { LOG.warning(e.toString()); return null; } }
11
Code Sample 1: public static int deleteHedgeCustTrade() { Connection conn = null; PreparedStatement psmt = null; StringBuffer SQL = new StringBuffer(200); int deleted = 0; SQL.append(" DELETE FROM JHF_HEDGE_CUSTTRADE "); try { conn = JdbcConnectionPool.mainConnection(); conn.setAutoCommit(false); conn.setReadOnly(false); psmt = conn.prepareStatement(SQL.toString()); 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; } Code Sample 2: @Override public String addUserIdentity(OpenIDItem identity, long userId) throws DatabaseException { if (identity == null) throw new NullPointerException("identity"); if (identity.getIdentity() == null || "".equals(identity.getIdentity())) throw new NullPointerException("identity.getIdentity()"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } String retID = "exist"; PreparedStatement insSt = null, seqSt = null; try { int modified = 0; insSt = getConnection().prepareStatement(INSERT_IDENTITY_STATEMENT); insSt.setLong(1, userId); insSt.setString(2, identity.getIdentity()); modified = insSt.executeUpdate(); seqSt = getConnection().prepareStatement(USER_IDENTITY_VALUE); ResultSet rs = seqSt.executeQuery(); while (rs.next()) { retID = rs.getString(1); } if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + seqSt + "\" and \"" + insSt + "\""); } else { getConnection().rollback(); LOGGER.debug("DB has not been updated -> rollback! Queries: \"" + seqSt + "\" and \"" + insSt + "\""); retID = "error"; } } catch (SQLException e) { LOGGER.error(e); retID = "error"; } finally { closeConnection(); } return retID; }
11
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 version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public static String loadURLToString(String url, String EOL) throws FileNotFoundException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); String result = ""; String str; while ((str = in.readLine()) != null) { result += str + EOL; } in.close(); return result; }
00
Code Sample 1: public void setUp() throws Exception { logger.finer("******************** set up ********************"); Properties props; if (XMLDBTestSuite.propertiesFileName == null) { String defaultPropsFileLocation = "test/xmldb/XMLDBTestSuite.properties"; URL url = this.getClass().getClassLoader().getResource(defaultPropsFileLocation); if (url == null) { throw new Exception("failed to find default props file at " + defaultPropsFileLocation); } props = loadProps(url.openConnection().getInputStream()); } else { props = loadProps(XMLDBTestSuite.propertiesFileName); } String driver = props.getProperty("driverName"); String collectionURI = props.getProperty("URI"); Database database = (Database) Class.forName(driver).newInstance(); collectionStorageHelper = new CollectionStorageHelper(collectionURI); rootCollectionName = collectionStorageHelper.getCollectionName(); Collection root = database.getCollection(collectionURI, null, null); CollectionManagementService service = (CollectionManagementService) root.getService(CollectionManagementService.SERVICE_NAME, "1.0"); String childCollection = "child"; removeChildCollection(root, childCollection, service); col = service.createCollection(childCollection); assertNotNull("XMLDBTestCase.setUp() - Collection could not be created", col); logger.info("created child collection '" + col.getName() + "' parent is '" + col.getParentCollection().getName() + "'"); assertEquals("Root collection name should match childs parent name", rootCollectionName, col.getParentCollection().getName()); document = createXMLFile(xmlFileName); assertNotNull("XMLDBTestCase.setUp() - failed to create XML file", document); } Code Sample 2: public static void readUrlWriteFileTest(String url, String fileName) throws Exception { System.out.println("Initiated reading source queue URL: " + url); InputStream instream = new URL(url).openStream(); Serializer serializer = new Serializer(); Response response = (Response) serializer.parse(instream); Queue queue = response.getQueue(); instream.close(); System.out.println("Completed reading source queue URL (jobs=" + queue.size() + ")"); System.out.println("Initiated writing target queue File: " + fileName); OutputStream outstream = new FileOutputStream(fileName); serializer.write(response, outstream); outstream.close(); System.out.println("Completed writing target queue file."); }
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: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: private static void grab(String urlString) throws MalformedURLException, IOException { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); BufferedReader in = null; StringBuffer sb = new StringBuffer(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; boolean f = false; while ((inputLine = in.readLine()) != null) { inputLine = inputLine.trim(); if (inputLine.startsWith("<tbody>")) { f = true; continue; } if (inputLine.startsWith("</table>")) { f = false; continue; } if (f) { sb.append(inputLine); sb.append("\n"); } } process(sb.toString()); } Code Sample 2: protected String contentString() { String result = null; URL url; String encoding = null; try { url = url(); URLConnection connection = url.openConnection(); connection.setDoInput(true); connection.setDoOutput(false); connection.setUseCaches(false); for (Enumeration e = bindingKeys().objectEnumerator(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); if (key.startsWith("?")) { connection.setRequestProperty(key.substring(1), valueForBinding(key).toString()); } } if (connection.getContentEncoding() != null) { encoding = connection.getContentEncoding(); } if (encoding == null) { encoding = (String) valueForBinding("encoding"); } if (encoding == null) { encoding = "UTF-8"; } InputStream stream = connection.getInputStream(); byte bytes[] = ERXFileUtilities.bytesFromInputStream(stream); stream.close(); result = new String(bytes, encoding); } catch (IOException ex) { throw NSForwardException._runtimeExceptionForThrowable(ex); } return result; }
00
Code Sample 1: @Override public void run() { HttpGet httpGet = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); DataModel model = DataModel.getInstance(); for (City city : citiesToBeUpdated) { String preferredUnitType = PreferenceManager.getDefaultSharedPreferences(context).getString(context.getString(R.string.settings_units_key), context.getString(R.string.settings_units_default_value)); String codePrefix = city.getCountryName().startsWith("United States") ? GET_PARAM_ZIP_PREFIX : GET_PARAM_CITY_CODE_PREFIX; String requestUri = new String(GET_URL + "?" + GET_PARAM_ACODE_PREFIX + "=" + GET_PARAM_ACODE + "&" + codePrefix + "=" + city.getId() + "&" + GET_PARAM_UNIT_PREFIX + "=" + preferredUnitType); httpGet = new HttpGet(requestUri); HttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { processXML(response.getEntity().getContent()); for (ForecastedDay day : forecast) { int pos = day.getImageURL().lastIndexOf('/'); if (pos < 0 || pos + 1 == day.getImageURL().length()) throw new Exception("Invalid image URL"); final String imageFilename = day.getImageURL().substring(pos + 1); File downloadDir = context.getDir(ForecastedDay.DOWNLOAD_DIR, Context.MODE_PRIVATE); File[] imagesFilteredByName = downloadDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { if (filename.equals(imageFilename)) return true; else return false; } }); if (imagesFilteredByName.length == 0) { httpGet = new HttpGet(day.getImageURL()); response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { BufferedOutputStream bus = null; try { bus = new BufferedOutputStream(new FileOutputStream(downloadDir.getAbsolutePath() + "/" + imageFilename)); response.getEntity().writeTo(bus); } finally { bus.close(); } } } } city.setDays(forecast); city.setLastUpdated(Calendar.getInstance().getTime()); model.saveCity(city); } } } catch (Exception e) { httpGet.abort(); e.printStackTrace(); } finally { handler.sendEmptyMessage(1); } } Code Sample 2: protected void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
00
Code Sample 1: public static Set<Class<?>> getClasses(String pack) { Set<Class<?>> classes = new LinkedHashSet<Class<?>>(); boolean recursive = true; String packageName = pack; String packageDirName = packageName.replace('.', '/'); Enumeration<URL> dirs; try { dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); while (dirs.hasMoreElements()) { URL url = dirs.nextElement(); String protocol = url.getProtocol(); if ("file".equals(protocol)) { String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes); } else if ("jar".equals(protocol)) { JarFile jar; try { jar = ((JarURLConnection) url.openConnection()).getJarFile(); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (name.charAt(0) == '/') { name = name.substring(1); } if (name.startsWith(packageDirName)) { int idx = name.lastIndexOf('/'); if (idx != -1) { packageName = name.substring(0, idx).replace('/', '.'); } if ((idx != -1) || recursive) { if (name.endsWith(".class") && !entry.isDirectory()) { String className = name.substring(packageName.length() + 1, name.length() - 6); try { classes.add(Class.forName(packageName + '.' + className)); } catch (ClassNotFoundException e) { System.out.println("添加用户自定义视图类错误 找不到此类的.class文件"); e.printStackTrace(); } } } } } } catch (IOException e) { System.out.println("在扫描用户定义视图时从jar包获取文件出错"); e.printStackTrace(); } } } } catch (IOException e) { e.printStackTrace(); } return classes; } Code Sample 2: private void mergeOne(String level, char strand, String filename, Path outPath, FileSystem srcFS, FileSystem dstFS, Timer to) throws IOException { to.start(); final OutputStream outs = dstFS.create(new Path(outPath, filename)); final FileStatus[] parts = srcFS.globStatus(new Path(sorted ? getSortOutputDir(level, strand) : wrkDir, filename + "-[0-9][0-9][0-9][0-9][0-9][0-9]")); for (final FileStatus part : parts) { final InputStream ins = srcFS.open(part.getPath()); IOUtils.copyBytes(ins, outs, getConf(), false); ins.close(); } for (final FileStatus part : parts) srcFS.delete(part.getPath(), false); outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); outs.close(); System.out.printf("summarize :: Merged %s%c in %d.%03d s.\n", level, strand, to.stopS(), to.fms()); }
00
Code Sample 1: private static void ftpTest() { FTPClient f = new FTPClient(); try { f.connect("oscomak.net"); System.out.print(f.getReplyString()); f.setFileType(FTPClient.BINARY_FILE_TYPE); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String password = JOptionPane.showInputDialog("Enter password"); if (password == null || password.equals("")) { System.out.println("No password"); return; } try { f.login("oscomak_pointrel", password); System.out.print(f.getReplyString()); } catch (IOException e) { e.printStackTrace(); } try { String workingDirectory = f.printWorkingDirectory(); System.out.println("Working directory: " + workingDirectory); System.out.print(f.getReplyString()); } catch (IOException e1) { e1.printStackTrace(); } try { f.enterLocalPassiveMode(); System.out.print(f.getReplyString()); System.out.println("Trying to list files"); String[] fileNames = f.listNames(); System.out.print(f.getReplyString()); System.out.println("Got file list fileNames: " + fileNames.length); for (String fileName : fileNames) { System.out.println("File: " + fileName); } System.out.println(); System.out.println("done reading stream"); System.out.println("trying alterative way to read stream"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); f.retrieveFile(fileNames[0], outputStream); System.out.println("size: " + outputStream.size()); System.out.println(outputStream.toString()); System.out.println("done with alternative"); System.out.println("Trying to store file back"); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); boolean storeResult = f.storeFile("test.txt", inputStream); System.out.println("Done storing " + storeResult); f.disconnect(); System.out.print(f.getReplyString()); System.out.println("disconnected"); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static String getPageSource(String url) throws ClientProtocolException, IOException { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); InputStream in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder source = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) source.append(line); in.close(); return source.toString(); }
11
Code Sample 1: public static void copyFile(File source, File destination) throws IOException { FileInputStream fis = new FileInputStream(source); FileOutputStream fos = null; try { fos = new FileOutputStream(destination); FileChannel sourceChannel = fis.getChannel(); FileChannel destinationChannel = fos.getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); destinationChannel.close(); sourceChannel.close(); } finally { if (fos != null) fos.close(); fis.close(); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static void copyFile(File from, File to) throws Exception { if (!from.exists()) return; FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[8192]; int bytes_read; while (true) { bytes_read = in.read(buffer); if (bytes_read == -1) break; out.write(buffer, 0, bytes_read); } out.flush(); out.close(); in.close(); } Code Sample 2: public static void main(String args[]) throws IOException, TrimmerException, DataStoreException { Options options = new Options(); options.addOption(new CommandLineOptionBuilder("ace", "path to ace file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("phd", "path to phd file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("out", "path to new ace file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("min_sanger", "min sanger end coveage default =" + DEFAULT_MIN_SANGER_END_CLONE_CVG).build()); options.addOption(new CommandLineOptionBuilder("min_biDriection", "min bi directional end coveage default =" + DEFAULT_MIN_BI_DIRECTIONAL_END_COVERAGE).build()); options.addOption(new CommandLineOptionBuilder("ignore_threshold", "min end coveage threshold to stop trying to trim default =" + DEFAULT_IGNORE_END_CVG_THRESHOLD).build()); CommandLine commandLine; PhdDataStore phdDataStore = null; AceContigDataStore datastore = null; try { commandLine = CommandLineUtils.parseCommandLine(options, args); int minSangerEndCloneCoverage = commandLine.hasOption("min_sanger") ? Integer.parseInt(commandLine.getOptionValue("min_sanger")) : DEFAULT_MIN_SANGER_END_CLONE_CVG; int minBiDirectionalEndCoverage = commandLine.hasOption("min_biDriection") ? Integer.parseInt(commandLine.getOptionValue("min_biDriection")) : DEFAULT_MIN_BI_DIRECTIONAL_END_COVERAGE; int ignoreThresholdEndCoverage = commandLine.hasOption("ignore_threshold") ? Integer.parseInt(commandLine.getOptionValue("ignore_threshold")) : DEFAULT_IGNORE_END_CVG_THRESHOLD; AceContigTrimmer trimmer = new NextGenClosureAceContigTrimmer(minSangerEndCloneCoverage, minBiDirectionalEndCoverage, ignoreThresholdEndCoverage); File aceFile = new File(commandLine.getOptionValue("ace")); File phdFile = new File(commandLine.getOptionValue("phd")); phdDataStore = new DefaultPhdFileDataStore(phdFile); datastore = new IndexedAceFileDataStore(aceFile); File tempFile = File.createTempFile("nextGenClosureAceTrimmer", ".ace"); tempFile.deleteOnExit(); OutputStream tempOut = new FileOutputStream(tempFile); int numberOfContigs = 0; int numberOfTotalReads = 0; for (AceContig contig : datastore) { AceContig trimmedAceContig = trimmer.trimContig(contig); if (trimmedAceContig != null) { numberOfContigs++; numberOfTotalReads += trimmedAceContig.getNumberOfReads(); AceFileWriter.writeAceFile(trimmedAceContig, phdDataStore, tempOut); } } IOUtil.closeAndIgnoreErrors(tempOut); OutputStream masterAceOut = new FileOutputStream(new File(commandLine.getOptionValue("out"))); masterAceOut.write(String.format("AS %d %d%n", numberOfContigs, numberOfTotalReads).getBytes()); InputStream tempInput = new FileInputStream(tempFile); IOUtils.copy(tempInput, masterAceOut); } catch (ParseException e) { System.err.println(e.getMessage()); printHelp(options); } finally { IOUtil.closeAndIgnoreErrors(phdDataStore, datastore); } }
00
Code Sample 1: public void testDoubleNaN() { double value = 0; boolean wasEqual = false; String message = "DB operation completed"; String ddl1 = "DROP TABLE t1 IF EXISTS;" + "CREATE TABLE t1 ( d DECIMAL, f DOUBLE, l BIGINT, i INTEGER, s SMALLINT, t TINYINT, " + "dt DATE DEFAULT CURRENT_DATE, ti TIME DEFAULT CURRENT_TIME, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP );"; try { stmnt.execute(ddl1); PreparedStatement ps = connection.prepareStatement("INSERT INTO t1 (d,f,l,i,s,t,dt,ti,ts) VALUES (?,?,?,?,?,?,?,?,?)"); ps.setString(1, "0.2"); ps.setDouble(2, 0.2); ps.setLong(3, java.lang.Long.MAX_VALUE); ps.setInt(4, Integer.MAX_VALUE); ps.setInt(5, Short.MAX_VALUE); ps.setInt(6, 0); ps.setDate(7, new java.sql.Date(System.currentTimeMillis())); ps.setTime(8, new java.sql.Time(System.currentTimeMillis())); ps.setTimestamp(9, new java.sql.Timestamp(System.currentTimeMillis())); ps.execute(); ps.setInt(1, 0); ps.setDouble(2, java.lang.Double.NaN); ps.setLong(3, java.lang.Long.MIN_VALUE); ps.setInt(4, Integer.MIN_VALUE); ps.setInt(5, Short.MIN_VALUE); ps.setInt(6, 0); ps.setTimestamp(7, new java.sql.Timestamp(System.currentTimeMillis() + 1)); ps.setTime(8, new java.sql.Time(System.currentTimeMillis() + 1)); ps.setDate(9, new java.sql.Date(System.currentTimeMillis() + 1)); ps.execute(); ps.setInt(1, 0); ps.setDouble(2, java.lang.Double.POSITIVE_INFINITY); ps.setInt(4, Integer.MIN_VALUE); ps.setObject(5, Boolean.TRUE); ps.setBoolean(5, true); ps.setObject(5, new Short((short) 2), Types.SMALLINT); ps.setObject(6, new Integer(2), Types.TINYINT); ps.setObject(7, new java.sql.Date(System.currentTimeMillis() + 2)); ps.setObject(8, new java.sql.Time(System.currentTimeMillis() + 2)); ps.setObject(9, new java.sql.Timestamp(System.currentTimeMillis() + 2)); ps.execute(); ps.setObject(1, new Float(0), Types.INTEGER); ps.setObject(4, new Float(1), Types.INTEGER); ps.setDouble(2, java.lang.Double.NEGATIVE_INFINITY); ps.execute(); ResultSet rs = stmnt.executeQuery("SELECT d, f, l, i, s*2, t FROM t1"); boolean result = rs.next(); value = rs.getDouble(2); int integerValue = rs.getInt(4); if (rs.next()) { value = rs.getDouble(2); wasEqual = Double.isNaN(value); integerValue = rs.getInt(4); integerValue = rs.getInt(1); } if (rs.next()) { value = rs.getDouble(2); wasEqual = wasEqual && value == Double.POSITIVE_INFINITY; } if (rs.next()) { value = rs.getDouble(2); wasEqual = wasEqual && value == Double.NEGATIVE_INFINITY; } rs = stmnt.executeQuery("SELECT MAX(i) FROM t1"); if (rs.next()) { int max = rs.getInt(1); System.out.println("Max value for i: " + max); } { stmnt.execute("drop table CDTYPE if exists"); rs = stmnt.executeQuery("CREATE TABLE cdType (ID INTEGER NOT NULL, name VARCHAR(50), PRIMARY KEY(ID))"); rs = stmnt.executeQuery("SELECT MAX(ID) FROM cdType"); if (rs.next()) { int max = rs.getInt(1); System.out.println("Max value for ID: " + max); } else { System.out.println("Max value for ID not returned"); } stmnt.executeUpdate("INSERT INTO cdType VALUES (10,'Test String');"); stmnt.executeQuery("CALL IDENTITY();"); try { stmnt.executeUpdate("INSERT INTO cdType VALUES (10,'Test String');"); } catch (SQLException e1) { stmnt.execute("ROLLBACK"); connection.rollback(); } } } catch (SQLException e) { fail(e.getMessage()); } System.out.println("testDoubleNaN complete"); assertEquals(true, wasEqual); } Code Sample 2: @NotNull private Properties loadProperties() { File file = new File(homeLocator.getHomeDir(), configFilename); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { throw new RuntimeException("IOException while creating \"" + file.getAbsolutePath() + "\".", e); } } if (!file.canRead() || !file.canWrite()) { throw new RuntimeException("Cannot read and write from file: " + file.getAbsolutePath()); } if (lastModifiedByUs < file.lastModified()) { if (logger.isLoggable(Level.FINE)) { logger.fine("File \"" + file + "\" is newer on disk. Read it ..."); } Properties properties = new Properties(); try { FileInputStream in = new FileInputStream(file); try { properties.loadFromXML(in); } catch (InvalidPropertiesFormatException e) { FileOutputStream out = new FileOutputStream(file); try { properties.storeToXML(out, comment); } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new RuntimeException("IOException while reading from \"" + file.getAbsolutePath() + "\".", e); } this.lastModifiedByUs = file.lastModified(); this.properties = properties; if (logger.isLoggable(Level.FINE)) { logger.fine("... read done."); } } assert this.properties != null; return this.properties; }
11
Code Sample 1: public static boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String CFDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, CFDataFolderName); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictPearsonWeightedSlopeOneRating(knn, movieToProcess, customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = movieAverages.get(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, CFDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictPearsonWeightedSlopeOneRating(knn, movieToProcess, customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else { finalPrediction = movieAverages.get(movieToProcess); System.out.println("NaN Prediction"); } buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } } Code Sample 2: public static void fileCopy(final File src, final File dest, final boolean overwrite) throws IOException { if (!dest.exists() || (dest.exists() && overwrite)) { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } }
11
Code Sample 1: public int procesar() { int mas = 0; String uriOntologia = "", source = "", uri = ""; String fichOrigenHTML = "", fichOrigenLN = ""; String ficheroOutOWL = ""; md5 firma = null; StringTokenV2 entra = null, entra2 = null, entra3 = null; FileInputStream lengNat = null; BufferedInputStream lengNat2 = null; DataInputStream entradaLenguajeNatural = null; FileWriter salOWL = null; BufferedWriter salOWL2 = null; PrintWriter salidaOWL = null; String sujeto = "", verbo = "", CD = "", CI = "", fraseOrigen = ""; StringTokenV2 token2; boolean bandera = false; OntClass c = null; OntClass cBak = null; String claseTrabajo = ""; String nombreClase = "", nombrePropiedad = "", variasPalabras = ""; int incre = 0, emergencia = 0; String lineaSalida = ""; String[] ontologia = new String[5]; ontologia[0] = "http://www.criado.info/owl/vertebrados_es.owl#"; ontologia[1] = "http://www.w3.org/2001/sw/WebOnt/guide-src/wine#"; ontologia[2] = "http://www.co-ode.org/ontologies/pizza/2005/10/18/pizza.owl#"; ontologia[3] = "http://www.w3.org/2001/sw/WebOnt/guide-src/food#"; ontologia[4] = "http://www.daml.org/2001/01/gedcom/gedcom#"; String[] ontologiaSource = new String[5]; ontologiaSource[0] = this.directorioMapeo + "\\" + "mapeo_vertebrados_es.xml"; ontologiaSource[1] = this.directorioMapeo + "\\" + "mapeo_wine_es.xml"; ontologiaSource[2] = this.directorioMapeo + "\\" + "mapeo_pizza_es.xml"; ontologiaSource[3] = this.directorioMapeo + "\\" + "mapeo_food_es.xml"; ontologiaSource[4] = this.directorioMapeo + "\\" + "mapeo_parentesco_es.xml"; mapeoIdiomas clasesOntologias; try { if ((entrada = entradaFichero.readLine()) != null) { if (entrada.trim().length() > 10) { entrada2 = new StringTokenV2(entrada.trim(), "\""); if (entrada2.isIncluidaSubcadena("<fichero ontologia=")) { ontologiaOrigen = entrada2.getToken(2); fichOrigenHTML = entrada2.getToken(4); fichOrigenLN = entrada2.getToken(6); if (ontologiaOrigen.equals("VERTEBRADOS")) { source = ontologiaSource[0]; uriOntologia = ontologia[0]; } if (ontologiaOrigen.equals("WINE")) { source = ontologiaSource[1]; uriOntologia = ontologia[1]; } if (ontologiaOrigen.equals("PIZZA")) { source = ontologiaSource[2]; uriOntologia = ontologia[2]; } if (ontologiaOrigen.equals("FOOD")) { source = ontologiaSource[3]; uriOntologia = ontologia[3]; } if (ontologiaOrigen.equals("PARENTESCOS")) { source = ontologiaSource[4]; uriOntologia = ontologia[4]; } firma = new md5(uriOntologia, false); clasesOntologias = new mapeoIdiomas(source); uri = ""; ficheroOutOWL = ""; entra2 = new StringTokenV2(fichOrigenHTML, "\\"); int numToken = entra2.getNumeroTokenTotales(); entra = new StringTokenV2(fichOrigenHTML, " "); if (entra.isIncluidaSubcadena(directorioLocal)) { entra = new StringTokenV2(entra.getQuitar(directorioLocal) + "", " "); uri = entra.getCambiar("\\", "/"); uri = entra.getQuitar(entra2.getToken(numToken)) + ""; entra3 = new StringTokenV2(entra2.getToken(numToken), "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; uri = urlPatron + uri + ficheroOutOWL; } entra3 = new StringTokenV2(fichOrigenHTML, "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; lineaSalida = "<vistasemantica origen=\"" + fichOrigenLN + "\" destino=\"" + uri + "\" />"; lengNat = new FileInputStream(fichOrigenLN); lengNat2 = new BufferedInputStream(lengNat); entradaLenguajeNatural = new DataInputStream(lengNat2); salOWL = new FileWriter(ficheroOutOWL); salOWL2 = new BufferedWriter(salOWL); salidaOWL = new PrintWriter(salOWL2); while ((entradaInstancias = entradaLenguajeNatural.readLine()) != null) { sujeto = ""; verbo = ""; CD = ""; CI = ""; fraseOrigen = ""; if (entradaInstancias.trim().length() > 10) { entrada2 = new StringTokenV2(entradaInstancias.trim(), "\""); if (entrada2.isIncluidaSubcadena("<oracion sujeto=")) { sujeto = entrada2.getToken(2).trim(); verbo = entrada2.getToken(4).trim(); CD = entrada2.getToken(6).trim(); CI = entrada2.getToken(8).trim(); fraseOrigen = entrada2.getToken(10).trim(); if (sujeto.length() > 0 & verbo.length() > 0 & CD.length() > 0) { bandera = false; c = null; cBak = null; nombreClase = clasesOntologias.getClaseInstancia(CD); if (nombreClase.length() > 0) { bandera = true; } if (bandera) { if (incre == 0) { salidaOWL.write(" <rdf:RDF " + "\n"); salidaOWL.write(" xmlns:j.0=\"" + uriOntologia + "\"" + "\n"); salidaOWL.write(" xmlns:protege=\"http://protege.stanford.edu/plugins/owl/protege#\"" + "\n"); salidaOWL.write(" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"" + "\n"); salidaOWL.write(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"" + "\n"); salidaOWL.write(" xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"" + "\n"); salidaOWL.write(" xmlns:owl=\"http://www.w3.org/2002/07/owl#\" " + "\n"); salidaOWL.write(" xmlns=\"" + uri + "#\"" + "\n"); salidaOWL.write(" xml:base=\"" + uri + "\">" + "\n"); salidaOWL.write(" <owl:Ontology rdf:about=\"\">" + "\n"); salidaOWL.write(" <owl:imports rdf:resource=\"" + uriOntologia + "\"/>" + "\n"); salidaOWL.write(" </owl:Ontology>" + "\n"); salidaOWL.flush(); salida.write(lineaSalida + "\n"); salida.flush(); incre = 1; } salidaOWL.write(" <j.0:" + nombreClase + " rdf:ID=\"" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" <owl:AllDifferent>" + "\n"); salidaOWL.write(" <owl:distinctMembers rdf:parseType=\"Collection\">" + "\n"); salidaOWL.write(" <" + nombreClase + " rdf:about=\"#" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" </owl:distinctMembers>" + "\n"); salidaOWL.write(" </owl:AllDifferent>" + "\n"); salidaOWL.flush(); bandera = false; } } } } } salidaOWL.write(" </rdf:RDF>" + "\n" + "\n"); salidaOWL.write("<!-- Creado por [html2ws] http://www.luis.criado.org -->" + "\n"); salidaOWL.flush(); } } mas = 1; } else { salida.write("</listaVistasSemanticas>\n"); salida.flush(); salida.close(); bw2.close(); fw2.close(); salidaOWL.close(); entradaFichero.close(); ent2.close(); ent1.close(); mas = -1; } } catch (Exception e) { mas = -2; salida.write("No se encuentra: " + fichOrigen + "\n"); salida.flush(); } return mas; } Code Sample 2: private boolean copyOldSetupClass(File lastVerPath, File destPath) throws java.io.FileNotFoundException, IOException { byte[] buf; File oldClass = new File(lastVerPath.getAbsolutePath() + File.separator + installClassName_ + ".class"); if (oldClass.exists()) { FileOutputStream out = new FileOutputStream(destPath.getAbsolutePath() + File.separator + installClassName_ + ".class"); FileInputStream in = new FileInputStream(oldClass); buf = new byte[(new Long(oldClass.length())).intValue()]; int read = in.read(buf, 0, buf.length); out.write(buf, 0, read); out.close(); in.close(); return true; } return false; }
11
Code Sample 1: public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>"); System.exit(1); } try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream in = new FileInputStream(args[1]); int len = 0; byte buf[] = new byte[1024]; while ((len = in.read(buf)) > 0) os.write(buf, 0, len); in.close(); os.close(); byte[] data = null; if (args[0].equals("dec")) data = decode(os.toString()); else { String strData = encode(os.toByteArray()); data = strData.getBytes(); } FileOutputStream fos = new FileOutputStream(args[2]); fos.write(data); fos.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: @Override public Collection<IAuthor> doImport() throws Exception { progress.initialize(2, "Ściągam autorów amerykańskich"); String url = "http://pl.wikipedia.org/wiki/Kategoria:Ameryka%C5%84scy_autorzy_fantastyki"; UrlResource resource = new UrlResource(url); InputStream urlInputStream = resource.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(urlInputStream, writer); progress.advance("Parsuję autorów amerykańskich"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); String httpDoc = writer.toString(); httpDoc = httpDoc.replaceFirst("(?s)<!DOCTYPE.+?>\\n", ""); httpDoc = httpDoc.replaceAll("(?s)<script.+?</script>", ""); httpDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" + httpDoc; ByteArrayInputStream byteInputStream = new ByteArrayInputStream(httpDoc.getBytes("UTF-8")); Document doc = builder.parse(byteInputStream); ArrayList<String> authorNames = new ArrayList<String>(); ArrayList<IAuthor> authors = new ArrayList<IAuthor>(); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); NodeList list = (NodeList) xpath.evaluate("//ul/li/div/div/a", doc, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { String name = list.item(i).getTextContent(); if (StringUtils.isNotBlank(name)) { authorNames.add(name); } } list = (NodeList) xpath.evaluate("//td/ul/li/a", doc, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { String name = list.item(i).getTextContent(); if (StringUtils.isNotBlank(name)) { authorNames.add(name); } } for (String name : authorNames) { int idx = name.lastIndexOf(' '); String fname = name.substring(0, idx).trim(); String lname = name.substring(idx + 1).trim(); authors.add(new Author(fname, lname)); } progress.advance("Wykonano"); return authors; }
11
Code Sample 1: private void trainSRLParser(byte flag, JarArchiveOutputStream zout) throws Exception { AbstractSRLParser labeler = null; AbstractDecoder[] decoder = null; if (flag == SRLParser.FLAG_TRAIN_LEXICON) { System.out.println("\n* Save lexica"); labeler = new SRLParser(flag, s_featureXml); } else if (flag == SRLParser.FLAG_TRAIN_INSTANCE) { System.out.println("\n* Print training instances"); System.out.println("- loading lexica"); labeler = new SRLParser(flag, t_xml, s_lexiconFiles); } else if (flag == SRLParser.FLAG_TRAIN_BOOST) { System.out.println("\n* Train boost"); decoder = new AbstractDecoder[m_model.length]; for (int i = 0; i < decoder.length; i++) decoder[i] = new OneVsAllDecoder((OneVsAllModel) m_model[i]); labeler = new SRLParser(flag, t_xml, t_map, decoder); } AbstractReader<DepNode, DepTree> reader = new SRLReader(s_trainFile, true); DepTree tree; int n; labeler.setLanguage(s_language); reader.setLanguage(s_language); for (n = 0; (tree = reader.nextTree()) != null; n++) { labeler.parse(tree); if (n % 1000 == 0) System.out.printf("\r- parsing: %dK", n / 1000); } System.out.println("\r- labeling: " + n); if (flag == SRLParser.FLAG_TRAIN_LEXICON) { System.out.println("- labeling"); labeler.saveTags(s_lexiconFiles); t_xml = labeler.getSRLFtrXml(); } else if (flag == SRLParser.FLAG_TRAIN_INSTANCE || flag == SRLParser.FLAG_TRAIN_BOOST) { a_yx = labeler.a_trans; zout.putArchiveEntry(new JarArchiveEntry(ENTRY_FEATURE)); IOUtils.copy(new FileInputStream(s_featureXml), zout); zout.closeArchiveEntry(); for (String lexicaFile : s_lexiconFiles) { zout.putArchiveEntry(new JarArchiveEntry(lexicaFile)); IOUtils.copy(new FileInputStream(lexicaFile), zout); zout.closeArchiveEntry(); } if (flag == SRLParser.FLAG_TRAIN_INSTANCE) t_map = labeler.getSRLFtrMap(); } } Code Sample 2: public static void copyFile(String sourceFilePath, String destFilePath) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sourceFilePath).getChannel(); out = new FileOutputStream(destFilePath).getChannel(); long inputSize = in.size(); in.transferTo(0, inputSize, out); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, inputSize); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
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: public static void unzip1(File zipfile, File outputdir) throws IOException { //Buffer for copying the files out of the zip input stream byte[] buffer = new byte[1024]; //Create parent output directory if it doesn't exist if(!outputdir.exists()) { outputdir.mkdirs(); } //Create the zip input stream //OR ArchiveInputStream zis = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP, new FileInputStream(zipfile)); ArchiveInputStream zis = new ZipArchiveInputStream(new FileInputStream(zipfile)); //Iterate through the entries of the zip file, and extract them to the output directory ArchiveEntry ae = zis.getNextEntry(); // OR zis.getNextZipEntry() while(ae != null) { //Resolve new file File newFile = new File(outputdir + File.separator + ae.getName()); //Create parent directories if not exists if(!newFile.getParentFile().exists()) newFile.getParentFile().mkdirs(); if(ae.isDirectory()) { //If directory, create if not exists if(!newFile.exists()) newFile.mkdir(); } else { //If file, write file FileOutputStream fos = new FileOutputStream(newFile); int len; while((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); } //Proceed to the next entry in the zip file ae = zis.getNextEntry(); } //Cleanup zis.close(); }
11
Code Sample 1: private void doProcess(HttpServletRequest request, HttpServletResponse resp) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { Analyzer analyzer = new Analyzer(); ServletContext context = getServletContext(); String xml = context.getRealPath("data\\log.xml"); String xsd = context.getRealPath("data\\log.xsd"); String grs = context.getRealPath("reports\\" + request.getParameter("type") + ".grs"); String pdf = context.getRealPath("html\\report.pdf"); System.out.println("omg: " + request.getParameter("type")); System.out.println("omg: " + request.getParameter("pc")); int pcount = Integer.parseInt(request.getParameter("pc")); String[] params = new String[pcount]; for (int i = 0; i < pcount; i++) { params[i] = request.getParameter("p" + i); } try { analyzer.generateReport(xml, xsd, grs, pdf, params); } catch (Exception e) { e.printStackTrace(); } File file = new File(pdf); byte[] bs = tryLoadFile(pdf); if (bs == null) throw new NullPointerException(); resp.setHeader("Content-Disposition", " filename=\"" + file.getName() + "\";"); resp.setContentLength(bs.length); InputStream is = new ByteArrayInputStream(bs); IOUtils.copy(is, resp.getOutputStream()); } Code Sample 2: private String getResourceAsString(final String name) throws IOException { final InputStream is = JiBXTestCase.class.getResourceAsStream(name); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyAndClose(is, baos); return baos.toString(); }
11
Code Sample 1: public static String generateHash(final String sText, final String sAlgo) throws NoSuchAlgorithmException { final MessageDigest md = MessageDigest.getInstance(sAlgo); md.update(sText.getBytes()); final Formatter formatter = new Formatter(); for (final Byte curByte : md.digest()) formatter.format("%x", curByte); return formatter.toString(); } Code Sample 2: public Login authenticateClient() { Object o; String user, password; Vector<Login> clientLogins = ClientLoginsTableModel.getClientLogins(); Login login = null; try { socket.setSoTimeout(25000); objectOut.writeObject("JFRITZ SERVER 1.1"); objectOut.flush(); o = objectIn.readObject(); if (o instanceof String) { user = (String) o; objectOut.flush(); for (Login l : clientLogins) { if (l.getUser().equals(user)) { login = l; break; } } if (login != null) { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(login.getPassword().getBytes()); DESKeySpec desKeySpec = new DESKeySpec(md.digest()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); desCipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] dataKeySeed = new byte[32]; Random random = new Random(); random.nextBytes(dataKeySeed); md.reset(); md.update(dataKeySeed); dataKeySeed = md.digest(); SealedObject dataKeySeedSealed; dataKeySeedSealed = new SealedObject(dataKeySeed, desCipher); objectOut.writeObject(dataKeySeedSealed); objectOut.flush(); desKeySpec = new DESKeySpec(dataKeySeed); secretKey = keyFactory.generateSecret(desKeySpec); inCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); outCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); inCipher.init(Cipher.DECRYPT_MODE, secretKey); outCipher.init(Cipher.ENCRYPT_MODE, secretKey); SealedObject sealedObject = (SealedObject) objectIn.readObject(); o = sealedObject.getObject(inCipher); if (o instanceof String) { String response = (String) o; if (response.equals("OK")) { SealedObject ok_sealed = new SealedObject("OK", outCipher); objectOut.writeObject(ok_sealed); return login; } else { Debug.netMsg("Client sent false response to challenge!"); } } else { Debug.netMsg("Client sent false object as response to challenge!"); } } else { Debug.netMsg("client sent unkown username: " + user); } } } catch (IllegalBlockSizeException e) { Debug.netMsg("Wrong blocksize for sealed object!"); Debug.error(e.toString()); e.printStackTrace(); } catch (ClassNotFoundException e) { Debug.netMsg("received unrecognized object from client!"); Debug.error(e.toString()); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { Debug.netMsg("MD5 Algorithm not present in this JVM!"); Debug.error(e.toString()); e.printStackTrace(); } catch (InvalidKeySpecException e) { Debug.netMsg("Error generating cipher, problems with key spec?"); Debug.error(e.toString()); e.printStackTrace(); } catch (InvalidKeyException e) { Debug.netMsg("Error genertating cipher, problems with key?"); Debug.error(e.toString()); e.printStackTrace(); } catch (NoSuchPaddingException e) { Debug.netMsg("Error generating cipher, problems with padding?"); Debug.error(e.toString()); e.printStackTrace(); } catch (IOException e) { Debug.netMsg("Error authenticating client!"); Debug.error(e.toString()); e.printStackTrace(); } catch (BadPaddingException e) { Debug.netMsg("Bad padding exception!"); Debug.error(e.toString()); e.printStackTrace(); } return null; }
11
Code Sample 1: public void save(InputStream is) throws IOException { File dest = Config.getDataFile(getInternalDate(), getPhysMessageID()); OutputStream os = null; try { os = new FileOutputStream(dest); IOUtils.copyLarge(is, os); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } } Code Sample 2: 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!"); }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile) { FileChannel source = null; FileChannel destination = null; try { if (!destFile.exists()) { destFile.createNewFile(); } source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } catch (Exception e) { e.printStackTrace(); } } } Code Sample 2: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); getLog().info("Process request " + pathInfo); if (null != pathInfo) { String pathId = getPathId(pathInfo); JobResources res = ContextUtil.getJobResource(pathId); if (null != res) { RequestType requType = getRequestType(request); ResultAccess access = new ResultAccess(res); Collection<Long> uIdColl = res.getUniqIds(); boolean isFiltered = false; { List<String> postSeqIds = getSeqList(request); if (!postSeqIds.isEmpty()) { isFiltered = true; uIdColl = access.loadIds(postSeqIds); } } try { if ((requType.equals(RequestType.FASTA)) || (requType.equals(RequestType.SWISSPROT))) { OutputStreamWriter out = null; out = new OutputStreamWriter(response.getOutputStream()); for (Long uid : uIdColl) { if (requType.equals(RequestType.FASTA)) { SwissProt sw = access.getSwissprotEntry(uid); if (null != sw) { PrintFactory.instance().print(ConvertFactory.instance().SwissProt2fasta(sw), out); } else { System.err.println("Not able to read Swissprot entry " + uid + " in project " + res.getBaseDir()); } } else if (requType.equals(RequestType.SWISSPROT)) { File swissFile = res.getSwissprotFile(uid); if (swissFile.exists()) { InputStream in = null; try { in = new FileInputStream(swissFile); IOUtils.copy(in, out); } catch (IOException e) { e.printStackTrace(); System.err.println("Problems with reading file to output stream " + swissFile); } finally { IOUtils.closeQuietly(in); } } else { System.err.println("Swissprot file does not exist: " + swissFile); } } } out.flush(); } else { if (uIdColl.size() <= 2) { isFiltered = false; uIdColl = res.getUniqIds(); } Tree tree = access.getTreeByUniquId(uIdColl); if (requType.equals(RequestType.TREE)) { response.getWriter().write(tree.toNewHampshireX()); } else if (requType.equals(RequestType.PNG)) { List<SwissProt> sp = access.getSwissprotEntriesByUniquId(uIdColl); ImageMap map = ImageFactory.instance().createProteinCard(sp, tree, true, res); response.setContentType("image/png"); response.addHeader("Content-Disposition", "filename=ProteinCards.png"); ImageFactory.instance().printPNG(map.getImage(), response.getOutputStream()); response.getOutputStream().flush(); } else if (requType.equals(RequestType.HTML)) { List<SwissProt> sp = access.getSwissprotEntriesByUniquId(uIdColl); createHtml(res, access, tree, request, response, sp, isFiltered); } } } catch (Exception e) { e.printStackTrace(); getLog().error("Problem with Request: " + pathInfo + "; type " + requType, e); } } else { getLog().error("Resource is null: " + pathId + "; path " + pathInfo); } } else { getLog().error("PathInfo is null!!!"); } }
11
Code Sample 1: private String transferWSDL(String usernameAndPassword) throws WiseConnectionException { String filePath = null; try { URL endpoint = new URL(wsdlURL); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); conn.setRequestProperty("Connection", "close"); if (this.password != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(usernameAndPassword.getBytes())); } InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } File file = new File(tmpDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { logger.error("Failed to download wsdl from URL : " + wsdlURL); throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; } Code Sample 2: public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); int i; for (i = 0; ((i < list.length) && !stop); i++) { current = i; if ((list[i].compareTo("Images") != 0) && ((list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".jpg") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".bmp") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".png") == 0))) { String name = list[i]; String pathSrc = directoryPath.concat(list[i]); name = name.replace(' ', '_').replace(',', '-').replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u').replace('Á', 'A').replace('É', 'E').replace('Í', 'I').replace('Ó', 'O').replace('Ú', 'U'); String pathDst = directoryPath.concat(name); Vector aux = new Vector(); aux = dataBase.imageSearch(name.substring(0, name.lastIndexOf('.'))); if (aux.size() != 0) pathDst = pathDst.substring(0, pathDst.lastIndexOf('.')) + '_' + aux.size() + ".png"; File src = new File(pathSrc); File absPath = new File(""); String nameSrc = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase() + src.separator + pathDst.substring(pathDst.lastIndexOf(src.separator) + 1, pathDst.length()); String newDirectory = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase(); String imagePathThumb = (nameSrc.substring(0, nameSrc.lastIndexOf("."))).concat("_th.jpg"); ImageIcon image = null; if (src != null) { if (TFileUtils.isJAIRequired(src)) { RenderedOp src_aux = JAI.create("fileload", src.getAbsolutePath()); BufferedImage bufferedImage = src_aux.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(src.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { System.out.print("Error al insertar imagen: "); System.out.println(pathDst); } else { int option = 0; imageFile = new File(directoryPath + "Images"); if (!imageFile.exists()) { TIGNewImageDataDialog dialog = new TIGNewImageDataDialog(editor, dataBase, image, nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length()), list[i].substring(0, list[i].lastIndexOf('.')), myTask); option = dialog.getOption(); if (option != 0) { File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } } if (imageFile.exists()) { dataBase.insertImageDB(list[i].substring(0, list[i].lastIndexOf('.')), nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length())); File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } try { int thumbWidth = PREVIEW_WIDTH; int thumbHeight = PREVIEW_HEIGHT; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getIconWidth(); int imageHeight = image.getIconHeight(); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image.getImage(), 0, 0, thumbWidth, thumbHeight, null); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imagePathThumb)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = 100; quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float) quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } } } } if (imageFile.exists() && !stop) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(imageFile); Element dataBaseElement = doc.getDocumentElement(); if (dataBaseElement.getTagName().equals("dataBase")) { NodeList imageNodeList = dataBaseElement.getElementsByTagName("image"); for (int j = 0; j < imageNodeList.getLength(); j++) { current++; Node imageNode = imageNodeList.item(j); NodeList lista = imageNode.getChildNodes(); Node nameNode = imageNode.getChildNodes().item(0); String imageName = nameNode.getChildNodes().item(0).getNodeValue(); int imageKey = dataBase.imageKeySearchName(imageName.substring(0, imageName.lastIndexOf('.'))); if (imageKey != -1) { for (int k = 1; k < imageNode.getChildNodes().getLength(); k++) { Node keyWordNode = imageNode.getChildNodes().item(k); String keyWord = keyWordNode.getChildNodes().item(0).getNodeValue(); int conceptKey = dataBase.conceptKeySearch(keyWord); if (conceptKey == -1) { dataBase.insertConceptDB(keyWord); conceptKey = dataBase.conceptKeySearch(keyWord); } dataBase.insertAsociatedDB(conceptKey, imageKey); } } } } } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } current = lengthOfTask; }
00
Code Sample 1: public void setPassword(String plaintext) throws java.security.NoSuchAlgorithmException { StringBuffer encrypted = new StringBuffer(); java.security.MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(plaintext.getBytes()); byte[] digestArray = digest.digest(); for (int i = 0; i < digestArray.length; i++) { encrypted.append(byte2hex(digestArray[i])); } setEncryptedPassword(encrypted.toString()); } Code Sample 2: @Test public void shouldDownloadFileUsingPublicLink() throws Exception { String bucketName = "test-" + UUID.randomUUID(); Service service = new WebClientService(credentials); service.createBucket(bucketName); File file = folder.newFile("foo.txt"); FileUtils.writeStringToFile(file, UUID.randomUUID().toString()); service.createObject(bucketName, file.getName(), file, new NullProgressListener()); String publicUrl = service.getPublicUrl(bucketName, file.getName(), new DateTime().plusDays(5)); File saved = folder.newFile("saved.txt"); InputStream input = new URL(publicUrl).openConnection().getInputStream(); FileOutputStream output = new FileOutputStream(saved); IOUtils.copy(input, output); output.close(); assertThat("Corrupted download", Files.computeMD5(saved), equalTo(Files.computeMD5(file))); service.deleteObject(bucketName, file.getName()); service.deleteBucket(bucketName); }
11
Code Sample 1: private Datastream addManagedDatastreamVersion(Entry entry) throws StreamIOException, ObjectIntegrityException { Datastream ds = new DatastreamManagedContent(); setDSCommonProperties(ds, entry); ds.DSLocationType = "INTERNAL_ID"; ds.DSMIME = getDSMimeType(entry); IRI contentLocation = entry.getContentSrc(); if (contentLocation != null) { if (m_obj.isNew()) { ValidationUtility.validateURL(contentLocation.toString(), ds.DSControlGrp); } if (m_format.equals(ATOM_ZIP1_1)) { if (!contentLocation.isAbsolute() && !contentLocation.isPathAbsolute()) { File f = getContentSrcAsFile(contentLocation); contentLocation = new IRI(DatastreamManagedContent.TEMP_SCHEME + f.getAbsolutePath()); } } ds.DSLocation = contentLocation.toString(); ds.DSLocation = (DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), ds, m_transContext)).DSLocation; return ds; } try { File temp = File.createTempFile("binary-datastream", null); OutputStream out = new FileOutputStream(temp); if (MimeTypeHelper.isText(ds.DSMIME) || MimeTypeHelper.isXml(ds.DSMIME)) { IOUtils.copy(new StringReader(entry.getContent()), out, m_encoding); } else { IOUtils.copy(entry.getContentStream(), out); } ds.DSLocation = DatastreamManagedContent.TEMP_SCHEME + temp.getAbsolutePath(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } return ds; } Code Sample 2: void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); }
11
Code Sample 1: @SmallTest public void testSha1() throws Exception { MessageDigest digest = MessageDigest.getInstance("SHA-1"); int numTests = mTestData.length; for (int i = 0; i < numTests; i++) { digest.update(mTestData[i].input.getBytes()); byte[] hash = digest.digest(); String encodedHash = encodeHex(hash); assertEquals(encodedHash, mTestData[i].result); } } Code Sample 2: public String generateDigest(String password, String saltHex, String algorithm) throws NoSuchAlgorithmException { if (algorithm.equalsIgnoreCase("crypt")) { return "{CRYPT}" + UnixCrypt.crypt(password); } else if (algorithm.equalsIgnoreCase("sha")) { algorithm = "SHA-1"; } else if (algorithm.equalsIgnoreCase("md5")) { algorithm = "MD5"; } MessageDigest msgDigest = MessageDigest.getInstance(algorithm); byte[] salt = {}; if (saltHex != null) { salt = fromHex(saltHex); } String label = null; if (algorithm.startsWith("SHA")) { label = (salt.length > 0) ? "{SSHA}" : "{SHA}"; } else if (algorithm.startsWith("MD5")) { label = (salt.length > 0) ? "{SMD5}" : "{MD5}"; } msgDigest.reset(); msgDigest.update(password.getBytes()); msgDigest.update(salt); byte[] pwhash = msgDigest.digest(); StringBuffer digest = new StringBuffer(label); digest.append(Base64.encode(concatenate(pwhash, salt))); return digest.toString(); }
11
Code Sample 1: private void doLogin(String password) throws LoginFailedException, IncorrectPasswordException { final long mgr = Constants.MANAGER; Data data, response; try { response = sendAndWait(new Request(mgr)).get(0); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 hash not supported."); } byte[] challenge = response.getBytes(); md.update(challenge); md.update(password.getBytes(Data.STRING_ENCODING)); try { data = Data.valueOf(md.digest()); response = sendAndWait(new Request(mgr).add(0, data)).get(0); } catch (ExecutionException ex) { throw new IncorrectPasswordException(); } setLoginMessage(response.getString()); response = sendAndWait(new Request(mgr).add(0, getLoginData())).get(0); ID = response.getWord(); registerSettings(); } catch (InterruptedException ex) { throw new LoginFailedException(ex); } catch (ExecutionException ex) { throw new LoginFailedException(ex); } catch (IOException ex) { throw new LoginFailedException(ex); } } Code Sample 2: public ChatClient registerPlayer(int playerId, String playerLogin) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.reset(); md.update(playerLogin.getBytes("UTF-8"), 0, playerLogin.length()); byte[] accountToken = md.digest(); byte[] token = generateToken(accountToken); ChatClient chatClient = new ChatClient(playerId, token); players.put(playerId, chatClient); return chatClient; }
11
Code Sample 1: public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } Code Sample 2: public void run() { try { File outDir = new File(outDirTextField.getText()); if (!outDir.exists()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "The chosen directory does not exist!", "Directory Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (!outDir.isDirectory()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "The chosen file is not a directory!", "Not a Directory Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (!outDir.canWrite()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "Cannot write to the chosen directory!", "Directory Not Writeable Error", JOptionPane.ERROR_MESSAGE); } }); return; } File archiveDir = new File("foo.bar").getAbsoluteFile().getParentFile(); URL baseUrl = UnpackWizard.class.getClassLoader().getResource(UnpackWizard.class.getName().replaceAll("\\.", "/") + ".class"); if (baseUrl.getProtocol().equals("jar")) { String jarPath = baseUrl.getPath(); jarPath = jarPath.substring(0, jarPath.indexOf('!')); if (jarPath.startsWith("file:")) { try { archiveDir = new File(new URI(jarPath)).getAbsoluteFile().getParentFile(); } catch (URISyntaxException e1) { e1.printStackTrace(System.err); } } } SortedMap<Integer, String> inputFileNames = new TreeMap<Integer, String>(); for (Entry<Object, Object> anEntry : indexProperties.entrySet()) { String key = anEntry.getKey().toString(); if (key.startsWith("archive file ")) { inputFileNames.put(Integer.parseInt(key.substring("archive file ".length())), anEntry.getValue().toString()); } } byte[] buff = new byte[64 * 1024]; try { long bytesToWrite = 0; long bytesReported = 0; long bytesWritten = 0; for (String aFileName : inputFileNames.values()) { File aFile = new File(archiveDir, aFileName); if (aFile.exists()) { if (aFile.isFile()) { bytesToWrite += aFile.length(); } else { final File wrongFile = aFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "File \"" + wrongFile.getAbsolutePath() + "\" is not a standard file!", "Non Standard File Error", JOptionPane.ERROR_MESSAGE); } }); return; } } else { final File wrongFile = aFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "File \"" + wrongFile.getAbsolutePath() + "\" does not exist!", "File Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } } MultiFileInputStream mfis = new MultiFileInputStream(archiveDir, inputFileNames.values().toArray(new String[inputFileNames.size()])); TarArchiveInputStream tis = new TarArchiveInputStream(new BufferedInputStream(mfis)); TarArchiveEntry tarEntry = tis.getNextTarEntry(); while (tarEntry != null) { File outFile = new File(outDir.getAbsolutePath() + "/" + tarEntry.getName()); if (outFile.exists()) { final File wrongFile = outFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "Was about to write out file \"" + wrongFile.getAbsolutePath() + "\" but it already " + "exists.\nPlease [re]move existing files out of the way " + "and try again.", "File Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (tarEntry.isDirectory()) { outFile.getAbsoluteFile().mkdirs(); } else { outFile.getAbsoluteFile().getParentFile().mkdirs(); OutputStream os = new BufferedOutputStream(new FileOutputStream(outFile)); int len = tis.read(buff, 0, buff.length); while (len != -1) { os.write(buff, 0, len); bytesWritten += len; if (bytesWritten - bytesReported > (10 * 1024 * 1024)) { bytesReported = bytesWritten; final int progress = (int) (bytesReported * 100 / bytesToWrite); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setValue(progress); } }); } len = tis.read(buff, 0, buff.length); } os.close(); } tarEntry = tis.getNextTarEntry(); } long expectedCrc = 0; try { expectedCrc = Long.parseLong(indexProperties.getProperty("CRC32", "0")); } catch (NumberFormatException e) { System.err.println("Error while obtaining the expected CRC"); e.printStackTrace(System.err); } if (mfis.getCRC() == expectedCrc) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "Extraction completed successfully!", "Done!", JOptionPane.INFORMATION_MESSAGE); } }); return; } else { System.err.println("CRC Error: was expecting " + expectedCrc + " but got " + mfis.getCRC()); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "CRC Error: the data extracted does not have the expected CRC!\n" + "You should probably delete the extracted files, as they are " + "likely to be invalid.", "CRC Error", JOptionPane.ERROR_MESSAGE); } }); return; } } catch (final IOException e) { e.printStackTrace(System.err); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "Input/Output Error: " + e.getLocalizedMessage(), "Input/Output Error", JOptionPane.ERROR_MESSAGE); } }); return; } } finally { SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); setEnabled(true); } }); } }
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: public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getCanonicalPath()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getCanonicalPath()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getCanonicalPath()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getCanonicalPath()); throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[1024 * 1024]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); if (fromFile.isHidden()) { } toFile.setLastModified(fromFile.lastModified()); toFile.setExecutable(fromFile.canExecute()); toFile.setReadable(fromFile.canRead()); toFile.setWritable(toFile.canWrite()); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
11
Code Sample 1: public void copyFile(File s, File t) { try { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); } catch (Exception e) { System.out.println(e); } } Code Sample 2: public static void main(String[] args) throws Exception { if (args.length < 3) { usage(System.out); System.exit(1); } final File tmpFile = File.createTempFile("sej", null); tmpFile.deleteOnExit(); final FileOutputStream destination = new FileOutputStream(tmpFile); final String mainClass = args[1]; final Collection jars = new LinkedList(); for (int i = 2; i < args.length; i++) { String arg = args[i]; jars.add(arg); } JarInterpretted interpretted = new JarInterpretted(destination); JarCat rowr = new JarCat(destination, createManifest(mainClass), jars); interpretted.write(); rowr.write(); destination.close(); final File finalDestinationFile = new File(args[0]); final FileOutputStream finalDestination = new FileOutputStream(finalDestinationFile); IOUtils.copy(new FileInputStream(tmpFile), finalDestination); finalDestination.close(); Chmod chmod = new Chmod("a+rx", new File[] { finalDestinationFile }); chmod.invoke(); }
11
Code Sample 1: public static byte[] readUrl(URL url) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream is = url.openStream(); try { IOUtils.copy(is, os); return os.toByteArray(); } finally { is.close(); } } Code Sample 2: public static boolean nioWriteFile(FileInputStream inputStream, FileOutputStream out) { if (inputStream == null && out == null) { return false; } try { FileChannel fci = inputStream.getChannel(); FileChannel fco = out.getChannel(); fco.transferFrom(fci, 0, fci.size()); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { FileUtil.safeClose(inputStream); FileUtil.safeClose(out); } }
11
Code Sample 1: private void detachFile(File file, Block b) throws IOException { File tmpFile = volume.createDetachFile(b, file.getName()); try { IOUtils.copyBytes(new FileInputStream(file), new FileOutputStream(tmpFile), 16 * 1024, true); if (file.length() != tmpFile.length()) { throw new IOException("Copy of file " + file + " size " + file.length() + " into file " + tmpFile + " resulted in a size of " + tmpFile.length()); } FileUtil.replaceFile(tmpFile, file); } catch (IOException e) { boolean done = tmpFile.delete(); if (!done) { DataNode.LOG.info("detachFile failed to delete temporary file " + tmpFile); } throw e; } } Code Sample 2: public static boolean copyFile(File sourceFile, File destFile) throws IOException { long flag = 0; if (!destFile.exists()) destFile.createNewFile(); FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); flag = destination.transferFrom(source, 0, source.size()); } catch (Exception e) { Logger.getLogger(FileUtils.class.getPackage().getName()).log(Level.WARNING, "ERROR: Problem copying file", e); } finally { if (source != null) source.close(); if (destination != null) destination.close(); } if (flag == 0) return false; else return true; }
11
Code Sample 1: private String getXML(String url) throws ClientProtocolException, IOException { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); HttpResponse responseGet = client.execute(get); HttpEntity resEntityGet = responseGet.getEntity(); BufferedReader in = new BufferedReader(new InputStreamReader(resEntityGet.getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String xml = sb.toString(); return xml; } Code Sample 2: public String buscaCDA() { Properties prop = new CargaProperties().Carga(); URL url; BufferedReader in; String inputLine; String miLinea = null; try { url = new URL(prop.getProperty("CDA")); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = in.readLine()) != null) { if (inputLine.contains("cda-TRUNK-")) { miLinea = inputLine; miLinea = miLinea.substring(miLinea.indexOf("lastSuccessfulBuild/artifact/dist/cda-TRUNK")); miLinea = miLinea.substring(0, miLinea.indexOf("\">")); miLinea = url + miLinea; } } } catch (Throwable t) { } log.debug("Detetectado last build CDA: " + miLinea); return miLinea; }
11
Code Sample 1: public void writeToStream(OutputStream out) throws IOException { InputStream result = null; if (tempFile != null) { InputStream input = new BufferedInputStream(new FileInputStream(tempFile)); IOUtils.copy(input, out); IOUtils.closeQuietly(input); } else if (tempBuffer != null) { out.write(tempBuffer); } } Code Sample 2: public static String CreateZip(String[] filesToZip, String zipFileName) { byte[] buffer = new byte[18024]; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); out.setLevel(Deflater.BEST_COMPRESSION); for (int i = 0; i < filesToZip.length; i++) { FileInputStream in = new FileInputStream(filesToZip[i]); String fileName = null; for (int X = filesToZip[i].length() - 1; X >= 0; X--) { if (filesToZip[i].charAt(X) == '\\' || filesToZip[i].charAt(X) == '/') { fileName = filesToZip[i].substring(X + 1); break; } else if (X == 0) fileName = filesToZip[i]; } out.putNextEntry(new ZipEntry(fileName)); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); } out.close(); } catch (IllegalArgumentException e) { return "Failed to create zip: " + e.toString(); } catch (FileNotFoundException e) { return "Failed to create zip: " + e.toString(); } catch (IOException e) { return "Failed to create zip: " + e.toString(); } return "Success"; }
11
Code Sample 1: @RequestMapping("/import") public String importPicture(@ModelAttribute PictureImportCommand command) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); URL url = command.getUrl(); IOUtils.copy(url.openStream(), baos); byte[] imageData = imageFilterService.touchupImage(baos.toByteArray()); String filename = StringUtils.substringAfterLast(url.getPath(), "/"); String email = userService.getCurrentUser().getEmail(); Picture picture = new Picture(email, filename, command.getDescription(), imageData); pictureRepository.store(picture); return "redirect:/picture/gallery"; } Code Sample 2: private static void copyFile(String from, String to) throws IOException { FileReader in = new FileReader(from); FileWriter out = new FileWriter(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
00
Code Sample 1: private SystemProperties() { Properties p = new Properties(); ClassLoader classLoader = getClass().getClassLoader(); try { URL url = classLoader.getResource("system.properties"); if (url != null) { InputStream is = url.openStream(); p.load(is); is.close(); System.out.println("Loading " + url); } } catch (Exception e) { e.printStackTrace(); } try { URL url = classLoader.getResource("system-ext.properties"); if (url != null) { InputStream is = url.openStream(); p.load(is); is.close(); System.out.println("Loading " + url); } } catch (Exception e) { e.printStackTrace(); } boolean systemPropertiesLoad = GetterUtil.get(System.getProperty(SYSTEM_PROPERTIES_LOAD), true); boolean systemPropertiesFinal = GetterUtil.get(System.getProperty(SYSTEM_PROPERTIES_FINAL), true); if (systemPropertiesLoad) { Enumeration enu = p.propertyNames(); while (enu.hasMoreElements()) { String key = (String) enu.nextElement(); if (systemPropertiesFinal || Validator.isNull(System.getProperty(key))) { System.setProperty(key, (String) p.get(key)); } } } PropertiesUtil.fromProperties(p, _props); } Code Sample 2: public static void sendPostRequest() { String data = "text=Eschirichia coli"; try { URL url = new URL("http://taxonfinder.ubio.org/analyze?"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); StringBuffer answer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { answer.append(line); } writer.close(); reader.close(); System.out.println(answer.toString()); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
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: public String getClass(EmeraldjbBean eb) throws EmeraldjbException { Entity entity = (Entity) eb; StringBuffer sb = new StringBuffer(); String myPackage = getPackageName(eb); sb.append("package " + myPackage + ";\n"); sb.append("\n"); DaoValuesGenerator valgen = new DaoValuesGenerator(); String values_class_name = valgen.getClassName(entity); sb.append("\n"); List importList = new Vector(); importList.add("java.io.FileOutputStream;"); importList.add("java.io.FileInputStream;"); importList.add("java.io.DataInputStream;"); importList.add("java.io.DataOutputStream;"); importList.add("java.io.IOException;"); importList.add("java.sql.Date;"); importList.add(valgen.getPackageName(eb) + "." + values_class_name + ";"); Iterator it = importList.iterator(); while (it.hasNext()) { String importName = (String) it.next(); sb.append("import " + importName + "\n"); } sb.append("\n"); String proto_version = entity.getPatternValue(GeneratorConst.PATTERN_STREAM_PROTO_VERSION, "1"); String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + "\n"); sb.append("{" + "\n public static final int PROTO_VERSION=" + proto_version + ";"); sb.append("\n\n"); StringBuffer f_writer = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); while (it.hasNext()) { Member member = (Member) it.next(); String nm = member.getName(); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToBinaryCode(pad, "dos", getter + "()")); f_reader.append(gen_type.getFromBinaryCode(pad, "din", setter)); } String reader_vars = ""; sb.append("\n public static void writeToFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileOutputStream fos = new FileOutputStream(file_nm);" + "\n DataOutputStream dos = new DataOutputStream(fos);" + "\n writeStream(dos, obj);" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileInputStream fis = new FileInputStream(file_nm);" + "\n DataInputStream dis = new DataInputStream(fis);" + "\n readStream(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeStream(DataOutputStream dos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n dos.writeByte(PROTO_VERSION);" + "\n " + f_writer + "\n } // end of writeStream" + "\n" + "\n public static void readStream(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + "\n int proto_version = din.readByte();" + "\n if (proto_version==" + proto_version + ") readStreamV1(din,obj);" + "\n } // end of readStream" + "\n" + "\n public static void readStreamV1(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + reader_vars + f_reader + "\n } // end of readStreamV1" + "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"); return sb.toString(); }
11
Code Sample 1: public static String encrypt(final String password, final String algorithm, final byte[] salt) { final StringBuffer buffer = new StringBuffer(); MessageDigest digest = null; int size = 0; if ("CRYPT".equalsIgnoreCase(algorithm)) { throw new InternalError("Not implemented"); } else if ("SHA".equalsIgnoreCase(algorithm) || "SSHA".equalsIgnoreCase(algorithm)) { size = 20; if (salt != null && salt.length > 0) { buffer.append("{SSHA}"); } else { buffer.append("{SHA}"); } try { digest = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if ("MD5".equalsIgnoreCase(algorithm) || "SMD5".equalsIgnoreCase(algorithm)) { size = 16; if (salt != null && salt.length > 0) { buffer.append("{SMD5}"); } else { buffer.append("{MD5}"); } try { digest = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } int outSize = size; digest.reset(); digest.update(password.getBytes()); if (salt != null && salt.length > 0) { digest.update(salt); outSize += salt.length; } final byte[] out = new byte[outSize]; System.arraycopy(digest.digest(), 0, out, 0, size); if (salt != null && salt.length > 0) { System.arraycopy(salt, 0, out, size, salt.length); } buffer.append(Base64.encode(out)); return buffer.toString(); } Code Sample 2: public static String digest(String algorithm, String text) { MessageDigest mDigest = null; try { mDigest = MessageDigest.getInstance(algorithm); mDigest.update(text.getBytes(ENCODING)); } catch (Exception e) { e.printStackTrace(); mDigest = null; } if (mDigest == null) return null; byte[] raw = mDigest.digest(); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(raw); }
11
Code Sample 1: public static void decryptFile(String input, String output, String pwd) throws Exception { CipherInputStream in; OutputStream out; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.DECRYPT_MODE, key); in = new CipherInputStream(new FileInputStream(input), cipher); out = new FileOutputStream(output); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
00
Code Sample 1: public static boolean copyFile(File from, File tu) { final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(tu); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { return false; } return true; } Code Sample 2: public static synchronized Map<String, Object> getURLContentMap(String wwwurl) throws IOException, URISyntaxException { Map<String, Object> resultMap = new HashMap<String, Object>(); URI uri = new URI(wwwurl); URL url = new URL(uri.toASCIIString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10 * 1000); HttpURLConnection.setFollowRedirects(true); try { conn.setRequestMethod("GET"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.17) Gecko/20110421 Red Hat/3.6-1.el5_6 Firefox/3.6.17"); for (String key : conn.getHeaderFields().keySet()) { List<String> headerInfo = conn.getHeaderFields().get(key); if (headerInfo.size() > 0) { resultMap.put(key, headerInfo.get(0)); } } String contentType = conn.getContentType(); if (!(contentType == null || contentType.toLowerCase().contains("text") || contentType.toLowerCase().contains("html"))) { return resultMap; } ByteArrayOutputStream outstream = new ByteArrayOutputStream(); InputStream instream = conn.getInputStream(); synchronized (instream) { int readSize = 0; int totalSize = 0; byte[] contentByte = null; byte[] buffer = new byte[1024]; while ((readSize = instream.read(buffer)) > 0) { outstream.write(buffer, 0, readSize); totalSize += readSize; if (totalSize >= MAX_CONTENT_SIZE) { contentByte = ("[FAILD] content size is larger than " + MAX_CONTENT_SIZE + " byte.").getBytes(); } } if (contentByte == null) { contentByte = outstream.toByteArray(); } instream.close(); outstream.close(); resultMap.put(contentByteField, contentByte); } } finally { } return resultMap; }
11
Code Sample 1: public static final String convertPassword(final String srcPwd) { StringBuilder out; MessageDigest md; byte[] byteValues; byte singleChar = 0; try { md = MessageDigest.getInstance("MD5"); md.update(srcPwd.getBytes()); byteValues = md.digest(); if ((byteValues == null) || (byteValues.length <= 0)) { return null; } out = new StringBuilder(byteValues.length * 2); for (byte element : byteValues) { singleChar = (byte) (element & 0xF0); singleChar = (byte) (singleChar >>> 4); singleChar = (byte) (singleChar & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); singleChar = (byte) (element & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); } return out.toString(); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } Code Sample 2: public static String digest(String value, String algorithm) throws Exception { MessageDigest algo = MessageDigest.getInstance(algorithm); algo.reset(); algo.update(value.getBytes("UTF-8")); return StringTool.byteArrayToString(algo.digest()); }
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: public static void copy(File source, 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(); } }
00
Code Sample 1: public boolean connentServer() { boolean result = false; try { ftpClient = new FTPClient(); ftpClient.setDefaultPort(port); ftpClient.setControlEncoding("GBK"); strOut = strOut + "Connecting to host " + host + "\r\n"; ftpClient.connect(host); if (!ftpClient.login(user, password)) return false; FTPClientConfig conf = new FTPClientConfig(getSystemKey(ftpClient.getSystemName())); conf.setServerLanguageCode("zh"); ftpClient.configure(conf); strOut = strOut + "User " + user + " login OK.\r\n"; if (!ftpClient.changeWorkingDirectory(sDir)) { ftpClient.makeDirectory(sDir); ftpClient.changeWorkingDirectory(sDir); } strOut = strOut + "Directory: " + sDir + "\r\n"; ftpClient.setFileType(FTP.BINARY_FILE_TYPE); strOut = strOut + "Connect Success.\r\n"; result = true; } catch (Exception e) { e.printStackTrace(); result = false; } return result; } Code Sample 2: private ArrayList loadResults(String text, String index, int from) { loadingMore = true; JSONObject job = new JSONObject(); ArrayList al = new ArrayList(); try { String req = job.put("OperationId", "2").toString(); InputStream is = null; String result = ""; JSONObject jArray = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://192.168.1.4:8080/newgenlibctxt/CarbonServlet"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("OperationId", "2")); nameValuePairs.add(new BasicNameValuePair("Text", text)); nameValuePairs.add(new BasicNameValuePair("Index", index)); nameValuePairs.add(new BasicNameValuePair("From", from + "")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } try { JSONObject jobres = new JSONObject(result); JSONArray jarr = jobres.getJSONArray("Records"); for (int i = 0; i < jarr.length(); i++) { String title = jarr.getJSONObject(i).getString("title"); String author = jarr.getJSONObject(i).getString("author"); String[] id = new String[2]; id[0] = jarr.getJSONObject(i).getString("cataloguerecordid"); id[1] = jarr.getJSONObject(i).getString("ownerlibraryid"); alOnlyIds.add(id); al.add(Html.fromHtml("<html><body><b>" + title + "</b><br>by " + author + "</body></html>")); } } catch (JSONException e) { e.printStackTrace(); } } catch (Exception exp) { exp.printStackTrace(); } loadingMore = false; return al; }
11
Code Sample 1: private void copyPhoto(final IPhoto photo, final Map.Entry<String, Integer> size) { final File fileIn = new File(storageService.getPhotoPath(photo, storageService.getOriginalDir())); final File fileOut = new File(storageService.getPhotoPath(photo, size.getKey())); InputStream fileInputStream; OutputStream fileOutputStream; try { fileInputStream = new FileInputStream(fileIn); fileOutputStream = new FileOutputStream(fileOut); IOUtils.copy(fileInputStream, fileOutputStream); fileInputStream.close(); fileOutputStream.close(); } catch (final IOException e) { log.error("file io exception", e); return; } } Code Sample 2: private void saveFile(Folder folder, Object key, InputStream stream) throws FileManagerException { File file = new File(folder, key.toString()); LOGGER.debug("Writing file: " + file.getAbsolutePath()); Writer writer = null; Writer encodedWriter = null; try { encodedWriter = new OutputStreamWriter(new FileOutputStream(file), getEncodeCharset()); IOUtils.copy(stream, encodedWriter, getDecodeCharset()); LOGGER.info("saveFile(), decode charset: " + getDecodeCharset() + ", encode charset: " + getEncodeCharset()); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } finally { try { encodedWriter.close(); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } } }
11
Code Sample 1: public static boolean copyFileToContentFolder(String source, LearningDesign learningDesign) { File inputFile = new File(source); File outputFile = new File(getRootFilePath(learningDesign) + inputFile.getName()); FileReader in; try { in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; } Code Sample 2: private ParserFileReader createParserFileReader(final FromNetRecord record) throws IOException { final String strUrl = record.getStrUrl(); ParserFileReader parserFileReader; try { parserFileReader = parserFileReaderFactory.create(strUrl); } catch (Exception exception) { _log.error("can not create reader for \"" + strUrl + "\"", exception); parserFileReader = null; } url = parserFileReaderFactory.getUrl(); if (parserFileReader != null) { parserFileReader.mark(); final String outFileName = urlToFile("runtime/tests", url, ""); final File outFile = new File(outFileName); outFile.getParentFile().mkdirs(); final Writer writer = new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"); int readed; while ((readed = parserFileReader.read()) != -1) { writer.write(readed); } writer.close(); parserFileReader.reset(); } return parserFileReader; }
00
Code Sample 1: private static void readServicesFromUrl(Collection<String> list, URL url) throws IOException { InputStream in = url.openStream(); try { if (in == null) return; BufferedReader r = new BufferedReader(new InputStreamReader(in, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) break; int idx = line.indexOf('#'); if (idx != -1) line = line.substring(0, idx); line = line.trim(); if (line.length() == 0) continue; list.add(line); } } finally { try { if (in != null) in.close(); } catch (Throwable ignore) { } } } Code Sample 2: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/jar"); byte[] bufor = new byte[BUF_LEN]; ServletContext context = getServletContext(); URL url = context.getResource(FILE_NAME); InputStream in = url.openStream(); OutputStream out = response.getOutputStream(); while (in.read(bufor) != -1) out.write(bufor); in.close(); out.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: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
11
Code Sample 1: protected void downgradeHistory(Collection<String> versions) { Assert.notEmpty(versions); try { Connection connection = this.database.getDefaultConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE " + this.logTableName + " SET RESULT = 'DOWNGRADED' WHERE TYPE = 'B' AND TARGET = ? AND RESULT = 'COMPLETE'"); boolean commit = false; try { for (String version : versions) { statement.setString(1, version); int modified = statement.executeUpdate(); Assert.isTrue(modified <= 1, "Expecting not more than 1 record to be updated, not " + modified); } commit = true; } finally { statement.close(); if (commit) connection.commit(); else connection.rollback(); } } catch (SQLException e) { throw new SystemException(e); } } Code Sample 2: private long getNextHighValue() throws Exception { Connection con = null; PreparedStatement psGetHighValue = null; PreparedStatement psUpdateHighValue = null; ResultSet rs = null; long high = -1L; int isolation = -1; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { con = dbo.getConnection(); psGetHighValue = con.prepareStatement(strGetHighValue); psGetHighValue.setString(1, this.name); for (rs = psGetHighValue.executeQuery(); rs.next(); ) { high = rs.getLong("high"); } psUpdateHighValue = con.prepareStatement(strUpdateHighValue); psUpdateHighValue.setLong(1, high + 1L); psUpdateHighValue.setString(2, this.name); psUpdateHighValue.executeUpdate(); } catch (SQLException e) { if (con != null) { con.rollback(); } throw e; } finally { if (psUpdateHighValue != null) { psUpdateHighValue.close(); } close(dbo, psGetHighValue, rs); } return high; }
00
Code Sample 1: public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { BufferedReader reader; if (baseUrl == null) setBaseUrlFromUrl(url); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); } catch (IOException e) { throw new FileNotFoundException(e.getMessage()); } fromUrl = true; return load(reader); } Code Sample 2: public void testCommitRollback() throws Exception { Statement stmt = con.createStatement(); assertNotNull(stmt); assertTrue(con.getAutoCommit()); stmt.execute("CREATE TABLE #TESTCOMMIT (id int primary key)"); con.setAutoCommit(false); assertFalse(con.getAutoCommit()); assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (1)")); con.commit(); assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (2)")); assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (3)")); con.rollback(); assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (4)")); con.setAutoCommit(true); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM #TESTCOMMIT"); rs.next(); assertEquals("commit", 2, rs.getInt(1)); stmt.close(); }
11
Code Sample 1: public static void main(String[] a) { ArrayList<String> allFilesToBeCopied = new ArrayList<String>(); new File(outputDir).mkdirs(); try { FileReader fis = new FileReader(completeFileWithDirToCathFileList); BufferedReader bis = new BufferedReader(fis); String line = ""; String currentCombo = ""; while ((line = bis.readLine()) != null) { String[] allEntries = line.split("\\s+"); String fileName = allEntries[0]; String thisCombo = allEntries[1] + allEntries[2] + allEntries[3] + allEntries[4]; if (currentCombo.equals(thisCombo)) { } else { System.out.println("merke: " + fileName); allFilesToBeCopied.add(fileName); currentCombo = thisCombo; } } System.out.println(allFilesToBeCopied.size()); for (String file : allFilesToBeCopied) { try { FileChannel srcChannel = new FileInputStream(CathDir + file).getChannel(); FileChannel dstChannel = new FileOutputStream(outputDir + file).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public void getFile(OutputStream output, Fragment fragment) throws Exception { Assert.Arg.notNull(output, "output"); Assert.Arg.notNull(fragment, "fragment"); Assert.Arg.notNull(fragment.getId(), "fragment.getId()"); if (this.delegate != null) { this.delegate.getFile(output, fragment); return; } ensureBaseDirectoryCreated(); File filePath = getFragmentFilePath(fragment); InputStream input = FileUtils.openInputStream(filePath); try { IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(input); } }
00
Code Sample 1: public static String md5(String text) { String encrypted = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); encrypted = hex(md.digest()); } catch (NoSuchAlgorithmException nsaEx) { } return encrypted; } Code Sample 2: public void register(URL codeBase, String filePath) throws Exception { Properties properties = new Properties(); URL url = new URL(codeBase + filePath); properties.load(url.openStream()); initializeContext(codeBase, properties); }
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 detachFile(File file, Block b) throws IOException { File tmpFile = volume.createDetachFile(b, file.getName()); try { IOUtils.copyBytes(new FileInputStream(file), new FileOutputStream(tmpFile), 16 * 1024, true); if (file.length() != tmpFile.length()) { throw new IOException("Copy of file " + file + " size " + file.length() + " into file " + tmpFile + " resulted in a size of " + tmpFile.length()); } FileUtil.replaceFile(tmpFile, file); } catch (IOException e) { boolean done = tmpFile.delete(); if (!done) { DataNode.LOG.info("detachFile failed to delete temporary file " + tmpFile); } throw e; } }
11
Code Sample 1: @Override protected RequestLogHandler createRequestLogHandler() { try { File logbackConf = File.createTempFile("logback-access", ".xml"); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("logback-access.xml"), new FileOutputStream(logbackConf)); RequestLogHandler requestLogHandler = new RequestLogHandler(); RequestLogImpl requestLog = new RequestLogImpl(); requestLog.setFileName(logbackConf.getPath()); requestLogHandler.setRequestLog(requestLog); } catch (FileNotFoundException e) { log.error("Could not create request log handler", e); } catch (IOException e) { log.error("Could not create request log handler", e); } return null; } 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(); } }
00
Code Sample 1: public Object run() { if (type == GET_THEME_DIR) { String sep = File.separator; String[] dirs = new String[] { userHome + sep + ".themes", System.getProperty("swing.metacitythemedir"), "/usr/share/themes", "/usr/gnome/share/themes", "/opt/gnome2/share/themes" }; URL themeDir = null; for (int i = 0; i < dirs.length; i++) { if (dirs[i] == null) { continue; } File dir = new File(dirs[i] + sep + arg + sep + "metacity-1"); if (new File(dir, "metacity-theme-1.xml").canRead()) { try { themeDir = dir.toURL(); } catch (MalformedURLException ex) { themeDir = null; } break; } } if (themeDir == null) { String filename = "resources/metacity/" + arg + "/metacity-1/metacity-theme-1.xml"; URL url = getClass().getResource(filename); if (url != null) { String str = url.toString(); try { themeDir = new URL(str.substring(0, str.lastIndexOf('/')) + "/"); } catch (MalformedURLException ex) { themeDir = null; } } } return themeDir; } else if (type == GET_USER_THEME) { try { userHome = System.getProperty("user.home"); String theme = System.getProperty("swing.metacitythemename"); if (theme != null) { return theme; } URL url = new URL(new File(userHome).toURL(), ".gconf/apps/metacity/general/%25gconf.xml"); Reader reader = new InputStreamReader(url.openStream(), "ISO-8859-1"); char[] buf = new char[1024]; StringBuffer strBuf = new StringBuffer(); int n; while ((n = reader.read(buf)) >= 0) { strBuf.append(buf, 0, n); } reader.close(); String str = strBuf.toString(); if (str != null) { String strLowerCase = str.toLowerCase(); int i = strLowerCase.indexOf("<entry name=\"theme\""); if (i >= 0) { i = strLowerCase.indexOf("<stringvalue>", i); if (i > 0) { i += "<stringvalue>".length(); int i2 = str.indexOf("<", i); return str.substring(i, i2); } } } } catch (MalformedURLException ex) { } catch (IOException ex) { } return null; } else if (type == GET_IMAGE) { return new ImageIcon((URL) arg).getImage(); } else { return null; } } 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: @Override public void run() { EventType type = event.getEventType(); IBaseObject field = event.getField(); log.info("select----->" + field.getAttribute(IDatafield.URL)); try { IParent parent = field.getParent(); String name = field.getName(); if (type == EventType.ON_BTN_CLICK) { invoke(parent, "eventRule_" + name); Object value = event.get(Event.ARG_VALUE); if (value != null && value instanceof String[]) { String[] args = (String[]) value; for (String arg : args) log.info("argument data: " + arg); } } else if (type == EventType.ON_BEFORE_DOWNLOAD) invoke(parent, "eventRule_" + name); else if (type == EventType.ON_VALUE_CHANGE) { String pattern = (String) event.get(Event.ARG_PATTERN); Object value = event.get(Event.ARG_VALUE); Class cls = field.getDataType(); if (cls == null || value == null || value.getClass().equals(cls)) field.setValue(value); else if (pattern == null) field.setValue(ConvertUtils.convert(value.toString(), cls)); else if (Date.class.isAssignableFrom(cls)) field.setValue(new SimpleDateFormat(pattern).parse((String) value)); else if (Number.class.isAssignableFrom(cls)) field.setValue(new DecimalFormat(pattern).parse((String) value)); else field.setValue(new MessageFormat(pattern).parse((String) value)); invoke(parent, "checkRule_" + name); invoke(parent, "defaultRule_" + name); } else if (type == EventType.ON_ROW_SELECTED) { log.info("table row selected."); Object selected = event.get(Event.ARG_ROW_INDEX); if (selected instanceof Integer) presentation.setSelectedRowIndex((IModuleList) field, (Integer) selected); else if (selected instanceof List) { String s = ""; String conn = ""; for (Integer item : (List<Integer>) selected) { s = s + conn + item; conn = ","; } log.info("row " + s + " line(s) been selected."); } } else if (type == EventType.ON_ROW_DBLCLICK) { log.info("table row double-clicked."); presentation.setSelectedRowIndex((IModuleList) field, (Integer) event.get(Event.ARG_ROW_INDEX)); } else if (type == EventType.ON_ROW_INSERT) { log.info("table row inserted."); listAdd((IModuleList) field, (Integer) event.get(Event.ARG_ROW_INDEX)); } else if (type == EventType.ON_ROW_REMOVE) { log.info("table row removed."); listRemove((IModuleList) field, (Integer) event.get(Event.ARG_ROW_INDEX)); } else if (type == EventType.ON_FILE_UPLOAD) { log.info("file uploaded."); InputStream is = (InputStream) event.get(Event.ARG_VALUE); String uploadFileName = (String) event.get(Event.ARG_FILE_NAME); log.info("<-----file name:" + uploadFileName); OutputStream os = (OutputStream) field.getValue(); IOUtils.copy(is, os); is.close(); os.close(); } } catch (Exception e) { if (field != null) log.info("field type is :" + field.getDataType().getName()); log.info("select", e); } } Code Sample 2: public void extractPrincipalClasses(String[] info, int numFiles) { String methodName = ""; String finalClass = ""; String WA; String MC; String RA; int[] readCount = new int[numFiles]; int[] writeCount = new int[numFiles]; int[] methodCallCount = new int[numFiles]; int writeMax1; int writeMax2; int readMax; int methodCallMax; int readMaxIndex = 0; int writeMaxIndex1 = 0; int writeMaxIndex2; int methodCallMaxIndex = 0; try { MethodsDestClass = new BufferedWriter(new FileWriter("InfoFiles/MethodsDestclass.txt")); FileInputStream fstreamWriteAttr = new FileInputStream("InfoFiles/WriteAttributes.txt"); DataInputStream inWriteAttr = new DataInputStream(fstreamWriteAttr); BufferedReader writeAttr = new BufferedReader(new InputStreamReader(inWriteAttr)); FileInputStream fstreamMethodsCalled = new FileInputStream("InfoFiles/MethodsCalled.txt"); DataInputStream inMethodsCalled = new DataInputStream(fstreamMethodsCalled); BufferedReader methodsCalled = new BufferedReader(new InputStreamReader(inMethodsCalled)); FileInputStream fstreamReadAttr = new FileInputStream("InfoFiles/ReadAttributes.txt"); DataInputStream inReadAttr = new DataInputStream(fstreamReadAttr); BufferedReader readAttr = new BufferedReader(new InputStreamReader(inReadAttr)); while ((WA = writeAttr.readLine()) != null && (RA = readAttr.readLine()) != null && (MC = methodsCalled.readLine()) != null) { WA = writeAttr.readLine(); RA = readAttr.readLine(); MC = methodsCalled.readLine(); while (WA.compareTo("EndOfClass") != 0 && RA.compareTo("EndOfClass") != 0 && MC.compareTo("EndOfClass") != 0) { methodName = writeAttr.readLine(); readAttr.readLine(); methodsCalled.readLine(); WA = writeAttr.readLine(); MC = methodsCalled.readLine(); RA = readAttr.readLine(); while (true) { if (WA.compareTo("EndOfMethod") == 0 && RA.compareTo("EndOfMethod") == 0 && MC.compareTo("EndOfMethod") == 0) { break; } if (WA.compareTo("EndOfMethod") != 0) { if (WA.indexOf(".") > 0) { WA = WA.substring(0, WA.indexOf(".")); } } if (RA.compareTo("EndOfMethod") != 0) { if (RA.indexOf(".") > 0) { RA = RA.substring(0, RA.indexOf(".")); } } if (MC.compareTo("EndOfMethod") != 0) { if (MC.indexOf(".") > 0) { MC = MC.substring(0, MC.indexOf(".")); } } for (int i = 0; i < numFiles && info[i] != null; i++) { if (info[i].compareTo(WA) == 0) { writeCount[i]++; } if (info[i].compareTo(RA) == 0) { readCount[i]++; } if (info[i].compareTo(MC) == 0) { methodCallCount[i]++; } } if (WA.compareTo("EndOfMethod") != 0) { WA = writeAttr.readLine(); } if (MC.compareTo("EndOfMethod") != 0) { MC = methodsCalled.readLine(); } if (RA.compareTo("EndOfMethod") != 0) { RA = readAttr.readLine(); } } WA = writeAttr.readLine(); MC = methodsCalled.readLine(); RA = readAttr.readLine(); writeMax1 = writeCount[0]; writeMaxIndex1 = 0; for (int i = 1; i < numFiles; i++) { if (writeCount[i] > writeMax1) { writeMax1 = writeCount[i]; writeMaxIndex1 = i; } } writeCount[writeMaxIndex1] = 0; writeMax2 = writeCount[0]; writeMaxIndex2 = 0; for (int i = 1; i < numFiles; i++) { if (writeCount[i] > writeMax2) { writeMax2 = writeCount[i]; writeMaxIndex2 = i; } } readMax = readCount[0]; readMaxIndex = 0; for (int i = 1; i < numFiles; i++) { if (readCount[i] > readMax) { readMax = readCount[i]; readMaxIndex = i; } } methodCallMax = methodCallCount[0]; methodCallMaxIndex = 0; for (int i = 1; i < numFiles; i++) { if (methodCallCount[i] > methodCallMax) { methodCallMax = methodCallCount[i]; methodCallMaxIndex = i; } } boolean isNotEmpty = false; if (writeMax1 > 0 && writeMax2 == 0) { finalClass = info[writeMaxIndex1]; isNotEmpty = true; } else if (writeMax1 == 0) { if (readMax != 0) { finalClass = info[readMaxIndex]; isNotEmpty = true; } else if (methodCallMax != 0) { finalClass = info[methodCallMaxIndex]; isNotEmpty = true; } } if (isNotEmpty == true) { MethodsDestClass.write(methodName); MethodsDestClass.newLine(); MethodsDestClass.write(finalClass); MethodsDestClass.newLine(); isNotEmpty = false; } for (int j = 0; j < numFiles; j++) { readCount[j] = 0; writeCount[j] = 0; methodCallCount[j] = 0; } } } writeAttr.close(); methodsCalled.close(); readAttr.close(); MethodsDestClass.close(); int sizeInfoArray = 0; sizeInfoArray = infoArraySize(); boolean classWritten = false; principleClass = new String[100]; principleMethod = new String[100]; principleMethodsClass = new String[100]; String infoArray[] = new String[sizeInfoArray]; String field; int counter = 0; FileInputStream fstreamDestMethod = new FileInputStream("InfoFiles/MethodsDestclass.txt"); DataInputStream inDestMethod = new DataInputStream(fstreamDestMethod); BufferedReader destMethod = new BufferedReader(new InputStreamReader(inDestMethod)); PrincipleClassGroup = new BufferedWriter(new FileWriter("InfoFiles/PrincipleClassGroup.txt")); while ((field = destMethod.readLine()) != null) { infoArray[counter] = field; counter++; } for (int i = 0; i < numFiles; i++) { for (int j = 0; j < counter - 1 && info[i] != null; j++) { if (infoArray[j + 1].compareTo(info[i]) == 0) { if (classWritten == false) { PrincipleClassGroup.write(infoArray[j + 1]); PrincipleClassGroup.newLine(); principleClass[principleClassCount] = infoArray[j + 1]; principleClassCount++; classWritten = true; } PrincipleClassGroup.write(infoArray[j]); principleMethod[principleMethodCount] = infoArray[j]; principleMethodsClass[principleMethodCount] = infoArray[j + 1]; principleMethodCount++; PrincipleClassGroup.newLine(); } } if (classWritten == true) { PrincipleClassGroup.write("EndOfClass"); PrincipleClassGroup.newLine(); classWritten = false; } } destMethod.close(); PrincipleClassGroup.close(); readFileCount = readFileCount(); writeFileCount = writeFileCount(); methodCallFileCount = methodCallFileCount(); readArray = new String[readFileCount]; writeArray = new String[writeFileCount]; callArray = new String[methodCallFileCount]; initializeArrays(); constructFundamentalView(); constructInteractionView(); constructAssociationView(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public void deleteGroupInstruction(int id, int rank) throws FidoDatabaseException, InstructionNotFoundException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); String sql = "delete from InstructionGroups " + "where InstructionId = " + id + " and Rank = " + rank; stmt.executeUpdate(sql); bumpAllRowsUp(stmt, id, rank); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: private static void executeSQLScript() { File f = new File(System.getProperty("user.dir") + "/resources/umc.sql"); if (f.exists()) { Connection con = null; PreparedStatement pre_stmt = null; try { Class.forName("org.sqlite.JDBC"); con = DriverManager.getConnection("jdbc:sqlite:database/umc.db", "", ""); BufferedReader br = new BufferedReader(new FileReader(f)); String line = ""; con.setAutoCommit(false); while ((line = br.readLine()) != null) { if (!line.equals("") && !line.startsWith("--") && !line.contains("--")) { log.debug(line); pre_stmt = con.prepareStatement(line); pre_stmt.executeUpdate(); } } con.commit(); File dest = new File(f.getAbsolutePath() + ".executed"); if (dest.exists()) dest.delete(); f.renameTo(dest); f.delete(); } catch (Throwable exc) { log.error("Fehler bei Ausführung der SQL Datei", exc); try { con.rollback(); } catch (SQLException exc1) { } } finally { try { if (pre_stmt != null) pre_stmt.close(); if (con != null) con.close(); } catch (SQLException exc2) { log.error("Fehler bei Ausführung von SQL Datei", exc2); } } } }
00
Code Sample 1: public final String latestVersion() { String latestVersion = ""; try { URL url = new URL(Constants.officialSite + ":80/LatestVersion"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { latestVersion = str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } return latestVersion; } Code Sample 2: public void fillTableValues() { java.util.ArrayList cpool = newgen.presentation.NewGenMain.getAppletInstance().getCataloguingPool(); String xmlreq = AdministrationXMLGenerator.getInstance().getPoolChronologicalSubDivision("4", cpool); System.out.println(xmlreq); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SubDivisionServlet"); 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(); java.util.List onelist = rootelement.getChildren(); for (int i = 0; i < onelist.size(); i++) { Element rec = (Element) onelist.get(i); Object[] r = new Object[7]; String[] chronolib = new String[2]; chronolib[0] = rec.getChild("ChronologicalSubDivisionId").getText(); chronolib[1] = rec.getChild("LibraryId").getText(); this.chronoid_libid.add(chronolib); r[0] = rec.getChild("ChronologicalSubDivision").getText(); this.dtmSearch.addRow(r); } } catch (Exception e) { System.out.println(e); } }