label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
11
|
Code Sample 1:
private static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("�������� ���� �� ���������" + from_file); if (!from_file.isFile()) abort("���������� ����������� ��������" + from_file); if (!from_file.canRead()) abort("�������� ���� ���������� ��� ������" + from_file); if (from_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("�������� ���� ���������� ��� ������" + to_file); System.out.println("������������ ������� ����?" + to_file.getName() + "?(Y/N):"); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("������������ ���� �� ��� �����������"); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("������� ���������� �� ���������" + parent); if (!dir.isFile()) abort("�� �������� ���������" + parent); if (!dir.canWrite()) abort("������ �� ������" + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
@Override public Document duplicate() { BinaryDocument b = new BinaryDocument(this.name, this.content.getContentType()); try { IOUtils.copy(this.getContent().getInputStream(), this.getContent().getOutputStream()); return b; } catch (IOException e) { throw ManagedIOException.manage(e); } }
|
11
|
Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { log.info("Copying file '" + sourceFile + "' to '" + destFile + "'"); if (!sourceFile.isFile()) { throw new IllegalArgumentException("The sourceFile '" + sourceFile + "' does not exist or is not a normal file."); } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); long numberOfBytes = destination.transferFrom(source, 0, source.size()); log.debug("Transferred " + numberOfBytes + " bytes from '" + sourceFile + "' to '" + destFile + "'."); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public static boolean copyFile(File src, File des) { try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(des)); int b; while ((b = in.read()) != -1) out.write(b); out.flush(); out.close(); in.close(); return true; } catch (IOException ie) { m_logCat.error("Copy file + " + src + " to " + des + " failed!", ie); return false; } }
|
00
|
Code Sample 1:
static byte[] genDigest(String pad, byte[] passwd) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance(DIGEST_ALGORITHM); digest.update(pad.getBytes()); digest.update(passwd); return digest.digest(); }
Code Sample 2:
public void processAction(DatabaseAdapter db_, DataDefinitionActionDataListType parameters) throws Exception { PreparedStatement ps = null; try { if (log.isDebugEnabled()) log.debug("db connect - " + db_.getClass().getName()); String seqName = DefinitionService.getString(parameters, "sequence_name", null); if (seqName == null) { String errorString = "Name of sequnce not found"; log.error(errorString); throw new Exception(errorString); } String tableName = DefinitionService.getString(parameters, "name_table", null); if (tableName == null) { String errorString = "Name of table not found"; log.error(errorString); throw new Exception(errorString); } String columnName = DefinitionService.getString(parameters, "name_pk_field", null); if (columnName == null) { String errorString = "Name of column not found"; log.error(errorString); throw new Exception(errorString); } CustomSequenceType seqSite = new CustomSequenceType(); seqSite.setSequenceName(seqName); seqSite.setTableName(tableName); seqSite.setColumnName(columnName); long seqValue = db_.getSequenceNextValue(seqSite); String valueColumnName = DefinitionService.getString(parameters, "name_value_field", null); if (columnName == null) { String errorString = "Name of valueColumnName not found"; log.error(errorString); throw new Exception(errorString); } String insertValue = DefinitionService.getString(parameters, "insert_value", null); if (columnName == null) { String errorString = "Name of insertValue not found"; log.error(errorString); throw new Exception(errorString); } String sql = "insert into " + tableName + " " + "(" + columnName + "," + valueColumnName + ")" + "values" + "(?,?)"; if (log.isDebugEnabled()) { log.debug(sql); log.debug("pk " + seqValue); log.debug("value " + insertValue); } ps = db_.prepareStatement(sql); ps.setLong(1, seqValue); ps.setString(2, insertValue); ps.executeUpdate(); db_.commit(); } catch (Exception e) { try { db_.rollback(); } catch (Exception e1) { } log.error("Error insert value", e); throw e; } finally { org.riverock.generic.db.DatabaseManager.close(ps); ps = null; } }
|
11
|
Code Sample 1:
private static synchronized boolean doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { destFile = new File(destFile + FILE_SEPARATOR + srcFile.getName()); } 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()); } return destFile.exists(); }
Code Sample 2:
public SpreadSheetFrame(FileManager owner, File file, Delimiter delim) { super(owner, file.getPath()); JPanel pane = new JPanel(new BorderLayout()); super.contentPane.add(pane); this.tableModel = new BigTableModel(file, delim); this.table = new JTable(tableModel); this.table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); this.tableModel.setTable(this.table); pane.add(new JScrollPane(this.table)); addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosed(InternalFrameEvent e) { tableModel.close(); } }); JMenu menu = new JMenu("Tools"); getJMenuBar().add(menu); menu.add(new AbstractAction("NCBI") { @Override public void actionPerformed(ActionEvent e) { try { Pattern delim = Pattern.compile("[ ]"); BufferedReader r = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("/home/lindenb/jeter.txt.gz")))); String line = null; URL url = new URL("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write("db=snp&retmode=xml"); while ((line = r.readLine()) != null) { String tokens[] = delim.split(line, 2); if (!tokens[0].startsWith("rs")) continue; wr.write("&id=" + tokens[0].substring(2).trim()); } wr.flush(); r.close(); InputStream in = conn.getInputStream(); IOUtils.copyTo(in, System.err); in.close(); wr.close(); } catch (IOException err) { err.printStackTrace(); } } }); }
|
11
|
Code Sample 1:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
Code Sample 2:
public void copyFile(File source, File destination) { try { FileInputStream sourceStream = new FileInputStream(source); try { FileOutputStream destinationStream = new FileOutputStream(destination); try { FileChannel sourceChannel = sourceStream.getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationStream.getChannel()); } finally { try { destinationStream.close(); } catch (Exception e) { throw new RuntimeIoException(e, IoMode.CLOSE); } } } finally { try { sourceStream.close(); } catch (Exception e) { throw new RuntimeIoException(e, IoMode.CLOSE); } } } catch (IOException e) { throw new RuntimeIoException(e, IoMode.COPY); } }
|
11
|
Code Sample 1:
public static void compressFile(File f) throws IOException { File target = new File(f.toString() + ".gz"); System.out.print("Compressing: " + f.getName() + ".. "); long initialSize = f.length(); FileInputStream fis = new FileInputStream(f); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(target)); byte[] buf = new byte[1024]; int read; while ((read = fis.read(buf)) != -1) { out.write(buf, 0, read); } System.out.println("Done."); fis.close(); out.close(); long endSize = target.length(); System.out.println("Initial size: " + initialSize + "; Compressed size: " + endSize); }
Code Sample 2:
private static boolean moveFiles(String sourceDir, String targetDir) { boolean isFinished = false; boolean fileMoved = false; File stagingDir = new File(sourceDir); if (!stagingDir.exists()) { System.out.println(getTimeStamp() + "ERROR - source directory does not exist."); return true; } if (stagingDir.listFiles() == null) { System.out.println(getTimeStamp() + "ERROR - Empty file list. Possible permission error on source directory " + sourceDir); return true; } File[] fileList = stagingDir.listFiles(); for (int x = 0; x < fileList.length; x++) { File f = fileList[x]; if (f.getName().startsWith(".")) { continue; } String targetFileName = targetDir + File.separator + f.getName(); String operation = "move"; boolean success = f.renameTo(new File(targetFileName)); if (success) { fileMoved = true; } else { operation = "mv"; try { Process process = Runtime.getRuntime().exec(new String[] { "mv", f.getCanonicalPath(), targetFileName }); process.waitFor(); process.destroy(); if (!new File(targetFileName).exists()) { success = false; } else { success = true; fileMoved = true; } } catch (Exception e) { success = false; } if (!success) { operation = "copy"; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(f).getChannel(); File outFile = new File(targetFileName); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); in.close(); in = null; out.close(); out = null; f.delete(); success = true; } catch (Exception e) { success = false; } finally { if (in != null) { try { in.close(); } catch (Exception e) { } } if (out != null) { try { out.close(); } catch (Exception e) { } } } } } if (success) { System.out.println(getTimeStamp() + operation + " " + f.getAbsolutePath() + " to " + targetDir); fileMoved = true; } else { System.out.println(getTimeStamp() + "ERROR - " + operation + " " + f.getName() + " to " + targetFileName + " failed."); isFinished = true; } } if (fileMoved && !isFinished) { try { currentLastActivity = System.currentTimeMillis(); updateLastActivity(currentLastActivity); } catch (NumberFormatException e) { System.out.println(getTimeStamp() + "ERROR: NumberFormatException when trying to update lastActivity."); isFinished = true; } catch (IOException e) { System.out.println(getTimeStamp() + "ERROR: IOException when trying to update lastActivity. " + e.toString()); isFinished = true; } } return isFinished; }
|
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 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 void setBckImg(String newPath) { try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = null; try { out = new FileOutputStream(outputFile); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); JOptionPane.showMessageDialog(null, ex1.getMessage().substring(0, Math.min(ex1.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } int c; if (out != null) { while ((c = in.read()) != -1) out.write(c); out.close(); } in.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } setPath(newPath); bckImg = new ImageIcon(getPath()); }
Code Sample 2:
public final String encrypt(String input) throws Exception { try { MessageDigest messageDigest = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); messageDigest.reset(); messageDigest.update(input.getBytes()); String output = convert(messageDigest.digest()); return output; } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Fatal Error while digesting input string", ex); } } return input; }
|
00
|
Code Sample 1:
public static void addIntegrityEnforcements(Session session) throws HibernateException { Transaction tx = null; try { tx = session.beginTransaction(); Statement st = session.connection().createStatement(); st.executeUpdate("DROP TABLE hresperformsrole;" + "CREATE TABLE hresperformsrole" + "(" + "hresid varchar(255) NOT NULL," + "rolename varchar(255) NOT NULL," + "CONSTRAINT hresperformsrole_pkey PRIMARY KEY (hresid, rolename)," + "CONSTRAINT ResourceFK FOREIGN KEY (hresid) REFERENCES resserposid (id) ON UPDATE CASCADE ON DELETE CASCADE," + "CONSTRAINT RoleFK FOREIGN KEY (rolename) REFERENCES role (rolename) ON UPDATE CASCADE ON DELETE CASCADE" + ");"); tx.commit(); } catch (Exception e) { tx.rollback(); } }
Code Sample 2:
public static String encrypt(String value) { MessageDigest messageDigest; byte[] raw = null; try { messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(((String) value).getBytes("UTF-8")); raw = messageDigest.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return (new BASE64Encoder()).encode(raw); }
|
00
|
Code Sample 1:
private void zipdir(File base, String zipname) throws IOException { FilenameFilter ff = new ExporterFileNameFilter(); String[] files = base.list(ff); File zipfile = new File(base, zipname + ".zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipfile)); byte[] buf = new byte[10240]; for (int i = 0; i < files.length; i++) { File f = new File(base, files[i]); FileInputStream fis = new FileInputStream(f); zos.putNextEntry(new ZipEntry(f.getName())); int len; while ((len = fis.read(buf)) > 0) zos.write(buf, 0, len); zos.closeEntry(); fis.close(); f.delete(); } zos.close(); }
Code Sample 2:
@Override protected FTPClient ftpConnect() throws SocketException, IOException, NoSuchAlgorithmException { FilePathItem fpi = getFilePathItem(); FTPClient f = new FTPSClient(); f.connect(fpi.getHost()); f.login(fpi.getUsername(), fpi.getPassword()); return f; }
|
00
|
Code Sample 1:
public void compareResult(String path, String expected) throws IOException { if (path.length() == 0 || path.charAt(0) != '/') path = "/" + path; URL url = new URL(getBase() + path); String actual = IOUtils.toString(url.openStream()); Assert.assertEquals(url.toString(), expected, actual); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
public char check(String password) { if (captchaRandom.equals("null")) { return 's'; } if (captchaRandom.equals("used")) { return 'm'; } String encryptionBase = secret + captchaRandom; if (!alphabet.equals(ALPHABET_DEFAULT) || letters != LETTERS_DEFAULT) { encryptionBase += ":" + alphabet + ":" + letters; } MessageDigest md5; byte[] digest = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; try { md5 = MessageDigest.getInstance("MD5"); md5.update(encryptionBase.getBytes()); digest = md5.digest(); } catch (NoSuchAlgorithmException e) { } String correctPassword = ""; int index; for (int i = 0; i < letters; i++) { index = (digest[i] + 256) % 256 % alphabet.length(); correctPassword += alphabet.substring(index, index + 1); } if (!password.equals(correctPassword)) { return 'w'; } else { captchaRandom = "used"; return 't'; } }
Code Sample 2:
public String sendRequestAndGetNormalStringOutPut(java.lang.String servletName, java.lang.String request) { String myurl = java.util.prefs.Preferences.systemRoot().get("serverurl", ""); String myport = java.util.prefs.Preferences.systemRoot().get("portno", "8080"); if (myport == null || myport.trim().equals("")) { myport = "80"; } if (this.serverURL == null) { try { java.net.URL codebase = newgen.presentation.NewGenMain.getAppletInstance().getCodeBase(); if (codebase != null) serverURL = codebase.getHost(); else serverURL = "localhost"; } catch (Exception exp) { exp.printStackTrace(); serverURL = "localhost"; } newgen.presentation.component.IPAddressPortNoDialog ipdig = new newgen.presentation.component.IPAddressPortNoDialog(myurl, myport); ipdig.show(); serverURL = myurl = ipdig.getIPAddress(); myport = ipdig.getPortNo(); java.util.prefs.Preferences.systemRoot().put("serverurl", serverURL); java.util.prefs.Preferences.systemRoot().put("portno", myport); System.out.println(serverURL); } String response = ""; try { System.out.println("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName); java.net.URL url = new java.net.URL("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); urlconn.setRequestProperty("Content-type", "text/xml; charset=UTF-8"); java.io.OutputStream os = urlconn.getOutputStream(); String req1xml = request; java.util.zip.CheckedOutputStream cos = new java.util.zip.CheckedOutputStream(os, new java.util.zip.Adler32()); java.util.zip.GZIPOutputStream gop = new java.util.zip.GZIPOutputStream(cos); java.io.OutputStreamWriter dos = new java.io.OutputStreamWriter(gop, "UTF-8"); System.out.println(req1xml); dos.write(req1xml); dos.flush(); dos.close(); System.out.println("url conn: " + urlconn.getContentEncoding() + " " + urlconn.getContentType()); java.io.InputStream ios = urlconn.getInputStream(); java.util.zip.CheckedInputStream cis = new java.util.zip.CheckedInputStream(ios, new java.util.zip.Adler32()); java.util.zip.GZIPInputStream gip = new java.util.zip.GZIPInputStream(cis); java.io.InputStreamReader br = new java.io.InputStreamReader(gip, "UTF-8"); int n = -1; while ((n = br.read()) != -1) response += (char) n; } catch (java.net.ConnectException conexp) { javax.swing.JOptionPane.showMessageDialog(null, "<html>Could not establish connection with the NewGenLib server, " + "<br>These might be the possible reasons." + "<br><li>Check the network connectivity between this machine and the server." + "<br><li>Check whether NewGenLib server is running on the server machine." + "<br><li>NewGenLib server might not have initialized properly. In this case" + "<br>go to server machine, open NewGenLibDesktop Application," + "<br> utility ->Send log to NewGenLib Customer Support</html>", "Critical error", javax.swing.JOptionPane.ERROR_MESSAGE); } catch (Exception exp) { exp.printStackTrace(System.out); TroubleShootConnectivity troubleShoot = new TroubleShootConnectivity(); } return response; }
|
00
|
Code Sample 1:
private void gravaOp(Vector<?> op) { PreparedStatement ps = null; String sql = null; ResultSet rs = null; int seqop = 0; Date dtFabrOP = null; try { sql = "SELECT MAX(SEQOP) FROM PPOP WHERE CODEMP=? AND CODFILIAL=? AND CODOP=?"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); rs = ps.executeQuery(); if (rs.next()) { seqop = rs.getInt(1) + 1; } rs.close(); ps.close(); con.commit(); sql = "SELECT DTFABROP FROM PPOP WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=?"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); ps.setInt(4, txtSeqOP.getVlrInteger().intValue()); rs = ps.executeQuery(); if (rs.next()) { dtFabrOP = rs.getDate(1); } rs.close(); ps.close(); con.commit(); sql = "INSERT INTO PPOP (CODEMP,CODFILIAL,CODOP,SEQOP,CODEMPPD,CODFILIALPD,CODPROD,SEQEST,DTFABROP," + "QTDPREVPRODOP,QTDFINALPRODOP,DTVALIDPDOP,CODEMPLE,CODFILIALLE,CODLOTE,CODEMPTM,CODFILIALTM,CODTIPOMOV," + "CODEMPAX,CODFILIALAX,CODALMOX,CODEMPOPM,CODFILIALOPM,CODOPM,SEQOPM,QTDDISTIOP,QTDSUGPRODOP)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); ps.setInt(4, seqop); ps.setInt(5, Aplicativo.iCodEmp); ps.setInt(6, ListaCampos.getMasterFilial("PPESTRUTURA")); ps.setInt(7, ((Integer) op.elementAt(4)).intValue()); ps.setInt(8, ((Integer) op.elementAt(6)).intValue()); ps.setDate(9, dtFabrOP); ps.setFloat(10, ((BigDecimal) op.elementAt(7)).floatValue()); ps.setFloat(11, 0); ps.setDate(12, (Funcoes.strDateToSqlDate((String) op.elementAt(11)))); ps.setInt(13, Aplicativo.iCodEmp); ps.setInt(14, ListaCampos.getMasterFilial("EQLOTE")); ps.setString(15, ((String) op.elementAt(10))); ps.setInt(16, Aplicativo.iCodEmp); ps.setInt(17, ListaCampos.getMasterFilial("EQTIPOMOV")); ps.setInt(18, buscaTipoMov()); ps.setInt(19, ((Integer) op.elementAt(13)).intValue()); ps.setInt(20, ((Integer) op.elementAt(14)).intValue()); ps.setInt(21, ((Integer) op.elementAt(12)).intValue()); ps.setInt(22, Aplicativo.iCodEmp); ps.setInt(23, ListaCampos.getMasterFilial("PPOP")); ps.setInt(24, txtCodOP.getVlrInteger().intValue()); ps.setInt(25, txtSeqOP.getVlrInteger().intValue()); ps.setFloat(26, ((BigDecimal) op.elementAt(9)).floatValue()); ps.setFloat(27, ((BigDecimal) op.elementAt(7)).floatValue()); ps.executeUpdate(); ps.close(); con.commit(); geraRMA(seqop); } catch (SQLException e) { Funcoes.mensagemErro(null, "Erro ao gerar OP's de distribui��o!\n" + e.getMessage()); try { con.rollback(); } catch (SQLException eb) { } } }
Code Sample 2:
public static String generateMD5(String str) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { logger.log(Level.SEVERE, null, nsae); } return hashword; }
|
11
|
Code Sample 1:
public String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
Code Sample 2:
private String calculateMD5(String value) { String finalString; try { MessageDigest md5Alg = MessageDigest.getInstance("MD5"); md5Alg.reset(); md5Alg.update(value.getBytes()); byte messageDigest[] = md5Alg.digest(); StringBuilder hexString = new StringBuilder(256); 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); } finalString = hexString.toString(); } catch (NoSuchAlgorithmException exc) { throw new RuntimeException("Hashing error happened:", exc); } return finalString; }
|
00
|
Code Sample 1:
public static String createRecoveryContent(String password) { try { password = encryptGeneral1(password); String data = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); URL url = new URL("https://mypasswords-server.appspot.com/recovery_file"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder finalResult = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { finalResult.append(line); } wr.close(); rd.close(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new InputSource(new StringReader(finalResult.toString()))); document.normalizeDocument(); Element root = document.getDocumentElement(); String textContent = root.getTextContent(); return textContent; } catch (Exception e) { System.out.println(e.getMessage()); } return null; }
Code Sample 2:
public static File createTempFile(InputStream contentStream, String ext) throws IOException { ExceptionUtils.throwIfNull(contentStream, "contentStream"); File file = File.createTempFile("test", ext); FileOutputStream fos = new FileOutputStream(file); try { IOUtils.copy(contentStream, fos, false); } finally { fos.close(); } return file; }
|
11
|
Code Sample 1:
void shutdown(final boolean unexpected) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } log.error("check if we need the controler listener infrastructure"); if (this.dumpDataAtEnd) { new PopulationWriter(this.population, this.network).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); }
Code Sample 2:
@Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final String url = req.getParameter("url"); if (!isAllowed(url)) { resp.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } final HttpClient client = new HttpClient(); client.getParams().setVersion(HttpVersion.HTTP_1_0); final PostMethod method = new PostMethod(url); method.getParams().setVersion(HttpVersion.HTTP_1_0); method.setFollowRedirects(false); final RequestEntity entity = new InputStreamRequestEntity(req.getInputStream()); method.setRequestEntity(entity); try { final int statusCode = client.executeMethod(method); if (statusCode != -1) { InputStream is = null; ServletOutputStream os = null; try { is = method.getResponseBodyAsStream(); try { os = resp.getOutputStream(); IOUtils.copy(is, os); } finally { if (os != null) { try { os.flush(); } catch (IOException ignored) { } } } } catch (IOException ioex) { final String message = ioex.getMessage(); if (!"chunked stream ended unexpectedly".equals(message)) { throw ioex; } } finally { IOUtils.closeQuietly(is); } } } finally { method.releaseConnection(); } }
|
00
|
Code Sample 1:
public void overwriteTest() throws Exception { SRBAccount srbAccount = new SRBAccount("srb1.ngs.rl.ac.uk", 5544, this.cred); srbAccount.setDefaultStorageResource("ral-ngs1"); SRBFileSystem client = new SRBFileSystem(srbAccount); client.setFirewallPorts(64000, 65000); String home = client.getHomeDirectory(); System.out.println("home: " + home); SRBFile file = new SRBFile(client, home + "/test.txt"); assertTrue(file.exists()); File filefrom = new File("/tmp/from.txt"); assertTrue(filefrom.exists()); SRBFileOutputStream to = null; InputStream from = null; try { to = new SRBFileOutputStream((SRBFile) file); from = new FileInputStream(filefrom); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } to.flush(); } finally { try { if (to != null) { to.close(); } } catch (Exception ex) { } try { if (from != null) { from.close(); } } catch (Exception ex) { } } }
Code Sample 2:
public static void readDefault() { ClassLoader l = Skeleton.class.getClassLoader(); URL url = l.getResource("weka/core/parser/JFlex/skeleton.default"); if (url == null) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } try { InputStreamReader reader = new InputStreamReader(url.openStream()); readSkel(new BufferedReader(reader)); } catch (IOException e) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } }
|
00
|
Code Sample 1:
public void readHTMLFromURL(URL url) throws IOException { InputStream in = url.openStream(); try { readHTMLFromStream(new InputStreamReader(in)); } finally { try { in.close(); } catch (IOException ex) { Logger.getLogger(HTMLTextAreaModel.class.getName()).log(Level.SEVERE, "Exception while closing InputStream", ex); } } }
Code Sample 2:
public static JSONObject update(String name, String uid, double lat, double lon, boolean online) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpPost post = new HttpPost(UPDATE_URI); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("name", name)); parameters.add(new BasicNameValuePair("uid", uid)); parameters.add(new BasicNameValuePair("latitude", Double.toString(lat))); parameters.add(new BasicNameValuePair("longitude", Double.toString(lon))); parameters.add(new BasicNameValuePair("online", Boolean.toString(online))); post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8)); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); return new JSONObject(res); } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); }
|
00
|
Code Sample 1:
private void initialize() { StringBuffer license = new StringBuffer(); URL url; InputStreamReader in; BufferedReader reader; String str; JTextArea textArea; JButton button; GridBagConstraints c; setTitle("Mibble License"); setSize(600, 600); setDefaultCloseOperation(DISPOSE_ON_CLOSE); getContentPane().setLayout(new GridBagLayout()); url = getClass().getClassLoader().getResource("LICENSE.txt"); if (url == null) { license.append("Couldn't locate license file (LICENSE.txt)."); } else { try { in = new InputStreamReader(url.openStream()); reader = new BufferedReader(in); while ((str = reader.readLine()) != null) { if (!str.equals(" ")) { license.append(str); } license.append("\n"); } reader.close(); } catch (IOException e) { license.append("Error reading license file "); license.append("(LICENSE.txt):\n\n"); license.append(e.getMessage()); } } textArea = new JTextArea(license.toString()); textArea.setEditable(false); c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0d; c.weighty = 1.0d; c.insets = new Insets(4, 5, 4, 5); getContentPane().add(new JScrollPane(textArea), c); button = new JButton("Close"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); c = new GridBagConstraints(); c.gridy = 1; c.anchor = GridBagConstraints.CENTER; c.insets = new Insets(10, 10, 10, 10); getContentPane().add(button, c); }
Code Sample 2:
public void removeRoom(int thisRoom) { DBConnection con = null; try { con = DBServiceManager.allocateConnection(); con.setAutoCommit(false); String query = "DELETE FROM cafe_Chat_Category WHERE cafe_Chat_Category_id=? "; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, thisRoom); ps.executeUpdate(); query = "DELETE FROM cafe_Chatroom WHERE cafe_chatroom_category=? "; ps = con.prepareStatement(query); ps.setInt(1, thisRoom); ps.executeUpdate(); con.commit(); con.setAutoCommit(true); } catch (SQLException e) { try { con.rollback(); } catch (SQLException sqle) { } } finally { if (con != null) con.release(); } }
|
11
|
Code Sample 1:
public void copy(File source, File destination) { try { FileInputStream fileInputStream = new FileInputStream(source); FileOutputStream fileOutputStream = new FileOutputStream(destination); FileChannel inputChannel = fileInputStream.getChannel(); FileChannel outputChannel = fileOutputStream.getChannel(); transfer(inputChannel, outputChannel, source.length(), 1024 * 1024 * 32, true, true); fileInputStream.close(); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
@Test public void testCopyOverSize() throws IOException { final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(TEST_DATA.length); final int cpySize = ExtraIOUtils.copy(in, out, TEST_DATA.length + Long.SIZE); assertEquals("Mismatched copy size", TEST_DATA.length, cpySize); final byte[] outArray = out.toByteArray(); assertArrayEquals("Mismatched data", TEST_DATA, outArray); }
|
11
|
Code Sample 1:
private void fileCopy(File filename) throws IOException { if (this.stdOut) { this.fileDump(filename); return; } File source_file = new File(spoolPath + "/" + filename); File destination_file = new File(copyPath + "/" + filename); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("no such source file: " + source_file); if (!source_file.canRead()) throw new FileCopyException("source file is unreadable: " + source_file); if (destination_file.exists()) { if (destination_file.isFile()) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); if (!destination_file.canWrite()) throw new FileCopyException("destination file is unwriteable: " + destination_file); if (!this.overwrite) { System.out.print("File " + destination_file + " already exists. Overwrite? (Y/N): "); System.out.flush(); if (!in.readLine().toUpperCase().equals("Y")) throw new FileCopyException("copy cancelled."); } } else throw new FileCopyException("destination is not a file: " + destination_file); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("destination directory doesn't exist: " + destination_file); if (!parentdir.canWrite()) throw new FileCopyException("destination directory is unwriteable: " + destination_file); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while ((bytes_read = source.read(buffer)) != -1) { destination.write(buffer, 0, bytes_read); } System.out.println("File " + filename + " successfull copied to " + destination_file); if (this.keep == false && source_file.isFile()) { try { source.close(); } catch (Exception e) { } if (source_file.delete()) { new File(this.spoolPath + "/info/" + filename + ".desc").delete(); } } } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.flush(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } }
Code Sample 2:
public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } }
|
00
|
Code Sample 1:
public DefaultMainControl(@NotNull final FileFilter scriptFileFilter, @NotNull final String scriptExtension, @NotNull final String scriptName, final int spellType, @Nullable final String spellFile, @NotNull final String scriptsDir, final ErrorView errorView, @NotNull final EditorFactory<G, A, R> editorFactory, final boolean forceReadFromFiles, @NotNull final GlobalSettings globalSettings, @NotNull final ConfigSourceFactory configSourceFactory, @NotNull final PathManager pathManager, @NotNull final GameObjectMatchers gameObjectMatchers, @NotNull final GameObjectFactory<G, A, R> gameObjectFactory, @NotNull final ArchetypeTypeSet archetypeTypeSet, @NotNull final ArchetypeSet<G, A, R> archetypeSet, @NotNull final ArchetypeChooserModel<G, A, R> archetypeChooserModel, @NotNull final AutojoinLists<G, A, R> autojoinLists, @NotNull final AbstractMapManager<G, A, R> mapManager, @NotNull final PluginModel<G, A, R> pluginModel, @NotNull final DelegatingMapValidator<G, A, R> validators, @NotNull final ScriptedEventEditor<G, A, R> scriptedEventEditor, @NotNull final AbstractResources<G, A, R> resources, @NotNull final Spells<NumberSpell> numberSpells, @NotNull final Spells<GameObjectSpell<G, A, R>> gameObjectSpells, @NotNull final PluginParameterFactory<G, A, R> pluginParameterFactory, @NotNull final ValidatorPreferences validatorPreferences, @NotNull final MapWriter<G, A, R> mapWriter) { final XmlHelper xmlHelper; try { xmlHelper = new XmlHelper(); } catch (final ParserConfigurationException ex) { log.fatal("Cannot create XML parser: " + ex.getMessage()); throw new MissingResourceException("Cannot create XML parser: " + ex.getMessage(), null, null); } final AttributeRangeChecker<G, A, R> attributeRangeChecker = new AttributeRangeChecker<G, A, R>(validatorPreferences); final EnvironmentChecker<G, A, R> environmentChecker = new EnvironmentChecker<G, A, R>(validatorPreferences); final DocumentBuilder documentBuilder = xmlHelper.getDocumentBuilder(); try { final URL url = IOUtils.getResource(globalSettings.getConfigurationDirectory(), "GameObjectMatchers.xml"); final ErrorViewCollector gameObjectMatchersErrorViewCollector = new ErrorViewCollector(errorView, url); try { documentBuilder.setErrorHandler(new ErrorViewCollectorErrorHandler(gameObjectMatchersErrorViewCollector, ErrorViewCategory.GAMEOBJECTMATCHERS_FILE_INVALID)); try { final GameObjectMatchersParser gameObjectMatchersParser = new GameObjectMatchersParser(documentBuilder, xmlHelper.getXPath()); gameObjectMatchersParser.readGameObjectMatchers(url, gameObjectMatchers, gameObjectMatchersErrorViewCollector); } finally { documentBuilder.setErrorHandler(null); } } catch (final IOException ex) { gameObjectMatchersErrorViewCollector.addWarning(ErrorViewCategory.GAMEOBJECTMATCHERS_FILE_INVALID, ex.getMessage()); } final ValidatorFactory<G, A, R> validatorFactory = new ValidatorFactory<G, A, R>(validatorPreferences, gameObjectMatchers, globalSettings, mapWriter); loadValidators(validators, validatorFactory, errorView); editorFactory.initMapValidators(validators, gameObjectMatchersErrorViewCollector, globalSettings, gameObjectMatchers, attributeRangeChecker, validatorPreferences); validators.addValidator(attributeRangeChecker); validators.addValidator(environmentChecker); } catch (final FileNotFoundException ex) { errorView.addWarning(ErrorViewCategory.GAMEOBJECTMATCHERS_FILE_INVALID, "GameObjectMatchers.xml: " + ex.getMessage()); } final GameObjectMatcher shopSquareMatcher = gameObjectMatchers.getMatcher("system_shop_square", "shop_square"); if (shopSquareMatcher != null) { final GameObjectMatcher noSpellsMatcher = gameObjectMatchers.getMatcher("system_no_spells", "no_spells"); if (noSpellsMatcher != null) { final GameObjectMatcher blockedMatcher = gameObjectMatchers.getMatcher("system_blocked", "blocked"); validators.addValidator(new ShopSquareChecker<G, A, R>(validatorPreferences, shopSquareMatcher, noSpellsMatcher, blockedMatcher)); } final GameObjectMatcher paidItemMatcher = gameObjectMatchers.getMatcher("system_paid_item"); if (paidItemMatcher != null) { validators.addValidator(new PaidItemShopSquareChecker<G, A, R>(validatorPreferences, shopSquareMatcher, paidItemMatcher)); } } Map<String, TreasureTreeNode> specialTreasureLists; try { final URL url = IOUtils.getResource(globalSettings.getConfigurationDirectory(), "TreasureLists.xml"); final ErrorViewCollector treasureListsErrorViewCollector = new ErrorViewCollector(errorView, url); try { final InputStream inputStream = url.openStream(); try { documentBuilder.setErrorHandler(new ErrorViewCollectorErrorHandler(treasureListsErrorViewCollector, ErrorViewCategory.TREASURES_FILE_INVALID)); try { final Document specialTreasureListsDocument = documentBuilder.parse(new InputSource(inputStream)); specialTreasureLists = TreasureListsParser.parseTreasureLists(specialTreasureListsDocument); } finally { documentBuilder.setErrorHandler(null); } } finally { inputStream.close(); } } catch (final IOException ex) { treasureListsErrorViewCollector.addWarning(ErrorViewCategory.TREASURES_FILE_INVALID, ex.getMessage()); specialTreasureLists = Collections.emptyMap(); } catch (final SAXException ex) { treasureListsErrorViewCollector.addWarning(ErrorViewCategory.TREASURES_FILE_INVALID, ex.getMessage()); specialTreasureLists = Collections.emptyMap(); } } catch (final FileNotFoundException ex) { errorView.addWarning(ErrorViewCategory.TREASURES_FILE_INVALID, "TreasureLists.xml: " + ex.getMessage()); specialTreasureLists = Collections.emptyMap(); } final ConfigSource configSource = forceReadFromFiles ? configSourceFactory.getFilesConfigSource() : configSourceFactory.getConfigSource(globalSettings.getConfigSourceName()); treasureTree = TreasureLoader.parseTreasures(errorView, specialTreasureLists, configSource, globalSettings); final ArchetypeAttributeFactory archetypeAttributeFactory = new DefaultArchetypeAttributeFactory(); final ArchetypeAttributeParser archetypeAttributeParser = new ArchetypeAttributeParser(archetypeAttributeFactory); final ArchetypeTypeParser archetypeTypeParser = new ArchetypeTypeParser(archetypeAttributeParser); ArchetypeTypeList eventTypeSet = null; try { final URL url = IOUtils.getResource(globalSettings.getConfigurationDirectory(), CommonConstants.TYPEDEF_FILE); final ErrorViewCollector typesErrorViewCollector = new ErrorViewCollector(errorView, url); documentBuilder.setErrorHandler(new ErrorViewCollectorErrorHandler(typesErrorViewCollector, ErrorViewCategory.GAMEOBJECTMATCHERS_FILE_INVALID)); try { final ArchetypeTypeSetParser archetypeTypeSetParser = new ArchetypeTypeSetParser(documentBuilder, archetypeTypeSet, archetypeTypeParser); archetypeTypeSetParser.loadTypesFromXML(typesErrorViewCollector, new InputSource(url.toString())); } finally { documentBuilder.setErrorHandler(null); } final ArchetypeTypeList eventTypeSetTmp = archetypeTypeSet.getList("event"); if (eventTypeSetTmp == null) { typesErrorViewCollector.addWarning(ErrorViewCategory.TYPES_ENTRY_INVALID, "list 'list_event' does not exist"); } else { eventTypeSet = eventTypeSetTmp; } } catch (final FileNotFoundException ex) { errorView.addWarning(ErrorViewCategory.TYPES_FILE_INVALID, CommonConstants.TYPEDEF_FILE + ": " + ex.getMessage()); } if (eventTypeSet == null) { eventTypeSet = new ArchetypeTypeList(); } scriptArchUtils = editorFactory.newScriptArchUtils(eventTypeSet); final ScriptedEventFactory<G, A, R> scriptedEventFactory = editorFactory.newScriptedEventFactory(scriptArchUtils, gameObjectFactory, scriptedEventEditor, archetypeSet); scriptArchEditor = new DefaultScriptArchEditor<G, A, R>(scriptedEventFactory, scriptExtension, scriptName, scriptArchUtils, scriptFileFilter, globalSettings, mapManager, pathManager); scriptedEventEditor.setScriptArchEditor(scriptArchEditor); scriptArchData = editorFactory.newScriptArchData(); scriptArchDataUtils = editorFactory.newScriptArchDataUtils(scriptArchUtils, scriptedEventFactory, scriptedEventEditor); final long timeStart = System.currentTimeMillis(); if (log.isInfoEnabled()) { log.info("Start to load archetypes..."); } configSource.read(globalSettings, resources, errorView); for (final R archetype : archetypeSet.getArchetypes()) { final CharSequence editorFolder = archetype.getEditorFolder(); if (editorFolder != null && !editorFolder.equals(GameObject.EDITOR_FOLDER_INTERN)) { final String[] tmp = StringUtils.PATTERN_SLASH.split(editorFolder, 2); if (tmp.length == 2) { final String panelName = tmp[0]; final String folderName = tmp[1]; archetypeChooserModel.addArchetype(panelName, folderName, archetype); } } } if (log.isInfoEnabled()) { log.info("Archetype loading took " + (double) (System.currentTimeMillis() - timeStart) / 1000.0 + " seconds."); } if (spellType != 0) { new ArchetypeSetSpellLoader<G, A, R>(gameObjectFactory).load(archetypeSet, spellType, gameObjectSpells); gameObjectSpells.sort(); } if (spellFile != null) { try { final URL url = IOUtils.getResource(globalSettings.getConfigurationDirectory(), spellFile); final ErrorViewCollector errorViewCollector = new ErrorViewCollector(errorView, url); documentBuilder.setErrorHandler(new ErrorViewCollectorErrorHandler(errorViewCollector, ErrorViewCategory.SPELLS_FILE_INVALID)); try { XMLSpellLoader.load(errorViewCollector, url, xmlHelper.getDocumentBuilder(), numberSpells); } finally { documentBuilder.setErrorHandler(null); } } catch (final FileNotFoundException ex) { errorView.addWarning(ErrorViewCategory.SPELLS_FILE_INVALID, spellFile + ": " + ex.getMessage()); } numberSpells.sort(); } final File scriptsFile = new File(globalSettings.getMapsDirectory(), scriptsDir); final PluginModelParser<G, A, R> pluginModelParser = new PluginModelParser<G, A, R>(pluginParameterFactory); new PluginModelLoader<G, A, R>(pluginModelParser).loadPlugins(errorView, scriptsFile, pluginModel); new AutojoinListsParser<G, A, R>(errorView, archetypeSet, autojoinLists).loadList(globalSettings.getConfigurationDirectory()); ArchetypeTypeChecks.addChecks(archetypeTypeSet, attributeRangeChecker, environmentChecker); }
Code Sample 2:
private Document getOpenLinkResponse(String queryDoc) throws IOException, UnvalidResponseException { URL url = new URL(WS_URI); URLConnection conn = url.openConnection(); logger.debug(".conn open"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "text/xml"); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(queryDoc); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); logger.debug(".resp obtained"); StringBuffer responseBuffer = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { responseBuffer.append(line); responseBuffer.append(NEWLINE); } wr.close(); rd.close(); logger.debug(".done"); try { return documentParser.parse(responseBuffer.toString()); } catch (SAXException e) { throw new UnvalidResponseException("Response is not a valid XML file", e); } }
|
00
|
Code Sample 1:
private Callable<Request> newRequestCall(final Request request) { return new Callable<Request>() { public Request call() { InputStream is = null; try { if (DEBUG) Log.d(TAG, "Requesting: " + request.uri); HttpGet httpGet = new HttpGet(request.uri.toString()); httpGet.addHeader("Accept-Encoding", "gzip"); HttpResponse response = mHttpClient.execute(httpGet); String mimeType = response.getHeaders("Content-Type")[0].getValue(); if (DEBUG) Log.d(TAG, "mimeType:" + mimeType); if (mimeType.startsWith("image")) { HttpEntity entity = response.getEntity(); is = getUngzippedContent(entity); Bitmap bitmap = BitmapFactory.decodeStream(is); if (mResourceCache.store(request.hash, bitmap)) { mCache.put(request.uri.toString(), new SoftReference<Bitmap>(bitmap)); if (DEBUG) Log.d(TAG, "Request successful: " + request.uri); } else { mResourceCache.invalidate(request.hash); } } } catch (IOException e) { if (DEBUG) Log.d(TAG, "IOException", e); } finally { if (DEBUG) Log.e(TAG, "Request finished: " + request.uri); mActiveRequestsMap.remove(request); if (is != null) { notifyObservers(request.uri); } try { if (is != null) { is.close(); } } catch (IOException e) { if (DEBUG) e.printStackTrace(); } } return request; } }; }
Code Sample 2:
public void runTask(HashMap pjobParms) throws Exception { FTPClient lftpClient = null; FileInputStream lfisSourceFile = null; JBJFPluginDefinition lpluginCipher = null; IJBJFPluginCipher theCipher = null; try { JBJFFTPDefinition lxmlFTP = null; if (getFTPDefinition() != null) { lxmlFTP = getFTPDefinition(); this.mstrSourceDirectory = lxmlFTP.getSourceDirectory(); this.mstrTargetDirectory = lxmlFTP.getTargetDirectory(); this.mstrFilename = lxmlFTP.getFilename(); this.mstrRemoteServer = lxmlFTP.getServer(); if (getResources().containsKey("plugin-cipher")) { lpluginCipher = (JBJFPluginDefinition) getResources().get("plugin-cipher"); } if (lpluginCipher != null) { theCipher = getTaskPlugins().getCipherPlugin(lpluginCipher.getPluginId()); } if (theCipher != null) { this.mstrServerUsr = theCipher.decryptString(lxmlFTP.getUser()); this.mstrServerPwd = theCipher.decryptString(lxmlFTP.getPass()); } else { this.mstrServerUsr = lxmlFTP.getUser(); this.mstrServerPwd = lxmlFTP.getPass(); } } else { throw new Exception("Work unit [ " + SHORT_NAME + " ] is missing an FTP Definition. Please check" + " your JBJF Batch Definition file an make sure" + " this work unit has a <resource> element added" + " within the <task> element."); } lfisSourceFile = new FileInputStream(mstrSourceDirectory + File.separator + mstrFilename); lftpClient = new FTPClient(); lftpClient.connect(mstrRemoteServer); lftpClient.setFileType(lxmlFTP.getFileTransferType()); if (!FTPReply.isPositiveCompletion(lftpClient.getReplyCode())) { throw new Exception("FTP server [ " + mstrRemoteServer + " ] refused connection."); } if (!lftpClient.login(mstrServerUsr, mstrServerPwd)) { throw new Exception("Unable to login to server [ " + mstrTargetDirectory + " ]."); } if (!lftpClient.changeWorkingDirectory(mstrTargetDirectory)) { throw new Exception("Unable to change to remote directory [ " + mstrTargetDirectory + "]"); } lftpClient.enterLocalPassiveMode(); if (!lftpClient.storeFile(mstrFilename, lfisSourceFile)) { throw new Exception("Unable to upload [ " + mstrSourceDirectory + "/" + mstrFilename + " ]" + " to " + mstrTargetDirectory + File.separator + mstrFilename + " to " + mstrRemoteServer); } lfisSourceFile.close(); lftpClient.logout(); } catch (Exception e) { throw e; } finally { if (lftpClient != null && lftpClient.isConnected()) { try { lftpClient.disconnect(); } catch (IOException ioe) { } } if (lfisSourceFile != null) { try { lfisSourceFile.close(); } catch (Exception e) { } } } }
|
00
|
Code Sample 1:
private void executeScript(SQLiteDatabase sqlDatabase, InputStream input) { StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer); } catch (IOException e) { throw new ComixException("Could not read the database script", e); } String multipleSql = writer.toString(); String[] split = multipleSql.split("-- SCRIPT_SPLIT --"); for (String sql : split) { if (!sql.trim().equals("")) { sqlDatabase.execSQL(sql); } } }
Code Sample 2:
public ActionForward dbExecute(ActionMapping pMapping, ActionForm pForm, HttpServletRequest pRequest, HttpServletResponse pResponse) throws DatabaseException { SubmitRegistrationForm newUserData = (SubmitRegistrationForm) pForm; if (!newUserData.getAcceptsEULA()) { pRequest.setAttribute("acceptsEULA", new Boolean(true)); pRequest.setAttribute("noEula", new Boolean(true)); return (pMapping.findForward("noeula")); } if (newUserData.getAction().equals("none")) { newUserData.setAction("submit"); pRequest.setAttribute("UserdataBad", new Boolean(true)); return (pMapping.findForward("success")); } boolean userDataIsOk = true; if (newUserData == null) { return (pMapping.findForward("failure")); } if (newUserData.getLastName().length() < 2) { userDataIsOk = false; pRequest.setAttribute("LastNameBad", new Boolean(true)); } if (newUserData.getFirstName().length() < 2) { userDataIsOk = false; pRequest.setAttribute("FirstNameBad", new Boolean(true)); } EmailValidator emailValidator = EmailValidator.getInstance(); if (!emailValidator.isValid(newUserData.getEmailAddress())) { pRequest.setAttribute("EmailBad", new Boolean(true)); userDataIsOk = false; } else { if (database.acquireUserByEmail(newUserData.getEmailAddress()) != null) { pRequest.setAttribute("EmailDouble", new Boolean(true)); userDataIsOk = false; } } if (newUserData.getFirstPassword().length() < 5) { userDataIsOk = false; pRequest.setAttribute("FirstPasswordBad", new Boolean(true)); } if (newUserData.getSecondPassword().length() < 5) { userDataIsOk = false; pRequest.setAttribute("SecondPasswordBad", new Boolean(true)); } if (!newUserData.getSecondPassword().equals(newUserData.getFirstPassword())) { userDataIsOk = false; pRequest.setAttribute("PasswordsNotEqual", new Boolean(true)); } if (userDataIsOk) { User newUser = new User(); newUser.setFirstName(newUserData.getFirstName()); newUser.setLastName(newUserData.getLastName()); if (!newUserData.getFirstPassword().equals("")) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new DatabaseException("Could not hash password for storage: no such algorithm"); } try { md.update(newUserData.getFirstPassword().getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new DatabaseException("Could not hash password for storage: no such encoding"); } newUser.setPassword((new BASE64Encoder()).encode(md.digest())); } newUser.setEmailAddress(newUserData.getEmailAddress()); newUser.setHomepage(newUserData.getHomepage()); newUser.setAddress(newUserData.getAddress()); newUser.setInstitution(newUserData.getInstitution()); newUser.setLanguages(newUserData.getLanguages()); newUser.setDegree(newUserData.getDegree()); newUser.setNationality(newUserData.getNationality()); newUser.setTitle(newUserData.getTitle()); newUser.setActive(true); try { database.updateUser(newUser); } catch (DatabaseException e) { pRequest.setAttribute("UserstoreBad", new Boolean(true)); return (pMapping.findForward("success")); } pRequest.setAttribute("UserdataFine", new Boolean(true)); } else { pRequest.setAttribute("UserdataBad", new Boolean(true)); } return (pMapping.findForward("success")); }
|
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 static boolean sendPostRequest(String path, Map<String, String> params, String encoding) throws Exception { StringBuilder sb = new StringBuilder(""); if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), encoding)).append('&'); } sb.deleteCharAt(sb.length() - 1); } byte[] data = sb.toString().getBytes(); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5 * 1000); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); OutputStream outStream = conn.getOutputStream(); outStream.write(data); outStream.flush(); outStream.close(); if (conn.getResponseCode() == 200) { InputStream inputStream = conn.getInputStream(); return ResponseResult.parseXML(inputStream); } return false; }
|
00
|
Code Sample 1:
public String encodePassword(String rawPass, Object salt) { MessageDigest sha; try { sha = MessageDigest.getInstance("SHA"); } catch (java.security.NoSuchAlgorithmException e) { throw new LdapDataAccessException("No SHA implementation available!"); } sha.update(rawPass.getBytes()); if (salt != null) { Assert.isInstanceOf(byte[].class, salt, "Salt value must be a byte array"); sha.update((byte[]) salt); } byte[] hash = combineHashAndSalt(sha.digest(), (byte[]) salt); return (salt == null ? SHA_PREFIX : SSHA_PREFIX) + new String(Base64.encodeBase64(hash)); }
Code Sample 2:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { log.fatal("not a http request"); return; } HttpServletRequest httpRequest = (HttpServletRequest) request; String uri = httpRequest.getRequestURI(); int pathStartIdx = 0; String resourceName = null; pathStartIdx = uri.indexOf(path); if (pathStartIdx <= -1) { log.fatal("the url pattern must match: " + path + " found uri: " + uri); return; } resourceName = uri.substring(pathStartIdx + path.length()); int suffixIdx = uri.lastIndexOf('.'); if (suffixIdx <= -1) { log.fatal("no file suffix found for resource: " + uri); return; } String suffix = uri.substring(suffixIdx + 1).toLowerCase(); String mimeType = (String) mimeTypes.get(suffix); if (mimeType == null) { log.fatal("no mimeType found for resource: " + uri); log.fatal("valid mimeTypes are: " + mimeTypes.keySet()); return; } String themeName = getThemeName(); if (themeName == null) { themeName = this.themeName; } if (!themeName.startsWith("/")) { themeName = "/" + themeName; } InputStream is = null; is = ResourceFilter.class.getResourceAsStream(themeName + resourceName); if (is != null) { IOUtils.copy(is, response.getOutputStream()); response.setContentType(mimeType); response.flushBuffer(); IOUtils.closeQuietly(response.getOutputStream()); IOUtils.closeQuietly(is); } else { log.fatal("error loading resource: " + resourceName); } }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private 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 void update() { try { String passwordMD5 = new String(); if (this.password != null && this.password.length() > 0) { MessageDigest md = MessageDigest.getInstance("md5"); md.update(this.password.getBytes()); byte[] digest = md.digest(); for (int i = 0; i < digest.length; i++) { passwordMD5 += Integer.toHexString((digest[i] >> 4) & 0xf); passwordMD5 += Integer.toHexString((digest[i] & 0xf)); } } this.authCode = new String(Base64Encoder.encode(new String(this.username + ";" + passwordMD5).getBytes())); } catch (Throwable throwable) { throwable.printStackTrace(); } }
Code Sample 2:
private boolean postCorrecao() { boolean valido = false; Integer newCodCorrecao = null; String sqlmaxac = "SELECT MAX(SEQAC) FROM PPOPACAOCORRET WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=?"; String sqlmaxcq = "SELECT MAX(SEQOPCQ) + 1 FROM PPOPCQ WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=?"; try { for (Entry<Integer, JCheckBoxPad> ek : analises.entrySet()) { JCheckBoxPad cb = ek.getValue(); if ("S".equals(cb.getVlrString())) { valido = true; keysItens[2] = ek.getKey(); break; } } if (!valido) { Funcoes.mensagemInforma(this, "Selecione as analises para aplicar a corre��o!"); return false; } if (txaCausa.getVlrString().trim().length() == 0) { Funcoes.mensagemInforma(this, "Informe as causas!"); return false; } if (txaAcao.getVlrString().trim().length() == 0) { Funcoes.mensagemInforma(this, "Detalhe a a��o corretiva!"); return false; } PreparedStatement ps = con.prepareStatement(sqlmaxac); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOPACAOCORRET")); ps.setInt(3, txtCodOP.getVlrInteger()); ps.setInt(4, txtSeqOP.getVlrInteger()); ResultSet rs = ps.executeQuery(); if (rs.next()) { newCodCorrecao = rs.getInt(1) + 1; keysItens[3] = newCodCorrecao; } rs.close(); ps.close(); if (newCodCorrecao != null) { StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO PPOPACAOCORRET "); sql.append("( CODEMP, CODFILIAL, CODOP, SEQOP, SEQAC, TPCAUSA, OBSCAUSA, TPACAO, OBSACAO ) "); sql.append("VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ? )"); ps = con.prepareStatement(sql.toString()); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOPACAOCORRET")); ps.setInt(3, txtCodOP.getVlrInteger()); ps.setInt(4, txtSeqOP.getVlrInteger()); ps.setInt(5, newCodCorrecao); ps.setString(6, m.getCode()); ps.setString(7, txaCausa.getVlrString()); ps.setString(8, rgSolucao.getVlrString()); ps.setString(9, txaAcao.getVlrString()); ps.execute(); ps.close(); String strAnalises = ""; for (Entry<Integer, JCheckBoxPad> ek : analises.entrySet()) { JCheckBoxPad cb = ek.getValue(); if ("S".equals(cb.getVlrString())) { if (strAnalises.trim().length() > 0) { strAnalises += ","; } strAnalises += String.valueOf(ek.getKey()); } } sql = new StringBuilder(); sql.append("UPDATE PPOPCQ SET SEQAC=? "); sql.append("WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=? AND SEQOPCQ IN ( " + strAnalises + " )"); ps = con.prepareStatement(sql.toString()); ps.setInt(1, newCodCorrecao); ps.setInt(2, Aplicativo.iCodEmp); ps.setInt(3, ListaCampos.getMasterFilial("PPOPACAOCORRET")); ps.setInt(4, txtCodOP.getVlrInteger()); ps.setInt(5, txtSeqOP.getVlrInteger()); ps.executeUpdate(); ps.close(); sql.delete(0, sql.length()); sql.append("INSERT INTO PPOPCQ (CODEMP,CODFILIAL,CODOP,SEQOP,SEQOPCQ,"); sql.append("CODEMPEA,CODFILIALEA,CODESTANALISE) "); sql.append("SELECT CODEMP,CODFILIAL,CODOP,SEQOP,("); sql.append(sqlmaxcq); sql.append("),CODEMPEA,CODFILIALEA,CODESTANALISE "); sql.append("FROM PPOPCQ "); sql.append("WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND "); sql.append("SEQOP=? AND SEQOPCQ IN ( " + strAnalises + " )"); System.out.println(sql.toString()); ps = con.prepareStatement(sql.toString()); ps = con.prepareStatement(sql.toString()); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOPCQ")); ps.setInt(3, txtCodOP.getVlrInteger()); ps.setInt(4, txtSeqOP.getVlrInteger()); ps.setInt(5, Aplicativo.iCodEmp); ps.setInt(6, ListaCampos.getMasterFilial("PPOPCQ")); ps.setInt(7, txtCodOP.getVlrInteger()); ps.setInt(8, txtSeqOP.getVlrInteger()); ps.executeUpdate(); ps.close(); montaAnalises(); Funcoes.mensagemInforma(this, "A��o corretiva aplicada com sucesso!"); } con.commit(); } catch (Exception err) { try { con.rollback(); } catch (SQLException e) { System.out.println("Erro ao realizar rollback!\n" + err.getMessage()); } err.printStackTrace(); Funcoes.mensagemErro(this, "Erro ao atualizar analises!\n" + err.getMessage(), true, con, err); valido = false; } return valido; }
|
11
|
Code Sample 1:
public File copyFile(File f) throws IOException { File t = createNewFile("fm", "cpy"); FileOutputStream fos = new FileOutputStream(t); FileChannel foc = fos.getChannel(); FileInputStream fis = new FileInputStream(f); FileChannel fic = fis.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); return t; }
Code Sample 2:
private void appendAndDelete(FileOutputStream outstream, String file) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(file); byte[] buffer = new byte[65536]; int l; while ((l = input.read(buffer)) != -1) outstream.write(buffer, 0, l); input.close(); new File(file).delete(); }
|
00
|
Code Sample 1:
public static String SHA256(String source) { logger.info(source); String result = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(source.getBytes()); byte[] bytes = digest.digest(); result = EncodeUtils.hexEncode(bytes); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } logger.info(result); return result; }
Code Sample 2:
private boolean getRemoteFiles() throws Exception { boolean resp = false; int respCode = 0; URL url = new URL(storageUrlString); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); RequestUtils requestUtils = new RequestUtils(); requestUtils.preRequestAddParameter("senderObj", "FileGetter"); requestUtils.preRequestAddParameter("wfiType", "zen"); requestUtils.preRequestAddParameter("portalID", this.portalID); requestUtils.preRequestAddParameter("userID", this.userID); addRenameFileParameters(requestUtils); requestUtils.createPostRequest(); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + requestUtils.getBoundary()); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); try { httpURLConnection.connect(); OutputStream out = httpURLConnection.getOutputStream(); byte[] preBytes = requestUtils.getPreRequestStringBytes(); out.write(preBytes); out.flush(); byte[] postBytes = requestUtils.getPostRequestStringBytes(); out.write(postBytes); out.flush(); out.close(); respCode = httpURLConnection.getResponseCode(); if (HttpURLConnection.HTTP_OK == respCode) { resp = true; InputStream in = httpURLConnection.getInputStream(); ZipUtils.getInstance().getFilesFromStream(in, getFilesDir); in.close(); } if (respCode == 500) { resp = false; } if (respCode == 560) { resp = false; throw new Exception("Server Side Remote Exeption !!! respCode = (" + respCode + ")"); } } catch (Exception e) { e.printStackTrace(); throw new Exception("Cannot connect to: " + storageUrlString, e); } return resp; }
|
11
|
Code Sample 1:
private void refreshCacheFile(RepositoryFile file, File cacheFile) throws FileNotFoundException, IOException { FileOutputStream fos = new FileOutputStream(cacheFile); InputStream is = file.getInputStream(); int count = IOUtils.copy(is, fos); logger.debug("===========================================================> wrote bytes to cache " + count); fos.flush(); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(file.getInputStream()); }
Code Sample 2:
public static void copyFile(String target, String source) { try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { ExceptionHelper.showErrorDialog(e); } }
|
00
|
Code Sample 1:
@Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
Code Sample 2:
public String getMarketInfo() { try { URL url = new URL("http://api.eve-central.com/api/evemon"); BufferedReader s = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; String xml = ""; while ((line = s.readLine()) != null) { xml += line; } return xml; } catch (IOException ex) { ex.printStackTrace(); } return null; }
|
00
|
Code Sample 1:
private void bokActionPerformed(java.awt.event.ActionEvent evt) { if (this.tfGeneralSubDivision.getText().trim().equals("")) { this.showWarningMessage("Enter general sub division"); } else { String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds(); String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveGeneralSubDivision("1", this.tfGeneralSubDivision.getText(), patlib); System.out.println(xmlreq); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SubDivisionServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); if (rootelement.getChild("Error") == null) { this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase")); } else { this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor")); } } catch (Exception e) { System.out.println(e); } } }
Code Sample 2:
@Test public void testTransactWriteAndRead() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwritetrans.txt"); RFileOutputStream out = new RFileOutputStream(file, WriteMode.TRANSACTED, false, 1); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } }
|
00
|
Code Sample 1:
private String getPlayerName(String id) throws UnsupportedEncodingException, IOException { String result = ""; Map<String, String> players = (Map<String, String>) sc.getAttribute("players"); if (players.containsKey(id)) { result = players.get(id); System.out.println("skip name:" + result); } else { String palyerURL = "http://goal.2010worldcup.163.com/player/" + id + ".html"; URL url = new URL(palyerURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; String nameFrom = "英文名:"; String nameTo = "</dd>"; while ((line = reader.readLine()) != null) { if (line.indexOf(nameFrom) != -1) { result = line.substring(line.indexOf(nameFrom) + nameFrom.length(), line.indexOf(nameTo)); break; } } reader.close(); players.put(id, result); } return result; }
Code Sample 2:
public int readLines() { int i = 0; if (istream == null) return 0; try { String s1; if ((new String("http")).compareTo(url.getProtocol()) == 0) { istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { last_contentLenght = istream.getContentLength(); istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println("Trace2Png: ContentLength: " + Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); String s; while ((s = reader.readLine()) != null) { bytes_read = bytes_read + s.length() + 1; t2pProcessLine(trace, s); i++; } } } else { while ((s1 = reader.readLine()) != null) { bytes_read = bytes_read + s1.length() + 1; t2pProcessLine(trace, s1); i++; } } t2pHandleEventPairs(trace); t2pSort(trace, sortby); } catch (IOException ioexception) { System.out.println("Trace2Png: IOException !!!"); } return i; }
|
11
|
Code Sample 1:
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpClientInfo clientInfo = HttpUtil.parseClientInfo((HttpServletRequest) request); if (request.getParameter("_debug_") != null) { StringBuffer buffer = new StringBuffer(); Enumeration iter = request.getHeaderNames(); while (iter.hasMoreElements()) { String name = (String) iter.nextElement(); buffer.append(name + "=" + request.getHeader(name)).append("\n"); } buffer.append("\n"); iter = request.getParameterNames(); while (iter.hasMoreElements()) { String name = (String) iter.nextElement(); String value = request.getParameter(name); if (!"ISO-8859-1".equalsIgnoreCase(clientInfo.getPreferCharset())) value = new String(value.getBytes("ISO-8859-1"), clientInfo.getPreferCharset()); buffer.append(name).append("=").append(value).append("\n"); } response.setContentType("text/plain; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(buffer.toString()); return null; } Object resultObj = handleRequest(request); if (resultObj == null) { String requestException = (String) request.getAttribute("XSMP.handleRequest.Exception"); if (requestException != null) response.sendError(500, requestException); else response.setContentLength(0); } else { if (resultObj instanceof DataHandler) { response.setContentType(((DataHandler) resultObj).getContentType()); response.setContentLength(((DataHandler) resultObj).getInputStream().available()); IOUtils.copy(((DataHandler) resultObj).getInputStream(), response.getOutputStream()); } else { String temp = resultObj.toString(); if (temp.startsWith("<") && temp.endsWith(">")) response.setContentType("text/html; charset=" + clientInfo.getPreferCharset()); else response.setContentType("text/plain; charset=" + clientInfo.getPreferCharset()); byte[] buffer = temp.getBytes(clientInfo.getPreferCharset()); response.setContentLength(buffer.length); response.getOutputStream().write(buffer); } } return null; }
Code Sample 2:
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); } }
|
11
|
Code Sample 1:
public static String SHA(String s) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(s.getBytes(), 0, s.getBytes().length); byte[] hash = md.digest(); StringBuilder sb = new StringBuilder(); int msb; int lsb = 0; int i; for (i = 0; i < hash.length; i++) { msb = ((int) hash[i] & 0x000000FF) / 16; lsb = ((int) hash[i] & 0x000000FF) % 16; sb.append(hexChars[msb]); sb.append(hexChars[lsb]); } return sb.toString(); } catch (NoSuchAlgorithmException e) { return null; } }
Code Sample 2:
public static byte[] createAuthenticator(ByteBuffer data, String secret) { assert data.isDirect() == false : "must not a direct ByteBuffer"; int pos = data.position(); if (pos < RadiusPacket.MIN_PACKET_LENGTH) { System.err.println("packet too small"); return null; } try { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] arr = data.array(); md5.reset(); md5.update(arr, 0, pos); md5.update(secret.getBytes()); return md5.digest(); } catch (NoSuchAlgorithmException nsaex) { throw new RuntimeException("Could not access MD5 algorithm, fatal error"); } }
|
11
|
Code Sample 1:
public static void executa(String arquivo, String filial, String ip) { String drive = arquivo.substring(0, 2); if (drive.indexOf(":") == -1) drive = ""; Properties p = Util.lerPropriedades(arquivo); String servidor = p.getProperty("servidor"); String impressora = p.getProperty("fila"); String arqRel = new String(drive + p.getProperty("arquivo")); String copias = p.getProperty("copias"); if (filial.equalsIgnoreCase(servidor)) { Socket s = null; int tentativas = 0; boolean conectado = false; while (!conectado) { try { tentativas++; System.out.println("Tentando conectar " + ip + " (" + tentativas + ")"); s = new Socket(ip, 7000); conectado = s.isConnected(); } catch (ConnectException ce) { System.err.println(ce.getMessage()); System.err.println(ce.getCause()); } catch (UnknownHostException uhe) { System.err.println(uhe.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } } FileInputStream in = null; BufferedOutputStream out = null; try { in = new FileInputStream(new File(arqRel)); out = new BufferedOutputStream(new GZIPOutputStream(s.getOutputStream())); } catch (FileNotFoundException e3) { e3.printStackTrace(); } catch (IOException e3) { e3.printStackTrace(); } String arqtr = arqRel.substring(2); System.out.println("Proximo arquivo: " + arqRel + " ->" + arqtr); while (arqtr.length() < 30) arqtr += " "; while (impressora.length() < 30) impressora += " "; byte aux[] = new byte[30]; byte cop[] = new byte[2]; try { aux = arqtr.getBytes("UTF8"); out.write(aux); aux = impressora.getBytes("UTF8"); out.write(aux); cop = copias.getBytes("UTF8"); out.write(cop); out.flush(); } catch (UnsupportedEncodingException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } byte b[] = new byte[1024]; int nBytes; try { while ((nBytes = in.read(b)) != -1) out.write(b, 0, nBytes); out.flush(); out.close(); in.close(); s.close(); } catch (IOException e1) { e1.printStackTrace(); } System.out.println("Arquivo " + arqRel + " foi transmitido. \n\n"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } SimpleDateFormat dfArq = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat dfLog = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String arqLog = "log" + filial + dfArq.format(new Date()) + ".txt"; PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(arqLog, true)); } catch (IOException e) { e.printStackTrace(); } pw.println("Arquivo: " + arquivo + " " + dfLog.format(new Date())); pw.flush(); pw.close(); File f = new File(arquivo); while (!f.delete()) { System.out.println("Erro apagando " + arquivo); } } }
Code Sample 2:
public static Board readStream(InputStream is) throws IOException { StringWriter stringWriter = new StringWriter(); IOUtils.copy(is, stringWriter); String s = stringWriter.getBuffer().toString(); Board board = read(s); return board; }
|
11
|
Code Sample 1:
public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } }
Code Sample 2:
public void copy(File source, File destination) { try { FileInputStream fileInputStream = new FileInputStream(source); FileOutputStream fileOutputStream = new FileOutputStream(destination); FileChannel inputChannel = fileInputStream.getChannel(); FileChannel outputChannel = fileOutputStream.getChannel(); transfer(inputChannel, outputChannel, source.length(), false); fileInputStream.close(); fileOutputStream.close(); destination.setLastModified(source.lastModified()); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
Code Sample 2:
public void writeOutput(String directory) throws IOException { File f = new File(directory); int i = 0; if (f.isDirectory()) { for (AppInventorScreen screen : screens.values()) { File screenFile = new File(getScreenFilePath(f.getAbsolutePath(), screen)); screenFile.getParentFile().mkdirs(); screenFile.createNewFile(); FileWriter out = new FileWriter(screenFile); String initial = files.get(i).toString(); Map<String, String> types = screen.getTypes(); String[] lines = initial.split("\n"); for (String key : types.keySet()) { if (!key.trim().equals(screen.getName().trim())) { String value = types.get(key); boolean varFound = false; boolean importFound = false; for (String line : lines) { if (line.matches("^\\s*(public|private)\\s+" + value + "\\s+" + key + "\\s*=.*;$")) varFound = true; if (line.matches("^\\s*(public|private)\\s+" + value + "\\s+" + key + "\\s*;$")) varFound = true; if (line.matches("^\\s*import\\s+.*" + value + "\\s*;$")) importFound = true; } if (!varFound) initial = initial.replaceFirst("(?s)(?<=\\{\n)", "\tprivate " + value + " " + key + ";\n"); if (!importFound) initial = initial.replaceFirst("(?=import)", "import com.google.devtools.simple.runtime.components.android." + value + ";\n"); } } out.write(initial); out.close(); i++; } File manifestFile = new File(getManifestFilePath(f.getAbsolutePath(), manifest)); manifestFile.getParentFile().mkdirs(); manifestFile.createNewFile(); FileWriter out = new FileWriter(manifestFile); out.write(manifest.toString()); out.close(); File projectFile = new File(getProjectFilePath(f.getAbsolutePath(), project)); projectFile.getParentFile().mkdirs(); projectFile.createNewFile(); out = new FileWriter(projectFile); out.write(project.toString()); out.close(); String[] copyResourceFilenames = { "proguard.cfg", "project.properties", "libSimpleAndroidRuntime.jar", "\\.classpath", "res/drawable/icon.png", "\\.settings/org.eclipse.jdt.core.prefs" }; for (String copyResourceFilename : copyResourceFilenames) { InputStream is = getClass().getResourceAsStream("/resources/" + copyResourceFilename.replace("\\.", "")); File outputFile = new File(f.getAbsoluteFile() + File.separator + copyResourceFilename.replace("\\.", ".")); outputFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(outputFile); byte[] buf = new byte[1024]; int readBytes; if (is == null) System.out.println("/resources/" + copyResourceFilename.replace("\\.", "")); if (os == null) System.out.println(f.getAbsolutePath() + File.separator + copyResourceFilename.replace("\\.", ".")); while ((readBytes = is.read(buf)) > 0) { os.write(buf, 0, readBytes); } } for (String assetName : assets) { InputStream is = new FileInputStream(new File(assetsDir.getAbsolutePath() + File.separator + assetName)); File outputFile = new File(f.getAbsoluteFile() + File.separator + assetName); outputFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(outputFile); byte[] buf = new byte[1024]; int readBytes; while ((readBytes = is.read(buf)) > 0) { os.write(buf, 0, readBytes); } } File assetsOutput = new File(getAssetsFilePath(f.getAbsolutePath())); new File(assetsDir.getAbsoluteFile() + File.separator + "assets").renameTo(assetsOutput); } }
|
11
|
Code Sample 1:
public void copiarMidias(final File vidDir, final File imgDir) { for (int i = 0; i < getMidias().size(); i++) { try { FileChannel src = new FileInputStream(getMidias().get(i).getUrl().trim()).getChannel(); FileChannel dest; if (getMidias().get(i).getTipo().equals("video")) { FileChannel vidDest = new FileOutputStream(vidDir + "/" + processaString(getMidias().get(i).getTitulo()) + "." + retornaExtensaoMidia(getMidias().get(i))).getChannel(); dest = vidDest; } else { FileChannel midDest = new FileOutputStream(imgDir + "/" + processaString(getMidias().get(i).getTitulo()) + "." + retornaExtensaoMidia(getMidias().get(i))).getChannel(); dest = midDest; } dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (Exception e) { System.err.print(e.getMessage()); e.printStackTrace(); } } }
Code Sample 2:
public static void moveOutputAsmFile(File inputLocation, File outputLocation) throws Exception { FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(inputLocation); outputStream = new FileOutputStream(outputLocation); byte buffer[] = new byte[1024]; while (inputStream.available() > 0) { int read = inputStream.read(buffer); outputStream.write(buffer, 0, read); } inputLocation.delete(); } finally { IOUtil.closeAndIgnoreErrors(inputStream); IOUtil.closeAndIgnoreErrors(outputStream); } }
|
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:
private File downloadPDB(String pdbId) { File tempFile = new File(path + "/" + pdbId + ".pdb.gz"); File pdbHome = new File(path); if (!pdbHome.canWrite()) { System.err.println("can not write to " + pdbHome); return null; } String ftp = String.format("ftp://ftp.ebi.ac.uk/pub/databases/msd/pdb_uncompressed/pdb%s.ent", pdbId.toLowerCase()); System.out.println("Fetching " + ftp); try { URL url = new URL(ftp); InputStream conn = url.openStream(); System.out.println("writing to " + tempFile); FileOutputStream outPut = new FileOutputStream(tempFile); GZIPOutputStream gzOutPut = new GZIPOutputStream(outPut); PrintWriter pw = new PrintWriter(gzOutPut); BufferedReader fileBuffer = new BufferedReader(new InputStreamReader(conn)); String line; while ((line = fileBuffer.readLine()) != null) { pw.println(line); } pw.flush(); pw.close(); outPut.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); return null; } return tempFile; }
|
11
|
Code Sample 1:
private void appendArchive(File instClass) throws IOException { FileOutputStream out = new FileOutputStream(instClass.getName(), true); FileInputStream zipStream = new FileInputStream("install.jar"); byte[] buf = new byte[2048]; int read = zipStream.read(buf); while (read > 0) { out.write(buf, 0, read); read = zipStream.read(buf); } zipStream.close(); out.close(); }
Code Sample 2:
public void doCompress(File[] files, File out, List<String> excludedKeys) { Map<String, File> map = new HashMap<String, File>(); String parent = FilenameUtils.getBaseName(out.getName()); for (File f : files) { CompressionUtil.list(f, parent, map, excludedKeys); } if (!map.isEmpty()) { FileOutputStream fos = null; ArchiveOutputStream aos = null; InputStream is = null; try { fos = new FileOutputStream(out); aos = getArchiveOutputStream(fos); for (Map.Entry<String, File> entry : map.entrySet()) { File file = entry.getValue(); ArchiveEntry ae = getArchiveEntry(file, entry.getKey()); aos.putArchiveEntry(ae); if (file.isFile()) { IOUtils.copy(is = new FileInputStream(file), aos); IOUtils.closeQuietly(is); is = null; } aos.closeArchiveEntry(); } aos.finish(); } catch (IOException ex) { ex.printStackTrace(); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(aos); IOUtils.closeQuietly(fos); } } }
|
11
|
Code Sample 1:
public void show(HttpServletRequest request, HttpServletResponse response, String pantalla, Atributos modelos) { URL url = getRecurso(pantalla); try { IOUtils.copy(url.openStream(), response.getOutputStream()); } catch (IOException e) { throw new RuntimeException(e); } }
Code Sample 2:
public static void copy(String source, String destination) { FileReader in = null; FileWriter out = null; try { File inputFile = new File(source); File outputFile = new File(destination); in = new FileReader(inputFile); out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } }
|
11
|
Code Sample 1:
public void putFile(CompoundName file, FileInputStream fileInput) throws IOException { File fullDir = new File(REMOTE_BASE_DIR.getCanonicalPath()); for (int i = 0; i < file.size() - 1; i++) fullDir = new File(fullDir, file.get(i)); fullDir.mkdirs(); File outputFile = new File(fullDir, file.get(file.size() - 1)); FileOutputStream outStream = new FileOutputStream(outputFile); for (int byteIn = fileInput.read(); byteIn != -1; byteIn = fileInput.read()) outStream.write(byteIn); fileInput.close(); outStream.close(); }
Code Sample 2:
public TempFileTextBody(InputStream is, String mimeCharset) throws IOException { this.mimeCharset = mimeCharset; TempPath tempPath = TempStorage.getInstance().getRootTempPath(); tempFile = tempPath.createTempFile("attachment", ".txt"); OutputStream out = tempFile.getOutputStream(); IOUtils.copy(is, out); out.close(); }
|
00
|
Code Sample 1:
private void writeToFile(Body b, File mime4jFile) throws FileNotFoundException, IOException { if (b instanceof TextBody) { String charset = CharsetUtil.toJavaCharset(b.getParent().getCharset()); if (charset == null) { charset = "ISO8859-1"; } OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((TextBody) b).getReader(), out, charset); } else { OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((BinaryBody) b).getInputStream(), out); } }
Code Sample 2:
public static void main(String args[]) { int i, j, l; short NUMNUMBERS = 256; short numbers[] = new short[NUMNUMBERS]; Darjeeling.print("START"); for (l = 0; l < 100; l++) { for (i = 0; i < NUMNUMBERS; i++) numbers[i] = (short) (NUMNUMBERS - 1 - i); for (i = 0; i < NUMNUMBERS; i++) { for (j = 0; j < NUMNUMBERS - i - 1; j++) if (numbers[j] > numbers[j + 1]) { short temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } Darjeeling.print("END"); }
|
00
|
Code Sample 1:
public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
Code Sample 2:
@Override protected String doInBackground(MarketData... market) { publishProgress(-1); InputStream input = null; OutputStream output = null; long lenghtOfFile = 0; int lengthRead = 0; try { HttpGet newReq = new HttpGet(market[0].apkURL); HttpResponse response = HttpManager.execute(newReq); Log.i(Main.TAG, "req:" + response.getStatusLine().getStatusCode()); while (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY || response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY) { Log.i(Main.TAG, "redirect to:" + response.getFirstHeader("Location").getValue()); newReq = new HttpGet(response.getFirstHeader("Location").getValue()); response = HttpManager.execute(newReq); Log.i(Main.TAG, "req:" + response.getStatusLine().getStatusCode()); } lenghtOfFile = response.getEntity().getContentLength(); input = response.getEntity().getContent(); output = new FileOutputStream(market[0].getFile()); lengthRead = copy(input, output, lenghtOfFile); } catch (MalformedURLException e) { Log.w(Main.TAG, "error downloading " + market[0].apkURL, e); } catch (IOException e) { Log.w(Main.TAG, "error downloading " + market[0].apkURL, e); } finally { Log.v(Main.TAG, "failed to download " + market[0].apkURL + " " + lengthRead + "/" + lenghtOfFile); if (lenghtOfFile != 0 && lengthRead != lenghtOfFile) { Log.w(Main.TAG, "failed to download " + market[0].apkURL + " " + lengthRead + "/" + lenghtOfFile); try { if (input != null) input.close(); if (output != null) output.close(); market[0].getFile().delete(); } catch (IOException e) { e.printStackTrace(); } } } Log.v(Main.TAG, "copied " + market[0].apkURL + " to " + market[0].getFile()); return null; }
|
00
|
Code Sample 1:
private void bokActionPerformed(java.awt.event.ActionEvent evt) { if (this.tfGeneralSubDivision.getText().trim().equals("")) { this.showWarningMessage("Enter general sub division"); } else { String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds(); String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveGeneralSubDivision("1", this.tfGeneralSubDivision.getText(), patlib); System.out.println(xmlreq); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SubDivisionServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); if (rootelement.getChild("Error") == null) { this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase")); } else { this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor")); } } catch (Exception e) { System.out.println(e); } } }
Code Sample 2:
public static String get_content(String _url) throws Exception { URL url = new URL(_url); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; String content = new String(); while ((inputLine = in.readLine()) != null) { content += inputLine; } in.close(); return content; }
|
00
|
Code Sample 1:
public String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
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 { if (System.getProperty("os.name").toUpperCase().indexOf("WIN") != -1) { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } else { inChannel.transferTo(0, inChannel.size(), outChannel); } } finally { if (inChannel != null) try { inChannel.close(); } catch (Exception e) { } ; if (outChannel != null) try { outChannel.close(); } catch (Exception e) { } ; } }
|
00
|
Code Sample 1:
@Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; }
Code Sample 2:
public String encrypt(String pwd) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.out.println("Error"); } try { md5.update(pwd.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "That is not a valid encrpytion type"); } byte raw[] = md5.digest(); String empty = ""; String hash = ""; for (byte b : raw) { String tmp = empty + Integer.toHexString(b & 0xff); if (tmp.length() == 1) { tmp = 0 + tmp; } hash += tmp; } return hash; }
|
00
|
Code Sample 1:
public static byte[] crypt(String key, String salt) throws NoSuchAlgorithmException { int key_len = key.length(); if (salt.startsWith(saltPrefix)) { salt = salt.substring(saltPrefix.length()); } int salt_len = Math.min(getDollarLessLength(salt), 8); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(key.getBytes()); md5.update(saltPrefix.getBytes()); md5.update(salt.getBytes(), 0, salt_len); MessageDigest md5_alt = MessageDigest.getInstance("MD5"); md5_alt.update(key.getBytes()); md5_alt.update(salt.getBytes(), 0, salt_len); md5_alt.update(key.getBytes()); byte[] altResult = md5_alt.digest(); int cnt; for (cnt = key_len; cnt > 16; cnt -= 16) { md5.update(altResult, 0, 16); } md5.update(altResult, 0, cnt); altResult[0] = 0; for (cnt = key_len; cnt > 0; cnt >>= 1) { md5.update(((cnt & 1) != 0) ? altResult : key.getBytes(), 0, 1); } altResult = md5.digest(); for (cnt = 0; cnt < 1000; cnt++) { md5.reset(); if ((cnt & 1) != 0) { md5.update(key.getBytes()); } else { md5.update(altResult, 0, 16); } if ((cnt % 3) != 0) { md5.update(salt.getBytes(), 0, salt_len); } if ((cnt % 7) != 0) { md5.update(key.getBytes()); } if ((cnt & 1) != 0) { md5.update(altResult, 0, 16); } else { md5.update(key.getBytes()); } altResult = md5.digest(); } StringBuilder sb = new StringBuilder(); sb.append(saltPrefix); sb.append(new String(salt.getBytes(), 0, salt_len)); sb.append('$'); sb.append(b64From24bit(altResult[0], altResult[6], altResult[12], 4)); sb.append(b64From24bit(altResult[1], altResult[7], altResult[13], 4)); sb.append(b64From24bit(altResult[2], altResult[8], altResult[14], 4)); sb.append(b64From24bit(altResult[3], altResult[9], altResult[15], 4)); sb.append(b64From24bit(altResult[4], altResult[10], altResult[5], 4)); sb.append(b64From24bit((byte) 0, (byte) 0, altResult[11], 2)); return sb.toString().getBytes(); }
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 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(); }
|
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 static void copyFile(String hostname, String url, String username, String password, File targetFile) throws Exception { org.apache.commons.httpclient.HttpClient client = WebDavUtility.initClient("files-cert.rxhub.net", username, password); HttpMethod method = new GetMethod(url); client.executeMethod(method); BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(targetFile)); IOUtils.copyLarge(method.getResponseBodyAsStream(), output); }
|
11
|
Code Sample 1:
protected String insertCommand(String command) throws ServletException { String digest; try { MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm); md.update(command.getBytes()); byte bytes[] = new byte[20]; m_random.nextBytes(bytes); md.update(bytes); digest = bytesToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new ServletException("NoSuchAlgorithmException while " + "attempting to generate graph ID: " + e); } String id = System.currentTimeMillis() + "-" + digest; m_map.put(id, command); return id; }
Code Sample 2:
private static String getDigestPassword(String streamId, String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw (RuntimeException) new IllegalStateException().initCause(e); } md.update((streamId + password).getBytes()); byte[] uid = md.digest(); int length = uid.length; StringBuilder digPass = new StringBuilder(); for (int i = 0; i < length; ) { int k = uid[i++]; int iint = k & 0xff; String buf = Integer.toHexString(iint); if (buf.length() == 1) { buf = "0" + buf; } digPass.append(buf); } return digPass.toString(); }
|
11
|
Code Sample 1:
protected boolean loadJarLibrary(final String jarLib) { final String tempLib = System.getProperty("java.io.tmpdir") + File.separator + jarLib; boolean copied = IOUtils.copyFile(jarLib, tempLib); if (!copied) { return false; } System.load(tempLib); return true; }
Code Sample 2:
private void createImageArchive() throws Exception { imageArchive = new File(resoutFolder, "images.CrAr"); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(imageArchive))); out.writeInt(toNativeEndian(imageFiles.size())); for (int i = 0; i < imageFiles.size(); i++) { File f = imageFiles.get(i); out.writeLong(toNativeEndian(f.length())); out.writeLong(toNativeEndian(new File(resFolder, f.getName().substring(0, f.getName().length() - 5)).length())); } for (int i = 0; i < imageFiles.size(); i++) { BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageFiles.get(i))); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); } out.close(); }
|
11
|
Code Sample 1:
public static void copyFile(String f_in, String f_out, boolean remove) throws FileNotFoundException, IOException { if (remove) { PogoString readcode = new PogoString(PogoUtil.readFile(f_in)); readcode = PogoUtil.removeLogMessages(readcode); PogoUtil.writeFile(f_out, readcode.str); } else { FileInputStream fid = new FileInputStream(f_in); FileOutputStream fidout = new FileOutputStream(f_out); int nb = fid.available(); byte[] inStr = new byte[nb]; if (fid.read(inStr) > 0) fidout.write(inStr); fid.close(); fidout.close(); } }
Code Sample 2:
public static void main(String[] args) { for (int i = 0; i < args.length - 2; i++) { if (!CommonArguments.parseArguments(args, i, u)) { u.usage(); System.exit(1); } if (CommonParameters.startArg > (i + 1)) i = CommonParameters.startArg - 1; } if (args.length < CommonParameters.startArg + 2) { u.usage(); System.exit(1); } try { int readsize = 1024; ContentName argName = ContentName.fromURI(args[CommonParameters.startArg]); CCNHandle handle = CCNHandle.open(); File theFile = new File(args[CommonParameters.startArg + 1]); if (theFile.exists()) { System.out.println("Overwriting file: " + args[CommonParameters.startArg + 1]); } FileOutputStream output = new FileOutputStream(theFile); long starttime = System.currentTimeMillis(); CCNInputStream input; if (CommonParameters.unversioned) input = new CCNInputStream(argName, handle); else input = new CCNFileInputStream(argName, handle); if (CommonParameters.timeout != null) { input.setTimeout(CommonParameters.timeout); } byte[] buffer = new byte[readsize]; int readcount = 0; long readtotal = 0; while ((readcount = input.read(buffer)) != -1) { readtotal += readcount; output.write(buffer, 0, readcount); output.flush(); } if (CommonParameters.verbose) System.out.println("ccngetfile took: " + (System.currentTimeMillis() - starttime) + "ms"); System.out.println("Retrieved content " + args[CommonParameters.startArg + 1] + " got " + readtotal + " bytes."); System.exit(0); } catch (ConfigurationException e) { System.out.println("Configuration exception in ccngetfile: " + e.getMessage()); e.printStackTrace(); } catch (MalformedContentNameStringException e) { System.out.println("Malformed name: " + args[CommonParameters.startArg] + " " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println("Cannot write file or read content. " + e.getMessage()); e.printStackTrace(); } System.exit(1); }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine, outputLine; inputLine = in.readLine(); String dist_metric = in.readLine(); File outFile = new File("data.txt"); FileWriter outw = new FileWriter(outFile); outw.write(inputLine); outw.close(); File sample_coords = new File("sample_coords.txt"); sample_coords.delete(); File sp_coords = new File("sp_coords.txt"); sp_coords.delete(); try { System.out.println("Running python script..."); System.out.println("Command: " + "python l19test.py " + "\"" + dist_metric + "\""); Process pr = Runtime.getRuntime().exec("python l19test.py " + dist_metric); BufferedReader br = new BufferedReader(new InputStreamReader(pr.getErrorStream())); String line; while ((line = br.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); System.out.println("Process Exit Value: " + exitVal); System.out.println("done."); } catch (Exception e) { System.out.println("Unable to run python script for PCoA analysis"); } File myFile = new File("sp_coords.txt"); byte[] mybytearray = new byte[(new Long(myFile.length())).intValue()]; FileInputStream fis = new FileInputStream(myFile); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); for (int i = 0; i < myFile.length(); i++) { out.writeByte(fis.read()); } myFile = new File("sample_coords.txt"); mybytearray = new byte[(int) myFile.length()]; fis = new FileInputStream(myFile); fis.read(mybytearray); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); out.write(mybytearray); myFile = new File("evals.txt"); mybytearray = new byte[(new Long(myFile.length())).intValue()]; fis = new FileInputStream(myFile); fis.read(mybytearray); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); out.write(mybytearray); out.flush(); out.close(); in.close(); clientSocket.close(); serverSocket.close(); }
Code Sample 2:
@SuppressWarnings("unchecked") public static void unzip(String input, String output) { try { if (!output.endsWith("/")) output = output + "/"; ZipFile zip = new ZipFile(input); Enumeration entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { FileUtils.forceMkdir(new File(output + entry.getName())); } else { FileOutputStream out = new FileOutputStream(output + entry.getName()); IOUtils.copy(zip.getInputStream(entry), out); IOUtils.closeQuietly(out); } } } catch (Exception e) { log.error("�����ҵ��ļ�:" + output, e); throw new RuntimeException("�����ҵ��ļ�:" + output, e); } }
|
00
|
Code Sample 1:
public static boolean compress(ArrayList sources, File target, Manifest manifest) { try { if (sources == null || sources.size() == 0) return false; if (target.exists()) target.delete(); ZipOutputStream output = null; boolean isJar = target.getName().toLowerCase().endsWith(".jar"); if (isJar) { if (manifest != null) output = new JarOutputStream(new FileOutputStream(target), manifest); else output = new JarOutputStream(new FileOutputStream(target)); } else output = new ZipOutputStream(new FileOutputStream(target)); String baseDir = ((File) sources.get(0)).getParentFile().getAbsolutePath().replace('\\', '/'); if (!baseDir.endsWith("/")) baseDir = baseDir + "/"; int baseDirLength = baseDir.length(); ArrayList list = new ArrayList(); for (Iterator it = sources.iterator(); it.hasNext(); ) { File fileOrDir = (File) it.next(); if (isJar && (manifest != null) && fileOrDir.getName().equals("META-INF")) continue; if (fileOrDir.isDirectory()) list.addAll(getContents(fileOrDir)); else list.add(fileOrDir); } byte[] buffer = new byte[1024]; int bytesRead; for (int i = 0, n = list.size(); i < n; i++) { File file = (File) list.get(i); FileInputStream f_in = new FileInputStream(file); String filename = file.getAbsolutePath().replace('\\', '/'); if (filename.startsWith(baseDir)) filename = filename.substring(baseDirLength); if (isJar) output.putNextEntry(new JarEntry(filename)); else output.putNextEntry(new ZipEntry(filename)); while ((bytesRead = f_in.read(buffer)) != -1) output.write(buffer, 0, bytesRead); f_in.close(); output.closeEntry(); } output.close(); } catch (Exception exc) { exc.printStackTrace(); return false; } return true; }
Code Sample 2:
@Override public boolean delete(String consulta, boolean autocommit, int transactionIsolation, Connection cx) throws SQLException { filasDelete = 0; if (!consulta.contains(";")) { this.tipoConsulta = new Scanner(consulta); if (this.tipoConsulta.hasNext()) { execConsulta = this.tipoConsulta.next(); if (execConsulta.equalsIgnoreCase("delete")) { Connection conexion = cx; Statement st = null; try { conexion.setAutoCommit(autocommit); if (transactionIsolation == 1 || transactionIsolation == 2 || transactionIsolation == 4 || transactionIsolation == 8) { conexion.setTransactionIsolation(transactionIsolation); } else { throw new IllegalArgumentException("Valor invalido sobre TransactionIsolation,\n TRANSACTION_NONE no es soportado por MySQL"); } st = (Statement) conexion.createStatement(ResultSetImpl.TYPE_SCROLL_SENSITIVE, ResultSetImpl.CONCUR_UPDATABLE); conexion.setReadOnly(false); filasDelete = st.executeUpdate(consulta.trim(), Statement.RETURN_GENERATED_KEYS); if (filasDelete > -1) { if (autocommit == false) { conexion.commit(); } return true; } else { return false; } } catch (MySQLIntegrityConstraintViolationException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } catch (MySQLNonTransientConnectionException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } catch (MySQLDataException e) { System.out.println("Datos incorrectos"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } return false; } catch (MySQLSyntaxErrorException e) { System.out.println("Error en la sintaxis de la Consulta en MySQL"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } return false; } catch (SQLException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } finally { try { if (st != null) { if (!st.isClosed()) { st.close(); } } if (!conexion.isClosed()) { conexion.close(); } } catch (NullPointerException ne) { ne.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } else { throw new IllegalArgumentException("No es una instruccion Delete"); } } else { try { throw new JMySQLException("Error Grave , notifique al departamento de Soporte Tecnico \n" + email); } catch (JMySQLException ex) { Logger.getLogger(JMySQL.class.getName()).log(Level.SEVERE, null, ex); return false; } } } else { throw new IllegalArgumentException("No estan permitidas las MultiConsultas en este metodo"); } }
|
00
|
Code Sample 1:
public InputStream getResourceAsStream(String name) { InputStream is = parent.getResourceAsStream(name); if (is == null) { URL url = findResource(name); if (url != null) { try { is = url.openStream(); } catch (IOException e) { is = null; } } } return is; }
Code Sample 2:
public String sruRead(String initialURL) { out('\n'); out(" trying: "); out(initialURL); out('\n'); numTests++; URL url = null; try { url = new URL(initialURL); } catch (java.net.MalformedURLException e) { out("</pre><pre class='red'>"); out("test failed: using URL: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } HttpURLConnection huc = null; try { huc = (HttpURLConnection) url.openConnection(); } catch (IOException e) { out("</pre><pre class='red'>"); out("test failed: using URL: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } String contentType = huc.getContentType(); if (contentType == null || (contentType.indexOf("text/xml") < 0 && contentType.indexOf("application/xml") < 0)) { out(" ** Warning: Content-Type not set to text/xml or application/xml"); out('\n'); out(" Content-type: "); out(contentType); out('\n'); numWarns++; } InputStream urlStream = null; try { urlStream = huc.getInputStream(); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: opening URL: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(urlStream)); boolean xml = true; String href = null, inputLine = null; StringBuffer content = new StringBuffer(), stylesheet = null; Transformer transformer = null; try { inputLine = in.readLine(); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: reading first line of response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } if (inputLine == null) { out("</pre><pre class='red'>"); out("test failed: No input read from URL"); out('\n'); out("</pre><pre>"); return null; } if (!inputLine.startsWith("<?xml ")) { xml = false; content.append(inputLine); } if (xml) { int offset = inputLine.indexOf('>'); if (offset + 2 < inputLine.length()) { inputLine = inputLine.substring(offset + 1); offset = inputLine.indexOf('<'); if (offset > 0) inputLine = inputLine.substring(offset); } else try { inputLine = in.readLine(); while (inputLine.length() == 0) inputLine = in.readLine(); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: reading response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } if (inputLine.startsWith("<?xml-stylesheet ")) { offset = inputLine.indexOf("href="); href = (inputLine.substring(inputLine.indexOf("href=") + 6)); href = href.substring(0, href.indexOf('"')); transformer = (Transformer) transformers.get(href); if (stylesheets.get(href) == null) try { out(" reading stylesheet: "); out(href); out('\n'); out(" from source: "); out(url.toString()); out('\n'); StreamSource source = new StreamSource(url.toString()); TransformerFactory tFactory = TransformerFactory.newInstance(); Source stylesht = tFactory.getAssociatedStylesheet(source, null, null, null); transformer = tFactory.newTransformer(stylesht); transformers.put(href, transformer); } catch (Exception e) { e.printStackTrace(); out("</pre><pre class='red'>"); out("unable to load stylesheet: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); } stylesheets.put(href, href); } else content.append(inputLine); } try { while ((inputLine = in.readLine()) != null) content.append(inputLine); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: reading response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } String contentStr = content.toString(); if (transformer != null) { StreamSource streamXMLRecord = new StreamSource(new StringReader(contentStr)); StringWriter xmlRecordWriter = new StringWriter(); try { transformer.transform(streamXMLRecord, new StreamResult(xmlRecordWriter)); out(" successfully applied stylesheet '"); out(href); out("'"); out('\n'); } catch (javax.xml.transform.TransformerException e) { out("</pre><pre class='red'>"); out("unable to apply stylesheet '"); out(href); out("'to response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); e.printStackTrace(); } } return contentStr; }
|
00
|
Code Sample 1:
public void login(String a_username, String a_password) throws GB_SecurityException { Exception l_exception = null; try { if (clientFtp == null) { clientFtp = new FTPClient(); clientFtp.connect("ftp://" + ftp); } boolean b = clientFtp.login(a_username, a_password); if (b) { username = a_username; password = a_password; return; } } catch (Exception ex) { l_exception = ex; } String l_msg = "Cannot login to ftp server with user [{1}], {2}"; String[] l_replaces = new String[] { a_username, ftp }; l_msg = STools.replace(l_msg, l_replaces); throw new GB_SecurityException(l_msg, l_exception); }
Code Sample 2:
public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
|
00
|
Code Sample 1:
public static String generateHash(String msg) throws NoSuchAlgorithmException { if (msg == null) { throw new IllegalArgumentException("Input string can not be null"); } MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); m.update(msg.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1, digest); String hashText = bigInt.toString(16); while (hashText.length() < 32) { hashText = "0" + hashText; } return hashText; }
Code Sample 2:
private static void executeSQLScript() { File f = new File(System.getProperty("user.dir") + "/resources/umc.sql"); if (f.exists()) { Connection con = null; PreparedStatement pre_stmt = null; try { Class.forName("org.sqlite.JDBC"); con = DriverManager.getConnection("jdbc:sqlite:database/umc.db", "", ""); BufferedReader br = new BufferedReader(new FileReader(f)); String line = ""; con.setAutoCommit(false); while ((line = br.readLine()) != null) { if (!line.equals("") && !line.startsWith("--") && !line.contains("--")) { log.debug(line); pre_stmt = con.prepareStatement(line); pre_stmt.executeUpdate(); } } con.commit(); File dest = new File(f.getAbsolutePath() + ".executed"); if (dest.exists()) dest.delete(); f.renameTo(dest); f.delete(); } catch (Throwable exc) { log.error("Fehler bei Ausführung der SQL Datei", exc); try { con.rollback(); } catch (SQLException exc1) { } } finally { try { if (pre_stmt != null) pre_stmt.close(); if (con != null) con.close(); } catch (SQLException exc2) { log.error("Fehler bei Ausführung von SQL Datei", exc2); } } } }
|
00
|
Code Sample 1:
private static void writeUrl(String filePath, String data, String charCoding, boolean urlIsFile) throws IOException { int chunkLength; OutputStream os = null; try { if (!urlIsFile) { URL urlObj = new URL(filePath); URLConnection uc = urlObj.openConnection(); os = uc.getOutputStream(); if (charCoding == null) { String type = uc.getContentType(); if (type != null) { charCoding = getCharCodingFromType(type); } } } else { File f = new File(filePath); os = new FileOutputStream(f); } Writer w; if (charCoding == null) { w = new OutputStreamWriter(os); } else { w = new OutputStreamWriter(os, charCoding); } w.write(data); w.flush(); } finally { if (os != null) os.close(); } }
Code Sample 2:
public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
|
00
|
Code Sample 1:
public RandomAccessFileOrArray(URL url) throws IOException { InputStream is = url.openStream(); try { this.arrayIn = InputStreamToArray(is); } finally { try { is.close(); } catch (IOException ioe) { } } }
Code Sample 2:
public static int executeNoQuery(String strStatement) throws SQLException { MyDBConnection myc = new MyDBConnection(); myc.init(); Statement statement = myc.getMyConnection().createStatement(); try { int rows = statement.executeUpdate(strStatement); myc.myConnection.commit(); return rows; } catch (SQLException e) { myc.myConnection.rollback(); throw new SQLException("rollback e close effettuato dopo " + e.getMessage()); } finally { myc.close(); } }
|
11
|
Code Sample 1:
public boolean executeUpdate(String strSql, HashMap<Integer, Object> prams) throws SQLException, ClassNotFoundException { getConnection(); boolean flag = false; try { pstmt = con.prepareStatement(strSql); setParamet(pstmt, prams); logger.info("###############::执行SQL语句操作(更新数据 有参数):" + strSql); if (0 < pstmt.executeUpdate()) { close_DB_Object(); flag = true; con.commit(); } } catch (SQLException ex) { logger.info("###############Error DBManager Line121::执行SQL语句操作(更新数据 无参数):" + strSql + "失败!"); flag = false; con.rollback(); throw ex; } catch (ClassNotFoundException ex) { logger.info("###############Error DBManager Line152::执行SQL语句操作(更新数据 无参数):" + strSql + "失败! 参数设置类型错误!"); con.rollback(); throw ex; } return flag; }
Code Sample 2:
public void delete(String language, String tag, int row) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { String sql = "delete from LanguageMorphologies " + "where LanguageName = '" + language + "' and MorphologyTag = '" + tag + "' and " + " Rank = " + row; conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate(sql); bumpAllRowsUp(stmt, language, tag, row); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
|
00
|
Code Sample 1:
private void weightAndPlaceClasses() { int rows = getRows(); for (int curRow = _maxPackageRank; curRow < rows; curRow++) { xPos = getHGap() / 2; BOTLObjectSourceDiagramNode[] rowObject = getObjectsInRow(curRow); for (int i = 0; i < rowObject.length; i++) { if (curRow == _maxPackageRank) { int nDownlinks = rowObject[i].getDownlinks().size(); rowObject[i].setWeight((nDownlinks > 0) ? (1 / nDownlinks) : 2); } else { Vector uplinks = rowObject[i].getUplinks(); int nUplinks = uplinks.size(); if (nUplinks > 0) { float average_col = 0; for (int j = 0; j < uplinks.size(); j++) { average_col += ((BOTLObjectSourceDiagramNode) (uplinks.elementAt(j))).getColumn(); } average_col /= nUplinks; rowObject[i].setWeight(average_col); } else { rowObject[i].setWeight(1000); } } } int[] pos = new int[rowObject.length]; for (int i = 0; i < pos.length; i++) { pos[i] = i; } boolean swapped = true; while (swapped) { swapped = false; for (int i = 0; i < pos.length - 1; i++) { if (rowObject[pos[i]].getWeight() > rowObject[pos[i + 1]].getWeight()) { int temp = pos[i]; pos[i] = pos[i + 1]; pos[i + 1] = temp; swapped = true; } } } for (int i = 0; i < pos.length; i++) { rowObject[pos[i]].setColumn(i); if ((i > _vMax) && (rowObject[pos[i]].getUplinks().size() == 0) && (rowObject[pos[i]].getDownlinks().size() == 0)) { if (getColumns(rows - 1) > _vMax) { rows++; } rowObject[pos[i]].setRank(rows - 1); } else { rowObject[pos[i]].setLocation(new Point(xPos, yPos)); xPos += rowObject[pos[i]].getSize().getWidth() + getHGap(); } } yPos += getRowHeight(curRow) + getVGap(); } }
Code Sample 2:
@SuppressWarnings("unchecked") public void handle(Map<String, Object> data, String urlPath) { try { URL url = new URL(urlPath); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; CMGroup currentGroup = null; List<CMGroup> groups = (List<CMGroup>) data.get(CMConstants.GROUP); List<CMTag> tags = (List<CMTag>) data.get(CMConstants.TAG); List<CMTagGroup> tagGroups = (List<CMTagGroup>) data.get(CMConstants.TAG_GROUP); while ((line = reader.readLine()) != null) { CMGroup group = null; try { group = FetchUtil.getCMGroup(line); } catch (Exception e) { CMLog.getLogger(this).severe("getCMGroup error:" + line); } if (group != null) { if (currentGroup != null) { groups.add(currentGroup); } currentGroup = group; } CMTag tag = null; try { tag = FetchUtil.getCMTag(line); } catch (Exception e) { CMLog.getLogger(this).severe("getCMTag error:" + line); } if (tag != null) { CMTagGroup tagGroup = new CMTagGroup(); tagGroup.setGroupName(currentGroup.getName()); tagGroup.setTagName(tag.getName()); tags.add(tag); tagGroups.add(tagGroup); } } groups.add(currentGroup); reader.close(); } catch (MalformedURLException e) { CMLog.getLogger(this).severe("GTagHandler error:" + e.getMessage()); e.printStackTrace(); } catch (IOException e) { CMLog.getLogger(this).severe("GTagHandler error:" + e.getMessage()); e.printStackTrace(); } }
|
11
|
Code Sample 1:
private void doTask() { try { log("\n\n\n\n\n\n\n\n\n"); log(" ================================================="); log(" = Starting PSCafePOS ="); log(" ================================================="); log(" = An open source point of sale system ="); log(" = for educational organizations. ="); log(" ================================================="); log(" = General Information ="); log(" = http://pscafe.sourceforge.net ="); log(" = Free Product Support ="); log(" = http://www.sourceforge.net/projects/pscafe ="); log(" ================================================="); log(" = License Overview ="); log(" ================================================="); log(" = PSCafePOS is a POS System for Schools ="); log(" = Copyright (C) 2007 Charles Syperski ="); log(" = ="); log(" = This program is free software; you can ="); log(" = redistribute it and/or modify it under the ="); log(" = terms of the GNU General Public License as ="); log(" = published by the Free Software Foundation; ="); log(" = either version 2 of the License, or any later ="); log(" = version. ="); log(" = ="); log(" = This program is distributed in the hope that ="); log(" = it will be useful, but WITHOUT ANY WARRANTY; ="); log(" = without even the implied warranty of ="); log(" = MERCHANTABILITY or FITNESS FOR A PARTICULAR ="); log(" = PURPOSE. ="); log(" = ="); log(" = See the GNU General Public License for more ="); log(" = details. ="); log(" = ="); log(" = You should have received a copy of the GNU ="); log(" = General Public License along with this ="); log(" = program; if not, write to the ="); log(" = ="); log(" = Free Software Foundation, Inc. ="); log(" = 59 Temple Place, Suite 330 ="); log(" = Boston, MA 02111-1307 USA ="); log(" ================================================="); log(" = If you have any questions of comments please ="); log(" = let us know at http://pscafe.sourceforge.net ="); log(" ================================================="); pause(); File settings; if (blAltSettings) { System.out.println("\n + Alternative path specified at run time:"); System.out.println(" Path: " + strAltPath); settings = new File(strAltPath); } else { settings = new File("etc" + File.separatorChar + "settings.dbp"); } System.out.print("\n + Checking for existance of settings..."); boolean blGo = false; if (settings.exists() && settings.canRead()) { log("[OK]"); blGo = true; if (forceConfig) { System.out.print("\n + Running Config Wizard (at user request)..."); Process pp = Runtime.getRuntime().exec("java -cp . PSSettingWizard etc" + File.separatorChar + "settings.dbp"); InputStream stderr = pp.getErrorStream(); InputStream stdin = pp.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String ln = null; while ((ln = br.readLine()) != null) System.out.println(" " + ln); pp.waitFor(); } } else { log("[FAILED]"); settings = new File("etc" + File.separatorChar + "settings.dbp.firstrun"); System.out.print("\n + Checking if this is the first run... "); if (settings.exists() && settings.canRead()) { log("[FOUND]"); File toFile = new File("etc" + File.separatorChar + "settings.dbp"); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(settings); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } if (toFile.exists() && toFile.canRead()) { settings = null; settings = new File("etc" + File.separatorChar + "settings.dbp"); } System.out.print("\n + Running Settings Wizard... "); try { Process p = Runtime.getRuntime().exec("java PSSettingWizard etc" + File.separatorChar + "settings.dbp"); InputStream stderr = p.getErrorStream(); InputStream stdin = p.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String ln = null; while ((ln = br.readLine()) != null) System.out.println(" " + ln); p.waitFor(); log("[OK]"); if (p.exitValue() == 0) blGo = true; } catch (InterruptedException i) { System.err.println(i.getMessage()); } } catch (Exception ex) { System.err.println(ex.getMessage()); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } else { settings = null; settings = new File("etc" + File.separatorChar + "settings.dbp"); DBSettingsWriter writ = new DBSettingsWriter(); writ.writeFile(new DBSettings(), settings); blGo = true; } } if (blGo) { String cp = "."; try { File classpath = new File("lib"); File[] subFiles = classpath.listFiles(); for (int i = 0; i < subFiles.length; i++) { if (subFiles[i].isFile()) { cp += File.pathSeparatorChar + "lib" + File.separatorChar + subFiles[i].getName() + ""; } } } catch (Exception e) { System.err.println(e.getMessage()); } try { boolean blExecutePOS = false; System.out.print("\n + Checking runtime settings... "); DBSettings info = null; if (settings == null) settings = new File("etc" + File.separatorChar + "settings.dbp"); if (settings.exists() && settings.canRead()) { DBSettingsWriter writ = new DBSettingsWriter(); info = (DBSettings) writ.loadSettingsDB(settings); if (info != null) { blExecutePOS = true; } } if (blExecutePOS) { log("[OK]"); String strSSL = ""; String strSSLDebug = ""; if (info != null) { debug = info.get(DBSettings.MAIN_DEBUG).compareTo("1") == 0; if (debug) log(" * Debug Mode is ON"); else log(" * Debug Mode is OFF"); if (info.get(DBSettings.POS_SSLENABLED).compareTo("1") == 0) { strSSL = "-Djavax.net.ssl.keyStore=" + info.get(DBSettings.POS_SSLKEYSTORE) + " -Djavax.net.ssl.keyStorePassword=pscafe -Djavax.net.ssl.trustStore=" + info.get(DBSettings.POS_SSLTRUSTSTORE) + " -Djavax.net.ssl.trustStorePassword=pscafe"; log(" * Using SSL"); debug(" " + strSSL); if (info.get(DBSettings.POS_SSLDEBUG).compareTo("1") == 0) { strSSLDebug = "-Djavax.net.debug=all"; log(" * SSL Debugging enabled"); debug(" " + strSSLDebug); } } } String strPOSRun = "java -cp " + cp + " " + strSSL + " " + strSSLDebug + " POSDriver " + settings.getPath(); debug(strPOSRun); System.out.print("\n + Running PSCafePOS... "); Process pr = Runtime.getRuntime().exec(strPOSRun); System.out.print("[OK]\n\n"); InputStream stderr = pr.getErrorStream(); InputStream stdin = pr.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); InputStreamReader isre = new InputStreamReader(stderr); BufferedReader br = new BufferedReader(isr); BufferedReader bre = new BufferedReader(isre); String line = null; String lineError = null; log(" ================================================="); log(" = Output from PSCafePOS System ="); log(" ================================================="); while ((line = br.readLine()) != null || (lineError = bre.readLine()) != null) { if (line != null) System.out.println(" [PSCafePOS]" + line); if (lineError != null) System.out.println(" [ERR]" + lineError); } pr.waitFor(); log(" ================================================="); log(" = End output from PSCafePOS System ="); log(" = PSCafePOS has exited ="); log(" ================================================="); } else { log("[Failed]"); } } catch (Exception i) { log(i.getMessage()); i.printStackTrace(); } } } catch (Exception e) { log(e.getMessage()); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
public static void fileCopy(File src, File dest) throws IOException { IOException xforward = null; FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); final int MB32 = 32 * 1024 * 1024; long size = fcin.size(); long position = 0; while (position < size) { position += fcin.transferTo(position, MB32, fcout); } } catch (IOException xio) { xforward = xio; } finally { if (fis != null) try { fis.close(); fis = null; } catch (IOException xio) { } if (fos != null) try { fos.close(); fos = null; } catch (IOException xio) { } if (fcin != null && fcin.isOpen()) try { fcin.close(); fcin = null; } catch (IOException xio) { } if (fcout != null && fcout.isOpen()) try { fcout.close(); fcout = null; } catch (IOException xio) { } } if (xforward != null) { throw xforward; } }
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 void xtest7() throws Exception { System.out.println("Lowagie"); FileInputStream inputStream = new FileInputStream("C:/Temp/arquivo.pdf"); PDFBoxManager manager = new PDFBoxManager(); InputStream[] images = manager.toImage(inputStream, "jpeg"); int count = 0; for (InputStream image : images) { FileOutputStream outputStream = new FileOutputStream("C:/Temp/arquivo_" + count + ".jpg"); IOUtils.copy(image, outputStream); count++; outputStream.close(); } inputStream.close(); }
Code Sample 2:
private RemoteObject createRemoteObject(final VideoEntry videoEntry, final RemoteContainer container) throws RemoteException { MessageDigest instance; try { instance = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RemoteException(StatusCreator.newStatus("Error creating MD5", e)); } StringWriter sw = new StringWriter(); YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup(); if (mediaGroup != null) { if (mediaGroup.getDescription() != null) { sw.append(mediaGroup.getDescription().getPlainTextContent()); } List<MediaCategory> keywordsGroup = mediaGroup.getCategories(); StringBuilder sb = new StringBuilder(); if (keywordsGroup != null) { for (MediaCategory mediaCategory : keywordsGroup) { sb.append(mediaCategory.getContent()); } } } instance.update(sw.toString().getBytes()); RemoteObject remoteVideo = InfomngmntFactory.eINSTANCE.createRemoteObject(); remoteVideo.setHash(asHex(instance.digest())); remoteVideo.setId(SiteInspector.getId(videoEntry.getHtmlLink().getHref())); remoteVideo.setName(videoEntry.getTitle().getPlainText()); remoteVideo.setRepositoryTypeObjectId(KEY_VIDEO); remoteVideo.setWrappedObject(videoEntry); setInternalUrl(remoteVideo, container); return remoteVideo; }
|
11
|
Code Sample 1:
public void applyTo(File source, File target) throws IOException { boolean failed = true; FileInputStream fin = new FileInputStream(source); try { FileChannel in = fin.getChannel(); FileOutputStream fos = new FileOutputStream(target); try { FileChannel out = fos.getChannel(); long pos = 0L; for (Replacement replacement : replacements) { in.transferTo(pos, replacement.pos - pos, out); if (replacement.val != null) out.write(ByteBuffer.wrap(replacement.val)); pos = replacement.pos + replacement.len; } in.transferTo(pos, source.length() - pos, out); failed = false; } finally { fos.close(); if (failed == true) target.delete(); } } finally { fin.close(); } }
Code Sample 2:
public static void writeToFile(final File file, final InputStream in) throws IOException { IOUtils.createFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copyStream(in, fos); } finally { IOUtils.closeIO(fos); } }
|
11
|
Code Sample 1:
private void copia(FileInputStream input, FileOutputStream output) throws ErrorException { if (input == null || output == null) { throw new ErrorException("Param null"); } FileChannel inChannel = input.getChannel(); FileChannel outChannel = output.getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (IOException e) { throw new ErrorException("Casino nella copia del file"); } }
Code Sample 2:
void execute(HttpClient client, MonitoredService svc) { try { URI uri = getURI(svc); PageSequenceHttpMethod method = getMethod(); method.setURI(uri); if (getVirtualHost() != null) { method.getParams().setVirtualHost(getVirtualHost()); } if (getUserAgent() != null) { method.addRequestHeader("User-Agent", getUserAgent()); } if (m_parms.length > 0) { method.setParameters(m_parms); } if (m_page.getUserInfo() != null) { String userInfo = m_page.getUserInfo(); String[] streetCred = userInfo.split(":", 2); if (streetCred.length == 2) { client.getState().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(streetCred[0], streetCred[1])); method.setDoAuthentication(true); } } int code = client.executeMethod(method); if (!getRange().contains(code)) { throw new PageSequenceMonitorException("response code out of range for uri:" + uri + ". Expected " + getRange() + " but received " + code); } InputStream inputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } String responseString = outputStream.toString(); if (getFailurePattern() != null) { Matcher matcher = getFailurePattern().matcher(responseString); if (matcher.find()) { throw new PageSequenceMonitorException(getResolvedFailureMessage(matcher)); } } if (getSuccessPattern() != null) { Matcher matcher = getSuccessPattern().matcher(responseString); if (!matcher.find()) { throw new PageSequenceMonitorException("failed to find '" + getSuccessPattern() + "' in page content at " + uri); } } } catch (URIException e) { throw new IllegalArgumentException("unable to construct URL for page: " + e, e); } catch (HttpException e) { throw new PageSequenceMonitorException("HTTP Error " + e, e); } catch (IOException e) { throw new PageSequenceMonitorException("I/O Error " + e, e); } }
|
00
|
Code Sample 1:
private void enumeratePathArchive(final String archive) throws IOException { final boolean trace1 = m_trace1; final File fullArchive = new File(m_currentPathDir, archive); JarInputStream in = null; try { in = new JarInputStream(new BufferedInputStream(new FileInputStream(fullArchive), 32 * 1024)); final IPathHandler handler = m_handler; Manifest manifest = in.getManifest(); if (manifest == null) manifest = readManifestViaJarFile(fullArchive); handler.handleArchiveStart(m_currentPathDir, new File(archive), manifest); for (ZipEntry entry; (entry = in.getNextEntry()) != null; ) { if (trace1) m_log.trace1("enumeratePathArchive", "processing archive entry [" + entry.getName() + "] ..."); handler.handleArchiveEntry(in, entry); in.closeEntry(); } if (m_processManifest) { if (manifest == null) manifest = in.getManifest(); if (manifest != null) { final Attributes attributes = manifest.getMainAttributes(); if (attributes != null) { final String jarClassPath = attributes.getValue(Attributes.Name.CLASS_PATH); if (jarClassPath != null) { final StringTokenizer tokenizer = new StringTokenizer(jarClassPath); for (int p = 1; tokenizer.hasMoreTokens(); ) { final String relPath = tokenizer.nextToken(); final File archiveParent = fullArchive.getParentFile(); final File path = archiveParent != null ? new File(archiveParent, relPath) : new File(relPath); final String fullPath = m_canonical ? Files.canonicalizePathname(path.getPath()) : path.getPath(); if (m_pathSet.add(fullPath)) { if (m_verbose) m_log.verbose(" added manifest Class-Path entry [" + path + "]"); m_path.add(m_pathIndex + (p++), path); } } } } } } } catch (FileNotFoundException fnfe) { if ($assert.ENABLED) throw fnfe; } finally { if (in != null) try { in.close(); } catch (Exception ignore) { } } }
Code Sample 2:
private CExtractHelper getData(String p_url) { CExtractHelper l_extractHelper = new CExtractHelper(); URL l_url; HttpURLConnection l_connection; try { System.out.println("Getting [" + p_url + "]"); l_url = new URL(p_url); try { URLConnection l_uconn = l_url.openConnection(); l_connection = (HttpURLConnection) l_uconn; l_connection.setConnectTimeout(2000); l_connection.setReadTimeout(2000); l_connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"); l_connection.connect(); int l_responseCode = l_connection.getResponseCode(); String response = l_connection.getResponseMessage(); System.out.println("HTTP/1.x " + l_responseCode + " " + response); for (int j = 1; ; j++) { String l_header = l_connection.getHeaderField(j); String l_key = l_connection.getHeaderFieldKey(j); if (l_header == null || l_key == null) { break; } } InputStream l_inputStream = new BufferedInputStream(l_connection.getInputStream()); CRemoteXML l_parser = new CRemoteXML(); try { Document l_document = l_parser.parse(l_inputStream); PrintWriter l_writerOut = new PrintWriter(new OutputStreamWriter(System.out, charsetName), true); OutputFormat l_format = OutputFormat.createPrettyPrint(); XMLWriter l_xmlWriter = new XMLWriter(l_writerOut, l_format); l_xmlWriter.write(l_document); l_xmlWriter.flush(); l_connection.disconnect(); l_extractHelper.m_document = l_document; return l_extractHelper; } catch (DocumentException e) { e.printStackTrace(); l_connection.disconnect(); System.out.println("XML parsing issue"); l_extractHelper.m_generalFailure = true; } } catch (SocketTimeoutException e) { l_extractHelper.m_timeoutFailure = true; System.out.println("Timed out"); } catch (IOException e) { e.printStackTrace(); l_extractHelper.m_generalFailure = true; } } catch (MalformedURLException e) { e.printStackTrace(); l_extractHelper.m_generalFailure = true; } return l_extractHelper; }
|
00
|
Code Sample 1:
public static void writeURLToFile(String url, String path) throws MalformedURLException, IOException { java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL(url).openStream()); java.io.FileOutputStream fos = new java.io.FileOutputStream(path); java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024); byte data[] = new byte[1024]; int count; while ((count = in.read(data, 0, 1024)) != -1) { ; bout.write(data, 0, count); } bout.close(); in.close(); }
Code Sample 2:
private void zipdir(File base, String zipname) throws IOException { FilenameFilter ff = new ExporterFileNameFilter(); String[] files = base.list(ff); File zipfile = new File(base, zipname + ".zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipfile)); byte[] buf = new byte[10240]; for (int i = 0; i < files.length; i++) { File f = new File(base, files[i]); FileInputStream fis = new FileInputStream(f); zos.putNextEntry(new ZipEntry(f.getName())); int len; while ((len = fis.read(buf)) > 0) zos.write(buf, 0, len); zos.closeEntry(); fis.close(); f.delete(); } zos.close(); }
|
11
|
Code Sample 1:
private void chooseGame(DefaultHttpClient httpclient) throws IOException, ClientProtocolException { HttpGet httpget = new HttpGet(Constants.STRATEGICDOMINATION_URL + "/gameboard.cgi?gameid=" + 1687); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("cg form get: " + response.getStatusLine()); if (entity != null) { InputStream inStream = entity.getContent(); IOUtils.copy(inStream, System.out); } System.out.println("cg set of cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } }
Code Sample 2:
public static boolean saveMap(LWMap map, boolean saveAs, boolean export) { Log.info("saveMap: " + map); GUI.activateWaitCursor(); if (map == null) return false; File file = map.getFile(); int response = -1; if (map.getSaveFileModelVersion() == 0) { final Object[] defaultOrderButtons = { VueResources.getString("saveaction.saveacopy"), VueResources.getString("saveaction.save") }; Object[] messageObject = { map.getLabel() }; response = VueUtil.option(VUE.getDialogParent(), VueResources.getFormatMessage(messageObject, "dialog.saveaction.message"), VueResources.getFormatMessage(messageObject, "dialog.saveaction.title"), JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, defaultOrderButtons, VueResources.getString("saveaction.saveacopy")); } if (response == 0) { saveAs = true; } if ((saveAs || file == null) && !export) { file = ActionUtil.selectFile("Save Map", null); } else if (export) { file = ActionUtil.selectFile("Export Map", "export"); } if (file == null) { try { return false; } finally { GUI.clearWaitCursor(); } } try { Log.info("saveMap: target[" + file + "]"); final String name = file.getName().toLowerCase(); if (name.endsWith(".rli.xml")) { new IMSResourceList().convert(map, file); } else if (name.endsWith(".xml") || name.endsWith(".vue")) { ActionUtil.marshallMap(file, map); } else if (name.endsWith(".jpeg") || name.endsWith(".jpg")) ImageConversion.createActiveMapJpeg(file, VueResources.getDouble("imageExportFactor")); else if (name.endsWith(".png")) ImageConversion.createActiveMapPng(file, VueResources.getDouble("imageExportFactor")); else if (name.endsWith(".svg")) SVGConversion.createSVG(file); else if (name.endsWith(".pdf")) { PresentationNotes.createMapAsPDF(file); } else if (name.endsWith(".zip")) { Vector resourceVector = new Vector(); Iterator i = map.getAllDescendents(LWComponent.ChildKind.PROPER).iterator(); while (i.hasNext()) { LWComponent component = (LWComponent) i.next(); System.out.println("Component:" + component + " has resource:" + component.hasResource()); if (component.hasResource() && (component.getResource() instanceof URLResource)) { URLResource resource = (URLResource) component.getResource(); try { if (resource.isLocalFile()) { String spec = resource.getSpec(); System.out.println(resource.getSpec()); Vector row = new Vector(); row.add(new Boolean(true)); row.add(resource); row.add(new Long(file.length())); row.add("Ready"); resourceVector.add(row); } } catch (Exception ex) { System.out.println("Publisher.setLocalResourceVector: Resource " + resource.getSpec() + ex); ex.printStackTrace(); } } } File savedCMap = PublishUtil.createZip(map, resourceVector); InputStream istream = new BufferedInputStream(new FileInputStream(savedCMap)); OutputStream ostream = new BufferedOutputStream(new FileOutputStream(file)); int fileLength = (int) savedCMap.length(); byte bytes[] = new byte[fileLength]; try { while (istream.read(bytes, 0, fileLength) != -1) ostream.write(bytes, 0, fileLength); } catch (Exception e) { e.printStackTrace(); } finally { istream.close(); ostream.close(); } } else if (name.endsWith(".html")) { HtmlOutputDialog hod = new HtmlOutputDialog(); hod.setVisible(true); if (hod.getReturnVal() > 0) new ImageMap().createImageMap(file, hod.getScale(), hod.getFormat()); } else if (name.endsWith(".rdf")) { edu.tufts.vue.rdf.RDFIndex index = new edu.tufts.vue.rdf.RDFIndex(); String selectionType = VueResources.getString("rdf.export.selection"); if (selectionType.equals("ALL")) { Iterator<LWMap> maps = VUE.getLeftTabbedPane().getAllMaps(); while (maps.hasNext()) { index.index(maps.next()); } } else if (selectionType.equals("ACTIVE")) { index.index(VUE.getActiveMap()); } else { index.index(VUE.getActiveMap()); } FileWriter writer = new FileWriter(file); index.write(writer); writer.close(); } else if (name.endsWith(VueUtil.VueArchiveExtension)) { Archive.writeArchive(map, file); } else { Log.warn("Unknown save type for filename extension: " + name); return false; } Log.debug("Save completed for " + file); if (!VUE.isApplet()) { VueFrame frame = (VueFrame) VUE.getMainWindow(); String title = VUE.getName() + ": " + name; frame.setTitle(title); } if (name.endsWith(".vue")) { RecentlyOpenedFilesManager rofm = RecentlyOpenedFilesManager.getInstance(); rofm.updateRecentlyOpenedFiles(file.getAbsolutePath()); } return true; } catch (Throwable t) { Log.error("Exception attempting to save file " + file + ": " + t); Throwable e = t; if (t.getCause() != null) e = t.getCause(); if (e instanceof java.io.FileNotFoundException) { Log.error("Save Failed: " + e); } else { Log.error("Save failed for \"" + file + "\"; ", e); } if (e != t) Log.error("Exception attempting to save file " + file + ": " + e); VueUtil.alert(String.format(Locale.getDefault(), VueResources.getString("saveaction.savemap.error") + "\"%s\";\n" + VueResources.getString("saveaction.targetfiel") + "\n\n" + VueResources.getString("saveaction.problem"), map.getLabel(), file, Util.formatLines(e.toString(), 80)), "Problem Saving Map"); } finally { GUI.invokeAfterAWT(new Runnable() { public void run() { GUI.clearWaitCursor(); } }); } return false; }
|
11
|
Code Sample 1:
@Override public boolean copyFile(String srcRootPath, String srcDir, String srcFileName, String destRootPath, String destDir, String destFileName) { File srcPath = new File(srcRootPath + separator() + Database.getDomainName() + separator() + srcDir); if (!srcPath.exists()) { try { srcPath.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + srcPath); return false; } } File destPath = new File(destRootPath + separator() + Database.getDomainName() + separator() + destDir); if (!destPath.exists()) { try { destPath.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + destPath); return false; } } File from = new File(srcPath + separator() + srcFileName); File to = new File(destPath + separator() + destFileName); boolean res = true; FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(from).getChannel(); destChannel = new FileOutputStream(to).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (Exception ex) { logger.error("Exception", ex); res = false; } finally { if (destChannel != null) { try { destChannel.close(); } catch (IOException ex) { logger.error("Exception", ex); res = false; } } if (srcChannel != null) { try { srcChannel.close(); } catch (IOException ex) { logger.error("Exception", ex); res = false; } } } return res; }
Code Sample 2:
private 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(); } }
|
00
|
Code Sample 1:
public static File copyFile(File file) { File src = file; File dest = new File(src.getName()); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
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); } }
|
11
|
Code Sample 1:
public static void copy(final File src, final File dst) throws IOException, IllegalArgumentException { long fileSize = src.length(); final FileInputStream fis = new FileInputStream(src); final FileOutputStream fos = new FileOutputStream(dst); final FileChannel in = fis.getChannel(), out = fos.getChannel(); try { long offs = 0, doneCnt = 0; final long copyCnt = Math.min(65536, fileSize); do { doneCnt = in.transferTo(offs, copyCnt, out); offs += doneCnt; fileSize -= doneCnt; } while (fileSize > 0); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } try { fis.close(); } catch (final IOException e) { } try { fos.close(); } catch (final IOException e) { } src.delete(); } }
Code Sample 2:
public File createFileFromClasspathResource(String resourceUrl) throws IOException { File fichierTest = File.createTempFile("xmlFieldTestFile", ""); FileOutputStream fos = new FileOutputStream(fichierTest); InputStream is = DefaultXmlFieldSelectorTest.class.getResourceAsStream(resourceUrl); IOUtils.copy(is, fos); is.close(); fos.close(); return fichierTest; }
|
00
|
Code Sample 1:
private String createCSVFile(String fileName) throws FileNotFoundException, IOException { String csvFile = fileName + ".csv"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); BufferedWriter out = new BufferedWriter(new FileWriter(csvFile)); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return csvFile; }
Code Sample 2:
protected String updateTwitter() { if (updatingTwitter) return null; updatingTwitter = true; String highestId = null; final Cursor cursor = query(TWITTER_TABLE, new String[] { KEY_TWEET_ID }, null, null, null); if (cursor.getCount() > 0) { cursor.moveToFirst(); highestId = cursor.getString(cursor.getColumnIndex(KEY_TWEET_ID)); } cursor.close(); final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); nameValuePairs.add(new BasicNameValuePair("screen_name", TWITTER_ACCOUNT)); nameValuePairs.add(new BasicNameValuePair("count", "" + MAX_TWEETS)); if (highestId != null) nameValuePairs.add(new BasicNameValuePair("since_id", highestId)); final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); final HttpParams params = new BasicHttpParams(); final SingleClientConnManager mgr = new SingleClientConnManager(params, schemeRegistry); final HttpClient httpclient = new DefaultHttpClient(mgr, params); final HttpGet request = new HttpGet(); final String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8"); String data = ""; try { final URI uri = new URI(TWITTER_URL + "?" + paramString); request.setURI(uri); final HttpResponse response = httpclient.execute(request); final BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) data += inputLine; in.close(); } catch (final URISyntaxException e) { e.printStackTrace(); updatingTwitter = false; return "failed"; } catch (final ClientProtocolException e) { e.printStackTrace(); updatingTwitter = false; return "failed"; } catch (final IOException e) { e.printStackTrace(); updatingTwitter = false; return "failed"; } try { final JSONArray tweets = new JSONArray(data); if (tweets == null) { updatingTwitter = false; return "failed"; } if (tweets.length() == 0) { updatingTwitter = false; return "none"; } final SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH); final SimpleDateFormat parser = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH); for (int i = 0; i < tweets.length(); i++) { final JSONObject tweet = tweets.getJSONObject(i); final ContentValues values = new ContentValues(); Log.v(TAG, "Datum van tweet: " + tweet.getString(KEY_TWEET_DATE)); values.put(KEY_TWEET_DATE, formatter.format(parser.parse(tweet.getString(KEY_TWEET_DATE)))); values.put(KEY_TWEET_TEXT, tweet.getString(KEY_TWEET_TEXT)); values.put(KEY_TWEET_ID, tweet.getString(KEY_TWEET_ID)); insert(TWITTER_TABLE, values); } } catch (final JSONException e) { Log.v(TAG, "JSON decodering is mislukt."); e.printStackTrace(); updatingTwitter = false; return "failed"; } catch (final ParseException e) { Log.v(TAG, "Datum decodering is mislukt."); e.printStackTrace(); updatingTwitter = false; return "failed"; } purgeTweets(); updatingTwitter = false; return "success"; }
|
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 String merge(int width, int height) throws Exception { htErrors.clear(); sendGetImageRequests(width, height); Vector files = new Vector(); ConcurrentHTTPTransactionHandler c = new ConcurrentHTTPTransactionHandler(); c.setCache(cache); c.checkIfModified(false); for (int i = 0; i < vImageUrls.size(); i++) { if ((String) vImageUrls.get(i) != null) { c.register((String) vImageUrls.get(i)); } else { } } c.doTransactions(); vTransparency = new Vector(); for (int i = 0; i < vImageUrls.size(); i++) { if (vImageUrls.get(i) != null) { String path = c.getResponseFilePath((String) vImageUrls.get(i)); if (path != null) { String contentType = c.getHeaderValue((String) vImageUrls.get(i), "content-type"); if (contentType.startsWith("image")) { files.add(path); vTransparency.add(htTransparency.get(vRank.get(i))); } } } } if (files.size() > 1) { File output = TempFiles.getFile(); String path = output.getPath(); ImageMerger.mergeAndSave(files, vTransparency, path, ImageMerger.GIF); imageName = output.getName(); imagePath = output.getPath(); return (imageName); } else if (files.size() == 1) { File f = new File((String) files.get(0)); File out = TempFiles.getFile(); BufferedInputStream is = new BufferedInputStream(new FileInputStream(f)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(out)); byte buf[] = new byte[1024]; for (int nRead; (nRead = is.read(buf, 0, 1024)) > 0; os.write(buf, 0, nRead)) ; os.flush(); os.close(); is.close(); imageName = out.getName(); return imageName; } else return ""; }
|
11
|
Code Sample 1:
public String getResource(String resourceName) throws IOException { InputStream resourceStream = resourceClass.getResourceAsStream(resourceName); ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); IOUtils.copyAndClose(resourceStream, baos); String expected = new String(baos.toByteArray()); return expected; }
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); InputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); } }
|
11
|
Code Sample 1:
private void unpackBundle() throws IOException { File useJarPath = null; if (DownloadManager.isWindowsVista()) { useJarPath = lowJarPath; File jarDir = useJarPath.getParentFile(); if (jarDir != null) { jarDir.mkdirs(); } } else { useJarPath = jarPath; } DownloadManager.log("Unpacking " + this + " to " + useJarPath); InputStream rawStream = new FileInputStream(localPath); JarInputStream in = new JarInputStream(rawStream) { public void close() throws IOException { } }; try { File jarTmp = null; JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { String entryName = entry.getName(); if (entryName.equals("classes.pack")) { File packTmp = new File(useJarPath + ".pack"); packTmp.getParentFile().mkdirs(); DownloadManager.log("Writing temporary .pack file " + packTmp); OutputStream tmpOut = new FileOutputStream(packTmp); try { DownloadManager.send(in, tmpOut); } finally { tmpOut.close(); } jarTmp = new File(useJarPath + ".tmp"); DownloadManager.log("Writing temporary .jar file " + jarTmp); unpack(packTmp, jarTmp); packTmp.delete(); } else if (!entryName.startsWith("META-INF")) { File dest; if (DownloadManager.isWindowsVista()) { dest = new File(lowJavaPath, entryName.replace('/', File.separatorChar)); } else { dest = new File(DownloadManager.JAVA_HOME, entryName.replace('/', File.separatorChar)); } if (entryName.equals(BUNDLE_JAR_ENTRY_NAME)) dest = useJarPath; File destTmp = new File(dest + ".tmp"); boolean exists = dest.exists(); if (!exists) { DownloadManager.log(dest + ".mkdirs()"); dest.getParentFile().mkdirs(); } try { DownloadManager.log("Using temporary file " + destTmp); FileOutputStream out = new FileOutputStream(destTmp); try { byte[] buffer = new byte[2048]; int c; while ((c = in.read(buffer)) > 0) out.write(buffer, 0, c); } finally { out.close(); } if (exists) dest.delete(); DownloadManager.log("Renaming from " + destTmp + " to " + dest); if (!destTmp.renameTo(dest)) { throw new IOException("unable to rename " + destTmp + " to " + dest); } } catch (IOException e) { if (!exists) throw e; } } } if (jarTmp != null) { if (useJarPath.exists()) jarTmp.delete(); else if (!jarTmp.renameTo(useJarPath)) { throw new IOException("unable to rename " + jarTmp + " to " + useJarPath); } } if (DownloadManager.isWindowsVista()) { DownloadManager.log("Using broker to move " + name); if (!DownloadManager.moveDirWithBroker(DownloadManager.getKernelJREDir() + name)) { throw new IOException("unable to create " + name); } DownloadManager.log("Broker finished " + name); } DownloadManager.log("Finished unpacking " + this); } finally { rawStream.close(); } if (deleteOnInstall) { localPath.delete(); } }
Code Sample 2:
public void run() { GZIPInputStream gzipInputStream = null; try { gzipInputStream = new GZIPInputStream(pipedInputStream); IOUtils.copy(gzipInputStream, outputStream); } catch (Throwable t) { ungzipThreadThrowableList.add(t); } finally { IOUtils.closeQuietly(gzipInputStream); IOUtils.closeQuietly(pipedInputStream); } }
|
11
|
Code Sample 1:
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String fileName = request.getParameter("tegsoftFileName"); if (fileName.startsWith("Tegsoft_BACKUP_")) { fileName = fileName.substring("Tegsoft_BACKUP_".length()); String targetFileName = "/home/customer/" + fileName; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (fileName.equals("Tegsoft_ASTMODULES")) { String targetFileName = tobeHome + "/setup/Tegsoft_ASTMODULES.tgz"; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (fileName.equals("Tegsoft_ASTSBIN")) { String targetFileName = tobeHome + "/setup/Tegsoft_ASTSBIN.tgz"; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (!fileName.startsWith("Tegsoft_")) { return; } if (!fileName.endsWith(".zip")) { return; } if (fileName.indexOf("_") < 0) { return; } fileName = fileName.substring(fileName.indexOf("_") + 1); if (fileName.indexOf("_") < 0) { return; } String fileType = fileName.substring(0, fileName.indexOf("_")); String destinationFileName = tobeHome + "/setup/Tegsoft_" + fileName; if (!new File(destinationFileName).exists()) { if ("FORMS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/forms", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("IMAGES".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/image", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("VIDEOS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/videos", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("TEGSOFTJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName, "Tegsoft", "jar"); } else if ("TOBEJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName, "Tobe", "jar"); } else if ("ALLJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("DB".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/sql", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("CONFIGSERVICE".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/init.d/", tobeHome + "/setup/Tegsoft_" + fileName, "tegsoft", null); } else if ("CONFIGSCRIPTS".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/root/", tobeHome + "/setup/Tegsoft_" + fileName, "tegsoft", null); } else if ("CONFIGFOP".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/fop/", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("CONFIGASTERISK".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/asterisk/", tobeHome + "/setup/Tegsoft_" + fileName); } } response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(destinationFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); } catch (Exception ex) { ex.printStackTrace(); } }
Code Sample 2:
public static File enregistrerFichier(String fileName, File file, String path, String fileMime) throws Exception { if (file != null) { try { HttpServletRequest request = ServletActionContext.getRequest(); HttpSession session = request.getSession(); String pathFile = session.getServletContext().getRealPath(path) + File.separator + fileName; File outfile = new File(pathFile); String[] nomPhotoTab = fileName.split("\\."); String extension = nomPhotoTab[nomPhotoTab.length - 1]; StringBuffer pathResBuff = new StringBuffer(nomPhotoTab[0]); for (int i = 1; i < nomPhotoTab.length - 1; i++) { pathResBuff.append(".").append(nomPhotoTab[i]); } String pathRes = pathResBuff.toString(); String nomPhoto = fileName; for (int i = 0; !outfile.createNewFile(); i++) { nomPhoto = pathRes + "_" + +i + "." + extension; pathFile = session.getServletContext().getRealPath(path) + File.separator + nomPhoto; outfile = new File(pathFile); } logger.debug(" enregistrerFichier - Enregistrement du fichier : " + pathFile); FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(outfile).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return outfile; } catch (IOException e) { logger.error("Erreur lors de l'enregistrement de l'image ", e); throw new Exception("Erreur lors de l'enregistrement de l'image "); } } return null; }
|
11
|
Code Sample 1:
public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>"); System.exit(1); } try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream in = new FileInputStream(args[1]); int len = 0; byte buf[] = new byte[1024]; while ((len = in.read(buf)) > 0) os.write(buf, 0, len); in.close(); os.close(); byte[] data = null; if (args[0].equals("dec")) data = decode(os.toString()); else { String strData = encode(os.toByteArray()); data = strData.getBytes(); } FileOutputStream fos = new FileOutputStream(args[2]); fos.write(data); fos.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private void copyFile(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(); }
|
11
|
Code Sample 1:
public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("GET REQUEST OR RESPONSE - Send content: " + file.getAbsolutePath()); FileInputStream in = null; try { in = new FileInputStream(file); int bytes = IOUtils.copy(in, out); LOGGER.debug("wrote bytes: " + bytes); out.flush(); } finally { IOUtils.closeQuietly(in); } }
Code Sample 2:
private void output(HttpServletResponse resp, InputStream is, long length, String fileName) throws Exception { resp.reset(); String mimeType = "image/jpeg"; resp.setContentType(mimeType); resp.setContentLength((int) length); resp.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\""); resp.setHeader("Cache-Control", "must-revalidate"); ServletOutputStream sout = resp.getOutputStream(); IOUtils.copy(is, sout); sout.flush(); resp.flushBuffer(); }
|
11
|
Code Sample 1:
@Deprecated public boolean backupLuceneIndex(int indexLocation, int backupLocation) { boolean result = false; try { System.out.println("lucene backup started"); String indexPath = this.getIndexFolderPath(indexLocation); String backupPath = this.getIndexFolderPath(backupLocation); File inDir = new File(indexPath); boolean flag = true; if (inDir.exists() && inDir.isDirectory()) { File filesList[] = inDir.listFiles(); if (filesList != null) { File parDirBackup = new File(backupPath); if (!parDirBackup.exists()) parDirBackup.mkdir(); String date = this.getDate(); backupPath += "/" + date; File dirBackup = new File(backupPath); if (!dirBackup.exists()) dirBackup.mkdir(); else { File files[] = dirBackup.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i] != null) { files[i].delete(); } } } dirBackup.delete(); dirBackup.mkdir(); } for (int i = 0; i < filesList.length; i++) { if (filesList[i].isFile()) { try { File destFile = new File(backupPath + "/" + filesList[i].getName()); if (!destFile.exists()) destFile.createNewFile(); FileInputStream in = new FileInputStream(filesList[i]); FileOutputStream out = new FileOutputStream(destFile); FileChannel fcIn = in.getChannel(); FileChannel fcOut = out.getChannel(); fcIn.transferTo(0, fcIn.size(), fcOut); } catch (FileNotFoundException ex) { System.out.println("FileNotFoundException ---->" + ex); flag = false; } catch (IOException excIO) { System.out.println("IOException ---->" + excIO); flag = false; } } } } } System.out.println("lucene backup finished"); System.out.println("flag ========= " + flag); if (flag) { result = true; } } catch (Exception e) { System.out.println("Exception in backupLuceneIndex Method : " + e); e.printStackTrace(); } return result; }
Code Sample 2:
public static File enregistrerFichier(String fileName, File file, String path, String fileMime) throws Exception { if (file != null) { try { HttpServletRequest request = ServletActionContext.getRequest(); HttpSession session = request.getSession(); String pathFile = session.getServletContext().getRealPath(path) + File.separator + fileName; File outfile = new File(pathFile); String[] nomPhotoTab = fileName.split("\\."); String extension = nomPhotoTab[nomPhotoTab.length - 1]; StringBuffer pathResBuff = new StringBuffer(nomPhotoTab[0]); for (int i = 1; i < nomPhotoTab.length - 1; i++) { pathResBuff.append(".").append(nomPhotoTab[i]); } String pathRes = pathResBuff.toString(); String nomPhoto = fileName; for (int i = 0; !outfile.createNewFile(); i++) { nomPhoto = pathRes + "_" + +i + "." + extension; pathFile = session.getServletContext().getRealPath(path) + File.separator + nomPhoto; outfile = new File(pathFile); } logger.debug(" enregistrerFichier - Enregistrement du fichier : " + pathFile); FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(outfile).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return outfile; } catch (IOException e) { logger.error("Erreur lors de l'enregistrement de l'image ", e); throw new Exception("Erreur lors de l'enregistrement de l'image "); } } return null; }
|
00
|
Code Sample 1:
@SuppressWarnings("unchecked") protected void displayFreeMarkerResponse(HttpServletRequest request, HttpServletResponse response, String templateName, Map<String, Object> variableMap) throws IOException { Enumeration<String> attrNameEnum = request.getSession().getAttributeNames(); String attrName; while (attrNameEnum.hasMoreElements()) { attrName = attrNameEnum.nextElement(); if (attrName != null && attrName.startsWith(ADMIN4J_SESSION_VARIABLE_PREFIX)) { variableMap.put("Session" + attrName, request.getSession().getAttribute(attrName)); } } variableMap.put("RequestAdmin4jCurrentUri", request.getRequestURI()); Template temp = FreemarkerUtils.createConfiguredTemplate(this.getClass(), templateName); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); try { temp.process(variableMap, new OutputStreamWriter(outStream)); response.setContentLength(outStream.size()); IOUtils.copy(new ByteArrayInputStream(outStream.toByteArray()), response.getOutputStream()); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e) { throw new Admin4jRuntimeException(e); } }
Code Sample 2:
@Override protected String doInBackground(Void... params) { try { HttpGet request = new HttpGet(UPDATE_URL); request.setHeader("Accept", "text/plain"); HttpResponse response = MyMovies.getHttpClient().execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { return "Error: Failed getting update notes"; } return EntityUtils.toString(response.getEntity()); } catch (Exception e) { return "Error: " + e.getMessage(); } }
|
00
|
Code Sample 1:
public void importarHistoricoDeProventos(File pArquivoXLS, boolean pFiltrarPelaDataDeCorteDoCabecalho, Andamento pAndamento) throws IOException, SQLException, InvalidFormatException { int iLinha = -1; String nomeDaColuna = ""; Statement stmtLimpezaInicialDestino = null; OraclePreparedStatement stmtDestino = null; try { Workbook arquivo = WorkbookFactory.create(new FileInputStream(pArquivoXLS)); Sheet plan1 = arquivo.getSheetAt(0); int QUANTIDADE_DE_REGISTROS_DE_METADADOS = 2; int quantidadeDeRegistrosEstimada = plan1.getPhysicalNumberOfRows() - QUANTIDADE_DE_REGISTROS_DE_METADADOS; String vNomeDePregao, vTipoDaAcao, vDataDaAprovacao, vTipoDoProvento, vDataDoUltimoPrecoCom; BigDecimal vValorDoProvento, vUltimoPrecoCom, vProventoPorPreco; int vProventoPor1Ou1000Acoes, vPrecoPor1Ou1000Acoes; java.sql.Date vUltimoDiaCom; DateFormat formatadorData = new SimpleDateFormat("yyyyMMdd"); DateFormat formatadorPadraoData = DateFormat.getDateInstance(); Row registro; Cell celula; java.util.Date dataLimite = plan1.getRow(0).getCell(CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.ordinal()).getDateCellValue(); Cell celulaUltimoDiaCom; java.util.Date tmpUltimoDiaCom; stmtLimpezaInicialDestino = conDestino.createStatement(); String sql = "TRUNCATE TABLE TMP_TB_PROVENTO_EM_DINHEIRO"; stmtLimpezaInicialDestino.executeUpdate(sql); sql = "INSERT INTO TMP_TB_PROVENTO_EM_DINHEIRO(NOME_DE_PREGAO, TIPO_DA_ACAO, DATA_DA_APROVACAO, VALOR_DO_PROVENTO, PROVENTO_POR_1_OU_1000_ACOES, TIPO_DO_PROVENTO, ULTIMO_DIA_COM, DATA_DO_ULTIMO_PRECO_COM, ULTIMO_PRECO_COM, PRECO_POR_1_OU_1000_ACOES, PERC_PROVENTO_POR_PRECO) VALUES(:NOME_DE_PREGAO, :TIPO_DA_ACAO, :DATA_DA_APROVACAO, :VALOR_DO_PROVENTO, :PROVENTO_POR_1_OU_1000_ACOES, :TIPO_DO_PROVENTO, :ULTIMO_DIA_COM, :DATA_DO_ULTIMO_PRECO_COM, :ULTIMO_PRECO_COM, :PRECO_POR_1_OU_1000_ACOES, :PERC_PROVENTO_POR_PRECO)"; stmtDestino = (OraclePreparedStatement) conDestino.prepareStatement(sql); stmtDestino.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosImportados = 0; final int NUMERO_DA_LINHA_INICIAL = 1; for (iLinha = NUMERO_DA_LINHA_INICIAL; true; iLinha++) { registro = plan1.getRow(iLinha); if (registro != null) { nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_DIA_COM.toString(); celulaUltimoDiaCom = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_DIA_COM.ordinal()); if (celulaUltimoDiaCom != null) { if (celulaUltimoDiaCom.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpUltimoDiaCom = celulaUltimoDiaCom.getDateCellValue(); if (tmpUltimoDiaCom.compareTo(dataLimite) <= 0 || !pFiltrarPelaDataDeCorteDoCabecalho) { vUltimoDiaCom = new java.sql.Date(celulaUltimoDiaCom.getDateCellValue().getTime()); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.toString(); vNomeDePregao = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DA_ACAO.toString(); vTipoDaAcao = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DA_ACAO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.DATA_DA_APROVACAO.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.DATA_DA_APROVACAO.ordinal()); try { java.util.Date tmpDataDaAprovacao; if (celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpDataDaAprovacao = celula.getDateCellValue(); } else { tmpDataDaAprovacao = formatadorPadraoData.parse(celula.getStringCellValue()); } vDataDaAprovacao = formatadorData.format(tmpDataDaAprovacao); } catch (ParseException ex) { vDataDaAprovacao = celula.getStringCellValue(); } nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.VALOR_DO_PROVENTO.toString(); vValorDoProvento = new BigDecimal(String.valueOf(registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.VALOR_DO_PROVENTO.ordinal()).getNumericCellValue())); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_1_OU_1000_ACOES.toString(); vProventoPor1Ou1000Acoes = (int) registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_1_OU_1000_ACOES.ordinal()).getNumericCellValue(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DO_PROVENTO.toString(); vTipoDoProvento = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DO_PROVENTO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.DATA_DO_ULTIMO_PRECO_COM.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.DATA_DO_ULTIMO_PRECO_COM.ordinal()); if (celula != null) { try { java.util.Date tmpDataDoUltimoPrecoCom; if (celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpDataDoUltimoPrecoCom = celula.getDateCellValue(); } else { tmpDataDoUltimoPrecoCom = formatadorPadraoData.parse(celula.getStringCellValue()); } vDataDoUltimoPrecoCom = formatadorData.format(tmpDataDoUltimoPrecoCom); } catch (ParseException ex) { vDataDoUltimoPrecoCom = celula.getStringCellValue().trim(); } } else { vDataDoUltimoPrecoCom = ""; } nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_PRECO_COM.toString(); vUltimoPrecoCom = new BigDecimal(String.valueOf(registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_PRECO_COM.ordinal()).getNumericCellValue())); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PRECO_POR_1_OU_1000_ACOES.toString(); vPrecoPor1Ou1000Acoes = (int) registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PRECO_POR_1_OU_1000_ACOES.ordinal()).getNumericCellValue(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_PRECO.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_PRECO.ordinal()); if (celula != null && celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { vProventoPorPreco = new BigDecimal(String.valueOf(celula.getNumericCellValue())); } else { vProventoPorPreco = null; } stmtDestino.clearParameters(); stmtDestino.setStringAtName("NOME_DE_PREGAO", vNomeDePregao); stmtDestino.setStringAtName("TIPO_DA_ACAO", vTipoDaAcao); stmtDestino.setStringAtName("DATA_DA_APROVACAO", vDataDaAprovacao); stmtDestino.setBigDecimalAtName("VALOR_DO_PROVENTO", vValorDoProvento); stmtDestino.setIntAtName("PROVENTO_POR_1_OU_1000_ACOES", vProventoPor1Ou1000Acoes); stmtDestino.setStringAtName("TIPO_DO_PROVENTO", vTipoDoProvento); stmtDestino.setDateAtName("ULTIMO_DIA_COM", vUltimoDiaCom); stmtDestino.setStringAtName("DATA_DO_ULTIMO_PRECO_COM", vDataDoUltimoPrecoCom); stmtDestino.setBigDecimalAtName("ULTIMO_PRECO_COM", vUltimoPrecoCom); stmtDestino.setIntAtName("PRECO_POR_1_OU_1000_ACOES", vPrecoPor1Ou1000Acoes); stmtDestino.setBigDecimalAtName("PERC_PROVENTO_POR_PRECO", vProventoPorPreco); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportados++; } } } else { break; } double percentualCompleto = (double) quantidadeDeRegistrosImportados / quantidadeDeRegistrosEstimada * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } else { break; } } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); ProblemaNaImportacaoDeArquivo problemaDetalhado = new ProblemaNaImportacaoDeArquivo(); problemaDetalhado.nomeDoArquivo = pArquivoXLS.getName(); problemaDetalhado.linhaProblematicaDoArquivo = iLinha + 1; problemaDetalhado.colunaProblematicaDoArquivo = nomeDaColuna; problemaDetalhado.detalhesSobreOProblema = ex; throw problemaDetalhado; } finally { pAndamento.setPercentualCompleto(100); if (stmtLimpezaInicialDestino != null && (!stmtLimpezaInicialDestino.isClosed())) { stmtLimpezaInicialDestino.close(); } if (stmtDestino != null && (!stmtDestino.isClosed())) { stmtDestino.close(); } } }
Code Sample 2:
public static synchronized String hash(String plaintext) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { return null; } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { return null; } byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); }
|
00
|
Code Sample 1:
private static void writeUrl(String filePath, String data, String charCoding, boolean urlIsFile) throws IOException { int chunkLength; OutputStream os = null; try { if (!urlIsFile) { URL urlObj = new URL(filePath); URLConnection uc = urlObj.openConnection(); os = uc.getOutputStream(); if (charCoding == null) { String type = uc.getContentType(); if (type != null) { charCoding = getCharCodingFromType(type); } } } else { File f = new File(filePath); os = new FileOutputStream(f); } Writer w; if (charCoding == null) { w = new OutputStreamWriter(os); } else { w = new OutputStreamWriter(os, charCoding); } w.write(data); w.flush(); } finally { if (os != null) os.close(); } }
Code Sample 2:
public void run() { isRunning = true; try { URL url = new URL("http://dcg.ethz.ch/projects/sinalgo/version"); URLConnection con = url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.connect(); PrintStream ps = new PrintStream(con.getOutputStream()); ps.println("GET index.html HTTP/1.1"); ps.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String line = in.readLine(); if (line != null) { if (line.equals(Configuration.versionString)) { if (displayIfOK) { Main.info("You are using the most recent version of Sinalgo."); } } else { String msg = "\n" + "+----------------------------------------------------------------------\n" + "| You are currently running Sinalgo " + Configuration.versionString + ".\n" + "| A more recent version of Sinalgo is available (" + line + ")\n" + "+---------------------------------------------------------------------\n" + "| To download the latest version, please visit\n" + "| http://sourceforge.net/projects/sinalgo/\n" + "+---------------------------------------------------------------------\n" + "| You may turn off these version checks through the 'Settings' dialog.\n" + "| Note: Sinalgo automatically tests for updates at most once\n" + "| every 24 hours.\n" + "+---------------------------------------------------------------------\n"; Main.warning(msg); } } } catch (Exception e) { String msg = "\n" + ">----------------------------------------------------------------------\n" + "> Unable to test for updates of Sinalgo. The installed version\n" + "> is " + Configuration.versionString + "\n" + ">---------------------------------------------------------------------\n" + "> To check for more recent versions, please visit\n" + "> http://sourceforge.net/projects/sinalgo/\n" + ">---------------------------------------------------------------------\n" + "> You may turn off these version checks through the 'Settings' dialog.\n" + "| Note: Sinalgo automatically tests for updates at most once\n" + "| every 24 hours.\n" + ">---------------------------------------------------------------------\n"; Main.warning(msg); } finally { isRunning = false; AppConfig.getAppConfig().timeStampOfLastUpdateCheck = System.currentTimeMillis(); } }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); }
Code Sample 2:
public static void main(String[] a) { ArrayList<String> allFilesToBeCopied = new ArrayList<String>(); new File(outputDir).mkdirs(); try { FileReader fis = new FileReader(completeFileWithDirToCathFileList); BufferedReader bis = new BufferedReader(fis); String line = ""; String currentCombo = ""; while ((line = bis.readLine()) != null) { String[] allEntries = line.split("\\s+"); String fileName = allEntries[0]; String thisCombo = allEntries[1] + allEntries[2] + allEntries[3] + allEntries[4]; if (currentCombo.equals(thisCombo)) { } else { System.out.println("merke: " + fileName); allFilesToBeCopied.add(fileName); currentCombo = thisCombo; } } System.out.println(allFilesToBeCopied.size()); for (String file : allFilesToBeCopied) { try { FileChannel srcChannel = new FileInputStream(CathDir + file).getChannel(); FileChannel dstChannel = new FileOutputStream(outputDir + file).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dst) throws IOException { FileChannel inChannel = new FileInputStream(src).getChannel(); FileChannel outChannel = new FileOutputStream(dst).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
Code Sample 2:
public static void main(String[] args) { final String filePath1 = "e:\\mysite\\data\\up\\itsite"; final String filePath2 = "d:\\works\\itsite\\itsite"; IOUtils.listAllFilesNoRs(new File(filePath2), new FileFilter() { @Override public boolean accept(File file) { if (file.getName().equals(".svn")) { return false; } final long modify = file.lastModified(); final long time = DateUtils.toDate("2012-03-21 17:43", "yyyy-MM-dd HH:mm").getTime(); if (modify >= time) { if (file.isFile()) { File f = new File(StringsUtils.replace(file.getAbsolutePath(), filePath2, filePath1)); f.getParentFile().mkdirs(); try { IOUtils.copyFile(file, f); } catch (IOException e) { e.printStackTrace(); } System.out.println(f.getName()); } } return true; } }); }
|
00
|
Code Sample 1:
public void loginToServer() { new Thread(new Runnable() { public void run() { if (!shouldLogin) { u.p("skipping the auto-login"); return; } try { u.p("logging in to the server"); String query = "hostname=blahfoo2.com" + "&osname=" + URLEncoder.encode(System.getProperty("os.name"), "UTF-8") + "&javaver=" + URLEncoder.encode(System.getProperty("java.runtime.version"), "UTF-8") + "&timezone=" + URLEncoder.encode(TimeZone.getDefault().getID(), "UTF-8"); u.p("unencoded query: \n" + query); String login_url = "http://joshy.org:8088/org.glossitopeTracker/login.jsp?"; String url = login_url + query; u.p("final encoded url = \n" + url); InputStream in = new URL(url).openStream(); byte[] buf = new byte[256]; while (true) { int n = in.read(buf); if (n == -1) break; for (int i = 0; i < n; i++) { } } } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } }, "LoginToServerAction").start(); }
Code Sample 2:
public static boolean urlStrIsDir(String urlStr) { if (urlStr.endsWith("/")) return true; int lastSlash = urlStr.lastIndexOf('/'); int lastPeriod = urlStr.lastIndexOf('.'); if (lastPeriod != -1 && (lastSlash == -1 || lastPeriod > lastSlash)) return false; String urlStrWithSlash = urlStr + "/"; try { URL url = new URL(urlStrWithSlash); InputStream f = url.openStream(); f.close(); return true; } catch (Exception e) { return false; } }
|
11
|
Code Sample 1:
private static long saveAndClosePDFDocument(PDDocument document, OutputStreamProvider outProvider) throws IOException, COSVisitorException { File tempFile = null; InputStream in = null; OutputStream out = null; try { tempFile = File.createTempFile("temp", "pdf"); OutputStream tempFileOut = new FileOutputStream(tempFile); tempFileOut = new BufferedOutputStream(tempFileOut); document.save(tempFileOut); document.close(); tempFileOut.close(); long length = tempFile.length(); in = new BufferedInputStream(new FileInputStream(tempFile)); out = new BufferedOutputStream(outProvider.getOutputStream()); IOUtils.copy(in, out); return length; } finally { if (in != null) { IOUtils.closeQuietly(in); } if (out != null) { IOUtils.closeQuietly(out); } if (tempFile != null && !FileUtils.deleteQuietly(tempFile)) { tempFile.deleteOnExit(); } } }
Code Sample 2:
public boolean copyFile(File source, File dest) { try { FileReader in = new FileReader(source); FileWriter out = new FileWriter(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return true; } catch (Exception e) { return false; } }
|
11
|
Code Sample 1:
public static java.io.ByteArrayOutputStream getFileByteStream(URL _url) { java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream(); try { InputStream input = _url.openStream(); IOUtils.copy(input, buffer); IOUtils.closeQuietly(input); } catch (Exception err) { throw new RuntimeException(err); } return buffer; }
Code Sample 2:
public static void main(String[] args) throws FileNotFoundException, IOException { String filePath = "/Users/francisbaril/Downloads/test-1.pdf"; String testFilePath = "/Users/francisbaril/Desktop/testpdfbox/test.pdf"; File file = new File(filePath); final File testFile = new File(testFilePath); if (testFile.exists()) { testFile.delete(); } IOUtils.copy(new FileInputStream(file), new FileOutputStream(testFile)); System.out.println(getLongProperty(new FileInputStream(testFile), PROPRIETE_ID_IGID)); }
|
00
|
Code Sample 1:
public static String httpUrlConnection_post(String targetURL, String urlParameters) { System.out.println("httpUrlConnection_post"); URL url; HttpURLConnection connection = null; try { url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setDoInput(true); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); return response.toString(); } catch (Exception e) { System.out.print(e); return null; } finally { if (connection != null) { connection.disconnect(); } } }
Code Sample 2:
public void removeBodyPart(int iPart) throws MessagingException, ArrayIndexOutOfBoundsException { if (DebugFile.trace) { DebugFile.writeln("Begin DBMimeMultipart.removeBodyPart(" + String.valueOf(iPart) + ")"); DebugFile.incIdent(); } DBMimeMessage oMsg = (DBMimeMessage) getParent(); DBFolder oFldr = ((DBFolder) oMsg.getFolder()); Statement oStmt = null; ResultSet oRSet = null; String sDisposition = null, sFileName = null; boolean bFound; try { oStmt = oFldr.getConnection().createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); if (DebugFile.trace) DebugFile.writeln("Statement.executeQuery(SELECT " + DB.id_disposition + "," + DB.file_name + " FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "='" + oMsg.getMessageGuid() + "' AND " + DB.id_part + "=" + String.valueOf(iPart) + ")"); oRSet = oStmt.executeQuery("SELECT " + DB.id_disposition + "," + DB.file_name + " FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "='" + oMsg.getMessageGuid() + "' AND " + DB.id_part + "=" + String.valueOf(iPart)); bFound = oRSet.next(); if (bFound) { sDisposition = oRSet.getString(1); if (oRSet.wasNull()) sDisposition = "inline"; sFileName = oRSet.getString(2); } oRSet.close(); oRSet = null; oStmt.close(); oStmt = null; if (!bFound) { if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException("Part not found"); } if (!sDisposition.equals("reference") && !sDisposition.equals("pointer")) { if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException("Only parts with reference or pointer disposition can be removed from a message"); } else { if (sDisposition.equals("reference")) { try { File oRef = new File(sFileName); if (oRef.exists()) oRef.delete(); } catch (SecurityException se) { if (DebugFile.trace) DebugFile.writeln("SecurityException " + sFileName + " " + se.getMessage()); if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException("SecurityException " + sFileName + " " + se.getMessage(), se); } } oStmt = oFldr.getConnection().createStatement(); if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate(DELETE FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "='" + oMsg.getMessageGuid() + "' AND " + DB.id_part + "=" + String.valueOf(iPart) + ")"); oStmt.executeUpdate("DELETE FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "='" + oMsg.getMessageGuid() + "' AND " + DB.id_part + "=" + String.valueOf(iPart)); oStmt.close(); oStmt = null; oFldr.getConnection().commit(); } } catch (SQLException sqle) { if (oRSet != null) { try { oRSet.close(); } catch (Exception ignore) { } } if (oStmt != null) { try { oStmt.close(); } catch (Exception ignore) { } } try { oFldr.getConnection().rollback(); } catch (Exception ignore) { } if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException(sqle.getMessage(), sqle); } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End DBMimeMultipart.removeBodyPart()"); } }
|
11
|
Code Sample 1:
public void write(URL exportUrl, OutputStream output) throws Exception { if (exportUrl == null || output == null) { throw new DocumentListException("null passed in for required parameters"); } MediaContent mc = new MediaContent(); mc.setUri(exportUrl.toString()); MediaSource ms = service.getMedia(mc); InputStream input = ms.getInputStream(); IOUtils.copy(input, output); }
Code Sample 2:
private File writeResourceToFile(String resource) throws IOException { File tmp = File.createTempFile("zfppt" + resource, null); InputStream res = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); OutputStream out = new FileOutputStream(tmp); IOUtils.copy(res, out); out.close(); return tmp; }
|
11
|
Code Sample 1:
private final String encryptPassword(String pass) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { log.log(Level.WARNING, "Error while obtaining decript algorithm", e); throw new RuntimeException("AccountData.encryptPassword()"); } try { md.update(pass.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { log.log(Level.WARNING, "Problem with decript algorithm occured.", e); throw new RuntimeException("AccountData.encryptPassword()"); } return new BASE64Encoder().encode(md.digest()); }
Code Sample 2:
public static String encrypt(String password, Long digestSeed) { try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes("UTF-8")); algorithm.update(digestSeed.toString().getBytes("UTF-8")); byte[] messageDigest = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xff & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
|
11
|
Code Sample 1:
public void createZip(File zipFileName, Vector<File> selected) { try { byte[] buffer = new byte[4096]; ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName), 8096)); out.setLevel(Deflater.BEST_COMPRESSION); out.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < selected.size(); i++) { FileInputStream in = new FileInputStream(selected.get(i)); String file = selected.get(i).getPath(); if (file.indexOf("\\") != -1) file = file.substring(file.lastIndexOf(fs) + 1, file.length()); ZipEntry ze = new ZipEntry(file); out.putNextEntry(ze); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); selected.get(i).delete(); } out.close(); } catch (IllegalArgumentException iae) { iae.printStackTrace(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } }
Code Sample 2:
void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); }
|
11
|
Code Sample 1:
public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new SoundFilter()); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.17")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "sonidos/" + file.getName(); String rutaRelativa = rutaDatos + "sonidos/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setSonidoURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonSonido.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); gui.getAudio().reproduceAudio(imagen); } catch (IOException ex) { ex.printStackTrace(); } } else { } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
@Override public void run() { URL url = null; FileOutputStream fos = null; FTPClient ftp = null; try { url = new URL(super.getAddress()); String host = url.getHost(); String folder = StringUtils.substringBeforeLast(url.getPath(), "/"); String fileName = StringUtils.substringAfterLast(url.getPath(), "/"); ftp = new FTPClient(host, 21); if (!ftp.connected()) { ftp.connect(); } ftp.login("anonymous", "[email protected]"); logger.info("Connected to " + host + "."); logger.info(ftp.getLastValidReply().getReplyText()); logger.debug("changing dir to " + folder); ftp.chdir(folder); fos = new FileOutputStream(localFileName); logger.info("Downloading file " + fileName + "..."); ftp.setType(FTPTransferType.BINARY); ftp.get(fos, fileName); logger.info("Done."); } catch (Exception e) { logger.error(e.getMessage()); logger.debug(e.getStackTrace()); } finally { try { ftp.quit(); fos.close(); } catch (Exception e) { } } }
Code Sample 2:
private static void ftpTest() { FTPClient f = new FTPClient(); try { f.connect("oscomak.net"); System.out.print(f.getReplyString()); f.setFileType(FTPClient.BINARY_FILE_TYPE); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String password = JOptionPane.showInputDialog("Enter password"); if (password == null || password.equals("")) { System.out.println("No password"); return; } try { f.login("oscomak_pointrel", password); System.out.print(f.getReplyString()); } catch (IOException e) { e.printStackTrace(); } try { String workingDirectory = f.printWorkingDirectory(); System.out.println("Working directory: " + workingDirectory); System.out.print(f.getReplyString()); } catch (IOException e1) { e1.printStackTrace(); } try { f.enterLocalPassiveMode(); System.out.print(f.getReplyString()); System.out.println("Trying to list files"); String[] fileNames = f.listNames(); System.out.print(f.getReplyString()); System.out.println("Got file list fileNames: " + fileNames.length); for (String fileName : fileNames) { System.out.println("File: " + fileName); } System.out.println(); System.out.println("done reading stream"); System.out.println("trying alterative way to read stream"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); f.retrieveFile(fileNames[0], outputStream); System.out.println("size: " + outputStream.size()); System.out.println(outputStream.toString()); System.out.println("done with alternative"); System.out.println("Trying to store file back"); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); boolean storeResult = f.storeFile("test.txt", inputStream); System.out.println("Done storing " + storeResult); f.disconnect(); System.out.print(f.getReplyString()); System.out.println("disconnected"); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static Cursor load(URL url, String descriptor) { if (url == null) { log.log(Level.WARNING, "Trying to load a cursor with a null url."); return null; } String cursorFile = url.getFile(); BufferedReader reader = null; int lineNumber = 0; try { DirectoryTextureLoader loader; URL cursorUrl; if (cursorFile.endsWith(cursorDescriptorFile)) { cursorUrl = url; Cursor cached = cursorCache.get(url); if (cached != null) return cached; reader = new BufferedReader(new InputStreamReader(url.openStream())); loader = new DirectoryTextureLoader(url, false); } else if (cursorFile.endsWith(cursorArchiveFile)) { loader = new DirectoryTextureLoader(url, true); if (descriptor == null) descriptor = defaultDescriptorFile; cursorUrl = loader.makeUrl(descriptor); Cursor cached = cursorCache.get(url); if (cached != null) return cached; ZipInputStream zis = new ZipInputStream(url.openStream()); ZipEntry entry; boolean found = false; while ((entry = zis.getNextEntry()) != null) { if (descriptor.equals(entry.getName())) { found = true; break; } } if (!found) { throw new IOException("Descriptor file \"" + descriptor + "\" was not found."); } reader = new BufferedReader(new InputStreamReader(zis)); } else { log.log(Level.WARNING, "Invalid cursor fileName \"{0}\".", cursorFile); return null; } Cursor cursor = new Cursor(); cursor.url = cursorUrl; List<Integer> delays = new ArrayList<Integer>(); List<String> frameFileNames = new ArrayList<String>(); Map<String, Texture> textureCache = new HashMap<String, Texture>(); String line; while ((line = reader.readLine()) != null) { lineNumber++; int commentIndex = line.indexOf(commentString); if (commentIndex != -1) { line = line.substring(0, commentIndex); } StringTokenizer tokens = new StringTokenizer(line, delims); if (!tokens.hasMoreTokens()) continue; String prefix = tokens.nextToken(); if (prefix.equals(hotSpotXPrefix)) { cursor.hotSpotOffset.x = Integer.valueOf(tokens.nextToken()); } else if (prefix.equals(hotSpotYPrefix)) { cursor.hotSpotOffset.y = Integer.valueOf(tokens.nextToken()); } else if (prefix.equals(timePrefix)) { delays.add(Integer.valueOf(tokens.nextToken())); if (tokens.nextToken().equals(imagePrefix)) { String file = tokens.nextToken(""); file = file.substring(file.indexOf('=') + 1); file.trim(); frameFileNames.add(file); if (textureCache.get(file) == null) { textureCache.put(file, loader.loadTexture(file)); } } else { throw new NoSuchElementException(); } } } cursor.frameFileNames = frameFileNames.toArray(new String[0]); cursor.textureCache = textureCache; cursor.delays = new int[delays.size()]; cursor.images = new Image[frameFileNames.size()]; cursor.textures = new Texture[frameFileNames.size()]; for (int i = 0; i < cursor.frameFileNames.length; i++) { cursor.textures[i] = textureCache.get(cursor.frameFileNames[i]); cursor.images[i] = cursor.textures[i].getImage(); cursor.delays[i] = delays.get(i); } if (delays.size() == 1) cursor.delays = null; if (cursor.images.length == 0) { log.log(Level.WARNING, "The cursor has no animation frames."); return null; } cursor.width = cursor.images[0].getWidth(); cursor.height = cursor.images[0].getHeight(); cursorCache.put(cursor.url, cursor); return cursor; } catch (MalformedURLException mue) { log.log(Level.WARNING, "Unable to load cursor.", mue); } catch (IOException ioe) { log.log(Level.WARNING, "Unable to load cursor.", ioe); } catch (NumberFormatException nfe) { log.log(Level.WARNING, "Numerical error while parsing the " + "file \"{0}\" at line {1}", new Object[] { url, lineNumber }); } catch (IndexOutOfBoundsException ioobe) { log.log(Level.WARNING, "Error, \"=\" expected in the file \"{0}\" at line {1}", new Object[] { url, lineNumber }); } catch (NoSuchElementException nsee) { log.log(Level.WARNING, "Error while parsing the file \"{0}\" at line {1}", new Object[] { url, lineNumber }); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { log.log(Level.SEVERE, "Unable to close the steam.", ioe); } } } return null; }
|
11
|
Code Sample 1:
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, final HttpServletResponse response) throws Exception { final String id = request.getParameter("id"); if (id == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } try { jaxrTemplate.execute(new JAXRCallback<Object>() { public Object execute(Connection connection) throws JAXRException { RegistryObject registryObject = connection.getRegistryService().getBusinessQueryManager().getRegistryObject(id); if (registryObject instanceof ExtrinsicObject) { ExtrinsicObject extrinsicObject = (ExtrinsicObject) registryObject; DataHandler dataHandler = extrinsicObject.getRepositoryItem(); if (dataHandler != null) { response.setContentType("text/html"); try { PrintWriter out = response.getWriter(); InputStream is = dataHandler.getInputStream(); try { final XMLStreamWriter xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(out); xmlStreamWriter.writeStartDocument(); xmlStreamWriter.writeStartElement("div"); xmlStreamWriter.writeStartElement("textarea"); xmlStreamWriter.writeAttribute("name", "repositoryItem"); xmlStreamWriter.writeAttribute("class", "xml"); xmlStreamWriter.writeAttribute("style", "display:none"); IOUtils.copy(new XmlInputStreamReader(is), new XmlStreamTextWriter(xmlStreamWriter)); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeStartElement("script"); xmlStreamWriter.writeAttribute("class", "javascript"); xmlStreamWriter.writeCharacters("dp.SyntaxHighlighter.HighlightAll('repositoryItem');"); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndDocument(); xmlStreamWriter.flush(); } finally { is.close(); } } catch (Throwable ex) { log.error("Error while trying to format repository item " + id, ex); } } else { } } else { } return null; } }); } catch (JAXRException ex) { throw new ServletException(ex); } return null; }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
public static String readFromURL(String urlStr) throws IOException { URL url = new URL(urlStr); StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } in.close(); return sb.toString(); }
Code Sample 2:
public static List<String> extract(String zipFilePath, String destDirPath) throws IOException { List<String> list = null; ZipFile zip = new ZipFile(zipFilePath); try { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File destFile = new File(destDirPath, entry.getName()); if (entry.isDirectory()) { destFile.mkdirs(); } else { InputStream in = zip.getInputStream(entry); OutputStream out = new FileOutputStream(destFile); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); try { out.close(); } catch (IOException ioe) { ioe.getMessage(); } try { in.close(); } catch (IOException ioe) { ioe.getMessage(); } } } if (list == null) { list = new ArrayList<String>(); } list.add(destFile.getAbsolutePath()); } return list; } finally { try { zip.close(); } catch (Exception e) { e.getMessage(); } } }
|
00
|
Code Sample 1:
public void loadJar(final String extName, final String url, final String fileName, final IProgressListener pl) throws Exception { pl.setName(fileName); pl.setProgress(0); pl.setFinished(false); pl.setStarted(true); String installDirName = extDir + File.separator + extName; Log.log("extension installation directory: " + installDirName); File installDir = new File(installDirName); if (!installDir.exists()) { if (!installDir.mkdirs()) { throw new Exception("ExtensionLoader.loadJar: Cannot create install directory: " + installDirName); } } URL downloadURL = new URL(url + fileName); File jarFile = new File(installDirName, fileName); File indexFile = null; long urlTimeStamp = downloadURL.openConnection().getLastModified(); String indexFileName = ""; int idx = fileName.lastIndexOf("."); if (idx > 0) { indexFileName = fileName.substring(0, idx); } else { indexFileName = fileName; } indexFileName = indexFileName + ".idx"; Log.log("index filename: " + indexFileName); boolean isDirty = true; if (jarFile.exists()) { Log.log("extensionfile already exists: " + fileName); indexFile = new File(installDir, indexFileName); if (indexFile.exists()) { Log.log("indexfile already exists"); long cachedTimeStamp = readTimeStamp(indexFile); isDirty = !(cachedTimeStamp == urlTimeStamp); Log.log("cached file dirty: " + isDirty + ", url timestamp: " + urlTimeStamp + " cache stamp: " + cachedTimeStamp); } else { Log.log("indexfile doesn't exist, assume cache is dirty"); } } if (isDirty) { if (jarFile.exists()) { if (indexFile != null && indexFile.exists()) { Log.log("deleting old index file"); indexFile.delete(); } indexFile = new File(installDirName, indexFileName); Log.log("deleting old cached file"); jarFile.delete(); } downloadJar(downloadURL, jarFile, pl); indexFile = new File(installDir, indexFileName); Log.log("writing timestamp to index file"); writeTimeStamp(indexFile, urlTimeStamp); } addJar(jarFile); }
Code Sample 2:
public static InputStream getResourceAsStream(String resourceName) { try { URL url = getEmbeddedFileUrl(WS_SEP + resourceName); if (url != null) { return url.openStream(); } } catch (MalformedURLException e) { GdtAndroidPlugin.getLogger().logError(e, "Failed to read stream '%s'", resourceName); } catch (IOException e) { GdtAndroidPlugin.getLogger().logError(e, "Failed to read stream '%s'", resourceName); } return null; }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.