label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: private 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 void process(Group group, List resourcesName, List excludeResources, ServletContext servletContext, Writer out, String location) throws IOException { LOG.debug("Merging content of group : " + group.getName()); for (Iterator iterator = group.getSubgroups().iterator(); iterator.hasNext(); ) { Group subGroup = (Group) iterator.next(); String subLocation = subGroup.getBestLocation(location); ResourcesProcessor subGroupProcessor = null; if (subGroup.isMinimize() == null) subGroupProcessor = this; else subGroupProcessor = subGroup.getJSProcessor(); subGroupProcessor.process(subGroup, subGroup.getJsNames(), excludeResources, servletContext, out, subLocation); } for (Iterator it = resourcesName.iterator(); it.hasNext(); ) { URL url = null; String path = (String) it.next(); if (!excludeResources.contains(path)) { url = URLUtils.getLocalURL(path, servletContext); if (url == null) { String webPath = URLUtils.concatUrlWithSlaches(group.getBestLocation(location), path); url = URLUtils.getWebUrlResource(webPath); } if (url == null) { throw new IOException("The resources '" + path + "' could not be found neither in the webapp folder nor in a jar"); } InputStream in = null; try { in = url.openStream(); IOUtils.copy(in, out, URLUtils.DEFAULT_ENCODING); out.write("\n\n"); } catch (Exception e) { LOG.error("Merge failed for file " + path, e); } finally { if (in != null) in.close(); } excludeResources.add(path); } } }
11
Code Sample 1: private InputStream open(String url) throws IOException { debug(url); if (!useCache) { return new URL(url).openStream(); } File f = new File(System.getProperty("java.io.tmpdir", "."), Digest.SHA1.encrypt(url) + ".xml"); debug("Cache : " + f); if (f.exists()) { return new FileInputStream(f); } InputStream in = new URL(url).openStream(); OutputStream out = new FileOutputStream(f); IOUtils.copyTo(in, out); out.flush(); out.close(); in.close(); return new FileInputStream(f); } 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"); }
00
Code Sample 1: public static String getStringFromAFileAtURL(String anURL) { String htmlCode = "<html><body></body></html>"; try { URL url = new URL(anURL); URLConnection urlConnection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine = ""; htmlCode = ""; while ((inputLine = in.readLine()) != null) htmlCode += inputLine + "\n"; in.close(); } catch (Exception e) { logs.info("URLResolver : lien mort"); JOptionPane.showMessageDialog(null, "lien mort"); return "<html><body></body></html>"; } return checkXMLTagsLowerCase(htmlCode); } Code Sample 2: public void sendMessageToServer(String msg, Map<String, String> args, StringCallback cb, URLConstructor ctor) { try { int tmpPort = port; for (; tmpPort < port + 10; tmpPort++) { Socket tmpSock; try { tmpSock = socketsManager.connect(new InetSocketAddress(host, port), 5000); tmpSock.close(); break; } catch (IOException e) { } } Map<String, String> newArgs = new HashMap<String, String>(args); newArgs.put("_f", String.valueOf(System.currentTimeMillis())); String request = ctor.constructURL(msg, newArgs); HttpClient client = new SimpleLimeHttpClient(); HttpGet get = new HttpGet("http://" + host + ":" + port + "/" + request); HttpProtocolParams.setVersion(client.getParams(), HttpVersion.HTTP_1_1); HttpResponse response = client.execute(get); String res = ""; if (response.getEntity() != null) { String result; if (response.getEntity() != null) { result = EntityUtils.toString(response.getEntity()); } else { result = null; } res = result; } cb.process(res); } catch (IOException e) { fail(e); } catch (HttpException e) { fail(e); } catch (URISyntaxException e) { fail(e); } catch (InterruptedException e) { fail(e); } }
00
Code Sample 1: public static String getDeclaredXMLEncoding(URL url) throws IOException { InputStream stream = url.openStream(); BufferedReader buffReader = new BufferedReader(new InputStreamReader(stream)); String firstLine = buffReader.readLine(); if (firstLine == null) { return SYSTEM_ENCODING; } int piStart = firstLine.indexOf("<?xml version=\"1.0\""); if (piStart != -1) { int attributeStart = firstLine.indexOf("encoding=\""); if (attributeStart >= 0) { int nextQuote = firstLine.indexOf('"', attributeStart + 10); if (nextQuote >= 0) { String encoding = firstLine.substring(attributeStart + 10, nextQuote); return encoding.trim(); } } } stream.close(); return SYSTEM_ENCODING; } Code Sample 2: protected Resolver queryResolver(String resolver, String command, String arg1, String arg2) { InputStream iStream = null; String RFC2483 = resolver + "?command=" + command + "&format=tr9401&uri=" + arg1 + "&uri2=" + arg2; String line = null; try { URL url = new URL(RFC2483); URLConnection urlCon = url.openConnection(); urlCon.setUseCaches(false); Resolver r = (Resolver) newCatalog(); String cType = urlCon.getContentType(); if (cType.indexOf(";") > 0) { cType = cType.substring(0, cType.indexOf(";")); } r.parseCatalog(cType, urlCon.getInputStream()); return r; } catch (CatalogException cex) { if (cex.getExceptionType() == CatalogException.UNPARSEABLE) { catalogManager.debug.message(1, "Unparseable catalog: " + RFC2483); } else if (cex.getExceptionType() == CatalogException.UNKNOWN_FORMAT) { catalogManager.debug.message(1, "Unknown catalog format: " + RFC2483); } return null; } catch (MalformedURLException mue) { catalogManager.debug.message(1, "Malformed resolver URL: " + RFC2483); return null; } catch (IOException ie) { catalogManager.debug.message(1, "I/O Exception opening resolver: " + RFC2483); return null; } }
11
Code Sample 1: private void loadNumberFormats() { String fileToLocate = "/" + FILENAME_NUMBER_FMT; URL url = getClass().getClassLoader().getResource(fileToLocate); if (url == null) { return; } List<String> lines; try { lines = IOUtils.readLines(url.openStream()); } catch (IOException e) { throw new ConfigurationException("Problem loading file " + fileToLocate, e); } for (String line : lines) { if (line.startsWith("#") || StringUtils.isBlank(line)) { continue; } String[] parts = StringUtils.split(line, "="); addFormat(parts[0], new DecimalFormat(parts[1])); } } Code Sample 2: 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(); }
00
Code Sample 1: public static String hashString(String sPassword) { if (sPassword == null || sPassword.equals("")) { return "empty:"; } else { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(sPassword.getBytes("UTF-8")); byte[] res = md.digest(); return "sha1:" + StringUtils.byte2hex(res); } catch (NoSuchAlgorithmException e) { return "plain:" + sPassword; } catch (UnsupportedEncodingException e) { return "plain:" + sPassword; } } } Code Sample 2: private FileInputStream getPackageStream(String archivePath) throws IOException, PackageManagerException { final int lastSlashInName = filename.lastIndexOf("/"); final String newFileName = filename.substring(lastSlashInName); File packageFile = new File((new StringBuilder()).append(archivePath).append(newFileName).toString()); if (null != packageFile) return new FileInputStream(packageFile); if (null != packageURL) { final InputStream urlStream = new ConnectToServer(null).getInputStream(packageURL); packageFile = new File((new StringBuilder()).append(getName()).append(".deb").toString()); final OutputStream fileStream = new FileOutputStream(packageFile); final byte buffer[] = new byte[10240]; for (int read = 0; (read = urlStream.read(buffer)) > 0; ) fileStream.write(buffer, 0, read); urlStream.close(); fileStream.close(); return new FileInputStream(packageFile); } else { final String errorMessage = PreferenceStoreHolder.getPreferenceStoreByName("Screen").getPreferenceAsString("package.getPackageStream.packageURLIsNull", "No entry found for package.getPackageStream.packageURLIsNull"); if (pm != null) { pm.addWarning(errorMessage); logger.error(errorMessage); } else logger.error(errorMessage); throw new FileNotFoundException(); } }
11
Code Sample 1: public void transform(File inputMatrixFile, MatrixIO.Format inputFormat, File outputMatrixFile) throws IOException { FileChannel original = new FileInputStream(inputMatrixFile).getChannel(); FileChannel copy = new FileOutputStream(outputMatrixFile).getChannel(); copy.transferFrom(original, 0, original.size()); original.close(); copy.close(); } Code Sample 2: private void writeFile(FileInputStream inFile, FileOutputStream outFile) throws IOException { byte[] buf = new byte[2048]; int read; while ((read = inFile.read(buf)) > 0 && !stopped) outFile.write(buf, 0, read); inFile.close(); }
11
Code Sample 1: public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { size = outputFile.length(); if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(outputFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } } } 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: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: private static void 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!"); }
00
Code Sample 1: public static void copy(File _from, File _to) throws IOException { if (_from == null || !_from.exists()) return; FileOutputStream out = null; FileInputStream in = null; try { out = new FileOutputStream(_to); in = new FileInputStream(_from); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } } catch (IOException _e) { throw _e; } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public MapInfo getMap(double latitude, double longitude, double wanted_mapblast_scale, int image_width, int image_height, String file_path_wo_extension, ProgressListener progress_listener) throws IOException { try { if (web_request_ == null) { web_request_ = new HttpRequester(HOST_NAME); } int zoom_index = getZoomLevelIndex(wanted_mapblast_scale); int google_zoom_level = GOOGLE_ZOOM_LEVELS[zoom_index]; double mapblast_scale = POSSIBLE_GOOGLE_SCALES[zoom_index]; Tile tile = new Tile(latitude, longitude, google_zoom_level); SimplePoint coords = tile.getTileLatLong(); SimplePoint google_xy = tile.getTileCoord(); MapInfo map_info = new MapInfo(); map_info.setLatitude(coords.getX()); map_info.setLongitude(coords.getY()); map_info.setScale((float) mapblast_scale); map_info.setWidth(256); map_info.setHeight(256); map_info.setFilename(file_path_wo_extension + "png"); Object[] params = new Object[] { new Integer(google_xy.getX()), new Integer(google_xy.getY()), new Integer(google_zoom_level) }; MessageFormat message_format = new MessageFormat(GOOGLE_MAPS_URL, Locale.US); String url_string = message_format.format(params); URL url = new URL(url_string); if (Debug.DEBUG) Debug.println("map_download", "loading map from url: " + url); URLConnection connection = url.openConnection(); if (resources_.getBoolean(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_USE)) { String proxy_userid = resources_.getString(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_USERNAME); String proxy_password = resources_.getString(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_PASSWORD); String auth_string = proxy_userid + ":" + proxy_password; auth_string = "Basic " + new sun.misc.BASE64Encoder().encode(auth_string.getBytes()); connection.setRequestProperty("Proxy-Authorization", auth_string); } connection.connect(); String mime_type = connection.getContentType().toLowerCase(); if (!mime_type.startsWith("image")) { if (mime_type.startsWith("text")) { HTMLViewerFrame viewer = new HTMLViewerFrame(url); viewer.setSize(640, 480); viewer.setTitle("ERROR on loading url: " + url); viewer.setVisible(true); throw new IOException("Invalid mime type (expected 'image/*'): received " + mime_type + "\nPage is displayed in HTML frame."); } throw new IOException("Invalid mime type (expected 'image/*'): received " + mime_type); } int content_length = connection.getContentLength(); if (content_length < 0) progress_listener.actionStart(PROGRESS_LISTENER_ID, 0, Integer.MIN_VALUE); else progress_listener.actionStart(PROGRESS_LISTENER_ID, 0, content_length); String extension = mime_type.substring(mime_type.indexOf('/') + 1); String filename = file_path_wo_extension + extension; FileOutputStream out = new FileOutputStream(filename); byte[] buffer = new byte[BUFFER_SIZE]; BufferedInputStream in = new BufferedInputStream(connection.getInputStream(), BUFFER_SIZE); int sum_bytes = 0; int num_bytes = 0; while ((num_bytes = in.read(buffer)) != -1) { out.write(buffer, 0, num_bytes); sum_bytes += num_bytes; progress_listener.actionProgress(PROGRESS_LISTENER_ID, sum_bytes); } progress_listener.actionEnd(PROGRESS_LISTENER_ID); in.close(); out.close(); return (map_info); } catch (NoRouteToHostException nrhe) { nrhe.printStackTrace(); progress_listener.actionEnd(PROGRESS_LISTENER_ID); String message = nrhe.getMessage() + ":\n" + resources_.getString(DownloadMouseModeLayer.KEY_LOCALIZE_MESSAGE_DOWNLOAD_ERROR_NO_ROUTE_TO_HOST_MESSAGE); throw new IOException(message); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); progress_listener.actionEnd(PROGRESS_LISTENER_ID); String message = fnfe.getMessage() + ":\n" + resources_.getString(DownloadMouseModeLayer.KEY_LOCALIZE_MESSAGE_DOWNLOAD_ERROR_FILE_NOT_FOUND_MESSAGE); throw new IOException(message); } catch (Exception e) { progress_listener.actionEnd(PROGRESS_LISTENER_ID); e.printStackTrace(); String message = e.getMessage(); if (message == null) { Throwable cause = e.getCause(); if (cause != null) message = cause.getMessage(); } throw new IOException(message); } }
00
Code Sample 1: public Image storeImage(String title, String pathToImage, Map<String, Object> additionalProperties) { File collectionFolder = ProjectManager.getInstance().getFolder(PropertyHandler.getInstance().getProperty("_default_collection_name")); File imageFile = new File(pathToImage); String filename = ""; String format = ""; File copiedImageFile; while (true) { filename = "image" + UUID.randomUUID().hashCode(); if (!DbEntryProvider.INSTANCE.idExists(filename)) { Path path = new Path(pathToImage); format = path.getFileExtension(); copiedImageFile = new File(collectionFolder.getAbsolutePath() + File.separator + filename + "." + format); if (!copiedImageFile.exists()) break; } } try { copiedImageFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); return null; } BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(imageFile), 4096); out = new BufferedOutputStream(new FileOutputStream(copiedImageFile), 4096); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } Image image = new ImageImpl(); image.setId(filename); image.setFormat(format); image.setEntryDate(new Date()); image.setTitle(title); image.setAdditionalProperties(additionalProperties); boolean success = DbEntryProvider.INSTANCE.storeNewImage(image); if (success) return image; return null; } Code Sample 2: public void connectToUrl(String url_address) { message = new StringBuffer(""); try { URL url = new URL(url_address); try { HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(); httpsConnection.setDoOutput(false); httpsConnection.connect(); message.append("<BR>\n Connection Code:[" + httpsConnection.getResponseCode() + "]"); message.append("<BR>\n Response Message:[" + httpsConnection.getResponseMessage() + "]"); InputStreamReader insr = new InputStreamReader(httpsConnection.getInputStream()); BufferedReader in = new BufferedReader(insr); fullStringBuffer = new StringBuffer(""); String temp = in.readLine(); while (temp != null) { fullStringBuffer.append(temp); temp = in.readLine(); } in.close(); } catch (IOException e) { message.append("<BR>\n [Error][IOException][" + e.getMessage() + "]"); } } catch (MalformedURLException e) { message.append("<BR>\n [Error][MalformedURLException][" + e.getMessage() + "]"); } catch (Exception e) { message.append("<BR>\n [Error][Exception][" + e.getMessage() + "]"); } }
11
Code Sample 1: public static String getSHA1Digest(String inputStr) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; byte[] sha1hash = null; md = MessageDigest.getInstance("SHA"); sha1hash = new byte[40]; md.update(inputStr.getBytes("iso-8859-1"), 0, inputStr.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: public static String getHash(String userName, String pass) { String hash = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(userName.getBytes()); hash = ISOUtil.hexString(md.digest(pass.getBytes())).toLowerCase(); } catch (NoSuchAlgorithmException e) { } return hash; }
11
Code Sample 1: 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()); } Code Sample 2: public static void main(String[] args) throws IOException { String uri = "hdfs://localhost:8020/user/leeing/maxtemp/sample.txt"; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); FSDataInputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 8192, false); System.out.println("\n"); in.seek(0); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); } }
00
Code Sample 1: public boolean loadURL(URL url) { try { propertyBundle.load(url.openStream()); LOG.info("Configuration loaded from " + url + "\n"); return true; } catch (Exception e) { if (canComplain) { LOG.warn("Unable to load configuration " + url + "\n"); } canComplain = false; return false; } } Code Sample 2: @Override public void run() { if (mMode == 0) { long currentVersion = Version.extractVersion(App.getVersion()); if (currentVersion == 0) { mMode = 2; RESULT = MSG_UP_TO_DATE; return; } long versionAvailable = currentVersion; mMode = 2; try { StringBuilder buffer = new StringBuilder(mCheckURL); try { NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()); if (!ni.isLoopback()) { if (ni.isUp()) { if (!ni.isVirtual()) { buffer.append('?'); byte[] macAddress = ni.getHardwareAddress(); for (byte one : macAddress) { buffer.append(Integer.toHexString(one >>> 4 & 0xF)); buffer.append(Integer.toHexString(one & 0xF)); } } } } } catch (Exception exception) { } URL url = new URL(buffer.toString()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); while (line != null) { StringTokenizer tokenizer = new StringTokenizer(line, "\t"); if (tokenizer.hasMoreTokens()) { try { if (tokenizer.nextToken().equalsIgnoreCase(mProductKey)) { String token = tokenizer.nextToken(); long version = Version.extractVersion(token); if (version > versionAvailable) { versionAvailable = version; } } } catch (Exception exception) { } } line = in.readLine(); } } catch (Exception exception) { } if (versionAvailable > currentVersion) { Preferences prefs = Preferences.getInstance(); String humanReadableVersion = Version.getHumanReadableVersion(versionAvailable); NEW_VERSION_AVAILABLE = true; RESULT = MessageFormat.format(MSG_OUT_OF_DATE, humanReadableVersion); if (versionAvailable > Version.extractVersion(prefs.getStringValue(MODULE, LAST_VERSION_KEY, App.getVersion()))) { prefs.setValue(MODULE, LAST_VERSION_KEY, humanReadableVersion); prefs.save(); mMode = 1; EventQueue.invokeLater(this); return; } } else { RESULT = MSG_UP_TO_DATE; } } else if (mMode == 1) { if (App.isNotificationAllowed()) { String result = getResult(); mMode = 2; if (WindowUtils.showConfirmDialog(null, result, MSG_UPDATE_TITLE, JOptionPane.OK_CANCEL_OPTION, new String[] { MSG_UPDATE_TITLE, MSG_IGNORE_TITLE }, MSG_UPDATE_TITLE) == JOptionPane.OK_OPTION) { goToUpdate(); } } else { DelayedTask.schedule(this, 250); } } }
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 File copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); copyChannel(inChannel, outChannel); return out; }
00
Code Sample 1: protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String realUrl = "http:/" + request.getPathInfo(); if (request.getQueryString() != null) { realUrl += "?" + request.getQueryString(); } URL url = new URL(realUrl); URLConnection connection = url.openConnection(); HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); } boolean hasContent = false; Enumeration headers = request.getHeaderNames(); while (headers.hasMoreElements()) { String header = (String) headers.nextElement(); if ("content-type".equals(header.toLowerCase())) hasContent = true; Enumeration values = request.getHeaders(header); while (values.hasMoreElements()) { String value = (String) values.nextElement(); if (value != null) { connection.addRequestProperty(header, value); } } } try { connection.setDoInput(true); if (hasContent) { InputStream proxyRequest = request.getInputStream(); connection.setDoOutput(true); IO.copy(proxyRequest, connection.getOutputStream()); } connection.connect(); } catch (Exception e) { context.log("proxy", e); } InputStream proxyResponse = null; int code = 500; if (http != null) { proxyResponse = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code); } if (proxyResponse == null) { try { proxyResponse = connection.getInputStream(); } catch (Exception e) { if (http != null) proxyResponse = http.getErrorStream(); context.log("stream", e); } } int i = 0; String header = connection.getHeaderFieldKey(i); String value = connection.getHeaderField(i); while (header != null || value != null) { if (header != null && value != null) { response.addHeader(header, value); } ++i; header = connection.getHeaderFieldKey(i); value = connection.getHeaderField(i); } if (proxyResponse != null) { IO.copy(proxyResponse, response.getOutputStream()); } } Code Sample 2: private long config(final String options) throws SQLException { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } msgDigest.update(options.getBytes()); final String md5sum = Concrete.md5(msgDigest.digest()); Statement stmt = connection.createStatement(); ResultSet rst = stmt.executeQuery("SELECT configId FROM configs WHERE md5='" + md5sum + "'"); final long configId; if (rst.next()) { configId = rst.getInt(1); } else { stmt.executeUpdate("INSERT INTO configs(config, md5) VALUES ('" + options + "', '" + md5sum + "')"); ResultSet aiRst = stmt.getGeneratedKeys(); if (aiRst.next()) { configId = aiRst.getInt(1); } else { throw new SQLException("Could not retrieve generated id"); } } stmt.executeUpdate("UPDATE executions SET configId=" + configId + " WHERE executionId=" + executionId); return configId; }
11
Code Sample 1: public static void copyFile(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(); } } Code Sample 2: public static void copy(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
00
Code Sample 1: private static void readIzvestiyaArticles() throws IOException { CsvReader reader = new CsvReader(new InputStreamReader(IzvestiyaUtil.class.getClassLoader().getResourceAsStream("mathnet_izvestiya.csv")), ';'); reader.setTrimWhitespace(true); try { while (reader.readRecord()) { String id = reader.get(0); String filename = reader.get(1); StringTokenizer st = new StringTokenizer(filename, "-."); String name = st.nextToken(); String volume = st.nextToken(); String year = st.nextToken(); String extension = st.nextToken(); String filepath = String.format("%s/%s/%s-%s.%s", year, volume.length() == 1 ? "0" + volume : volume, name, volume, extension); id2filename.put(id, filepath); } } finally { reader.close(); } for (Map.Entry<String, String> entry : id2filename.entrySet()) { String filepath = String.format("%s/%s", INPUT_DIR, entry.getValue()); filepath = new File(filepath).exists() ? filepath : filepath.replace(".tex", ".TEX"); if (new File(filepath).exists()) { InputStream in = new FileInputStream(filepath); FileOutputStream out = new FileOutputStream(String.format("%s/%s.tex", OUTPUT_DIR, entry.getKey()), false); try { org.apache.commons.io.IOUtils.copy(in, out); } catch (Exception e) { org.apache.commons.io.IOUtils.closeQuietly(in); org.apache.commons.io.IOUtils.closeQuietly(out); } } else { logger.log(Level.INFO, "File with the path=" + filepath + " doesn't exist"); } } } Code Sample 2: public static String getUrl(String url) { BufferedInputStream in = null; BufferedOutputStream out = null; try { ByteArrayOutputStream bytearray = new ByteArrayOutputStream(); in = new BufferedInputStream(new URL(url).openStream()); out = new BufferedOutputStream(bytearray, 1024); byte[] data = new byte[1024]; int x = 0; while ((x = in.read(data, 0, 1024)) >= 0) { out.write(data, 0, x); } return bytearray.toString(); } catch (Exception e) { throw new CVardbException(e); } finally { try { if (out != null) out.close(); if (in != null) in.close(); } catch (Exception e) { } } }
00
Code Sample 1: public static String hashSHA1(String value) { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(value.getBytes()); BigInteger hash = new BigInteger(1, digest.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException e) { } return null; } Code Sample 2: public void test() throws Exception { File temp = File.createTempFile("test", ".test"); temp.deleteOnExit(); StorageFile s = new StorageFile(temp, "UTF-8"); s.addText("Test"); s.getOutputStream().write("ing is important".getBytes("UTF-8")); s.getWriter().write(" but overrated"); assertEquals("Testing is important but overrated", s.getText()); s.close(ResponseStateOk.getInstance()); assertEquals("Testing is important but overrated", s.getText()); InputStream input = s.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer, "UTF-8"); assertEquals("Testing is important but overrated", writer.toString()); try { s.getOutputStream(); fail("Should thow an IOException as it is closed."); } catch (IOException e) { } }
11
Code Sample 1: public void testStorageString() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); r.addText("This is an example"); r.addText(" and another one."); assertEquals("This is an example and another one.", r.getText()); InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); try { r.getOutputStream(); fail("Once addText() is used the text is stored as a String and you cannot use getOutputStream anymore"); } catch (IOException e) { } try { r.getWriter(); fail("Once addText() is used the text is stored as a String and you cannot use getOutputStream anymore"); } catch (IOException e) { } r.setEndState(ResponseStateOk.getInstance()); assertTrue(r.hasEnded()); } Code Sample 2: public void notifyTerminated(Writer r) { all_writers.remove(r); if (all_writers.isEmpty()) { all_terminated = true; Iterator iterator = open_files.iterator(); while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); do { try { fc.stream.flush(); fc.stream.close(); } catch (IOException e) { } fc = fc.next; } while (fc != null); } iterator = open_files.iterator(); boolean all_ok = true; while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); logger.logComment("File chunk <" + fc.name + "> " + fc.start_byte + " " + fc.position + " " + fc.actual_file); boolean ok = true; while (fc.next != null) { ok = ok && (fc.start_byte + fc.actual_file.length()) == fc.next.start_byte; fc = fc.next; } if (ok) { logger.logComment("Received file <" + fc.name + "> is contiguous (and hopefully complete)"); } else { logger.logError("Received file <" + fc.name + "> is NOT contiguous"); all_ok = false; } } if (all_ok) { byte[] buffer = new byte[16384]; iterator = open_files.iterator(); while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); try { if (fc.next != null) { FileOutputStream fos = new FileOutputStream(fc.actual_file, true); fc = fc.next; while (fc != null) { FileInputStream fis = new FileInputStream(fc.actual_file); int actually_read = fis.read(buffer); while (actually_read != -1) { fos.write(buffer, 0, actually_read); actually_read = fis.read(buffer); } fc.actual_file.delete(); fc = fc.next; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } fte.allWritersTerminated(); fte = null; } }
00
Code Sample 1: private boolean copyToFile(String folder, String fileName) throws StorageException { InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(folder + "/" + fileName); if (in == null) { return false; } FileOutputStream out = null; try { out = new FileOutputStream(new File(path, fileName)); IOUtils.copy(in, out); in.close(); out.flush(); } catch (Exception e) { throw new StorageException(e); } finally { if (in != null) { IOUtils.closeQuietly(in); } if (out != null) { IOUtils.closeQuietly(out); } } return true; } Code Sample 2: String fetch_m3u(String m3u) { InputStream pstream = null; if (m3u.startsWith("http://")) { try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), m3u); else url = new URL(m3u); URLConnection urlc = url.openConnection(); pstream = urlc.getInputStream(); } catch (Exception ee) { System.err.println(ee); return null; } } if (pstream == null && !running_as_applet) { try { pstream = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + m3u); } catch (Exception ee) { System.err.println(ee); return null; } } String line = null; while (true) { try { line = readline(pstream); } catch (Exception e) { } if (line == null) break; return line; } return null; }
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.InputStream(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 AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException { InputStream urlStream = url.openStream(); AudioFileFormat fileFormat = null; try { fileFormat = getFMT(urlStream, false); } finally { urlStream.close(); } return fileFormat; }
11
Code Sample 1: protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/zip"); response.setHeader("Content-Disposition", "inline; filename=c:/server1.zip"); try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("server.zip"); ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[BUFFER]; java.util.Properties props = new java.util.Properties(); props.load(new java.io.FileInputStream(ejb.bprocess.util.NewGenLibRoot.getRoot() + "/SystemFiles/ENV_VAR.txt")); String jbossHomePath = props.getProperty("JBOSS_HOME"); jbossHomePath = jbossHomePath.replaceAll("deploy", "log"); FileInputStream fis = new FileInputStream(new File(jbossHomePath + "/server.log")); origin = new BufferedInputStream(fis, BUFFER); ZipEntry entry = new ZipEntry(jbossHomePath + "/server.log"); zipOut.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { zipOut.write(data, 0, count); } origin.close(); zipOut.closeEntry(); java.io.FileInputStream fis1 = new java.io.FileInputStream(new java.io.File("server.zip")); java.nio.channels.FileChannel fc1 = fis1.getChannel(); int length1 = (int) fc1.size(); byte buffer[] = new byte[length1]; System.out.println("size of zip file = " + length1); fis1.read(buffer); OutputStream out1 = response.getOutputStream(); out1.write(buffer); fis1.close(); out1.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private void copy(File srouceFile, File destinationFile) throws IOException { FileChannel sourceChannel = new FileInputStream(srouceFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
00
Code Sample 1: public static void copy(final File source, final File dest) throws IOException { FileChannel in = null; FileChannel 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); dest.setLastModified(source.lastModified()); } finally { close(in); close(out); } } Code Sample 2: private String doOAIQuery(String request) throws IOException, ProtocolException { DannoClient ac = getClient(); HttpGet get = new HttpGet(request); get.setHeader("Accept", "application/xml"); HttpResponse response = ac.execute(get); if (!ac.isOK()) { throw new DannoRequestFailureException("GET", response); } return massage(new BasicResponseHandler().handleResponse(response)); }
11
Code Sample 1: public String loadURLString(java.net.URL url) { try { BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String s = ""; while (br.ready() && s != null) { s = br.readLine(); if (s != null) { buf.append(s); buf.append("\n"); } } return buf.toString(); } catch (IOException ex) { return ""; } catch (NullPointerException npe) { return ""; } } Code Sample 2: protected BufferedReader getDataReader() { BufferedReader in = null; PrintWriter out = null; try { String line; URL url = new URL(this.catalog.getCatalogURL()); Debug.output("Catalog URL:" + url.toString()); in = new BufferedReader(new InputStreamReader(url.openStream())); File dir = (File) SessionHandler.getServletContext().getAttribute("javax.servlet.context.tempdir"); File temp = new File(dir, TEMP); Debug.output("Temp file:" + temp.toString()); out = new PrintWriter(new BufferedWriter(new FileWriter(temp))); while ((line = in.readLine()) != null) { out.println(line); } Debug.output("Temp file size:" + temp.length()); return new BufferedReader(new FileReader(temp)); } catch (IOException e) { throw new SeismoException(e); } finally { Util.close(in); Util.close(out); } }
11
Code Sample 1: public DialogSongList(JFrame frame) { super(frame, "Menu_SongList", "songList"); setMinimumSize(new Dimension(400, 200)); JPanel panel, spanel; Container contentPane; (contentPane = getContentPane()).add(songSelector = new SongSelector(configKey, null, true)); songSelector.setSelectionAction(new Runnable() { public void run() { final Item<URL, MidiFileInfo> item = songSelector.getSelectedInfo(); if (item != null) { try { selection = new File(item.getKey().toURI()); author.setEnabled(true); title.setEnabled(true); difficulty.setEnabled(true); save.setEnabled(true); final MidiFileInfo info = item.getValue(); author.setText(info.getAuthor()); title.setText(info.getTitle()); Util.selectKey(difficulty, info.getDifficulty()); return; } catch (Exception e) { } } selection = null; author.setEnabled(false); title.setEnabled(false); difficulty.setEnabled(false); save.setEnabled(false); } }); contentPane.add(panel = new JPanel(), BorderLayout.SOUTH); panel.setLayout(new BorderLayout()); JScrollPane scrollPane; panel.add(scrollPane = new JScrollPane(spanel = new JPanel()), BorderLayout.NORTH); scrollPane.setPreferredSize(new Dimension(0, 60)); Util.addLabeledComponent(spanel, "Lbl_Author", author = new JTextField(10)); Util.addLabeledComponent(spanel, "Lbl_Title", title = new JTextField(14)); Util.addLabeledComponent(spanel, "Lbl_Difficulty", difficulty = new JComboBox()); difficulty.addItem(new Item<Byte, String>((byte) -1, "")); for (Map.Entry<Byte, String> entry : SongSelector.DIFFICULTIES.entrySet()) { final String value = entry.getValue(); difficulty.addItem(new Item<Byte, String>(entry.getKey(), Util.getMsg(value, value), value)); } spanel.add(save = new JButton()); Util.updateButtonText(save, "Save"); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final File selected = MidiSong.setMidiFileInfo(selection, author.getText(), title.getText(), getAsByte(difficulty)); SongSelector.refresh(); try { songSelector.setSelected(selected == null ? null : selected.toURI().toURL()); } catch (MalformedURLException ex) { } } }); author.setEnabled(false); title.setEnabled(false); difficulty.setEnabled(false); save.setEnabled(false); JButton button; panel.add(spanel = new JPanel(), BorderLayout.WEST); spanel.add(button = new JButton()); Util.updateButtonText(button, "Import"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final File inputFile = KeyboardHero.midiFile(); try { if (inputFile == null) return; final File dir = (new File(Util.DATA_FOLDER + MidiSong.MIDI_FILES_DIR)); if (dir.exists()) { if (!dir.isDirectory()) { Util.error(Util.getMsg("Err_MidiFilesDirNotDirectory"), dir.getParent()); return; } } else if (!dir.mkdirs()) { Util.error(Util.getMsg("Err_CouldntMkDir"), dir.getParent()); return; } File outputFile = new File(dir.getPath() + File.separator + inputFile.getName()); if (!outputFile.exists() || KeyboardHero.confirm("Que_FileExistsOverwrite")) { final FileChannel inChannel = new FileInputStream(inputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), new FileOutputStream(outputFile).getChannel()); } } catch (Exception ex) { Util.getMsg(Util.getMsg("Err_CouldntImportSong"), ex.toString()); } SongSelector.refresh(); } }); spanel.add(button = new JButton()); Util.updateButtonText(button, "Delete"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (KeyboardHero.confirm(Util.getMsg("Que_SureToDelete"))) { try { new File(songSelector.getSelectedFile().toURI()).delete(); } catch (Exception ex) { Util.error(Util.getMsg("Err_CouldntDeleteFile"), ex.toString()); } SongSelector.refresh(); } } }); panel.add(spanel = new JPanel(), BorderLayout.CENTER); spanel.setLayout(new FlowLayout()); spanel.add(button = new JButton()); Util.updateButtonText(button, "Close"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { close(); } }); spanel.add(button = new JButton()); Util.updateButtonText(button, "Play"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Game.newGame(songSelector.getSelectedFile()); close(); } }); panel.add(spanel = new JPanel(), BorderLayout.EAST); spanel.add(button = new JButton()); Util.updateButtonText(button, "Refresh"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SongSelector.refresh(); } }); getRootPane().setDefaultButton(button); instance = this; } Code Sample 2: private String createDefaultRepoConf() throws IOException { InputStream confIn = getClass().getResourceAsStream(REPO_CONF_PATH); File tempConfFile = File.createTempFile("repository", "xml"); tempConfFile.deleteOnExit(); IOUtils.copy(confIn, new FileOutputStream(tempConfFile)); return tempConfFile.getAbsolutePath(); }
00
Code Sample 1: public static String rename_tag(String sessionid, String originalTag, String newTagName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_tag"); 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", "rename_tag")); nameValuePairs.add(new BasicNameValuePair("new_tag_name", newTagName)); nameValuePairs.add(new BasicNameValuePair("absolute_tag", originalTag)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; } Code Sample 2: public static String read(URL url) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringWriter res = new StringWriter(); PrintWriter writer = new PrintWriter(new BufferedWriter(res)); String line; while ((line = reader.readLine()) != null) { writer.println(line); } reader.close(); writer.close(); return res.toString(); }
11
Code Sample 1: public static String md5Encode(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes()); return toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return s; } } Code Sample 2: public static Properties addAttributes(Node node, String[] names, Properties props, LogEvent evt) throws ConfigurationException { if (props == null) props = new Properties(); try { MessageDigest md = MessageDigest.getInstance("MD5"); for (int i = 0; i < names.length; i++) { String value = addProperty(names[i], props, node, evt); if (value != null) { md.update(names[i].getBytes()); md.update(value.getBytes()); } } byte[] digest = md.digest(); evt.addMessage("digest " + ISOUtil.hexString(digest)); props.put(DIGEST_PROPERTY, digest); } catch (NoSuchAlgorithmException e) { throw new ConfigurationException(e); } return props; }
00
Code Sample 1: public final InputSource getInputSource() { if (url == null) throw new RuntimeException("Cannot find table defs"); try { InputStream stream = url.openStream(); InputStreamReader reader = new InputStreamReader(stream); return new InputSource(reader); } catch (IOException e) { throw new RuntimeException(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]; int readBytes; while ((readBytes = fis.read(b)) > 0) fos.write(b, 0, readBytes); fis.close(); fos.close(); }
11
Code Sample 1: @Override public void objectToEntry(String object, TupleOutput output) { byte array[] = object.getBytes(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream out = new GZIPOutputStream(baos); ByteArrayInputStream in = new ByteArrayInputStream(array); IOUtils.copyTo(in, out); in.close(); out.close(); byte array2[] = baos.toByteArray(); if (array2.length + 4 < array.length) { output.writeBoolean(true); output.writeInt(array2.length); output.write(array2); } else { output.writeBoolean(false); output.writeString(object); } } catch (IOException err) { throw new RuntimeException(err); } } 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; }
00
Code Sample 1: private void loadFile(File file) throws Exception { Edl edl = new Edl("file:///" + file.getAbsolutePath()); URL url = ExtractaHelper.retrieveUrl(edl.getUrlRetrievalDescriptor()); String sUrlString = url.toExternalForm(); if (sUrlString.startsWith("file:/") && (sUrlString.charAt(6) != '/')) { sUrlString = sUrlString.substring(0, 6) + "//" + sUrlString.substring(6); } Document document = DomHelper.parseHtml(url.openStream()); m_inputPanel.setDocument(document); m_resultPanel.setContext(new ResultContext(edl, document, url)); initNameCounters(edl.getItemDescriptors()); m_outputFile = file; m_sUrlString = sUrlString; m_urlTF.setText(m_sUrlString); updateHistroy(m_outputFile); setModified(false); } Code Sample 2: private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { jButton1.setEnabled(false); for (int i = 0; i < max; i++) { Card crd = WLP.getSelectedCard(WLP.jTable1.getSelectedRows()[i]); String s, s2; s = ""; s2 = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + crd.getWord()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("popWin\\('/cgi-bin/(.+?)'", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); if (matcher.find()) { String newurl = "http://m-w.com/cgi-bin/" + matcher.group(1); try { URL url2 = new URL(newurl); BufferedReader in2 = new BufferedReader(new InputStreamReader(url2.openStream())); String str; while ((str = in2.readLine()) != null) { s2 = s2 + str; } in2.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern2 = Pattern.compile("<A HREF=\"http://(.+?)\">Click here to listen with your default audio player", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher2 = pattern2.matcher(s2); if (matcher2.find()) { getWave("http://" + matcher2.group(1), crd.getWord()); } int val = jProgressBar1.getValue(); val++; jProgressBar1.setValue(val); this.paintAll(this.getGraphics()); } } jButton1.setEnabled(true); }
00
Code Sample 1: public static void uncompress(File srcFile, File destFile) throws IOException { InputStream input = null; OutputStream output = null; try { input = new GZIPInputStream(new FileInputStream(srcFile)); output = new BufferedOutputStream(new FileOutputStream(destFile)); IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } } Code Sample 2: public static String md5(String str) { StringBuffer buf = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] data = new byte[32]; md.update(str.getBytes(md5Encoding), 0, str.length()); data = md.digest(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } } catch (Exception e) { errorLog("{Malgn.md5} " + e.getMessage()); } return buf.toString(); }
00
Code Sample 1: public static Pedido insert(Pedido objPedido) { final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; int result; if (c == null) { return null; } try { c.setAutoCommit(false); String sql = ""; int idPedido; idPedido = PedidoDAO.getLastCodigo(); if (idPedido < 1) { return null; } sql = "insert into pedido " + "(id_pedido, id_funcionario,data_pedido,valor) " + "values(?,?,now(),truncate(?,2))"; pst = c.prepareStatement(sql); pst.setInt(1, idPedido); pst.setInt(2, objPedido.getFuncionario().getCodigo()); pst.setString(3, new DecimalFormat("#0.00").format(objPedido.getValor())); result = pst.executeUpdate(); pst = null; if (result > 0) { Iterator<ItemPedido> itItemPedido = (objPedido.getItemPedido()).iterator(); while ((itItemPedido != null) && (itItemPedido.hasNext())) { ItemPedido objItemPedido = (ItemPedido) itItemPedido.next(); sql = ""; sql = "insert into item_pedido " + "(id_pedido,id_produto,quantidade,subtotal) " + "values (?,?,?,truncate(?,2))"; pst = c.prepareStatement(sql); pst.setInt(1, idPedido); pst.setInt(2, (objItemPedido.getProduto()).getCodigo()); pst.setInt(3, objItemPedido.getQuantidade()); pst.setString(4, new DecimalFormat("#0.00").format(objItemPedido.getSubtotal())); result = pst.executeUpdate(); } } pst = null; sql = ""; sql = "insert into pedido_situacao " + "(id_pedido,id_situacao, em, observacao, id_funcionario) " + "values (?,?,now(), ?, ?)"; pst = c.prepareStatement(sql); pst.setInt(1, idPedido); pst.setInt(2, 1); pst.setString(3, "Inclus�o de pedido"); pst.setInt(4, objPedido.getFuncionario().getCodigo()); result = pst.executeUpdate(); pst = null; sql = ""; sql = "insert into tramitacao " + "(data_tramitacao, id_pedido, id_dep_origem, id_dep_destino) " + "values (now(),?,?, ?)"; pst = c.prepareStatement(sql); pst.setInt(1, idPedido); pst.setInt(2, 6); pst.setInt(3, 2); result = pst.executeUpdate(); c.commit(); objPedido.setCodigo(idPedido); } catch (final Exception e) { try { c.rollback(); } catch (final Exception e1) { System.out.println("[PedidoDAO.insert] Erro ao inserir -> " + e1.getMessage()); } System.out.println("[PedidoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } return objPedido; } Code Sample 2: 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.InputStream(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; }
11
Code Sample 1: public static InputSource getInputSource(URL url) throws IOException { String proto = url.getProtocol().toLowerCase(); if (!("http".equals(proto) || "https".equals(proto))) throw new IllegalArgumentException("OAI-PMH only allows HTTP(S) as network protocol!"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); StringBuilder ua = new StringBuilder("Java/"); ua.append(System.getProperty("java.version")); ua.append(" ("); ua.append(OAIHarvester.class.getName()); ua.append(')'); conn.setRequestProperty("User-Agent", ua.toString()); conn.setRequestProperty("Accept-Encoding", "gzip, deflate, identity;q=0.3, *;q=0"); conn.setRequestProperty("Accept-Charset", "utf-8, *;q=0.1"); conn.setRequestProperty("Accept", "text/xml, application/xml, *;q=0.1"); conn.setUseCaches(false); conn.setFollowRedirects(true); log.debug("Opening connection..."); InputStream in = null; try { conn.connect(); in = conn.getInputStream(); } catch (IOException ioe) { int after, code; try { after = conn.getHeaderFieldInt("Retry-After", -1); code = conn.getResponseCode(); } catch (IOException ioe2) { after = -1; code = -1; } if (code == HttpURLConnection.HTTP_UNAVAILABLE && after > 0) throw new RetryAfterIOException(after, ioe); throw ioe; } String encoding = conn.getContentEncoding(); if (encoding == null) encoding = "identity"; encoding = encoding.toLowerCase(); log.debug("HTTP server uses " + encoding + " content encoding."); if ("gzip".equals(encoding)) in = new GZIPInputStream(in); else if ("deflate".equals(encoding)) in = new InflaterInputStream(in); else if (!"identity".equals(encoding)) throw new IOException("Server uses an invalid content encoding: " + encoding); String contentType = conn.getContentType(); String charset = null; if (contentType != null) { contentType = contentType.toLowerCase(); int charsetStart = contentType.indexOf("charset="); if (charsetStart >= 0) { int charsetEnd = contentType.indexOf(";", charsetStart); if (charsetEnd == -1) charsetEnd = contentType.length(); charsetStart += "charset=".length(); charset = contentType.substring(charsetStart, charsetEnd).trim(); } } log.debug("Charset from Content-Type: '" + charset + "'"); InputSource src = new InputSource(in); src.setSystemId(url.toString()); src.setEncoding(charset); return src; } Code Sample 2: public static int UsePassword(String username, String password, String new_password) { try { URL url = new URL("http://eiffel.itba.edu.ar/hci/service/Security.groovy?method=ChangePassword&username=" + username + "&password=" + password + "&new_password=" + new_password); URLConnection urlc = url.openConnection(); urlc.setDoOutput(false); urlc.setAllowUserInteraction(false); BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); String response = sb.toString(); if (response == null) { return -1; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document dom = db.parse(is); NodeList nl = dom.getElementsByTagName("response"); String status = ((Element) nl.item(0)).getAttributes().item(0).getTextContent(); if (status.toString().equals("fail")) { return -1; } return 0; } catch (Exception e) { e.printStackTrace(); } return -1; }
11
Code Sample 1: public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) dir.mkdir(); 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[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: 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(); } }
11
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 void run() { FileInputStream src; FileOutputStream dest; try { src = new FileInputStream(srcName); dest = new FileOutputStream(destName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileChannel srcC = src.getChannel(); FileChannel destC = dest.getChannel(); ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE); try { int i; System.out.println(srcC.size()); while ((i = srcC.read(buf)) > 0) { System.out.println(buf.getChar(2)); buf.flip(); destC.write(buf); buf.compact(); } destC.close(); dest.close(); } catch (IOException e1) { e1.printStackTrace(); return; } }
00
Code Sample 1: public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if (src == submitButton) { SubmissionProfile profile = (SubmissionProfile) destinationCombo.getSelectedItem(); String uri = profile.endpoint; String authPoint = profile.authenticationPoint; String user = userIDField.getText(); String passwd = new String(passwordField.getPassword()); try { URL url = new URL(authPoint + "?username=" + user + "&password=" + passwd); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; String text = ""; while ((line = reader.readLine()) != null) { text = text + line; } reader.close(); submit(uri, user); JOptionPane.showMessageDialog(null, "Submission accepted", "Success", JOptionPane.INFORMATION_MESSAGE); this.setVisible(false); this.dispose(); } catch (Exception ex) { ex.printStackTrace(); if (ex instanceof java.io.IOException) { String msg = ex.getMessage(); if (msg.indexOf("HTTP response code: 401") != -1) JOptionPane.showMessageDialog(null, "Invalid Username/Password", "Invalid Username/Password", JOptionPane.ERROR_MESSAGE); else if (msg.indexOf("HTTP response code: 404") != -1) { try { submit(uri, user); JOptionPane.showMessageDialog(null, "Submission accepted", "Success", JOptionPane.INFORMATION_MESSAGE); } catch (Exception exc) { exc.printStackTrace(); } } } } } else if (src == cancelButton) { this.setVisible(false); this.dispose(); } } Code Sample 2: public static String getEncryptedPassword(String password) throws PasswordException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); } catch (Exception e) { throw new PasswordException(e); } return convertToString(md.digest()); }
00
Code Sample 1: public File download(Show s) throws Exception { Collection<String> exclude = Util.toCollection((List<String>) this.exclude.clone(), Util.nonNullString(s.getExclude()).split(",")); URL url = new URL("http://v3.newzbin.com/search/" + buildQuery(s)); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { if (!Util.containsNone(line, exclude)) continue; String id = line.split("\",\"", 3)[1]; File downloaded = download(s, id); if (downloaded != null) return downloaded; } return null; } Code Sample 2: public static Bitmap[] getMaps(double lat, double lon, int zoom) throws MalformedURLException, IOException { int latitudeTileNumber = lat2tile(lat, zoom); int longitudeTileNumber = lon2tile(lon, zoom); Bitmap[] maps = new Bitmap[10]; int cpt = 0; for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { try { URL url = new URL(("http://tile.openstreetmap.org/" + zoom + "/" + (longitudeTileNumber + j) + "/" + (latitudeTileNumber + i) + ".png")); Bitmap bmImg = BitmapFactory.decodeStream(url.openStream()); maps[cpt] = bmImg; cpt++; } catch (IOException e) { e.printStackTrace(); } } } return maps; }
00
Code Sample 1: public String kodetu(String testusoila) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(testusoila.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { new MezuLeiho("Ez da zifraketa algoritmoa aurkitu", "Ados", "Zifraketa Arazoa", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } catch (UnsupportedEncodingException e) { new MezuLeiho("Errorea kodetzerakoan", "Ados", "Kodeketa Errorea", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: public static String doGetWithBasicAuthentication(URL url, String username, String password, int timeout, Map<String, String> headers) throws Throwable { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setDoInput(true); if (username != null || password != null) { byte[] encodedPassword = (username + ":" + password).getBytes(); BASE64Encoder encoder = new BASE64Encoder(); con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword)); } if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { con.setRequestProperty(header.getKey(), header.getValue()); } } con.setConnectTimeout(timeout); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); is.close(); con.disconnect(); return response.toString(); }
00
Code Sample 1: protected String readFileUsingHttp(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Type", "text/html"); httpConn.setRequestProperty("Content-Length", "0"); httpConn.setRequestMethod("GET"); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setAllowUserInteraction(false); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; } Code Sample 2: private boolean getCached(Get g) throws IOException { boolean ret = false; File f = getCachedFile(g); if (f.exists()) { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(f); os = new FileOutputStream(getDestFile(g)); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } ret = true; } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } } return ret; }
00
Code Sample 1: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); HttpClient client = new DefaultHttpClient(); HttpGet httpGetRequest = new HttpGet("http://www.google.com/"); String line = "", responseString = ""; try { HttpResponse response = client.execute(httpGetRequest); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); while ((line = br.readLine()) != null) { responseString += line; } br.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } tv.setText(responseString); setContentView(tv); } Code Sample 2: public void addStadium(Stadium stadium) throws StadiumException { Connection conn = ConnectionManager.getManager().getConnection(); if (findStadiumBy_N_C(stadium.getName(), stadium.getCity()) != -1) throw new StadiumException("Stadium already exists"); try { PreparedStatement stm = conn.prepareStatement(Statements.INSERT_STADIUM); conn.setAutoCommit(false); stm.setString(1, stadium.getName()); stm.setString(2, stadium.getCity()); stm.executeUpdate(); int id = getMaxId(); TribuneLogic logic = TribuneLogic.getInstance(); for (Tribune trib : stadium.getTribunes()) { int tribuneId = logic.addTribune(trib); if (tribuneId != -1) { stm = conn.prepareStatement(Statements.INSERT_STAD_TRIBUNE); stm.setInt(1, id); stm.setInt(2, tribuneId); stm.executeUpdate(); } } } catch (SQLException e) { try { conn.rollback(); conn.setAutoCommit(true); } catch (SQLException e1) { e1.printStackTrace(); } throw new StadiumException("Adding stadium failed", e); } try { conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } }
00
Code Sample 1: public byte[] computeMD5(String plainText) throws VHException { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw new VHException("The MD5 hash algorithm is not available.", ex); } try { md.update(plainText.getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { throw new VHException("The UTF-8 encoding is not supported.", ex); } return md.digest(); } Code Sample 2: @Test public void testSQLite() { log("trying SQLite.."); for (int i = 0; i < 10; i++) { Connection c = null; try { Class.forName("SQLite.JDBCDriver"); c = DriverManager.getConnection("jdbc:sqlite:/C:/Source/SRFSurvey/app/src/org/speakright/srfsurvey/results.db", "", ""); c.setAutoCommit(false); Statement st = c.createStatement(); int rc = st.executeUpdate("INSERT INTO tblAnswers(fQID,fQNAME) VALUES('q1','zoo')"); st.close(); c.commit(); c.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(1); try { if (c != null && !c.isClosed()) { c.rollback(); c.close(); } } catch (SQLException sql) { } } } log("end"); }
11
Code Sample 1: private void copyJdbcDriverToWL(final WLPropertyPage page) { final File url = new File(page.getDomainDirectory()); final File lib = new File(url, "lib"); final File mysqlLibrary = new File(lib, NexOpenUIActivator.getDefault().getMySQLDriver()); if (!mysqlLibrary.exists()) { InputStream driver = null; FileOutputStream fos = null; try { driver = AppServerPropertyPage.toInputStream(new Path("jdbc/" + NexOpenUIActivator.getDefault().getMySQLDriver())); fos = new FileOutputStream(mysqlLibrary); IOUtils.copy(driver, fos); } catch (final IOException e) { Logger.log(Logger.ERROR, "Could not copy the MySQL Driver jar file to Bea WL", e); final Status status = new Status(Status.ERROR, NexOpenUIActivator.PLUGIN_ID, Status.ERROR, "Could not copy the MySQL Driver jar file to Bea WL", e); ErrorDialog.openError(page.getShell(), "Bea WebLogic MSQL support", "Could not copy the MySQL Driver jar file to Bea WL", status); } finally { try { if (driver != null) { driver.close(); driver = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } } Code Sample 2: private void generateDocFile(String srcFileName, String s, String destFileName) { try { ZipFile docxFile = new ZipFile(new File(srcFileName)); ZipEntry documentXML = docxFile.getEntry("word/document.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); InputStream documentXMLIS1 = docxFile.getInputStream(documentXML); Document doc = dbf.newDocumentBuilder().parse(documentXMLIS1); Transformer t = TransformerFactory.newInstance().newTransformer(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); t.transform(new DOMSource(doc), new StreamResult(baos)); ZipOutputStream docxOutFile = new ZipOutputStream(new FileOutputStream(destFileName)); Enumeration<ZipEntry> entriesIter = (Enumeration<ZipEntry>) docxFile.entries(); while (entriesIter.hasMoreElements()) { ZipEntry entry = entriesIter.nextElement(); if (entry.getName().equals("word/document.xml")) { docxOutFile.putNextEntry(new ZipEntry(entry.getName())); byte[] datas = s.getBytes("UTF-8"); docxOutFile.write(datas, 0, datas.length); docxOutFile.closeEntry(); } else if (entry.getName().equals("word/media/image1.png")) { InputStream incoming = new FileInputStream("c:/aaa.jpg"); byte[] data = new byte[incoming.available()]; int readCount = incoming.read(data, 0, data.length); docxOutFile.putNextEntry(new ZipEntry(entry.getName())); docxOutFile.write(data, 0, readCount); docxOutFile.closeEntry(); } else { InputStream incoming = docxFile.getInputStream(entry); byte[] data = new byte[incoming.available()]; int readCount = incoming.read(data, 0, data.length); docxOutFile.putNextEntry(new ZipEntry(entry.getName())); docxOutFile.write(data, 0, readCount); docxOutFile.closeEntry(); } } docxOutFile.close(); } catch (Exception e) { } }
00
Code Sample 1: public int delete(BusinessObject o) throws DAOException { int delete = 0; Bill bill = (Bill) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_BILL")); pst.setInt(1, bill.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; } Code Sample 2: private byte[] digestPassword(byte[] salt, String password) throws AuthenticationException { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF8")); return md.digest(); } catch (Exception e) { throw new AuthenticationException(MESSAGE_CONFIGURATION_ERROR_KEY, e); } }
00
Code Sample 1: public static String md5EncodeString(String s) throws UnsupportedEncodingException, NoSuchAlgorithmException { if (s == null) return null; if (StringUtils.isBlank(s)) return ""; MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(s.getBytes("UTF-8")); byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String hex = Integer.toHexString(0xFF & messageDigest[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString(); } Code Sample 2: public static OMElement createOMRequest(String file, int count, String[] documentIds) throws Exception { ObjectFactory factory = new ObjectFactory(); SubmitDocumentRequest sdr = factory.createSubmitDocumentRequest(); IdType pid = factory.createIdType(); pid.setRoot("1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478"); sdr.setPatientId(pid); ClassLoader classLoader = JUnitHelper.class.getClassLoader(); DocumentsType documents = factory.createDocumentsType(); for (int i = 0; i < count; ++i) { DocumentType document = factory.createDocumentType(); if ((documentIds != null) && (documentIds.length > i)) { document.setId(documentIds[i]); } CodeType type = factory.createCodeType(); type.setCode("51855-5"); type.setCodeSystem("2.16.840.1.113883.6.1"); document.setType(type); ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream is = classLoader.getResourceAsStream(file); assertNotNull(is); IOUtils.copy(is, bos); document.setContent(bos.toByteArray()); documents.getDocument().add(document); } sdr.setDocuments(documents); QName qname = new QName(URIConstants.XDSBRIDGE_URI, "SubmitDocumentRequest"); JAXBContext jc = JAXBContext.newInstance(SubmitDocumentRequest.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); JAXBElement element = new JAXBElement(qname, sdr.getClass(), sdr); StringWriter sw = new StringWriter(); marshaller.marshal(element, sw); String xml = sw.toString(); logger.debug(xml); OMElement result = AXIOMUtil.stringToOM(OMAbstractFactory.getOMFactory(), xml); List<OMElement> list = XPathHelper.selectNodes(result, "./ns:Documents/ns:Document/ns:Content", URIConstants.XDSBRIDGE_URI); for (OMElement contentNode : list) { OMText binaryNode = (OMText) contentNode.getFirstOMChild(); if (binaryNode != null) { binaryNode.setOptimize(true); } } return result; }
00
Code Sample 1: static void createCompleteXML(File file) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(errorFile); fos = new FileOutputStream(file); byte[] data = new byte[Integer.parseInt(BlueXStatics.prop.getProperty("allocationUnit"))]; int offset; while ((offset = fis.read(data)) != -1) fos.write(data, 0, offset); } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); } catch (Exception e) { } try { fos.close(); } catch (Exception e) { } } FileWriter fw = null; try { fw = new FileWriter(file, true); fw.append("</detail>"); fw.append("\n</exception>"); fw.append("\n</log>"); } catch (Exception e) { e.printStackTrace(); } finally { try { fw.close(); } catch (Exception e) { } } } Code Sample 2: public ISpieler[] sortiereSpielerRamsch(ISpieler[] spieler) { for (int i = 0; i < spieler.length; i++) { for (int j = 0; j < spieler.length - 1; j++) { if (werteAugen(spieler[j].getStiche()) > werteAugen(spieler[j + 1].getStiche())) { ISpieler a = spieler[j]; spieler[j] = spieler[j + 1]; spieler[j + 1] = a; } } } return spieler; }
11
Code Sample 1: @Override public CasAssembly build() { try { prepareForBuild(); File casWorkingDirectory = casFile.getParentFile(); DefaultCasFileReadIndexToContigLookup read2contigMap = new DefaultCasFileReadIndexToContigLookup(); AbstractDefaultCasFileLookup readIdLookup = new DefaultReadCasFileLookup(casWorkingDirectory); CasParser.parseOnlyMetaData(casFile, MultipleWrapper.createMultipleWrapper(CasFileVisitor.class, read2contigMap, readIdLookup)); ReadWriteDirectoryFileServer consedOut = DirectoryFileServer.createReadWriteDirectoryFileServer(commandLine.getOptionValue("o")); long startTime = DateTimeUtils.currentTimeMillis(); int numberOfCasContigs = read2contigMap.getNumberOfContigs(); for (long i = 0; i < numberOfCasContigs; i++) { File outputDir = consedOut.createNewDir("" + i); Command aCommand = new Command(new File("fakeCommand")); aCommand.setOption("-casId", "" + i); aCommand.setOption("-cas", commandLine.getOptionValue("cas")); aCommand.setOption("-o", outputDir.getAbsolutePath()); aCommand.setOption("-tempDir", tempDir.getAbsolutePath()); aCommand.setOption("-prefix", "temp"); if (commandLine.hasOption("useIllumina")) { aCommand.addFlag("-useIllumina"); } if (commandLine.hasOption("useClosureTrimming")) { aCommand.addFlag("-useClosureTrimming"); } if (commandLine.hasOption("trim")) { aCommand.setOption("-trim", commandLine.getOptionValue("trim")); } if (commandLine.hasOption("trimMap")) { aCommand.setOption("-trimMap", commandLine.getOptionValue("trimMap")); } if (commandLine.hasOption("chromat_dir")) { aCommand.setOption("-chromat_dir", commandLine.getOptionValue("chromat_dir")); } submitSingleCasAssemblyConversion(aCommand); } waitForAllAssembliesToFinish(); int numContigs = 0; int numReads = 0; for (int i = 0; i < numberOfCasContigs; i++) { File countMap = consedOut.getFile(i + "/temp.counts"); Scanner scanner = new Scanner(countMap); if (!scanner.hasNextInt()) { throw new IllegalStateException("single assembly conversion # " + i + " did not complete"); } numContigs += scanner.nextInt(); numReads += scanner.nextInt(); scanner.close(); } System.out.println("num contigs =" + numContigs); System.out.println("num reads =" + numReads); consedOut.createNewDir("edit_dir"); consedOut.createNewDir("phd_dir"); String prefix = commandLine.hasOption("prefix") ? commandLine.getOptionValue("prefix") : DEFAULT_PREFIX; OutputStream masterAceOut = new FileOutputStream(consedOut.createNewFile("edit_dir/" + prefix + ".ace.1")); OutputStream masterPhdOut = new FileOutputStream(consedOut.createNewFile("phd_dir/" + prefix + ".phd.ball")); OutputStream masterConsensusOut = new FileOutputStream(consedOut.createNewFile(prefix + ".consensus.fasta")); OutputStream logOut = new FileOutputStream(consedOut.createNewFile(prefix + ".log")); try { masterAceOut.write(String.format("AS %d %d%n", numContigs, numReads).getBytes()); for (int i = 0; i < numberOfCasContigs; i++) { InputStream aceIn = consedOut.getFileAsStream(i + "/temp.ace"); IOUtils.copy(aceIn, masterAceOut); InputStream phdIn = consedOut.getFileAsStream(i + "/temp.phd"); IOUtils.copy(phdIn, masterPhdOut); InputStream consensusIn = consedOut.getFileAsStream(i + "/temp.consensus.fasta"); IOUtils.copy(consensusIn, masterConsensusOut); IOUtil.closeAndIgnoreErrors(aceIn, phdIn, consensusIn); File tempDir = consedOut.getFile(i + ""); IOUtil.recursiveDelete(tempDir); } consedOut.createNewSymLink("../phd_dir/" + prefix + ".phd.ball", "edit_dir/phd.ball"); if (commandLine.hasOption("chromat_dir")) { consedOut.createNewDir("chromat_dir"); File originalChromatDir = new File(commandLine.getOptionValue("chromat_dir")); for (File chromat : originalChromatDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".scf"); } })) { File newChromatFile = consedOut.createNewFile("chromat_dir/" + FilenameUtils.getBaseName(chromat.getName())); FileOutputStream newChromat = new FileOutputStream(newChromatFile); InputStream in = new FileInputStream(chromat); IOUtils.copy(in, newChromat); IOUtil.closeAndIgnoreErrors(in, newChromat); } } System.out.println("finished making casAssemblies"); for (File traceFile : readIdLookup.getFiles()) { final String name = traceFile.getName(); String extension = FilenameUtils.getExtension(name); if (name.contains("fastq")) { if (!consedOut.contains("solexa_dir")) { consedOut.createNewDir("solexa_dir"); } if (consedOut.contains("solexa_dir/" + name)) { IOUtil.delete(consedOut.getFile("solexa_dir/" + name)); } consedOut.createNewSymLink(traceFile.getAbsolutePath(), "solexa_dir/" + name); } else if ("sff".equals(extension)) { if (!consedOut.contains("sff_dir")) { consedOut.createNewDir("sff_dir"); } if (consedOut.contains("sff_dir/" + name)) { IOUtil.delete(consedOut.getFile("sff_dir/" + name)); } consedOut.createNewSymLink(traceFile.getAbsolutePath(), "sff_dir/" + name); } } long endTime = DateTimeUtils.currentTimeMillis(); logOut.write(String.format("took %s%n", new Period(endTime - startTime)).getBytes()); } finally { IOUtil.closeAndIgnoreErrors(masterAceOut, masterPhdOut, masterConsensusOut, logOut); } } catch (Exception e) { handleException(e); } finally { cleanup(); } return null; } Code Sample 2: public void compressFile(String filePath) { String outPut = filePath + ".zip"; try { FileInputStream in = new FileInputStream(filePath); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outPut)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); } catch (Exception c) { c.printStackTrace(); } }
11
Code Sample 1: public void saveProjectFile(File aFile) { SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"); File destDir = new File(theProjectsDirectory, sdf.format(Calendar.getInstance().getTime())); if (destDir.mkdirs()) { File outFile = new File(destDir, "project.xml"); try { FileChannel sourceChannel = new FileInputStream(aFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(outFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException e) { e.printStackTrace(); } finally { aFile.delete(); } } } Code Sample 2: public void notifyTerminated(Writer r) { all_writers.remove(r); if (all_writers.isEmpty()) { all_terminated = true; Iterator iterator = open_files.iterator(); while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); do { try { fc.stream.flush(); fc.stream.close(); } catch (IOException e) { } fc = fc.next; } while (fc != null); } iterator = open_files.iterator(); boolean all_ok = true; while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); logger.logComment("File chunk <" + fc.name + "> " + fc.start_byte + " " + fc.position + " " + fc.actual_file); boolean ok = true; while (fc.next != null) { ok = ok && (fc.start_byte + fc.actual_file.length()) == fc.next.start_byte; fc = fc.next; } if (ok) { logger.logComment("Received file <" + fc.name + "> is contiguous (and hopefully complete)"); } else { logger.logError("Received file <" + fc.name + "> is NOT contiguous"); all_ok = false; } } if (all_ok) { byte[] buffer = new byte[16384]; iterator = open_files.iterator(); while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); try { if (fc.next != null) { FileOutputStream fos = new FileOutputStream(fc.actual_file, true); fc = fc.next; while (fc != null) { FileInputStream fis = new FileInputStream(fc.actual_file); int actually_read = fis.read(buffer); while (actually_read != -1) { fos.write(buffer, 0, actually_read); actually_read = fis.read(buffer); } fc.actual_file.delete(); fc = fc.next; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } fte.allWritersTerminated(); fte = null; } }
11
Code Sample 1: public void zipUp() throws PersistenceException { ZipOutputStream out = null; try { if (!backup.exists()) backup.createNewFile(); out = new ZipOutputStream(new FileOutputStream(backup)); out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String file : backupDirectory.list()) { logger.debug("Deflating: " + file); FileInputStream in = null; try { in = new FileInputStream(new File(backupDirectory, file)); out.putNextEntry(new ZipEntry(file)); IOUtils.copy(in, out); } finally { out.closeEntry(); if (null != in) in.close(); } } FileUtils.deleteDirectory(backupDirectory); } catch (Exception ex) { logger.error("Unable to ZIP the backup {" + backupDirectory.getAbsolutePath() + "}.", ex); throw new PersistenceException(ex); } finally { try { if (null != out) out.close(); } catch (IOException e) { logger.error("Unable to close ZIP output stream.", e); } } } Code Sample 2: public void copyJarContent(File jarPath, File targetDir) throws IOException { log.info("Copying natives from " + jarPath.getName()); JarFile jar = new JarFile(jarPath); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry file = entries.nextElement(); File f = new File(targetDir, file.getName()); log.info("Copying native - " + file.getName()); File parentFile = f.getParentFile(); parentFile.mkdirs(); if (file.isDirectory()) { f.mkdir(); continue; } InputStream is = null; FileOutputStream fos = null; try { is = jar.getInputStream(file); fos = new FileOutputStream(f); IOUtils.copy(is, fos); } finally { if (fos != null) fos.close(); if (is != null) is.close(); } } }
00
Code Sample 1: public SysSequences getSeqs(String tableName) throws SQLException { SysSequences seq = new SysSequences(); if (tableName == null || tableName.trim().equals("")) return null; Connection conn = null; try { conn = ConnectUtil.getConnect(); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("update ss_sys_sequences set next_value=next_value+step_value where table_name='" + tableName + "'"); ps.executeUpdate(); ps.close(); ps = conn.prepareStatement("select * from ss_sys_sequences where table_name='" + tableName + "'"); ResultSet rs = ps.executeQuery(); while (rs.next()) { long nextValue = rs.getLong(2); long stepValue = rs.getLong(3); seq.setTableName(tableName); seq.setNextValue(nextValue - stepValue + 1); seq.setStepValue(stepValue); } rs.close(); ps.close(); if (seq.getTableName() == null) { ps = conn.prepareStatement("insert into ss_sys_sequences values('" + tableName + "'," + (Constants.DEFAULT_CURR_VALUE + Constants.DEFAULT_STEP_VALUE) + "," + Constants.DEFAULT_STEP_VALUE + ")"); ps.executeUpdate(); ps.close(); seq.setTableName(tableName); seq.setNextValue(Constants.DEFAULT_CURR_VALUE + 1); seq.setStepValue(Constants.DEFAULT_STEP_VALUE); } conn.commit(); } catch (Exception e) { conn.rollback(); e.printStackTrace(); } finally { try { conn.setAutoCommit(true); } catch (Exception e) { } ConnectUtil.closeConn(conn); } return seq; } Code Sample 2: private void callbackWS(String xmlControl, String ws_results, long docId) { SimpleProvider config; Service service; Object ret; Call call; Object[] parameter; String method; String wsurl; URL url; NodeList delegateNodes; Node actualNode; InputSource xmlcontrolstream; try { xmlcontrolstream = new InputSource(new StringReader(xmlControl)); delegateNodes = SimpleXMLParser.parseDocument(xmlcontrolstream, AgentBehaviour.XML_CALLBACK); actualNode = delegateNodes.item(0); wsurl = SimpleXMLParser.findChildEntry(actualNode, AgentBehaviour.XML_URL); method = SimpleXMLParser.findChildEntry(actualNode, AgentBehaviour.XML_METHOD); if (wsurl == null || method == null) { System.out.println("----- Did not get method or wsurl from the properties! -----"); return; } url = new java.net.URL(wsurl); try { url.openConnection().connect(); } catch (IOException ex) { System.out.println("----- Could not connect to the webservice! -----"); } Vector v_param = new Vector(); v_param.add(ws_results); v_param.add(new Long(docId)); parameter = v_param.toArray(); config = new SimpleProvider(); config.deployTransport("http", new HTTPSender()); service = new Service(config); call = (Call) service.createCall(); call.setTargetEndpointAddress(url); call.setOperationName(new QName("http://schemas.xmlsoap.org/soap/encoding/", method)); try { ret = call.invoke(parameter); if (ret == null) { ret = new String("No response from callback function!"); } System.out.println("Callback function returned: " + ret); } catch (RemoteException ex) { System.out.println("----- Could not invoke the method! -----"); } } catch (Exception ex) { ex.printStackTrace(System.err); } }
00
Code Sample 1: public static void main(String[] args) throws IOException { FileOutputStream f = new FileOutputStream("test.zip"); CheckedOutputStream csum = new CheckedOutputStream(f, new CRC32()); ZipOutputStream zos = new ZipOutputStream(csum); BufferedOutputStream out = new BufferedOutputStream(zos); zos.setComment("A test of Java Zipping"); for (String arg : args) { print("Writing file " + arg); BufferedReader in = new BufferedReader(new FileReader(arg)); zos.putNextEntry(new ZipEntry(arg)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.flush(); } out.close(); print("Checksum: " + csum.getChecksum().getValue()); print("Reading file"); FileInputStream fi = new FileInputStream("test.zip"); CheckedInputStream csumi = new CheckedInputStream(fi, new CRC32()); ZipInputStream in2 = new ZipInputStream(csumi); BufferedInputStream bis = new BufferedInputStream(in2); ZipEntry ze; while ((ze = in2.getNextEntry()) != null) { print("Reading file " + ze); int x; while ((x = bis.read()) != -1) { System.out.write(x); } if (args.length == 1) { print("Checksum: " + csumi.getChecksum().getValue()); } bis.close(); } } Code Sample 2: private byte[] _generate() throws NoSuchAlgorithmException { if (host == null) { try { seed = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { seed = "localhost/127.0.0.1"; } catch (SecurityException e) { seed = "localhost/127.0.0.1"; } host = seed; } else { seed = host; } seed = seed + new Date().toString(); seed = seed + Long.toString(rnd.nextLong()); md = MessageDigest.getInstance(algorithm); md.update(seed.getBytes()); return md.digest(); }
11
Code Sample 1: private static File copyFileTo(File file, File directory) throws IOException { File newFile = new File(directory, file.getName()); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(file); fos = new FileOutputStream(newFile); byte buff[] = new byte[1024]; int val; while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val); } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } return newFile; } Code Sample 2: public void gzipCompress(String file) { try { File inputFile = new File(file); FileInputStream fileinput = new FileInputStream(inputFile); File outputFile = new File(file.substring(0, file.length() - 1) + "z"); FileOutputStream stream = new FileOutputStream(outputFile); GZIPOutputStream gzipstream = new GZIPOutputStream(stream); BufferedInputStream bis = new BufferedInputStream(fileinput); int bytes_read = 0; byte[] buf = new byte[READ_BUFFER_SIZE]; while ((bytes_read = bis.read(buf, 0, BLOCK_SIZE)) != -1) { gzipstream.write(buf, 0, bytes_read); } bis.close(); inputFile.delete(); gzipstream.finish(); gzipstream.close(); } catch (FileNotFoundException fnfe) { System.out.println("Compressor: Cannot find file " + fnfe.getMessage()); } catch (SecurityException se) { System.out.println("Problem saving file " + se.getMessage()); } catch (IOException ioe) { System.out.println("Problem saving file " + ioe.getMessage()); } }
11
Code Sample 1: private void setManagedContent(Entry entry, Datastream vds) throws StreamIOException { if (m_transContext == DOTranslationUtility.SERIALIZE_EXPORT_ARCHIVE && !m_format.equals(ATOM_ZIP1_1)) { String mimeType = vds.DSMIME; if (MimeTypeHelper.isText(mimeType) || MimeTypeHelper.isXml(mimeType)) { try { entry.setContent(IOUtils.toString(vds.getContentStream(), m_encoding), mimeType); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { entry.setContent(vds.getContentStream(), mimeType); } } else { String dsLocation; IRI iri; if (m_format.equals(ATOM_ZIP1_1) && m_transContext != DOTranslationUtility.AS_IS) { dsLocation = vds.DSVersionID + "." + MimeTypeUtils.fileExtensionForMIMEType(vds.DSMIME); try { m_zout.putNextEntry(new ZipEntry(dsLocation)); InputStream is = vds.getContentStream(); IOUtils.copy(is, m_zout); is.close(); m_zout.closeEntry(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { dsLocation = StreamUtility.enc(DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), vds, m_transContext).DSLocation); } iri = new IRI(dsLocation); entry.setSummary(vds.DSVersionID); entry.setContent(iri, vds.DSMIME); } } Code Sample 2: private String extractFileFromZip(ZipFile zip, String fileName) throws IOException { String contents = null; ZipEntry entry = zip.getEntry(fileName); if (entry != null) { InputStream input = zip.getInputStream(entry); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copyAndClose(input, buffer); contents = buffer.toString(); } return contents; }
11
Code Sample 1: public static void zip(File srcDir, File destFile, FileFilter filter) throws IOException { ZipOutputStream out = null; try { out = new ZipOutputStream(new FileOutputStream(destFile)); Collection<File> files = FileUtils.listFiles(srcDir, TrueFileFilter.TRUE, TrueFileFilter.TRUE); for (File f : files) { if (filter == null || filter.accept(f)) { FileInputStream in = FileUtils.openInputStream(f); out.putNextEntry(new ZipEntry(Util.relativePath(srcDir, f).replace('\\', '/'))); IOUtils.copyLarge(in, out); out.closeEntry(); IOUtils.closeQuietly(in); } } IOUtils.closeQuietly(out); } catch (Throwable t) { throw new IOException("Failed to create zip file", t); } finally { if (out != null) { out.flush(); IOUtils.closeQuietly(out); } } } Code Sample 2: public byte[] getFile(final String file) throws IOException { if (this.files.contains(file)) { ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(this.bytes)); ZipEntry entry = input.getNextEntry(); while (entry != null) { entry = input.getNextEntry(); if ((entry.getName().equals(file)) && (!entry.isDirectory())) { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(input, output); output.close(); input.close(); return output.toByteArray(); } } input.close(); } return null; }
11
Code Sample 1: 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(); } } Code Sample 2: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
11
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 static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); XSLTBuddy buddy = new XSLTBuddy(); buddy.parseArgs(args); XSLTransformer transformer = new XSLTransformer(); if (buddy.templateDir != null) { transformer.setTemplateDir(buddy.templateDir); } FileReader xslReader = new FileReader(buddy.xsl); Templates xslTemplate = transformer.getXSLTemplate(buddy.xsl, xslReader); for (Enumeration e = buddy.params.keys(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); transformer.addParam(key, buddy.params.get(key)); } Reader reader = null; if (buddy.src == null) { reader = new StringReader(XSLTBuddy.BLANK_XML); } else { reader = new FileReader(buddy.src); } if (buddy.out == null) { String result = transformer.doTransform(reader, xslTemplate, buddy.xsl); buddy.getLogger().info("\n\nXSLT Result:\n\n" + result + "\n"); } else { File file = new File(buddy.out); File dir = file.getParentFile(); if (dir != null) { dir.mkdirs(); } FileWriter writer = new FileWriter(buddy.out); transformer.doTransform(reader, xslTemplate, buddy.xsl, writer); writer.flush(); writer.close(); } buddy.getLogger().info("Transform done successfully in " + (System.currentTimeMillis() - start) + " milliseconds"); }
11
Code Sample 1: public static void copyFile(File source, File target) throws Exception { if (source.isDirectory()) { if (!target.isDirectory()) { target.mkdirs(); } String[] children = source.list(); for (int i = 0; i < children.length; i++) { copyFile(new File(source, children[i]), new File(target, children[i])); } } else { FileChannel inChannel = new FileInputStream(source).getChannel(); FileChannel outChannel = new FileOutputStream(target).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { errorLog("{Malgn.copyFile} " + e.getMessage()); throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } } Code Sample 2: public void createZipCopy(IUIContext ui, final String zipFileName, final File[] filesToZip, final FilenameFilter fileFilter, Timestamp timestamp) { TestCase.assertNotNull(ui); TestCase.assertNotNull(zipFileName); TestCase.assertFalse(zipFileName.trim().length() == 0); TestCase.assertNotNull(filesToZip); TestCase.assertNotNull(timestamp); String nameCopy = zipFileName; if (nameCopy.endsWith(".zip")) { nameCopy = nameCopy.substring(0, zipFileName.length() - 4); } nameCopy = nameCopy + "_" + timestamp.toString() + ".zip"; final String finalZip = nameCopy; IWorkspaceRunnable noResourceChangedEventsRunner = new IWorkspaceRunnable() { public void run(IProgressMonitor runnerMonitor) throws CoreException { try { Map<String, File> projectFiles = new HashMap<String, File>(); IPath basePath = new Path("/"); for (File nextLocation : filesToZip) { projectFiles.putAll(getFilesToZip(nextLocation, basePath, fileFilter)); } if (projectFiles.isEmpty()) { PlatformActivator.logDebug("Zip file (" + zipFileName + ") not created because there were no files to zip"); return; } IPath resultsPath = PlatformActivator.getDefault().getResultsPath(); File copyRoot = resultsPath.toFile(); copyRoot.mkdirs(); IPath zipFilePath = resultsPath.append(new Path(finalZip)); String zipFileName = zipFilePath.toPortableString(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); try { out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String filePath : projectFiles.keySet()) { File nextFile = projectFiles.get(filePath); FileInputStream fin = new FileInputStream(nextFile); try { out.putNextEntry(new ZipEntry(filePath)); try { byte[] bin = new byte[4096]; int bread = fin.read(bin, 0, 4096); while (bread != -1) { out.write(bin, 0, bread); bread = fin.read(bin, 0, 4096); } } finally { out.closeEntry(); } } finally { fin.close(); } } } finally { out.close(); } } catch (FileNotFoundException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } catch (IOException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } } }; try { IWorkspace workspace = ResourcesPlugin.getWorkspace(); workspace.run(noResourceChangedEventsRunner, workspace.getRoot(), IWorkspace.AVOID_UPDATE, new NullProgressMonitor()); } catch (CoreException ce) { PlatformActivator.logException(ce); } }
00
Code Sample 1: public void filter(File source, File destination, MNamespace mNamespace) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(source)); BufferedWriter writer = new BufferedWriter(new FileWriter(destination)); int line = 0; int column = 0; Stack parseStateStack = new Stack(); parseStateStack.push(new ParseState(mNamespace)); for (Iterator i = codePieces.iterator(); i.hasNext(); ) { NamedCodePiece cp = (NamedCodePiece) i.next(); while (line < cp.getStartLine()) { line++; column = 0; writer.write(reader.readLine()); writer.newLine(); } while (column < cp.getStartPosition()) { writer.write(reader.read()); column++; } cp.write(writer, parseStateStack, column); while (line < cp.getEndLine()) { line++; column = 0; reader.readLine(); } while (column < cp.getEndPosition()) { column++; reader.read(); } } String data; while ((data = reader.readLine()) != null) { writer.write(data); writer.newLine(); } reader.close(); writer.close(); } Code Sample 2: @Deprecated public static Collection<SearchKeyResult> searchKey(String iText, String iKeyServer) throws Exception { List<SearchKeyResult> outVec = new ArrayList<SearchKeyResult>(); String uri = iKeyServer + "/pks/lookup?search=" + URLEncoder.encode(iText, UTF8); URL url = new URL(uri); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); Pattern regex = Pattern.compile("pub.*?<a\\s+href\\s*=\"(.*?)\".*?>\\s*(\\w+)\\s*</a>.*?(\\d+-\\d+-\\d+).*?<a\\s+href\\s*=\".*?\".*?>\\s*(.+?)\\s*</a>", Pattern.CANON_EQ); String line; while ((line = input.readLine()) != null) { Matcher regexMatcher = regex.matcher(line); while (regexMatcher.find()) { String id = regexMatcher.group(2); String downUrl = iKeyServer + regexMatcher.group(1); String downDate = regexMatcher.group(3); String name = decodeHTML(regexMatcher.group(4)); outVec.add(new SearchKeyResult(id, name, downDate, downUrl)); } } IOUtils.closeQuietly(input); return outVec; }
11
Code Sample 1: protected String decrypt(final String data, final String key) throws CryptographicFailureException { Validate.notNull(data, "Provided data cannot be null."); Validate.notNull(key, "Provided key name cannot be null."); final PrivateKey pk = getPrivateKey(key); if (pk == null) { throw new CryptographicFailureException("PrivateKeyNotFound", String.format("Cannot find private key '%s'", key)); } try { final Cipher cipher = Cipher.getInstance(pk.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, pk); final ByteArrayInputStream bin = new ByteArrayInputStream(Base64.decodeBase64(data.getBytes())); final CipherInputStream cin = new CipherInputStream(bin, cipher); final ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(cin, bout); return new String(bout.toByteArray()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(String.format("Cannot find instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (NoSuchPaddingException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (InvalidKeyException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (IOException e) { throw new IllegalStateException("Cannot build in-memory cipher copy", e); } } Code Sample 2: public Void doInBackground() { setProgress(0); for (int i = 0; i < uploadFiles.size(); i++) { String filePath = uploadFiles.elementAt(i).getFilePath(); String fileName = uploadFiles.elementAt(i).getFileName(); String fileMsg = "Uploading file " + (i + 1) + "/" + uploadFiles.size() + "\n"; this.publish(fileMsg); try { File inFile = new File(filePath); FileInputStream in = new FileInputStream(inFile); byte[] inBytes = new byte[(int) chunkSize]; int count = 1; int maxCount = (int) (inFile.length() / chunkSize); if (inFile.length() % chunkSize > 0) { maxCount++; } int readCount = 0; readCount = in.read(inBytes); while (readCount > 0) { File splitFile = File.createTempFile("upl", null, null); String splitName = splitFile.getPath(); FileOutputStream out = new FileOutputStream(splitFile); out.write(inBytes, 0, readCount); out.close(); boolean chunkFinal = (count == maxCount); fileMsg = " - Sending chunk " + count + "/" + maxCount + ": "; this.publish(fileMsg); boolean uploadSuccess = false; int uploadTries = 0; while (!uploadSuccess && uploadTries <= 5) { uploadTries++; boolean uploadStatus = upload(splitName, fileName, count, chunkFinal); if (uploadStatus) { fileMsg = "OK\n"; this.publish(fileMsg); uploadSuccess = true; } else { fileMsg = "ERROR\n"; this.publish(fileMsg); uploadSuccess = false; } } if (!uploadSuccess) { fileMsg = "There was an error uploading your files. Please let the pipeline administrator know about this problem. Cut and paste the messages in this box, and supply them.\n"; this.publish(fileMsg); errorFlag = true; return null; } float thisProgress = (count * 100) / (maxCount); float completeProgress = (i * (100 / uploadFiles.size())); float totalProgress = completeProgress + (thisProgress / uploadFiles.size()); setProgress((int) totalProgress); splitFile.delete(); readCount = in.read(inBytes); count++; } } catch (Exception e) { this.publish(e.toString()); } } return null; }
00
Code Sample 1: @Override public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { URL baseUrl = this.baseUrl; if (this.baseUrl == null) { baseUrl = url; } InputStream in; try { in = url.openStream(); } catch (IOException ex) { throw new FileNotFoundException("Can't read " + url); } return load(new BufferedInputStream(in), baseUrl); } Code Sample 2: private void trySend(Primitive p) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { mSerializer.serialize(p, out); } catch (SerializerException e) { mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.SERIALIZER_ERROR, "Internal serializer error, primitive: " + p.getType()); out.close(); return; } HttpPost req = new HttpPost(mPostUri); req.addHeader(mContentTypeHeader); if (mMsisdnHeader != null) { req.addHeader(mMsisdnHeader); } ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray()); req.setEntity(entity); mLastActive = SystemClock.elapsedRealtime(); if (Log.isLoggable(ImpsLog.TAG, Log.DEBUG)) { long sendBytes = entity.getContentLength() + 176; ImpsLog.log(mConnection.getLoginUserName() + " >> " + p.getType() + " HTTP payload approx. " + sendBytes + " bytes"); } if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) { ImpsLog.dumpRawPacket(out.toByteArray()); ImpsLog.dumpPrimitive(p); } HttpResponse res = mHttpClient.execute(req); StatusLine statusLine = res.getStatusLine(); HttpEntity resEntity = res.getEntity(); InputStream in = resEntity.getContent(); if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) { Log.d(ImpsLog.PACKET_TAG, statusLine.toString()); Header[] headers = res.getAllHeaders(); for (Header h : headers) { Log.d(ImpsLog.PACKET_TAG, h.toString()); } int len = (int) resEntity.getContentLength(); if (len > 0) { byte[] content = new byte[len]; int offset = 0; int bytesRead = 0; do { bytesRead = in.read(content, offset, len); offset += bytesRead; len -= bytesRead; } while (bytesRead > 0); in.close(); ImpsLog.dumpRawPacket(content); in = new ByteArrayInputStream(content); } } try { if (statusLine.getStatusCode() != HttpURLConnection.HTTP_OK) { mTxManager.notifyErrorResponse(p.getTransactionID(), statusLine.getStatusCode(), statusLine.getReasonPhrase()); return; } if (resEntity.getContentLength() == 0) { if ((p.getTransactionMode() != TransactionMode.Response) && !p.getType().equals(ImpsTags.Polling_Request)) { mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.ILLEGAL_SERVER_RESPONSE, "bad response from server"); } return; } Primitive response = mParser.parse(in); if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) { ImpsLog.dumpPrimitive(response); } if (Log.isLoggable(ImpsLog.TAG, Log.DEBUG)) { long len = 2 + resEntity.getContentLength() + statusLine.toString().length() + 2; Header[] headers = res.getAllHeaders(); for (Header header : headers) { len += header.getName().length() + header.getValue().length() + 4; } ImpsLog.log(mConnection.getLoginUserName() + " << " + response.getType() + " HTTP payload approx. " + len + "bytes"); } if (!mReceiveQueue.offer(response)) { mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.UNKNOWN_ERROR, "receiving queue full"); } } catch (ParserException e) { ImpsLog.logError(e); mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.PARSER_ERROR, "Parser error, received a bad response from server"); } finally { resEntity.consumeContent(); } }
11
Code Sample 1: public static void copyFile(File source, File destination) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(destination).getChannel(); long size = in.size(); MappedByteBuffer buffer = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buffer); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } Code Sample 2: protected void zipFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(to)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); }
00
Code Sample 1: private String readUrl(String feature) { StringBuffer content = new StringBuffer(); try { URL url = new URL(feature); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { content.append(line); } conn.disconnect(); } catch (Exception e) { } return content.toString(); } Code Sample 2: private boolean authenticateWithServer(String user, String password) { Object o; String response; byte[] dataKey; try { o = objectIn.readObject(); if (o instanceof String) { response = (String) o; Debug.netMsg("Connected to JFritz Server: " + response); if (!response.equals("JFRITZ SERVER 1.1")) { Debug.netMsg("Unkown Server version, newer JFritz protocoll version?"); Debug.netMsg("Canceling login attempt!"); } objectOut.writeObject(user); objectOut.flush(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.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.DECRYPT_MODE, secretKey); SealedObject sealedObject = (SealedObject) objectIn.readObject(); o = sealedObject.getObject(desCipher); if (o instanceof byte[]) { dataKey = (byte[]) o; desKeySpec = new DESKeySpec(dataKey); 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 sealed_ok = new SealedObject("OK", outCipher); objectOut.writeObject(sealed_ok); SealedObject sealed_response = (SealedObject) objectIn.readObject(); o = sealed_response.getObject(inCipher); if (o instanceof String) { if (o.equals("OK")) { return true; } else { Debug.netMsg("Server sent wrong string as response to authentication challenge!"); } } else { Debug.netMsg("Server sent wrong object as response to authentication challenge!"); } } else { Debug.netMsg("Server sent wrong type for data key!"); } } } catch (ClassNotFoundException e) { Debug.error("Server authentication response invalid!"); 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 (EOFException e) { Debug.error("Server closed Stream unexpectedly!"); Debug.error(e.toString()); e.printStackTrace(); } catch (SocketTimeoutException e) { Debug.error("Read timeout while authenticating with server!"); Debug.error(e.toString()); e.printStackTrace(); } catch (IOException e) { Debug.error("Error reading response during authentication!"); Debug.error(e.toString()); e.printStackTrace(); } catch (IllegalBlockSizeException e) { Debug.error("Illegal block size exception!"); Debug.error(e.toString()); e.printStackTrace(); } catch (BadPaddingException e) { Debug.error("Bad padding exception!"); Debug.error(e.toString()); e.printStackTrace(); } return false; }
11
Code Sample 1: 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(); } } } Code Sample 2: public static FileChannel getFileChannel(Object o) throws IOException { Class c = o.getClass(); try { Method m = c.getMethod("getChannel", null); return (FileChannel) m.invoke(o, null); } catch (IllegalAccessException x) { } catch (NoSuchMethodException x) { } catch (InvocationTargetException x) { if (x.getTargetException() instanceof IOException) throw (IOException) x.getTargetException(); } if (o instanceof FileInputStream) return new MyFileChannelImpl((FileInputStream) o); if (o instanceof FileOutputStream) return new MyFileChannelImpl((FileOutputStream) o); if (o instanceof RandomAccessFile) return new MyFileChannelImpl((RandomAccessFile) o); Assert.UNREACHABLE(o.getClass().toString()); return null; }
11
Code Sample 1: 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.*;"); importList.add("java.sql.Date;"); importList.add("com.emeraldjb.runtime.patternXmlObj.*;"); importList.add("javax.xml.parsers.*;"); importList.add("java.text.ParseException;"); importList.add("org.xml.sax.*;"); importList.add("org.xml.sax.helpers.*;"); 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"); boolean short_version = entity.getPatternBooleanValue(GeneratorConst.PATTERN_STREAM_XML_SHORT, false); StringBuffer preface = new StringBuffer(); StringBuffer consts = new StringBuffer(); StringBuffer f_writer = new StringBuffer(); StringBuffer f_writer_short = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); StringBuffer end_elems = new StringBuffer(); boolean end_elem_needs_catch = false; consts.append("\n public static final String EL_CLASS_TAG=\"" + values_class_name + "\";"); preface.append("\n xos.print(\"<!-- This format is optimised for space, below are the column mappings\");"); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); int col_num = 0; while (it.hasNext()) { col_num++; Member member = (Member) it.next(); String nm = member.getName(); preface.append("\n xos.print(\"c" + col_num + " = " + nm + "\");"); String elem_name = nm; String elem_name_short = "c" + col_num; String el_name = nm.toUpperCase(); if (member.getColLen() > 0 || !member.isNullAllowed()) { end_elem_needs_catch = true; } String element_const = "EL_" + el_name; String element_const_short = "EL_" + el_name + "_SHORT"; consts.append("\n public static final String " + element_const + "=\"" + elem_name + "\";" + "\n public static final String " + element_const_short + "=\"" + elem_name_short + "\";"); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "values_." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToXmlCode(pad, element_const, getter + "()")); f_writer_short.append(gen_type.getToXmlCode(pad, element_const_short, getter + "()")); end_elems.append(gen_type.getFromXmlCode(pad, element_const, setter)); end_elems.append("\n //and also the short version"); end_elems.append(gen_type.getFromXmlCode(pad, element_const_short, setter)); } preface.append("\n xos.print(\"-->\");"); String body_part = f_writer.toString(); String body_part_short = preface.toString() + f_writer_short.toString(); String reader_vars = ""; String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + " extends DefaultHandler implements TSParser\n"); sb.append("{" + consts + "\n public static final int PROTO_VERSION=" + proto_version + ";" + "\n private transient StringBuffer cdata_=new StringBuffer();" + "\n private transient String endElement_;" + "\n private transient TSParser parentParser_;" + "\n private transient XMLReader theReader_;\n" + "\n private " + values_class_name + " values_;"); sb.append("\n\n"); sb.append("\n /**" + "\n * This is really only here as an example. It is very rare to write a single" + "\n * object to a file - far more likely to have a collection or object graph. " + "\n * in which case you can write something similar - maybe using the writeXmlShort" + "\n * version instread." + "\n */" + "\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 XmlOutputFilter xos = new XmlOutputFilter(fos);" + "\n xos.openElement(\"FILE_\"+EL_CLASS_TAG);" + "\n writeXml(xos, obj);" + "\n xos.closeElement();" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException, SAXException" + "\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 marshalFromXml(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeXml(XmlOutputFilter xos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n xos.openElement(EL_CLASS_TAG);" + body_part + "\n xos.closeElement();" + "\n } // end of writeXml" + "\n" + "\n public static void writeXmlShort(XmlOutputFilter xos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n xos.openElement(EL_CLASS_TAG);" + body_part_short + "\n xos.closeElement();" + "\n } // end of writeXml" + "\n" + "\n public " + streamer_class_name + "(" + values_class_name + " obj) {" + "\n values_ = obj;" + "\n } // end of ctor" + "\n"); String xml_bit = addXmlFunctions(streamer_class_name, values_class_name, end_elem_needs_catch, end_elems, f_reader); String close = "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"; return sb.toString() + xml_bit + close; } Code Sample 2: public static boolean filecopy(final File source, final File target) { boolean out = false; if (source.isDirectory() || !source.exists() || target.isDirectory() || source.equals(target)) return false; try { target.getParentFile().mkdirs(); target.createNewFile(); FileChannel sourceChannel = new FileInputStream(source).getChannel(); try { FileChannel targetChannel = new FileOutputStream(target).getChannel(); try { targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); out = true; } finally { targetChannel.close(); } } finally { sourceChannel.close(); } } catch (IOException e) { out = false; } return out; }
00
Code Sample 1: public boolean updatenum(int num, String pid) { boolean flag = false; Connection conn = null; PreparedStatement pm = null; try { conn = Pool.getConnection(); conn.setAutoCommit(false); pm = conn.prepareStatement("update addwuliao set innum=? where pid=?"); pm.setInt(1, num); pm.setString(2, pid); int a = pm.executeUpdate(); if (a == 0) { flag = false; } else { flag = true; } conn.commit(); Pool.close(pm); Pool.close(conn); } catch (Exception e) { e.printStackTrace(); flag = false; try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } Pool.close(pm); Pool.close(conn); } finally { Pool.close(pm); Pool.close(conn); } return flag; } Code Sample 2: private void openConnection() throws IOException { connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml"); }
11
Code Sample 1: 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(); } Code Sample 2: private void copy(FileInfo inputFile, FileInfo outputFile) { try { FileReader in = new FileReader(inputFile.file); FileWriter out = new FileWriter(outputFile.file); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); outputFile.file.setLastModified(inputFile.lastModified); } catch (IOException e) { } }
11
Code Sample 1: @Test public void testWriteModel() { Model model = new Model(); model.setName("MY_MODEL1"); Stereotype st1 = new Stereotype(); st1.setName("Pirulito1"); PackageObject p1 = new PackageObject("p1"); ClassType type1 = new ClassType("Class1"); type1.setStereotype(st1); type1.addMethod(new Method("doSomething")); p1.add(type1); ClassType type2 = new ClassType("Class2"); Method m2 = new Method("doSomethingElse"); m2.setType(type1); type2.addMethod(m2); p1.add(type2); Generalization g = new Generalization(); g.setSource(type1); g.setTarget(type1); p1.add(g); model.add(p1); ModelWriter writer = new ModelWriter(); try { File modelFile = new File("target", "test.model"); writer.write(model, modelFile); File xmlFile = new File("target", "test.xml"); xmlFile.createNewFile(); IOUtils.copy(new GZIPInputStream(new FileInputStream(modelFile)), new FileOutputStream(xmlFile)); } catch (IOException e) { log.error(e.getMessage(), e); Assert.fail(e.getMessage()); } } Code Sample 2: private boolean _copyPath(String source, String destination, Object handler) { try { FileInputStream fis = new FileInputStream(_fullPathForPath(source)); FileOutputStream fos = new FileOutputStream(_fullPathForPath(destination)); byte[] buffer = new byte[fis.available()]; int read; for (read = fis.read(buffer); read >= 0; read = fis.read(buffer)) { fos.write(buffer, 0, read); } fis.close(); fos.close(); return true; } catch (IOException ioe) { ioe.printStackTrace(); return false; } }
11
Code Sample 1: @SuppressWarnings("unchecked") @Override public synchronized void drop(DropTargetDropEvent arg0) { Helper.log().debug("Dropped"); Transferable t = arg0.getTransferable(); try { arg0.acceptDrop(arg0.getDropAction()); List<File> filelist = (List<File>) t.getTransferData(t.getTransferDataFlavors()[0]); for (File file : filelist) { Helper.log().debug(file.getAbsolutePath()); if (file.getName().toLowerCase().contains(".lnk")) { Helper.log().debug(file.getName() + " is a link"); File target = new File(rp.getRoot().getFullPath() + "/" + file.getName()); Helper.log().debug("I have opened the mayor at " + target.getAbsolutePath()); FileOutputStream fo = new FileOutputStream(target); FileInputStream fi = new FileInputStream(file); int i = 0; while (fi.available() > 0) { fo.write(fi.read()); System.out.print("."); i++; } Helper.log().debug(i + " bytes have been written to " + target.getAbsolutePath()); fo.close(); fi.close(); } } rp.redraw(); } catch (Throwable tr) { tr.printStackTrace(); } Helper.log().debug(arg0.getSource().toString()); } Code Sample 2: public static void copyFile(File in, File out) throws Exception { Permissions before = getFilePermissons(in); FileChannel inFile = new FileInputStream(in).getChannel(); FileChannel outFile = new FileOutputStream(out).getChannel(); inFile.transferTo(0, inFile.size(), outFile); inFile.close(); outFile.close(); setFilePermissions(out, before); }
00
Code Sample 1: @SuppressWarnings("unchecked") private final D loadMeta(URL url) throws IOException { SAXParser saxParser; try { saxParser = SAX_PARSER_FACTORY.newSAXParser(); } catch (ParserConfigurationException e) { throw new Error(e); } catch (SAXException e) { throw new Error(e); } try { saxParser.setProperty("http://xml.org/sax/features/validation", false); } catch (SAXNotRecognizedException e) { e.printStackTrace(); } catch (SAXNotSupportedException e) { e.printStackTrace(); } MetaParser handler = new MetaParser(); try { saxParser.parse(url.openStream(), handler); } catch (SAXException e) { throw new ParsingException(e); } return ((D) handler.getMetaData()); } Code Sample 2: void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } }
00
Code Sample 1: public void run() { Thread.currentThread().setName("zhongwen.com watcher"); String url = getURL(); try { while (m_shouldBeRunning) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream(), "ISO8859_1")); String line; Vector chatLines = new Vector(); boolean startGrabbing = false; while ((line = reader.readLine()) != null) { if (line.indexOf("</style>") >= 0) { startGrabbing = true; } else if (startGrabbing) { if (line.equals(m_mostRecentKnownLine)) { break; } chatLines.addElement(line); } } reader.close(); for (int i = chatLines.size() - 1; i >= 0; --i) { String chatLine = (String) chatLines.elementAt(i); m_mostRecentKnownLine = chatLine; if (chatLine.indexOf(":") >= 0) { String from = chatLine.substring(0, chatLine.indexOf(":")); String message = stripTags(chatLine.substring(chatLine.indexOf(":"))); m_source.pushMessage(new ZhongWenMessage(m_source, from, message)); } else { m_source.pushMessage(new ZhongWenMessage(m_source, null, stripTags(chatLine))); } } Thread.sleep(SLEEP_TIME); } catch (InterruptedIOException e) { } catch (InterruptedException e) { } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RuntimeException e) { m_source.disconnect(); throw e; } catch (Error e) { m_source.disconnect(); throw e; } } Code Sample 2: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) throw new IOException("Destination '" + destFile + "' exists but is a directory"); FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); if (preserveFileDate) destFile.setLastModified(srcFile.lastModified()); }
11
Code Sample 1: public boolean excuteBackup(String backupOrginlDrctry, String targetFileNm, String archiveFormat) throws JobExecutionException { File targetFile = new File(targetFileNm); File srcFile = new File(backupOrginlDrctry); if (!srcFile.exists()) { log.error("백업원본디렉토리[" + srcFile.getAbsolutePath() + "]가 존재하지 않습니다."); throw new JobExecutionException("백업원본디렉토리[" + srcFile.getAbsolutePath() + "]가 존재하지 않습니다."); } if (srcFile.isFile()) { log.error("백업원본디렉토리[" + srcFile.getAbsolutePath() + "]가 파일입니다. 디렉토리명을 지정해야 합니다. "); throw new JobExecutionException("백업원본디렉토리[" + srcFile.getAbsolutePath() + "]가 파일입니다. 디렉토리명을 지정해야 합니다. "); } boolean result = false; FileInputStream finput = null; FileOutputStream fosOutput = null; ArchiveOutputStream aosOutput = null; ArchiveEntry entry = null; try { log.debug("charter set : " + Charset.defaultCharset().name()); fosOutput = new FileOutputStream(targetFile); aosOutput = new ArchiveStreamFactory().createArchiveOutputStream(archiveFormat, fosOutput); if (ArchiveStreamFactory.TAR.equals(archiveFormat)) { ((TarArchiveOutputStream) aosOutput).setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); } File[] fileArr = srcFile.listFiles(); ArrayList list = EgovFileTool.getSubFilesByAll(fileArr); for (int i = 0; i < list.size(); i++) { File sfile = new File((String) list.get(i)); finput = new FileInputStream(sfile); if (ArchiveStreamFactory.TAR.equals(archiveFormat)) { entry = new TarArchiveEntry(sfile, new String(sfile.getAbsolutePath().getBytes(Charset.defaultCharset().name()), "8859_1")); ((TarArchiveEntry) entry).setSize(sfile.length()); } else { entry = new ZipArchiveEntry(sfile.getAbsolutePath()); ((ZipArchiveEntry) entry).setSize(sfile.length()); } aosOutput.putArchiveEntry(entry); IOUtils.copy(finput, aosOutput); aosOutput.closeArchiveEntry(); finput.close(); result = true; } aosOutput.close(); } catch (Exception e) { log.error("백업화일생성중 에러가 발생했습니다. 에러 : " + e.getMessage()); log.debug(e); result = false; throw new JobExecutionException("백업화일생성중 에러가 발생했습니다.", e); } finally { try { if (finput != null) finput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (aosOutput != null) aosOutput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (fosOutput != null) fosOutput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (result == false) targetFile.delete(); } catch (Exception e2) { log.error("IGNORE:", e2); } } return result; } Code Sample 2: public static void writeToFile(InputStream input, File file, ProgressListener listener, long length) { OutputStream output = null; try { output = new CountingOutputStream(new FileOutputStream(file), listener, length); IOUtils.copy(input, output); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } }
00
Code Sample 1: public static void fileCopy(File sourceFile, File destFile) throws IOException { FileChannel source = null; FileChannel destination = null; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(sourceFile); fos = new FileOutputStream(destFile); source = fis.getChannel(); destination = fos.getChannel(); destination.transferFrom(source, 0, source.size()); } finally { fis.close(); fos.close(); if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public void testSimpleHttpPostsHTTP10() throws Exception { int reqNo = 20; Random rnd = new Random(); List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(false); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); this.client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); assertEquals(HttpVersion.HTTP_1_0, response.getStatusLine().getProtocolVersion()); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } }
00
Code Sample 1: @Override public void configure() { initResouce(); if (this.locale == null) { this.locale = Locale.getDefault(); } InputStream[] ins = new InputStream[getResourceList().size()]; try { int i = 0; for (URL url : getResourceList()) { ins[i++] = url.openStream(); } this.resources = new ValidatorResources(ins); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (SAXException e) { e.printStackTrace(); throw new RuntimeException(e); } } Code Sample 2: private static LaunchablePlugin[] findLaunchablePlugins(LoggerChannelListener listener) { List res = new ArrayList(); File app_dir = getApplicationFile("plugins"); if (!(app_dir.exists()) && app_dir.isDirectory()) { listener.messageLogged(LoggerChannel.LT_ERROR, "Application dir '" + app_dir + "' not found"); return (new LaunchablePlugin[0]); } File[] plugins = app_dir.listFiles(); if (plugins == null || plugins.length == 0) { listener.messageLogged(LoggerChannel.LT_ERROR, "Application dir '" + app_dir + "' empty"); return (new LaunchablePlugin[0]); } for (int i = 0; i < plugins.length; i++) { File plugin_dir = plugins[i]; if (!plugin_dir.isDirectory()) { continue; } try { ClassLoader classLoader = PluginLauncherImpl.class.getClassLoader(); ClassLoader root_cl = classLoader; File[] contents = plugin_dir.listFiles(); if (contents == null || contents.length == 0) { continue; } String[] plugin_version = { null }; String[] plugin_id = { null }; contents = getHighestJarVersions(contents, plugin_version, plugin_id, true); for (int j = 0; j < contents.length; j++) { classLoader = addFileToClassPath(root_cl, classLoader, contents[j]); } Properties props = new Properties(); File properties_file = new File(plugin_dir, "plugin.properties"); if (properties_file.exists()) { FileInputStream fis = null; try { fis = new FileInputStream(properties_file); props.load(fis); } finally { if (fis != null) { fis.close(); } } } else { if (classLoader instanceof URLClassLoader) { URLClassLoader current = (URLClassLoader) classLoader; URL url = current.findResource("plugin.properties"); if (url != null) { props.load(url.openStream()); } } } String plugin_class = (String) props.get("plugin.class"); if (plugin_class == null || plugin_class.indexOf(';') != -1) { continue; } Class c = classLoader.loadClass(plugin_class); Plugin plugin = (Plugin) c.newInstance(); if (plugin instanceof LaunchablePlugin) { preloaded_plugins.put(plugin_class, plugin); res.add(plugin); } } catch (Throwable e) { listener.messageLogged("Load of plugin in '" + plugin_dir + "' fails", e); } } LaunchablePlugin[] x = new LaunchablePlugin[res.size()]; res.toArray(x); return (x); }
11
Code Sample 1: 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; } Code Sample 2: public static final void copyFile(File source, File target) { try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (java.io.IOException e) { } }
00
Code Sample 1: @SuppressWarnings("static-access") public FastCollection<String> load(Link link) { URL url = null; FastCollection<String> links = new FastList<String>(); FTPClient ftp = null; try { String address = link.getURI(); address = JGetFileUtils.removeTrailingString(address, "/"); url = new URL(address); host = url.getHost(); String folder = url.getPath(); logger.info("Traversing: " + address); ftp = new FTPClient(host); if (!ftp.connected()) { ftp.connect(); } ftp.login("anonymous", "me@mymail.com"); logger.info("Connected to " + host + "."); logger.debug("changing dir to " + folder); ftp.chdir(folder); String[] files = ftp.dir(); for (String file : files) { links.add(address + "/" + file); } } catch (Exception e) { logger.error(e.getMessage()); logger.debug(e.getStackTrace()); } finally { try { ftp.quit(); } catch (Exception e) { logger.error("Failed to logout or disconnect from the ftp server: ftp://" + host); } } return links; } Code Sample 2: private static void copyFile(File sourceFile, File targetFile) throws FileSaveException { try { FileInputStream inputStream = new FileInputStream(sourceFile); FileOutputStream outputStream = new FileOutputStream(targetFile); FileChannel readableChannel = inputStream.getChannel(); FileChannel writableChannel = outputStream.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); inputStream.close(); outputStream.close(); } catch (IOException ioException) { String exceptionMessage = "An error occurred when copying from the file \"" + sourceFile.getAbsolutePath() + "\" to the file \"" + targetFile.getAbsolutePath() + "\"."; throw new FileSaveException(exceptionMessage, ioException); } }
11
Code Sample 1: public Atividade insertAtividade(Atividade atividade) throws SQLException { Connection conn = null; String insert = "insert into Atividade (idatividade, requerente_idrequerente, datacriacao, datatermino, valor, tipoatividade, descricao, fase_idfase, estado) " + "values " + "(nextval('seq_atividade'), " + atividade.getRequerente().getIdRequerente() + ", " + "'" + atividade.getDataCriacao() + "', '" + atividade.getDataTermino() + "', '" + atividade.getValor() + "', '" + atividade.getTipoAtividade().getIdTipoAtividade() + "', '" + atividade.getDescricao() + "', " + atividade.getFaseIdFase() + ", " + atividade.getEstado() + ")"; try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); if (result == 1) { String sqlSelect = "select last_value from seq_atividade"; ResultSet rs = stmt.executeQuery(sqlSelect); while (rs.next()) { atividade.setIdAtividade(rs.getInt("last_value")); } } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } return null; } Code Sample 2: public void unlock(String oid, String key) throws PersisterException { String lock = getLock(oid); if (lock == null) { throw new PersisterException("Object does not exist: OID = " + oid); } else if (!NULL.equals(lock) && (!lock.equals(key))) { throw new PersisterException("The object is currently locked with another key: OID = " + oid + ", LOCK = " + lock + ", KEY = " + key); } Connection conn = null; PreparedStatement ps = null; try { conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("update " + _table_name + " set " + _key_col + " = NULL, " + _ts_col + " = ? where " + _oid_col + " = ?"); ps.setLong(1, System.currentTimeMillis()); ps.setString(2, oid); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to unlock object: OID = " + oid + ", KEY = " + key, th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } }
00
Code Sample 1: private String encryptPassword(String password) { String result = password; if (password != null) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); result = hash.toString(16); if ((result.length() % 2) != 0) { result = "0" + result; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); getLogger().error("Cannot generate MD5", e); } } return result; } Code Sample 2: public static boolean insert(final Cargo cargo) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into cargo (nome) values (?)"; pst = c.prepareStatement(sql); pst.setString(1, cargo.getNome()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { e1.printStackTrace(); } System.out.println("[CargoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
11
Code Sample 1: public File getFile(String file) { DirProperties dp; List files = new ArrayList(); for (int i = 0; i < locs.size(); i++) { dp = (DirProperties) locs.get(i); if (dp.isReadable()) { File g = new File(dp.getLocation() + slash() + file); if (g.exists()) files.add(g); } } if (files.size() == 0) { throw new UnsupportedOperationException("at least one DirProperty should get 'read=true'"); } else if (files.size() == 1) { return (File) files.get(0); } else { File fromFile = (File) files.get(files.size() - 2); File toFile = (File) files.get(files.size() - 1); byte reading[] = new byte[2024]; try { FileInputStream stream = new FileInputStream(fromFile); FileOutputStream outStr = new FileOutputStream(toFile); while (stream.read(reading) != -1) { outStr.write(reading); } } catch (FileNotFoundException ex) { getLogger().severe("FileNotFound: while copying from " + fromFile + " to " + toFile); } catch (IOException ex) { getLogger().severe("IOException: while copying from " + fromFile + " to " + toFile); } return toFile; } } Code Sample 2: private void putAlgosFromJar(File jarfile, AlgoDir dir, Model model) throws FileNotFoundException, IOException { URLClassLoader urlLoader = new URLClassLoader(new URL[] { jarfile.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(jarfile)); JarEntry entry = jis.getNextJarEntry(); String name = null; String tmpdir = System.getProperty("user.dir") + File.separator + Application.getProperty("dir.tmp") + File.separator; byte[] buffer = new byte[1000]; while (entry != null) { name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); try { Class<?> cls = urlLoader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && ((cls.getModifiers() & Modifier.ABSTRACT) == 0)) { dir.addAlgorithm(cls); model.putClass(cls.getName(), cls); } else if (ISerializable.class.isAssignableFrom(cls)) { model.putClass(cls.getName(), cls); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else if (Constants.isAllowedImageType(name)) { int lastSep = name.lastIndexOf("/"); if (lastSep != -1) { String dirs = tmpdir + name.substring(0, lastSep); File d = new File(dirs); if (!d.exists()) d.mkdirs(); } String filename = tmpdir + name; File f = new File(filename); if (!f.exists()) { f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); int read = -1; while ((read = jis.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.close(); } } entry = jis.getNextJarEntry(); } }
11
Code Sample 1: public static String getPasswordHash(String password) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } md.update(password.getBytes()); byte[] digest = md.digest(); BigInteger i = new BigInteger(1, digest); String hash = i.toString(16); while (hash.length() < 32) { hash = "0" + hash; } return hash; } Code Sample 2: static String getMD5Sum(String source) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(source.getBytes()); byte[] md5sum = digest.digest(); BigInteger bigInt = new BigInteger(1, md5sum); return bigInt.toString(16); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("MD5 algorithm seems to not be supported. This is a requirement!"); } }
11
Code Sample 1: private void setInlineXML(Entry entry, DatastreamXMLMetadata ds) throws UnsupportedEncodingException, StreamIOException { String content; if (m_obj.hasContentModel(Models.SERVICE_DEPLOYMENT_3_0) && (ds.DatastreamID.equals("SERVICE-PROFILE") || ds.DatastreamID.equals("WSDL"))) { content = DOTranslationUtility.normalizeInlineXML(new String(ds.xmlContent, m_encoding), m_transContext); } else { content = new String(ds.xmlContent, m_encoding); } if (m_format.equals(ATOM_ZIP1_1)) { String name = ds.DSVersionID + ".xml"; try { m_zout.putNextEntry(new ZipEntry(name)); InputStream is = new ByteArrayInputStream(content.getBytes(m_encoding)); IOUtils.copy(is, m_zout); m_zout.closeEntry(); is.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); entry.setSummary(ds.DSVersionID); entry.setContent(iri, ds.DSMIME); } else { entry.setContent(content, ds.DSMIME); } } Code Sample 2: private FileLog(LOG_LEVEL displayLogLevel, LOG_LEVEL logLevel, String logPath) { this.logLevel = logLevel; this.displayLogLevel = displayLogLevel; if (null != logPath) { logFile = new File(logPath, "current.log"); log(LOG_LEVEL.DEBUG, "FileLog", "Initialising logfile " + logFile.getAbsolutePath() + " ."); try { if (logFile.exists()) { if (!logFile.renameTo(new File(logPath, System.currentTimeMillis() + ".log"))) { File newFile = new File(logPath, System.currentTimeMillis() + ".log"); if (newFile.exists()) { log(LOG_LEVEL.WARN, "FileLog", "The file (" + newFile.getAbsolutePath() + newFile.getName() + ") already exists, will overwrite it."); newFile.delete(); } newFile.createNewFile(); FileInputStream inStream = new FileInputStream(logFile); FileOutputStream outStream = new FileOutputStream(newFile); byte buffer[] = null; int offSet = 0; while (inStream.read(buffer, offSet, 2048) != -1) { outStream.write(buffer); offSet += 2048; } inStream.close(); outStream.close(); logFile.delete(); logFile = new File(logPath, "current.log"); } } logFile.createNewFile(); } catch (IOException e) { logFile = null; } } else { logFile = null; } }
11
Code Sample 1: public String upload() throws IOException { int idx = docIndex.incrementAndGet(); String tmpName = "namefinder/doc_" + idx + "__" + fileFileName; File tmpFile = tmpFile(tmpName); if (tmpFile.exists()) { org.apache.commons.io.FileUtils.deleteQuietly(tmpFile); } org.apache.commons.io.FileUtils.touch(tmpFile); InputStream fileStream = new FileInputStream(file); OutputStream bos = new FileOutputStream(tmpFile); IOUtils.copy(fileStream, bos); bos.close(); fileStream.close(); return tmpUrl(tmpName); } Code Sample 2: private void collectImageFile(@NotNull final Progress progress, @NotNull final File collectedDirectory) throws IOException { final File file = new File(collectedDirectory, ActionBuilderUtils.getString(ACTION_BUILDER, "configSource.image.name")); final FileOutputStream fos = new FileOutputStream(file); try { final FileChannel outChannel = fos.getChannel(); try { final int numOfFaceObjects = faceObjects.size(); progress.setLabel(ActionBuilderUtils.getString(ACTION_BUILDER, "archCollectImages"), numOfFaceObjects); final ByteBuffer byteBuffer = ByteBuffer.allocate(1024); final Charset charset = Charset.forName("ISO-8859-1"); int i = 0; for (final FaceObject faceObject : faceObjects) { final String face = faceObject.getFaceName(); final String path = archFaceProvider.getFilename(face); try { final FileInputStream fin = new FileInputStream(path); try { final FileChannel inChannel = fin.getChannel(); final long imageSize = inChannel.size(); byteBuffer.clear(); byteBuffer.put(("IMAGE " + (faceObjects.isIncludeFaceNumbers() ? i + " " : "") + imageSize + " " + face + "\n").getBytes(charset)); byteBuffer.flip(); outChannel.write(byteBuffer); inChannel.transferTo(0L, imageSize, outChannel); } finally { fin.close(); } } catch (final FileNotFoundException ignored) { ACTION_BUILDER.showMessageDialog(progress.getParentComponent(), "archCollectErrorFileNotFound", path); return; } catch (final IOException e) { ACTION_BUILDER.showMessageDialog(progress.getParentComponent(), "archCollectErrorIOException", path, e); return; } if (i++ % 100 == 0) { progress.setValue(i); } } progress.setValue(faceObjects.size()); } finally { outChannel.close(); } } finally { fos.close(); } }
00
Code Sample 1: public static void main(String[] args) throws IOException { File inputFile = new File("D:/farrago.txt"); File outputFile = new File("D:/outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public String encryptStringWithKey(String to_be_encrypted, String aKey) { String encrypted_value = ""; char xdigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException exc) { globalErrorDictionary.takeValueForKey(("Security package does not contain appropriate algorithm"), ("Security package does not contain appropriate algorithm")); log.error("Security package does not contain appropriate algorithm"); return encrypted_value; } if (to_be_encrypted != null) { byte digest[]; byte fudge_constant[]; try { fudge_constant = ("X#@!").getBytes("UTF8"); } catch (UnsupportedEncodingException uee) { fudge_constant = ("X#@!").getBytes(); } byte fudgetoo_part[] = { (byte) xdigit[(int) (MSiteConfig.myrand() % 16)], (byte) xdigit[(int) (MSiteConfig.myrand() % 16)], (byte) xdigit[(int) (MSiteConfig.myrand() % 16)], (byte) xdigit[(int) (MSiteConfig.myrand() % 16)] }; int i = 0; if (aKey != null) { try { fudgetoo_part = aKey.getBytes("UTF8"); } catch (UnsupportedEncodingException uee) { fudgetoo_part = aKey.getBytes(); } } messageDigest.update(fudge_constant); try { messageDigest.update(to_be_encrypted.getBytes("UTF8")); } catch (UnsupportedEncodingException uee) { messageDigest.update(to_be_encrypted.getBytes()); } messageDigest.update(fudgetoo_part); digest = messageDigest.digest(); encrypted_value = new String(fudgetoo_part); for (i = 0; i < digest.length; i++) { int mashed; char temp[] = new char[2]; if (digest[i] < 0) { mashed = 127 + (-1 * digest[i]); } else { mashed = digest[i]; } temp[0] = xdigit[mashed / 16]; temp[1] = xdigit[mashed % 16]; encrypted_value = encrypted_value + (new String(temp)); } } return encrypted_value; }
11
Code Sample 1: public static synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: protected String getGraphPath(String name) throws ServletException { String hash; try { MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm); md.update(name.getBytes()); hash = bytesToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new ServletException("NoSuchAlgorithmException while " + "attempting to hash file name: " + e); } File tempDir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir"); return tempDir.getAbsolutePath() + File.separatorChar + hash; }
11
Code Sample 1: public static String encodePassword(String password) { try { MessageDigest messageDiegest = MessageDigest.getInstance("SHA-1"); messageDiegest.update(password.getBytes("UTF-8")); return Base64.encodeToString(messageDiegest.digest(), false); } catch (NoSuchAlgorithmException e) { log.error("Exception while encoding password"); throw new Error(e); } catch (UnsupportedEncodingException e) { log.error("Exception while encoding password"); throw new Error(e); } } Code Sample 2: @SuppressWarnings("unused") private static int chkPasswd(final String sInputPwd, final String sSshaPwd) { assert sInputPwd != null; assert sSshaPwd != null; int r = ERR_LOGIN_ACCOUNT; try { BASE64Decoder decoder = new BASE64Decoder(); byte[] ba = decoder.decodeBuffer(sSshaPwd); assert ba.length >= FIXED_HASH_SIZE; byte[] hash = new byte[FIXED_HASH_SIZE]; byte[] salt = new byte[FIXED_SALT_SIZE]; System.arraycopy(ba, 0, hash, 0, FIXED_HASH_SIZE); System.arraycopy(ba, FIXED_HASH_SIZE, salt, 0, FIXED_SALT_SIZE); MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(sInputPwd.getBytes()); md.update(salt); byte[] baPwdHash = md.digest(); if (MessageDigest.isEqual(hash, baPwdHash)) { r = ERR_LOGIN_OK; } } catch (Exception exc) { exc.printStackTrace(); } return r; }
11
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.InputStream(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 { closeQuietly(in); closeQuietly(out); } return success; } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public void deleteUser(String userID) throws XregistryException { try { userID = Utils.canonicalizeDN(userID); Connection connection = context.createConnection(); connection.setAutoCommit(false); try { PreparedStatement statement1 = connection.prepareStatement(DELETE_USER_SQL_MAIN); statement1.setString(1, userID); statement1.executeUpdate(); PreparedStatement statement2 = connection.prepareStatement(DELETE_USER_SQL_DEPEND); statement2.setString(1, userID); statement2.executeUpdate(); connection.commit(); Collection<Group> groupList = groups.values(); for (Group group : groupList) { group.removeUser(userID); } log.info("Delete User " + userID); } catch (SQLException e) { connection.rollback(); throw new XregistryException(e); } finally { context.closeConnection(connection); } } catch (SQLException e) { throw new XregistryException(e); } } Code Sample 2: private long newIndex(String indexname) { Connection con = null; ResultSet rs = null; Statement stm = null; StringBuffer sql = new StringBuffer(); indexname = indexname.trim().toUpperCase(); try { long index = -1; synchronized (FormularContextPersistensImpl.class) { con = getConnection(); stm = con.createStatement(); if ((con != null) && (stm != null)) { con.setAutoCommit(false); sql = new StringBuffer(); sql.append("SELECT * FROM INDX_EC WHERE INDX_NAME='"); sql.append(indexname); sql.append("' FOR UPDATE"); rs = stm.executeQuery(sql.toString()); if ((rs != null) && rs.next()) { sql = new StringBuffer(); index = rs.getLong("INDX_WERT") + 1; sql.append("UPDATE INDX_EC SET INDX_WERT = "); sql.append(index); sql.append(" WHERE INDX_NAME='"); sql.append(indexname); sql.append("'"); rs.close(); rs = null; if (stm.executeUpdate(sql.toString()) == 1) { con.commit(); } else { con.rollback(); index = -1; } } else { sql = new StringBuffer(); sql.append("INSERT INTO INDX_EC (INDX_NAME, INDX_WERT) VALUES('"); sql.append(indexname); sql.append("', "); sql.append(1); sql.append(")"); if (stm.executeUpdate(sql.toString()) == 1) { con.commit(); index = 1; } else { con.rollback(); } } } } return index; } catch (Exception e) { Log.getLogger().error("Error during execute SQL-Statement: " + sql.toString(), e); return -1; } finally { if (rs != null) { try { rs.close(); } catch (Exception ignore) { } } if (stm != null) { try { stm.close(); } catch (Exception ignore) { } } if (con != null) { try { con.close(); } catch (Exception ignore) { } } } }
11
Code Sample 1: public void getDataFiles(String server, String username, String password, String folder, String destinationFolder) { try { FTPClient ftp = new FTPClient(); ftp.connect(server); ftp.login(username, password); System.out.println("Connected to " + server + "."); System.out.print(ftp.getReplyString()); ftp.enterLocalActiveMode(); ftp.changeWorkingDirectory(folder); System.out.println("Changed to " + folder); FTPFile[] files = ftp.listFiles(); System.out.println("Number of files in dir: " + files.length); for (int i = 0; i < files.length; i++) { getFiles(ftp, files[i], destinationFolder); } ftp.logout(); ftp.disconnect(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private FTPClient getFTPConnection(String strUser, String strPassword, String strServer, boolean binaryTransfer, String connectionNote, boolean passiveMode) { FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(strServer); ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Connected to " + strServer + ", " + connectionNote); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP server refused connection."); return null; } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { return null; } } ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP Could not connect to server."); ResourcePool.LogException(e, this); return null; } try { if (!ftp.login(strUser, strPassword)) { ftp.logout(); ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP login failed."); return null; } ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Remote system is " + ftp.getSystemName() + ", " + connectionNote); if (binaryTransfer) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } else { ftp.setFileType(FTP.ASCII_FILE_TYPE); } if (passiveMode) { ftp.enterLocalPassiveMode(); } else { ftp.enterLocalActiveMode(); } } catch (FTPConnectionClosedException e) { ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "Server closed connection."); ResourcePool.LogException(e, this); return null; } catch (IOException e) { ResourcePool.LogException(e, this); return null; } return ftp; }
00
Code Sample 1: public void download() throws IOException { new File(file.getPath().substring(0, file.getPath().lastIndexOf(File.separator))).mkdirs(); URLConnection urlConnection = url.openConnection(); size = urlConnection.getContentLength(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file)); InputStream inputStream = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int numRead; fetchedSize = 0; date = urlConnection.getLastModified(); while (!failed && (numRead = inputStream.read(buffer)) != -1) { if (failed) { throw new IOException("Download manually stopped"); } bufferedOutputStream.write(buffer, 0, numRead); fetchedSize += numRead; for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).downloadProgress(this); } } } inputStream.close(); bufferedOutputStream.close(); if (file.toString().endsWith(".gz") || file.toString().endsWith(".gzip")) { for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).uncompressingProgress(this); } } try { GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(file)); String fileName = file.toString().substring(0, file.toString().lastIndexOf(".")); OutputStream outputStream = new FileOutputStream(fileName); byte[] unpackBuffer = new byte[1024]; int length; while ((length = gzipInputStream.read(unpackBuffer)) > 0) { outputStream.write(unpackBuffer, 0, length); } gzipInputStream.close(); outputStream.close(); file.delete(); file = new File(fileName); file.setLastModified(date); failed = false; finished = true; for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).uncompressingFinished(this); } } for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).downloadFinished(this); } } } catch (IOException ioException) { file.delete(); failed = true; for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).exceptionWasThrown(this, ioException); } } } try { Runtime.getRuntime().exec("chmod 777 " + file.getCanonicalPath()); } catch (Exception exception) { } } else { failed = false; finished = true; file.setLastModified(date); for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).downloadFinished(this); } } } } Code Sample 2: private File getTestFile() { final URL url = TestCrueLOG.class.getResource(FICHIER_TEST_XML); final File ctfaFile = new File(createTempDir(), "resultat.rtfa.xml"); try { CtuluLibFile.copyStream(url.openStream(), new FileOutputStream(ctfaFile), true, true); } catch (Exception e) { e.printStackTrace(); fail(); } return ctfaFile; }
11
Code Sample 1: protected synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws ApplicationException { PreparedStatement preStat = null; StringBuffer sqlStat = new StringBuffer(); DmsRelationalWord tmpDmsRelationalWord = (DmsRelationalWord) ((DmsRelationalWord) obj).clone(); synchronized (dbConn) { try { Integer nextID = getNextPrimaryID(); Timestamp currTime = Utility.getCurrentTimestamp(); sqlStat.append("INSERT "); sqlStat.append("INTO DMS_RELATIONAL_WORD(ID, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE, WORD, PARENT_ID, TYPE) "); sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "); preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); setPrepareStatement(preStat, 1, nextID); setPrepareStatement(preStat, 2, tmpDmsRelationalWord.getRecordStatus()); setPrepareStatement(preStat, 3, new Integer(0)); setPrepareStatement(preStat, 4, tmpDmsRelationalWord.getCreatorID()); setPrepareStatement(preStat, 5, currTime); setPrepareStatement(preStat, 6, tmpDmsRelationalWord.getUpdaterID()); setPrepareStatement(preStat, 7, currTime); if (tmpDmsRelationalWord.getWord() == null || "".equals(tmpDmsRelationalWord.getWord().trim())) { return null; } setPrepareStatement(preStat, 8, tmpDmsRelationalWord.getWord()); setPrepareStatement(preStat, 9, tmpDmsRelationalWord.getParentID()); setPrepareStatement(preStat, 10, tmpDmsRelationalWord.getType()); preStat.executeUpdate(); tmpDmsRelationalWord.setID(nextID); tmpDmsRelationalWord.setCreatorID(tmpDmsRelationalWord.getCreatorID()); tmpDmsRelationalWord.setCreateDate(currTime); tmpDmsRelationalWord.setUpdaterID(tmpDmsRelationalWord.getUpdaterID()); tmpDmsRelationalWord.setUpdateDate(currTime); tmpDmsRelationalWord.setUpdateCount(new Integer(0)); tmpDmsRelationalWord.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsRelationalWord.getCreatorID())); tmpDmsRelationalWord.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsRelationalWord.getUpdaterID())); dbConn.commit(); return (tmpDmsRelationalWord); } catch (Exception e) { try { dbConn.rollback(); } catch (Exception ee) { } log.error(e, e); throw new ApplicationException(ErrorConstant.DB_INSERT_ERROR, e); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } } } Code Sample 2: @Override public synchronized void deleteHardDiskStatistics(String contextName, String path, Date dateFrom, Date dateTo) throws DatabaseException { final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); String queryString = "DELETE " + this.getHardDiskInvocationsSchemaAndTableName() + " FROM " + this.getHardDiskInvocationsSchemaAndTableName() + " INNER JOIN " + this.getHardDiskElementsSchemaAndTableName() + " ON " + this.getHardDiskElementsSchemaAndTableName() + ".element_id = " + this.getHardDiskInvocationsSchemaAndTableName() + ".element_id WHERE "; if (contextName != null) { queryString = queryString + " context_name LIKE ? AND "; } if (path != null) { queryString = queryString + " path LIKE ? AND "; } if (dateFrom != null) { queryString = queryString + " start_timestamp >= ? AND "; } if (dateTo != null) { queryString = queryString + " start_timestamp <= ? AND "; } queryString = DefaultDatabaseHandler.removeOrphanWhereAndAndFromSelect(queryString); final PreparedStatement preparedStatement = DebugPreparedStatement.prepareStatement(connection, queryString); int indexCounter = 1; if (contextName != null) { preparedStatement.setString(indexCounter, contextName); indexCounter = indexCounter + 1; } if (path != null) { preparedStatement.setString(indexCounter, path); indexCounter = indexCounter + 1; } if (dateFrom != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateFrom.getTime())); indexCounter = indexCounter + 1; } if (dateTo != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateTo.getTime())); indexCounter = indexCounter + 1; } preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error deleting disk statistics.", e); } finally { this.releaseConnection(connection); } }
11
Code Sample 1: public synchronized String encrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); } Code Sample 2: public static String generateDigest(String password, String saltHex, String alg) { try { MessageDigest sha = MessageDigest.getInstance(alg); byte[] salt = new byte[0]; if (saltHex != null) { salt = fromHex(saltHex); } String label = null; if (alg.startsWith("SHA")) { label = (salt.length <= 0) ? "{SHA}" : "{SSHA}"; } else if (alg.startsWith("MD5")) { label = (salt.length <= 0) ? "{MD5}" : "{SMD5}"; } sha.reset(); sha.update(password.getBytes()); sha.update(salt); byte[] pwhash = sha.digest(); StringBuffer digest = new StringBuffer(label); digest.append(Base64.encode(concatenate(pwhash, salt)).toCharArray()); return digest.toString(); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException("failed to find " + "algorithm for password hashing.", nsae); } }
11
Code Sample 1: public void performOk(final IProject project, final TomcatPropertyPage page) { page.setPropertyValue("tomcat.jdbc.driver", c_drivers.getText()); page.setPropertyValue("tomcat.jdbc.url", url.getText()); page.setPropertyValue("tomcat.jdbc.user", username.getText()); page.setPropertyValue("tomcat.jdbc.password", password.getText()); File lib = new File(page.tomcatHome.getText(), "lib"); if (!lib.exists()) { lib = new File(new File(page.tomcatHome.getText(), "common"), "lib"); if (!lib.exists()) { Logger.log(Logger.ERROR, "Not properly location of Tomcat Home at :: " + lib); throw new IllegalStateException("Not properly location of Tomcat Home"); } } final File conf = new File(page.tomcatHome.getText(), "conf/Catalina/localhost"); if (!conf.exists()) { final boolean create = NexOpenUIActivator.getDefault().getTomcatConfProperty(); if (create) { if (Logger.getLog().isDebugEnabled()) { Logger.getLog().debug("Create directory " + conf); } try { conf.mkdirs(); } catch (final SecurityException se) { Logger.getLog().error("Retrieved a Security exception creating " + conf, se); Logger.log(Logger.ERROR, "Not created " + conf + " directory. Not enough privilegies. Message :: " + se.getMessage()); } } } String str_driverLibrary = LIBRARIES.get(c_drivers.getText()); if ("<mysql_driver>".equals(str_driverLibrary)) { str_driverLibrary = NexOpenUIActivator.getDefault().getMySQLDriver(); } final File driverLibrary = new File(lib, str_driverLibrary); if (!driverLibrary.exists()) { InputStream driver = null; FileOutputStream fos = null; try { driver = AppServerPropertyPage.toInputStream(new Path("jdbc/" + str_driverLibrary)); fos = new FileOutputStream(driverLibrary); IOUtils.copy(driver, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy the driver jar file to Tomcat", e); } finally { try { if (driver != null) { driver.close(); driver = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } page.processTomcatCfg(c_drivers.getText(), url.getText(), username.getText(), password.getText()); } Code Sample 2: public void testStorageByteArray() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); { OutputStream output = r.getOutputStream(); output.write("This is an example".getBytes("UTF-8")); output.write(" and another one.".getBytes("UTF-8")); assertEquals("This is an example and another one.", r.getText()); } { InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); } { OutputStream output = r.getOutputStream(); output.write(" and another line".getBytes("UTF-8")); assertEquals("This is an example and another one. and another line", r.getText()); } { Writer output = r.getWriter(); output.write(" and write some more"); assertEquals("This is an example and another one. and another line and write some more", r.getText()); } { r.addText(" and even more."); assertEquals("This is an example and another one. and another line and write some more and even more.", r.getText()); } assertFalse(r.hasEnded()); r.setEndState(ResponseStateOk.getInstance()); assertTrue(r.hasEnded()); try { r.getOutputStream(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } try { r.getWriter(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } }
00
Code Sample 1: public void saveAs(File f) throws CoverException { FileOutputStream fw = null; BufferedInputStream in = null; try { HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setDoInput(true); in = new BufferedInputStream(httpConn.getInputStream()); f.delete(); fw = new FileOutputStream(f); int b; while ((b = in.read()) != -1) fw.write(b); fw.close(); in.close(); } catch (IOException e) { throw new CoverException(e.getMessage()); } finally { try { if (fw != null) fw.close(); if (in != null) in.close(); } catch (IOException ex) { System.err.println("Glurps this is severe: " + ex.getMessage()); } } } Code Sample 2: public void testJDBCSavepoints() throws Exception { String sql; String msg; int i; PreparedStatement ps; ResultSet rs; Savepoint sp1; Savepoint sp2; Savepoint sp3; Savepoint sp4; Savepoint sp5; Savepoint sp6; Savepoint sp7; int rowcount = 0; sql = "drop table t if exists"; stmt.executeUpdate(sql); sql = "create table t(id int, fn varchar, ln varchar, zip int)"; stmt.executeUpdate(sql); conn1.setAutoCommit(true); conn1.setAutoCommit(false); sql = "insert into t values(?,?,?,?)"; ps = conn1.prepareStatement(sql); ps.setString(2, "Mary"); ps.setString(3, "Peterson-Clancy"); i = 0; for (; i < 10; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp1 = conn1.setSavepoint("savepoint1"); for (; i < 20; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp2 = conn1.setSavepoint("savepoint2"); for (; i < 30; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp3 = conn1.setSavepoint("savepoint3"); for (; i < 40; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp4 = conn1.setSavepoint("savepoint4"); for (; i < 50; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp5 = conn1.setSavepoint("savepoint5"); sp6 = conn1.setSavepoint("savepoint6"); sp7 = conn1.setSavepoint("savepoint7"); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select count(*) from t value"; try { assertEquals(msg, 50, rowcount); } catch (Exception e) { } conn2.setAutoCommit(false); conn2.setSavepoint("savepoint1"); conn2.setSavepoint("savepoint2"); msg = "savepoint released succesfully on non-originating connection"; try { conn2.releaseSavepoint(sp2); assertTrue(msg, false); } catch (Exception e) { } try { conn2.rollback(sp1); msg = "succesful rollback to savepoint on " + "non-originating connection"; assertTrue(msg, false); } catch (Exception e) { } msg = "direct execution of <release savepoint> statement failed to " + "release JDBC-created SQL-savepoint with identical savepoint name"; try { conn2.createStatement().executeUpdate("release savepoint \"savepoint2\""); } catch (Exception e) { try { assertTrue(msg, false); } catch (Exception e2) { } } msg = "direct execution of <rollback to savepoint> statement failed to " + "roll back to existing JDBC-created SQL-savepoint with identical " + "savepoint name"; try { conn2.createStatement().executeUpdate("rollback to savepoint \"savepoint1\""); } catch (Exception e) { e.printStackTrace(); try { assertTrue(msg, false); } catch (Exception e2) { } } conn1.releaseSavepoint(sp6); msg = "savepoint released succesfully > 1 times"; try { conn1.releaseSavepoint(sp6); assertTrue(msg, false); } catch (Exception e) { } msg = "savepoint released successfully after preceding savepoint released"; try { conn1.releaseSavepoint(sp7); assertTrue(msg, false); } catch (Exception e) { } msg = "preceding same-point savepoint destroyed by following savepoint release"; try { conn1.releaseSavepoint(sp5); } catch (Exception e) { try { assertTrue(msg, false); } catch (Exception e2) { } } conn1.rollback(sp4); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select * rowcount after 50 inserts - 10 rolled back:"; try { assertEquals(msg, 40, rowcount); } catch (Exception e) { } msg = "savepoint rolled back succesfully > 1 times"; try { conn1.rollback(sp4); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(sp3); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select count(*) after 50 inserts - 20 rolled back:"; try { assertEquals(msg, 30, rowcount); } catch (Exception e) { } msg = "savepoint released succesfully after use in rollback"; try { conn1.releaseSavepoint(sp3); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(sp1); msg = "savepoint rolled back without raising an exception after " + "rollback to a preceeding savepoint"; try { conn1.rollback(sp2); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(); msg = "savepoint released succesfully when it should have been " + "destroyed by a full rollback"; try { conn1.releaseSavepoint(sp1); assertTrue(msg, false); } catch (Exception e) { } conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.rollback(); conn1.setAutoCommit(false); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); }
11
Code Sample 1: private static void addFileToZip(String path, String srcFile, ZipOutputStream zip, String prefix, String suffix) throws Exception { File folder = new File(srcFile); if (folder.isDirectory()) { addFolderToZip(path, srcFile, zip, prefix, suffix); } else { if (isFileNameMatch(folder.getName(), prefix, suffix)) { FileInputStream fis = new FileInputStream(srcFile); zip.putNextEntry(new ZipEntry(path + "/" + folder.getName())); IOUtils.copy(fis, zip); fis.close(); } } } Code Sample 2: private static void addFile(File file, ZipArchiveOutputStream zaos) throws IOException { String filename = null; filename = file.getName(); ZipArchiveEntry zae = new ZipArchiveEntry(filename); zae.setSize(file.length()); zaos.putArchiveEntry(zae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, zaos); zaos.closeArchiveEntry(); }
11
Code Sample 1: public static void main(String arg[]) { try { String readFile = arg[0]; String writeFile = arg[1]; java.io.FileInputStream ss = new java.io.FileInputStream(readFile); ManagedMemoryDataSource ms = new ManagedMemoryDataSource(ss, 1024 * 1024, "foo/data", true); javax.activation.DataHandler dh = new javax.activation.DataHandler(ms); java.io.InputStream is = dh.getInputStream(); java.io.FileOutputStream fo = new java.io.FileOutputStream(writeFile); byte[] buf = new byte[512]; int read = 0; do { read = is.read(buf); if (read > 0) { fo.write(buf, 0, read); } } while (read > -1); fo.close(); is.close(); } catch (java.lang.Exception e) { log.error(Messages.getMessage("exception00"), e); } } Code Sample 2: public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel source = null; FileChannel destination = null; try { source = (inStream = new FileInputStream(sourceFile)).getChannel(); destination = (outStream = new FileOutputStream(destFile)).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { closeIO(source); closeIO(inStream); closeIO(destination); closeIO(outStream); } }
00
Code Sample 1: public void beforeMethod(TestBase testBase) throws IOException { TFileFactory fileFactory = new TFileFactory(new InMemoryFileSystem()); ftpServer.cleanFileSystem(fileFactory); TDirectory rootDir = fileFactory.dir("/"); testBase.inject(rootDir); FTPClient ftpClient = new FTPClient(); ftpClient.connect("localhost", 8021); ftpClient.login("anonymous", "test@test.com"); testBase.inject(ftpClient); } Code Sample 2: public final Reader open(URL url) throws IOException { Reader ret = null; Charset cs = this.detectCodepage(url); if (cs != null) { ret = new InputStreamReader(new BufferedInputStream(url.openStream()), cs); } return ret; }
00
Code Sample 1: public void connectToUrl(String url_address) { message = new StringBuffer(""); try { URL url = new URL(url_address); try { HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(); httpsConnection.setDoOutput(false); httpsConnection.connect(); message.append("<BR>\n Connection Code:[" + httpsConnection.getResponseCode() + "]"); message.append("<BR>\n Response Message:[" + httpsConnection.getResponseMessage() + "]"); InputStreamReader insr = new InputStreamReader(httpsConnection.getInputStream()); BufferedReader in = new BufferedReader(insr); fullStringBuffer = new StringBuffer(""); String temp = in.readLine(); while (temp != null) { fullStringBuffer.append(temp); temp = in.readLine(); } in.close(); } catch (IOException e) { message.append("<BR>\n [Error][IOException][" + e.getMessage() + "]"); } } catch (MalformedURLException e) { message.append("<BR>\n [Error][MalformedURLException][" + e.getMessage() + "]"); } catch (Exception e) { message.append("<BR>\n [Error][Exception][" + e.getMessage() + "]"); } } Code Sample 2: protected Scanner createScanner(InputSource source) { documentURI = source.getURI(); if (documentURI == null) { documentURI = ""; } Reader r = source.getCharacterStream(); if (r != null) { return new Scanner(r); } InputStream is = source.getByteStream(); if (is != null) { return new Scanner(is, source.getEncoding()); } String uri = source.getURI(); if (uri == null) { throw new CSSException(formatMessage("empty.source", null)); } try { ParsedURL purl = new ParsedURL(uri); is = purl.openStreamRaw(CSSConstants.CSS_MIME_TYPE); return new Scanner(is, source.getEncoding()); } catch (IOException e) { throw new CSSException(e); } }
00
Code Sample 1: public static void parseSohuStock(ArrayList<String> dataSource, final ArrayList<SohuStockBean> sohuStockBeanList) throws IOReactorException, InterruptedException { HttpAsyncClient httpclient = new DefaultHttpAsyncClient(); httpclient.start(); if (dataSource != null && dataSource.size() > 0) { final CountDownLatch latch = new CountDownLatch(dataSource.size()); for (int i = 0; i < dataSource.size(); i++) { final HttpGet request = new HttpGet(dataSource.get(i)); httpclient.execute(request, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { System.out.println(" Request completed " + count + " " + request.getRequestLine() + " " + response.getStatusLine()); try { HttpEntity he = response.getEntity(); try { String resp = EntityUtils.toString(he, "gb2312"); if (resp != null && resp.length() > 0) { SohuStockBean shstBean = SohuStockPostProcess.postSohuStockBeanProcess(resp); sohuStockBeanList.add(shstBean); } count++; } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } latch.countDown(); } catch (RuntimeException re) { latch.countDown(); } } public void failed(final Exception ex) { latch.countDown(); } public void cancelled() { latch.countDown(); } }); } latch.await(); System.out.println("done"); } if (httpclient != null) { httpclient.shutdown(); } System.out.println(sohuStockBeanList.size()); } Code Sample 2: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
00
Code Sample 1: public void init(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8"), 0, password.length()); byte[] rawKey = md.digest(); skeySpec = new SecretKeySpec(rawKey, "AES"); ivSpec = new IvParameterSpec(rawKey); cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchPaddingException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } } Code Sample 2: public String getInternetData() throws Exception { BufferedReader in = null; String data = null; try { HttpClient client = new DefaultHttpClient(); URI website = new URI("http://code.google.com/p/gadi-works"); HttpGet request = new HttpGet(); request.setURI(website); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String l = ""; String nl = System.getProperty("line.separator"); while ((l = in.readLine()) != null) { sb.append(l + nl); } in.close(); data = sb.toString(); return data; } finally { if (in != null) { try { in.close(); return data; } catch (Exception e) { e.printStackTrace(); } } } }
00
Code Sample 1: protected boolean process(final TranscodeJobImpl job) { TranscodePipe pipe = null; current_job = job; DeviceImpl device = job.getDevice(); device.setTranscoding(true); try { job.starts(); TranscodeProvider provider = job.getProfile().getProvider(); final TranscodeException[] error = { null }; TranscodeProfile profile = job.getProfile(); final TranscodeFileImpl transcode_file = job.getTranscodeFile(); TranscodeProviderAnalysis provider_analysis; boolean xcode_required; if (provider == null) { xcode_required = false; provider_analysis = null; } else { provider_analysis = analyse(job); xcode_required = provider_analysis.getBooleanProperty(TranscodeProviderAnalysis.PT_TRANSCODE_REQUIRED); int tt_req; if (job.isStream()) { tt_req = TranscodeTarget.TRANSCODE_ALWAYS; } else { tt_req = job.getTranscodeRequirement(); if (device instanceof TranscodeTarget) { if (provider_analysis.getLongProperty(TranscodeProviderAnalysis.PT_VIDEO_HEIGHT) == 0) { if (((TranscodeTarget) device).isAudioCompatible(transcode_file)) { tt_req = TranscodeTarget.TRANSCODE_NEVER; } } } } if (tt_req == TranscodeTarget.TRANSCODE_NEVER) { xcode_required = false; } else if (tt_req == TranscodeTarget.TRANSCODE_ALWAYS) { xcode_required = true; provider_analysis.setBooleanProperty(TranscodeProviderAnalysis.PT_FORCE_TRANSCODE, true); } } if (xcode_required) { final AESemaphore xcode_sem = new AESemaphore("xcode:proc"); final TranscodeProviderJob[] provider_job = { null }; TranscodeProviderAdapter xcode_adapter = new TranscodeProviderAdapter() { private boolean resolution_updated; private final int ETA_AVERAGE_SIZE = 10; private int last_eta; private int eta_samples; private Average eta_average = AverageFactory.MovingAverage(ETA_AVERAGE_SIZE); private int last_percent; public void updateProgress(int percent, int eta_secs, int new_width, int new_height) { last_eta = eta_secs; last_percent = percent; TranscodeProviderJob prov_job = provider_job[0]; if (prov_job == null) { return; } int job_state = job.getState(); if (job_state == TranscodeJob.ST_CANCELLED || job_state == TranscodeJob.ST_REMOVED) { prov_job.cancel(); } else if (paused || job_state == TranscodeJob.ST_PAUSED) { prov_job.pause(); } else { if (job_state == TranscodeJob.ST_RUNNING) { prov_job.resume(); } job.updateProgress(percent, eta_secs); prov_job.setMaxBytesPerSecond(max_bytes_per_sec); if (!resolution_updated) { if (new_width > 0 && new_height > 0) { transcode_file.setResolution(new_width, new_height); resolution_updated = true; } } } } public void streamStats(long connect_rate, long write_speed) { if (Constants.isOSX && job.getEnableAutoRetry() && job.canUseDirectInput() && job.getAutoRetryCount() == 0) { if (connect_rate > 5 && last_percent < 100) { long eta = (long) eta_average.update(last_eta); eta_samples++; if (eta_samples >= ETA_AVERAGE_SIZE) { long total_time = (eta * 100) / (100 - last_percent); long total_write = total_time * write_speed; DiskManagerFileInfo file = job.getFile(); long length = file.getLength(); if (length > 0) { double over_write = ((double) total_write) / length; if (over_write > 5.0) { failed(new TranscodeException("Overwrite limit exceeded, abandoning transcode")); provider_job[0].cancel(); } } } } else { eta_samples = 0; } } } public void failed(TranscodeException e) { if (error[0] == null) { error[0] = e; } xcode_sem.release(); } public void complete() { xcode_sem.release(); } }; boolean direct_input = job.useDirectInput(); if (job.isStream()) { pipe = new TranscodePipeStreamSource2(new TranscodePipeStreamSource2.streamListener() { public void gotStream(InputStream is) { job.setStream(is); } }); provider_job[0] = provider.transcode(xcode_adapter, provider_analysis, direct_input, job.getFile(), profile, new URL("tcp://127.0.0.1:" + pipe.getPort())); } else { File output_file = transcode_file.getCacheFile(); provider_job[0] = provider.transcode(xcode_adapter, provider_analysis, direct_input, job.getFile(), profile, output_file.toURI().toURL()); } provider_job[0].setMaxBytesPerSecond(max_bytes_per_sec); TranscodeQueueListener listener = new TranscodeQueueListener() { public void jobAdded(TranscodeJob job) { } public void jobChanged(TranscodeJob changed_job) { if (changed_job == job) { int state = job.getState(); if (state == TranscodeJob.ST_PAUSED) { provider_job[0].pause(); } else if (state == TranscodeJob.ST_RUNNING) { provider_job[0].resume(); } else if (state == TranscodeJob.ST_CANCELLED || state == TranscodeJob.ST_STOPPED) { provider_job[0].cancel(); } } } public void jobRemoved(TranscodeJob removed_job) { if (removed_job == job) { provider_job[0].cancel(); } } }; try { addListener(listener); xcode_sem.reserve(); } finally { removeListener(listener); } if (error[0] != null) { throw (error[0]); } } else { DiskManagerFileInfo source = job.getFile(); transcode_file.setTranscodeRequired(false); if (job.isStream()) { PluginInterface av_pi = PluginInitializer.getDefaultInterface().getPluginManager().getPluginInterfaceByID("azupnpav"); if (av_pi == null) { throw (new TranscodeException("Media Server plugin not found")); } IPCInterface av_ipc = av_pi.getIPC(); String url_str = (String) av_ipc.invoke("getContentURL", new Object[] { source }); if (url_str == null || url_str.length() == 0) { File source_file = source.getFile(); if (source_file.exists()) { job.setStream(new BufferedInputStream(new FileInputStream(source_file))); } else { throw (new TranscodeException("No UPnPAV URL and file doesn't exist")); } } else { URL source_url = new URL(url_str); job.setStream(source_url.openConnection().getInputStream()); } } else { if (device.getAlwaysCacheFiles()) { PluginInterface av_pi = PluginInitializer.getDefaultInterface().getPluginManager().getPluginInterfaceByID("azupnpav"); if (av_pi == null) { throw (new TranscodeException("Media Server plugin not found")); } IPCInterface av_ipc = av_pi.getIPC(); String url_str = (String) av_ipc.invoke("getContentURL", new Object[] { source }); InputStream is; long length; if (url_str == null || url_str.length() == 0) { File source_file = source.getFile(); if (source_file.exists()) { is = new BufferedInputStream(new FileInputStream(source_file)); length = source_file.length(); } else { throw (new TranscodeException("No UPnPAV URL and file doesn't exist")); } } else { URL source_url = new URL(url_str); URLConnection connection = source_url.openConnection(); is = source_url.openConnection().getInputStream(); String s = connection.getHeaderField("content-length"); if (s != null) { length = Long.parseLong(s); } else { length = -1; } } OutputStream os = null; final boolean[] cancel_copy = { false }; TranscodeQueueListener copy_listener = new TranscodeQueueListener() { public void jobAdded(TranscodeJob job) { } public void jobChanged(TranscodeJob changed_job) { if (changed_job == job) { int state = job.getState(); if (state == TranscodeJob.ST_PAUSED) { } else if (state == TranscodeJob.ST_RUNNING) { } else if (state == TranscodeJob.ST_CANCELLED || state == TranscodeJob.ST_STOPPED) { cancel_copy[0] = true; } } } public void jobRemoved(TranscodeJob removed_job) { if (removed_job == job) { cancel_copy[0] = true; } } }; try { addListener(copy_listener); os = new FileOutputStream(transcode_file.getCacheFile()); long total_copied = 0; byte[] buffer = new byte[128 * 1024]; while (true) { if (cancel_copy[0]) { throw (new TranscodeException("Copy cancelled")); } int len = is.read(buffer); if (len <= 0) { break; } os.write(buffer, 0, len); total_copied += len; if (length > 0) { job.updateProgress((int) (total_copied * 100 / length), -1); } total_copied += len; } } finally { try { is.close(); } catch (Throwable e) { Debug.out(e); } try { if (os != null) { os.close(); } } catch (Throwable e) { Debug.out(e); } removeListener(copy_listener); } } } } job.complete(); return (true); } catch (Throwable e) { job.failed(e); e.printStackTrace(); if (!job.isStream() && job.getEnableAutoRetry() && job.getAutoRetryCount() == 0 && job.canUseDirectInput() && !job.useDirectInput()) { log("Auto-retrying transcode with direct input"); job.setUseDirectInput(); job.setAutoRetry(true); queue_sem.release(); } return (false); } finally { if (pipe != null) { pipe.destroy(); } device.setTranscoding(false); current_job = null; } } Code Sample 2: public static String loadWebsiteHtmlCode(String url, String useragent) { HttpClient httpClient = new DefaultHttpClient(); HttpGet getMethod = new HttpGet(url); String htmlCode = ""; if (useragent != null) { getMethod.setHeader("user-agent", useragent); } try { HttpResponse resp = httpClient.execute(getMethod); int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.debug("Method failed!" + statusCode); } htmlCode = EntityUtils.toString(resp.getEntity()); } catch (Exception e) { logger.debug("Fatal protocol violation: " + e.getMessage()); logger.trace(e); } return htmlCode; }
00
Code Sample 1: public static void main(String[] args) throws Exception { if (args.length != 2) { PrintUtil.prt("arguments: sourcefile, destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); in.transferTo(0, in.size(), out); } Code Sample 2: public void sendBinaryFile(String filename) throws IOException { Checker.checkEmpty(filename, "filename"); URL url = _getFile(filename); OutputStream out = getOutputStream(); Streams.copy(url.openStream(), out); out.close(); }