label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; Closer c = new Closer(); try { source = c.register(new FileInputStream(sourceFile).getChannel()); destination = c.register(new FileOutputStream(destFile).getChannel()); destination.transferFrom(source, 0, source.size()); } catch (IOException e) { c.doNotThrow(); throw e; } finally { c.closeAll(); } } Code Sample 2: public static String getServerVersion() throws IOException { URL url; url = new URL(CHECKVERSIONURL); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(false); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("GET"); httpURLConnection.connect(); InputStream in = httpURLConnection.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); out.flush(); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); String buffer; String[] lines; String version = ""; buffer = out.toString(); lines = StringUtils.split(buffer); for (int i = 0; i < lines.length; i++) { if (lines[i].startsWith("version=")) { version = lines[i].substring(8).trim(); break; } } return version; }
11
Code Sample 1: public void reqservmodif(HttpServletRequest req, HttpServletResponse resp, SessionCommand command) { try { System.err.println(req.getSession().getServletContext().getRealPath("WEB-INF/syncWork")); File tempFile = File.createTempFile("localmodif-", ".medoorequest"); OutputStream fos = new FileOutputStream(tempFile); syncServer.getServerModifications(command.getSession(), fos); InputStream fis = new FileInputStream(tempFile); resp.setContentLength(fis.available()); while (fis.available() > 0) { resp.getOutputStream().write(fis.read()); } resp.getOutputStream().flush(); resp.flushBuffer(); tempFile.delete(); } catch (IOException ioe) { logger.error(ioe.getMessage()); } catch (ImogSerializationException ex) { logger.error(ex.getMessage()); } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: 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; } } Code Sample 2: private void parseXmlFile() throws IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); if (file != null) { dom = db.parse(file); } else { dom = db.parse(url.openStream()); } } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (SAXException se) { se.printStackTrace(); } }
11
Code Sample 1: private void copyFile(File source) throws IOException { File backup = new File(source.getCanonicalPath() + ".backup"); if (!backup.exists()) { FileChannel srcChannel = new FileInputStream(source).getChannel(); backup.createNewFile(); FileChannel dstChannel = new FileOutputStream(backup).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } Code Sample 2: public void performOk(final IProject project, final TomcatPropertyPage page) { page.setPropertyValue("tomcat.jdbc.driver", c_drivers.getText()); page.setPropertyValue("tomcat.jdbc.url", url.getText()); page.setPropertyValue("tomcat.jdbc.user", username.getText()); page.setPropertyValue("tomcat.jdbc.password", password.getText()); File lib = new File(page.tomcatHome.getText(), "lib"); if (!lib.exists()) { lib = new File(new File(page.tomcatHome.getText(), "common"), "lib"); if (!lib.exists()) { Logger.log(Logger.ERROR, "Not properly location of Tomcat Home at :: " + lib); throw new IllegalStateException("Not properly location of Tomcat Home"); } } final File conf = new File(page.tomcatHome.getText(), "conf/Catalina/localhost"); if (!conf.exists()) { final boolean create = NexOpenUIActivator.getDefault().getTomcatConfProperty(); if (create) { if (Logger.getLog().isDebugEnabled()) { Logger.getLog().debug("Create directory " + conf); } try { conf.mkdirs(); } catch (final SecurityException se) { Logger.getLog().error("Retrieved a Security exception creating " + conf, se); Logger.log(Logger.ERROR, "Not created " + conf + " directory. Not enough privilegies. Message :: " + se.getMessage()); } } } String str_driverLibrary = LIBRARIES.get(c_drivers.getText()); if ("<mysql_driver>".equals(str_driverLibrary)) { str_driverLibrary = NexOpenUIActivator.getDefault().getMySQLDriver(); } final File driverLibrary = new File(lib, str_driverLibrary); if (!driverLibrary.exists()) { InputStream driver = null; FileOutputStream fos = null; try { driver = AppServerPropertyPage.toInputStream(new Path("jdbc/" + str_driverLibrary)); fos = new FileOutputStream(driverLibrary); IOUtils.copy(driver, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy the driver jar file to Tomcat", e); } finally { try { if (driver != null) { driver.close(); driver = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } page.processTomcatCfg(c_drivers.getText(), url.getText(), username.getText(), password.getText()); }
00
Code Sample 1: public void execute(HttpResponse response) throws HttpException, IOException { StringBuffer content = new StringBuffer(); NodeSet allNodes = membershipRegistry.listAllMembers(); for (Node node : allNodes) { content.append(node.getId().toString()); content.append(SystemUtils.LINE_SEPARATOR); } StringEntity body = new StringEntity(content.toString()); body.setContentType(PLAIN_TEXT_RESPONSE_CONTENT_TYPE); response.setEntity(body); } Code Sample 2: public String crypt(String suppliedPassword) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(suppliedPassword.getBytes()); String encriptedPassword = null; try { encriptedPassword = new String(Base64.encode(md.digest()), "ASCII"); } catch (UnsupportedEncodingException e) { } return encriptedPassword; }
00
Code Sample 1: public boolean ReadFile() { boolean ret = false; FilenameFilter FileFilter = null; File dir = new File(fDir); String[] FeeFiles; int Lines = 0; BufferedReader FeeFile = null; PreparedStatement DelSt = null, InsSt = null; String Line = null, Term = null, CurTerm = null, TermType = null, Code = null; double[] Fee = new double[US_D + 1]; double FeeAm = 0; String UpdateSt = "INSERT INTO reporter.term_fee (TERM, TERM_TYPE, THEM_VC, THEM_VE, THEM_EC, THEM_EE, THEM_D," + "BA_VC, BA_VE, BA_EC, BA_EE, BA_D," + "US_VC, US_VE, US_EC, US_EE, US_D)" + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; try { FileFilter = new FilenameFilter() { public boolean accept(File dir, String name) { if ((new File(dir, name)).isDirectory()) return false; else return (name.matches(fFileMask)); } }; FeeFiles = dir.list(FileFilter); java.util.Arrays.sort(FeeFiles); System.out.println(FeeFiles[FeeFiles.length - 1] + " " + (new SimpleDateFormat("dd.MM.yy HH:mm:ss")).format(new Date())); Log.info(String.format("Load = %1s", fDir + FeeFiles[FeeFiles.length - 1])); FeeFile = new BufferedReader(new FileReader(fDir + FeeFiles[FeeFiles.length - 1])); FeeZero(Fee); DelSt = cnProd.prepareStatement("delete from reporter.term_fee"); DelSt.executeUpdate(); InsSt = cnProd.prepareStatement(UpdateSt); WriteTerm(FeeFiles[FeeFiles.length - 1] + " " + (new SimpleDateFormat("dd.MM.yy HH:mm:ss")).format(new Date()), "XXX", Fee, InsSt); while ((Line = FeeFile.readLine()) != null) { Lines++; if (!Line.matches("\\d{15}\\s+��������.+")) continue; Term = Line.substring(7, 15); if ((CurTerm == null) || !Term.equals(CurTerm)) { if (CurTerm != null) { WriteTerm(CurTerm, TermType, Fee, InsSt); } CurTerm = Term; if (Line.indexOf("���") > 0) TermType = "���"; else TermType = "���"; FeeZero(Fee); } Code = Line.substring(64, 68).trim().toUpperCase(); if (Code.equals("ST") || Code.equals("AC") || Code.equals("8110") || Code.equals("8160")) continue; FeeAm = new Double(Line.substring(140, 160)).doubleValue(); if (Line.indexOf("�� ����� ������") > 0) SetFee(Fee, CARD_THEM, Code, FeeAm); else if (Line.indexOf("�� ������ �����") > 0) SetFee(Fee, CARD_BA, Code, FeeAm); else if (Line.indexOf("�� ������ ��") > 0) SetFee(Fee, CARD_US, Code, FeeAm); else throw new Exception("������ ���� ����.:" + Line); } WriteTerm(CurTerm, TermType, Fee, InsSt); cnProd.commit(); ret = true; } catch (Exception e) { System.out.printf("Err = %1s\r\n", e.getMessage()); Log.error(String.format("Err = %1s", e.getMessage())); Log.error(String.format("Line = %1s", Line)); try { cnProd.rollback(); } catch (Exception ee) { } ; } finally { try { if (FeeFile != null) FeeFile.close(); } catch (Exception ee) { } } try { if (DelSt != null) DelSt.close(); if (InsSt != null) InsSt.close(); cnProd.setAutoCommit(true); } catch (Exception ee) { } Log.info(String.format("Lines = %1d", Lines)); return (ret); } Code Sample 2: public String index(URL url) { InputStream is = null; try { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setInstanceFollowRedirects(true); urlConnection.setAllowUserInteraction(false); System.setProperty("sun.net.client.defaultConnectTimeout", "15000"); System.setProperty("sun.net.client.defaultReadTimeout", "15000"); urlConnection.connect(); is = urlConnection.getInputStream(); return index(is); } catch (Throwable t) { } finally { IOUtils.closeQuietly(is); } return ""; }
00
Code Sample 1: @Override public CasAssembly build() { try { prepareForBuild(); File casWorkingDirectory = casFile.getParentFile(); DefaultCasFileReadIndexToContigLookup read2contigMap = new DefaultCasFileReadIndexToContigLookup(); AbstractDefaultCasFileLookup readIdLookup = new DefaultReadCasFileLookup(casWorkingDirectory); CasParser.parseOnlyMetaData(casFile, MultipleWrapper.createMultipleWrapper(CasFileVisitor.class, read2contigMap, readIdLookup)); ReadWriteDirectoryFileServer consedOut = DirectoryFileServer.createReadWriteDirectoryFileServer(commandLine.getOptionValue("o")); long startTime = DateTimeUtils.currentTimeMillis(); int numberOfCasContigs = read2contigMap.getNumberOfContigs(); for (long i = 0; i < numberOfCasContigs; i++) { File outputDir = consedOut.createNewDir("" + i); Command aCommand = new Command(new File("fakeCommand")); aCommand.setOption("-casId", "" + i); aCommand.setOption("-cas", commandLine.getOptionValue("cas")); aCommand.setOption("-o", outputDir.getAbsolutePath()); aCommand.setOption("-tempDir", tempDir.getAbsolutePath()); aCommand.setOption("-prefix", "temp"); if (commandLine.hasOption("useIllumina")) { aCommand.addFlag("-useIllumina"); } if (commandLine.hasOption("useClosureTrimming")) { aCommand.addFlag("-useClosureTrimming"); } if (commandLine.hasOption("trim")) { aCommand.setOption("-trim", commandLine.getOptionValue("trim")); } if (commandLine.hasOption("trimMap")) { aCommand.setOption("-trimMap", commandLine.getOptionValue("trimMap")); } if (commandLine.hasOption("chromat_dir")) { aCommand.setOption("-chromat_dir", commandLine.getOptionValue("chromat_dir")); } submitSingleCasAssemblyConversion(aCommand); } waitForAllAssembliesToFinish(); int numContigs = 0; int numReads = 0; for (int i = 0; i < numberOfCasContigs; i++) { File countMap = consedOut.getFile(i + "/temp.counts"); Scanner scanner = new Scanner(countMap); if (!scanner.hasNextInt()) { throw new IllegalStateException("single assembly conversion # " + i + " did not complete"); } numContigs += scanner.nextInt(); numReads += scanner.nextInt(); scanner.close(); } System.out.println("num contigs =" + numContigs); System.out.println("num reads =" + numReads); consedOut.createNewDir("edit_dir"); consedOut.createNewDir("phd_dir"); String prefix = commandLine.hasOption("prefix") ? commandLine.getOptionValue("prefix") : DEFAULT_PREFIX; OutputStream masterAceOut = new FileOutputStream(consedOut.createNewFile("edit_dir/" + prefix + ".ace.1")); OutputStream masterPhdOut = new FileOutputStream(consedOut.createNewFile("phd_dir/" + prefix + ".phd.ball")); OutputStream masterConsensusOut = new FileOutputStream(consedOut.createNewFile(prefix + ".consensus.fasta")); OutputStream logOut = new FileOutputStream(consedOut.createNewFile(prefix + ".log")); try { masterAceOut.write(String.format("AS %d %d%n", numContigs, numReads).getBytes()); for (int i = 0; i < numberOfCasContigs; i++) { InputStream aceIn = consedOut.getFileAsStream(i + "/temp.ace"); IOUtils.copy(aceIn, masterAceOut); InputStream phdIn = consedOut.getFileAsStream(i + "/temp.phd"); IOUtils.copy(phdIn, masterPhdOut); InputStream consensusIn = consedOut.getFileAsStream(i + "/temp.consensus.fasta"); IOUtils.copy(consensusIn, masterConsensusOut); IOUtil.closeAndIgnoreErrors(aceIn, phdIn, consensusIn); File tempDir = consedOut.getFile(i + ""); IOUtil.recursiveDelete(tempDir); } consedOut.createNewSymLink("../phd_dir/" + prefix + ".phd.ball", "edit_dir/phd.ball"); if (commandLine.hasOption("chromat_dir")) { consedOut.createNewDir("chromat_dir"); File originalChromatDir = new File(commandLine.getOptionValue("chromat_dir")); for (File chromat : originalChromatDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".scf"); } })) { File newChromatFile = consedOut.createNewFile("chromat_dir/" + FilenameUtils.getBaseName(chromat.getName())); FileOutputStream newChromat = new FileOutputStream(newChromatFile); InputStream in = new FileInputStream(chromat); IOUtils.copy(in, newChromat); IOUtil.closeAndIgnoreErrors(in, newChromat); } } System.out.println("finished making casAssemblies"); for (File traceFile : readIdLookup.getFiles()) { final String name = traceFile.getName(); String extension = FilenameUtils.getExtension(name); if (name.contains("fastq")) { if (!consedOut.contains("solexa_dir")) { consedOut.createNewDir("solexa_dir"); } if (consedOut.contains("solexa_dir/" + name)) { IOUtil.delete(consedOut.getFile("solexa_dir/" + name)); } consedOut.createNewSymLink(traceFile.getAbsolutePath(), "solexa_dir/" + name); } else if ("sff".equals(extension)) { if (!consedOut.contains("sff_dir")) { consedOut.createNewDir("sff_dir"); } if (consedOut.contains("sff_dir/" + name)) { IOUtil.delete(consedOut.getFile("sff_dir/" + name)); } consedOut.createNewSymLink(traceFile.getAbsolutePath(), "sff_dir/" + name); } } long endTime = DateTimeUtils.currentTimeMillis(); logOut.write(String.format("took %s%n", new Period(endTime - startTime)).getBytes()); } finally { IOUtil.closeAndIgnoreErrors(masterAceOut, masterPhdOut, masterConsensusOut, logOut); } } catch (Exception e) { handleException(e); } finally { cleanup(); } return null; } Code Sample 2: public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
11
Code Sample 1: public static boolean copyFile(File source, File dest) throws IOException { int answer = JOptionPane.YES_OPTION; if (dest.exists()) { answer = JOptionPane.showConfirmDialog(null, "File " + dest.getAbsolutePath() + "\n already exists. Overwrite?", "Warning", JOptionPane.YES_NO_OPTION); } if (answer == JOptionPane.NO_OPTION) return false; dest.createNewFile(); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(source); out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } return true; } catch (Exception e) { return false; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } Code Sample 2: public static void main(String[] args) throws Exception { String codecClassname = args[0]; Class<?> codecClass = Class.forName(codecClassname); Configuration conf = new Configuration(); CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf); CompressionOutputStream out = codec.createOutputStream(System.out); IOUtils.copyBytes(System.in, out, 4096, false); out.finish(); }
00
Code Sample 1: public void aprovarCandidato(Atividade atividade) throws SQLException { Connection conn = null; String insert = "update Atividade_has_recurso_humano set ativo='true' " + "where atividade_idatividade=" + atividade.getIdAtividade() + " and " + " usuario_idusuario=" + atividade.getRecursoHumano().getIdUsuario(); try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } } Code Sample 2: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
11
Code Sample 1: public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setFileView(new ImageFileView()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(Resorces.this, "Seleccione una imagen"); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + file.separator + "data" + file.separator + "imagenes" + file.separator + file.getName(); String rutaRelativa = "data" + file.separator + "imagenes" + file.separator + 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(); } catch (IOException ex) { ex.printStackTrace(); } imagen.setImagenURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.procesadorDatos.escalaImageIcon(imagen.getImagenURL())); } else { } } 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: @Override protected void copyContent(String filename) throws IOException { InputStream in = null; try { String resourceDir = System.getProperty("resourceDir"); File resource = new File(resourceDir, filename); ByteArrayOutputStream out = new ByteArrayOutputStream(); if (resource.exists()) { in = new FileInputStream(resource); } else { in = LOADER.getResourceAsStream(RES_PKG + filename); } IOUtils.copy(in, out); setResponseData(out.toByteArray()); } finally { if (in != null) { in.close(); } } } Code Sample 2: private void copyFile(File from, File to) throws IOException { FileUtils.ensureParentDirectoryExists(to); byte[] buffer = new byte[1024]; int read; FileInputStream is = new FileInputStream(from); FileOutputStream os = new FileOutputStream(to); while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } is.close(); os.close(); }
00
Code Sample 1: public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void process(String dir) { String[] list = new File(dir).list(); if (list == null) return; int n = list.length; long[] bubblesort = new long[list.length + 1]; if (!statustext) { IJ.log("Current Directory is: " + dir); IJ.log(" "); IJ.log("DICOM File Name / " + prefix1 + " / " + prefix2 + " / " + prefix3 + " / " + pick); IJ.log(" "); } for (int i = 0; i < n; i++) { IJ.showStatus(i + "/" + n); File f = new File(dir + list[i]); if (!f.isDirectory()) { ImagePlus img = new Opener().openImage(dir, list[i]); if (img != null && img.getStackSize() == 1) { if (!scoutengine(img)) return; if (!statustext) { IJ.log(list[i] + "/" + whichprefix1 + "/" + whichprefix2 + "/" + whichprefix3 + "/" + whichcase); } int lastDigit = whichcase.length() - 1; while (lastDigit > 0) { if (!Character.isDigit(whichcase.charAt(lastDigit))) lastDigit -= 1; else break; } if (lastDigit < whichcase.length() - 1) whichcase = whichcase.substring(0, lastDigit + 1); bubblesort[i] = Long.parseLong(whichcase); } } } if (statussorta || statussortd || statustext) { boolean sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < n - 1; i++) { if (statussorta) { if (bubblesort[i] > bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } else { if (bubblesort[i] < bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } } } IJ.log(" "); for (int i = 0; i < n; i++) { if (!statustext) { IJ.log(list[i] + " / " + bubblesort[i]); } else { IJ.log(dir + list[i]); } } } if (open_as_stack || only_images) { boolean sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < n - 1; i++) { if (bubblesort[i] > bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } } if (only_images) { Opener o = new Opener(); int counter = 0; IJ.log(" "); for (int i = 0; i < n; i++) { String path = (dir + list[i]); if (path == null) break; else { ImagePlus imp = o.openImage(path); counter++; if (imp != null) { IJ.log(counter + " + " + path); imp.show(); } else IJ.log(counter + " - " + path); } } return; } int width = 0, height = 0, type = 0; ImageStack stack = null; double min = Double.MAX_VALUE; double max = -Double.MAX_VALUE; int k = 0; try { for (int i = 0; i < n; i++) { String path = (dir + list[i]); if (path == null) break; if (list[i].endsWith(".txt")) continue; ImagePlus imp = new Opener().openImage(path); if (imp != null && stack == null) { width = imp.getWidth(); height = imp.getHeight(); type = imp.getType(); ColorModel cm = imp.getProcessor().getColorModel(); if (halfSize) stack = new ImageStack(width / 2, height / 2, cm); else stack = new ImageStack(width, height, cm); } if (stack != null) k = stack.getSize() + 1; IJ.showStatus(k + "/" + n); IJ.showProgress((double) k / n); if (imp == null) IJ.log(list[i] + ": unable to open"); else if (imp.getWidth() != width || imp.getHeight() != height) IJ.log(list[i] + ": wrong dimensions"); else if (imp.getType() != type) IJ.log(list[i] + ": wrong type"); else { ImageProcessor ip = imp.getProcessor(); if (grayscale) ip = ip.convertToByte(true); if (halfSize) ip = ip.resize(width / 2, height / 2); if (ip.getMin() < min) min = ip.getMin(); if (ip.getMax() > max) max = ip.getMax(); String label = imp.getTitle(); String info = (String) imp.getProperty("Info"); if (info != null) label += "\n" + info; stack.addSlice(label, ip); } System.gc(); } } catch (OutOfMemoryError e) { IJ.outOfMemory("FolderOpener"); stack.trim(); } if (stack != null && stack.getSize() > 0) { ImagePlus imp2 = new ImagePlus("Stack", stack); if (imp2.getType() == ImagePlus.GRAY16 || imp2.getType() == ImagePlus.GRAY32) imp2.getProcessor().setMinAndMax(min, max); imp2.show(); } IJ.showProgress(1.0); } }
11
Code Sample 1: public static int my_rename(String source, String dest) { logger.debug("RENAME " + source + " to " + dest); if (source == null || dest == null) return -1; { logger.debug("\tMoving file across file systems."); FileChannel srcChannel = null; FileChannel dstChannel = null; FileLock lock = null; try { srcChannel = new FileInputStream(source).getChannel(); dstChannel = new FileOutputStream(dest).getChannel(); lock = dstChannel.lock(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); dstChannel.force(true); } catch (IOException e) { logger.fatal("Error while copying file '" + source + "' to file '" + dest + "'. " + e.getMessage(), e); return common_h.ERROR; } finally { try { lock.release(); } catch (Throwable t) { logger.fatal("Error releasing file lock - " + dest); } try { srcChannel.close(); } catch (Throwable t) { } try { dstChannel.close(); } catch (Throwable t) { } } } return common_h.OK; } Code Sample 2: 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; }
00
Code Sample 1: private void post(String title, Document content, Set<String> tags) throws HttpException, IOException, TransformerException { PostMethod method = null; try { method = new PostMethod("http://www.blogger.com/feeds/" + this.blogId + "/posts/default"); method.addRequestHeader("GData-Version", String.valueOf(GDataVersion)); method.addRequestHeader("Authorization", "GoogleLogin auth=" + this.AuthToken); Document dom = this.domBuilder.newDocument(); Element entry = dom.createElementNS(Atom.NS, "entry"); dom.appendChild(entry); entry.setAttribute("xmlns", Atom.NS); Element titleNode = dom.createElementNS(Atom.NS, "title"); entry.appendChild(titleNode); titleNode.setAttribute("type", "text"); titleNode.appendChild(dom.createTextNode(title)); Element contentNode = dom.createElementNS(Atom.NS, "content"); entry.appendChild(contentNode); contentNode.setAttribute("type", "xhtml"); contentNode.appendChild(dom.importNode(content.getDocumentElement(), true)); for (String tag : tags) { Element category = dom.createElementNS(Atom.NS, "category"); category.setAttribute("scheme", "http://www.blogger.com/atom/ns#"); category.setAttribute("term", tag); entry.appendChild(category); } StringWriter out = new StringWriter(); this.xml2ascii.transform(new DOMSource(dom), new StreamResult(out)); method.setRequestEntity(new StringRequestEntity(out.toString(), "application/atom+xml", "UTF-8")); int status = getHttpClient().executeMethod(method); if (status == 201) { IOUtils.copyTo(method.getResponseBodyAsStream(), System.out); } else { throw new HttpException("post returned http-code=" + status + " expected 201 (CREATE)"); } } catch (TransformerException err) { throw err; } catch (HttpException err) { throw err; } catch (IOException err) { throw err; } finally { if (method != null) method.releaseConnection(); } } Code Sample 2: protected void handleConnection(Socket server) throws IOException { OutputStream out = server.getOutputStream(); PrintWriter pout = new PrintWriter(out, true); BufferedReader in = SocketUtil.getReader(server); String failureReason = null; int failureCode = 0; String httpVersion = "HTTP/1.0"; String uri = null; String command = in.readLine(); URL url = null; if (command != null) { StringTokenizer tokenizer = new StringTokenizer(command); if (tokenizer.countTokens() != 3) { failureCode = 400; failureReason = "Illformed Request-Line"; } else { String method = tokenizer.nextToken(); if (!method.equalsIgnoreCase("get")) { failureCode = 501; failureReason = "Only supports GET method"; } else { uri = tokenizer.nextToken(); httpVersion = tokenizer.nextToken(); try { url = getURL(uri); } catch (IOException e) { failureCode = 404; failureReason = "resource not found"; } } } } else { failureCode = 400; failureReason = "Null request"; } if (url != null) { InputStream stream = null; try { URLConnection connection = url.openConnection(); byte[] chunk = new byte[1024]; int read = 0; pout.println(httpVersion + " 200 "); pout.println("Content-Type: " + connection.getContentType()); pout.println("Content-Length: " + connection.getContentLength()); pout.println("Content-Encoding: " + connection.getContentEncoding()); pout.println(); stream = connection.getInputStream(); read = stream.read(chunk); while (read != -1) { out.write(chunk, 0, read); read = stream.read(chunk); } } catch (IOException e) { failureCode = 500; failureReason = "problem reading the resource content"; } finally { if (stream != null) { stream.close(); } } } else { failureCode = 404; failureReason = "resource not found"; } if (failureCode != 0) { pout.println(httpVersion + " " + failureCode + " " + failureReason); pout.println(); } doDelay(); server.close(); }
11
Code Sample 1: ServiceDescription getServiceDescription() throws ConfigurationException { final XPath pathsXPath = this.xPathFactory.newXPath(); try { final Node serviceDescriptionNode = (Node) pathsXPath.evaluate(ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration, XPathConstants.NODE); final String title = getMandatoryElementText(serviceDescriptionNode, ConfigurationFileTagsV1.TITLE_ELEMENT); ServiceDescription.Builder builder = new ServiceDescription.Builder(title, Migrate.class.getCanonicalName()); Property[] serviceProperties = getServiceProperties(serviceDescriptionNode); builder.author(getMandatoryElementText(serviceDescriptionNode, ConfigurationFileTagsV1.CREATOR_ELEMENT)); builder.classname(this.canonicalServiceName); builder.description(getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.DESCRIPTION_ELEMENT)); final String serviceVersion = getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.VERSION_ELEMENT); final Tool toolDescription = getToolDescriptionElement(serviceDescriptionNode); String identifier = getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.IDENTIFIER_ELEMENT); if (identifier == null || "".equals(identifier)) { try { final MessageDigest identDigest = MessageDigest.getInstance("MD5"); identDigest.update(this.canonicalServiceName.getBytes()); final String versionInfo = (serviceVersion != null) ? serviceVersion : ""; identDigest.update(versionInfo.getBytes()); final URI toolIDURI = toolDescription.getIdentifier(); final String toolIdentifier = toolIDURI == null ? "" : toolIDURI.toString(); identDigest.update(toolIdentifier.getBytes()); final BigInteger md5hash = new BigInteger(identDigest.digest()); identifier = md5hash.toString(16); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException(nsae); } } builder.identifier(identifier); builder.version(serviceVersion); builder.tool(toolDescription); builder.instructions(getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.INSTRUCTIONS_ELEMENT)); builder.furtherInfo(getOptionalURIElement(serviceDescriptionNode, ConfigurationFileTagsV1.FURTHER_INFO_ELEMENT)); builder.logo(getOptionalURIElement(serviceDescriptionNode, ConfigurationFileTagsV1.LOGO_ELEMENT)); builder.serviceProvider(this.serviceProvider); final DBMigrationPathFactory migrationPathFactory = new DBMigrationPathFactory(this.configuration); final MigrationPaths migrationPaths = migrationPathFactory.getAllMigrationPaths(); builder.paths(MigrationPathConverter.toPlanetsPaths(migrationPaths)); builder.inputFormats(migrationPaths.getInputFormatURIs().toArray(new URI[0])); builder.parameters(getUniqueParameters(migrationPaths)); builder.properties(serviceProperties); return builder.build(); } catch (XPathExpressionException xPathExpressionException) { throw new ConfigurationException(String.format("Failed parsing the '%s' element in the '%s' element.", ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration.getNodeName()), xPathExpressionException); } catch (NullPointerException nullPointerException) { throw new ConfigurationException(String.format("Failed parsing the '%s' element in the '%s' element.", ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration.getNodeName()), nullPointerException); } } Code Sample 2: public void loginMD5() throws Exception { GetMethod get = new GetMethod("http://login.yahoo.com/config/login?.src=www&.done=http://www.yahoo.com"); get.setRequestHeader("user-agent", "Mozilla/5.0 (Macintosh; U; PPC MacOS X; en-us) AppleWebKit/124 (KHTML, like Gecko) Safari/125.1"); client.executeMethod(get); parseResponse(get.getResponseBodyAsStream()); MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes("US-ASCII")); String hash1 = new String(digest.digest(), "US-ASCII"); String hash2 = hash1 + challenge; digest.update(hash2.getBytes("US-ASCII")); String hash = new String(digest.digest(), "US-ASCII"); NameValuePair[] pairs = { new NameValuePair("login", login), new NameValuePair("password", hash), new NameValuePair(".save", "1"), new NameValuePair(".tries", "1"), new NameValuePair(".src", "www"), new NameValuePair(".md5", "1"), new NameValuePair(".hash", "1"), new NameValuePair(".js", "1"), new NameValuePair(".last", ""), new NameValuePair(".promo", ""), new NameValuePair(".intl", "us"), new NameValuePair(".bypass", ""), new NameValuePair(".u", u), new NameValuePair(".v", "0"), new NameValuePair(".challenge", challenge), new NameValuePair(".yplus", ""), new NameValuePair(".emailCode", ""), new NameValuePair("pkg", ""), new NameValuePair("stepid", ""), new NameValuePair(".ev", ""), new NameValuePair("hasMsgr", "0"), new NameValuePair(".chkP", "Y"), new NameValuePair(".done", "http://www.yahoo.com"), new NameValuePair(".persistent", "y") }; get = new GetMethod("http://login.yahoo.com/config/login"); get.setRequestHeader("user-agent", "Mozilla/5.0 (Macintosh; U; PPC MacOS X; en-us) AppleWebKit/124 (KHTML, like Gecko) Safari/125.1"); get.addRequestHeader("Accept", "*/*"); get.addRequestHeader("Accept-Language", "en-us, ja;q=0.21, de-de;q=0.86, de;q=0.79, fr-fr;q=0.71, fr;q=0.64, nl-nl;q=0.57, nl;q=0.50, it-it;q=0.43, it;q=0.36, ja-jp;q=0.29, en;q=0.93, es-es;q=0.14, es;q=0.07"); get.setQueryString(pairs); client.executeMethod(get); get.getResponseBodyAsString(); }
00
Code Sample 1: public static boolean loadTestProperties(Properties props, Class<?> callingClazz, Class<?> hierarchyRootClazz, String resourceBaseName) { if (!hierarchyRootClazz.isAssignableFrom(callingClazz)) { throw new IllegalArgumentException("Class " + callingClazz + " is not derived from " + hierarchyRootClazz); } if (null == resourceBaseName) { throw new NullPointerException("resourceBaseName is null"); } String fqcn = callingClazz.getName(); String uqcn = fqcn.substring(fqcn.lastIndexOf('.') + 1); String callingClassResource = uqcn + ".properties"; String globalCallingClassResource = "/" + callingClassResource; String baseClassResource = resourceBaseName + "-" + uqcn + ".properties"; String globalBaseClassResource = "/" + baseClassResource; String pkgResource = resourceBaseName + ".properties"; String globalResource = "/" + pkgResource; boolean loaded = false; final String[] resources = { baseClassResource, globalBaseClassResource, callingClassResource, globalCallingClassResource, pkgResource, globalResource }; List<URL> urls = new ArrayList<URL>(); Class<?> clazz = callingClazz; do { for (String res : resources) { URL url = clazz.getResource(res); if (null != url && !urls.contains(url)) { urls.add(url); } } if (hierarchyRootClazz.equals(clazz)) { clazz = null; } else { clazz = clazz.getSuperclass(); } } while (null != clazz); ListIterator<URL> it = urls.listIterator(urls.size()); while (it.hasPrevious()) { URL url = it.previous(); InputStream in = null; try { LOG.info("Loading test properties from resource: " + url); in = url.openStream(); props.load(in); loaded = true; } catch (IOException ex) { LOG.warn("Failed to load properties from resource: " + url, ex); } IOUtil.closeSilently(in); } return loaded; } Code Sample 2: private static byte[] get256RandomBits() throws IOException { URL url = null; try { url = new URL(SRV_URL); } catch (MalformedURLException e) { e.printStackTrace(); } HttpsURLConnection hu = (HttpsURLConnection) url.openConnection(); hu.setConnectTimeout(2500); InputStream is = hu.getInputStream(); byte[] content = new byte[is.available()]; is.read(content); is.close(); hu.disconnect(); byte[] randomBits = new byte[32]; String line = new String(content); Matcher m = DETAIL.matcher(line); if (m.find()) { for (int i = 0; i < 32; i++) randomBits[i] = (byte) (Integer.parseInt(m.group(1).substring(i * 2, i * 2 + 2), 16) & 0xFF); } return randomBits; }
00
Code Sample 1: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } } Code Sample 2: public static synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
11
Code Sample 1: private void saveFile(InputStream in, String fullPath) { try { File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(in, out); out.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void update() { if (!updatable) { Main.fenetre().erreur(Fenetre.OLD_VERSION); return; } try { Main.fenetre().update(); Element remoteRoot = new SAXBuilder().build(xml).getRootElement(); addPackages = new HashMap<Integer, PackageVersion>(); Iterator<?> iterElem = remoteRoot.getChildren().iterator(); while (iterElem.hasNext()) { PackageVersion pack = new PackageVersion((Element) iterElem.next()); addPackages.put(pack.id(), pack); } removePackages = new HashMap<Integer, PackageVersion>(); iterElem = root.getChildren("package").iterator(); while (iterElem.hasNext()) { PackageVersion pack = new PackageVersion((Element) iterElem.next()); int id = pack.id(); if (!addPackages.containsKey(id)) { removePackages.put(id, pack); } else if (addPackages.get(id).version().equals(pack.version())) { addPackages.remove(id); } else { addPackages.get(id).ecrase(); } } Iterator<PackageVersion> iterPack = addPackages.values().iterator(); while (iterPack.hasNext()) { install(iterPack.next()); } iterPack = removePackages.values().iterator(); while (iterPack.hasNext()) { remove(iterPack.next()); } if (offline) { Runtime.getRuntime().addShutdownHook(new AddPackage(xml, "versions.xml")); Main.fenetre().erreur(Fenetre.UPDATE_TERMINE_RESTART); } else { File oldXML = new File("versions.xml"); oldXML.delete(); oldXML.createNewFile(); FileChannel out = new FileOutputStream(oldXML).getChannel(); FileChannel in = new FileInputStream(xml).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); xml.delete(); if (restart) { Main.fenetre().erreur(Fenetre.UPDATE_TERMINE_RESTART); } else { Main.updateVersion(); } } } catch (Exception e) { Main.fenetre().erreur(Fenetre.ERREUR_UPDATE, e); } }
11
Code Sample 1: private boolean streamDownload(URL url, File file) { try { InputStream in = url.openConnection().getInputStream(); BufferedInputStream bis = new BufferedInputStream(in); OutputStream out = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(out); int chunkSize = 63 * 1024; byte[] ba = new byte[chunkSize]; while (true) { int bytesRead = readBlocking(bis, ba, 0, chunkSize); if (bytesRead > 0) { if (bos != null) bos.write(ba, 0, bytesRead); } else { bos.close(); break; } } } catch (IOException e) { System.out.println("Error writing file " + file); return false; } System.out.println("OK writing file " + file); return true; } Code Sample 2: public void refreshStatus() { if (!enabledDisplay) return; try { String url = getServerFortURL(); BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String data = null; int counter = 0; while ((data = reader.readLine()) != null && counter < 9) { status[counter] = UNKNOWN; if (data.matches(".*_alsius.gif.*")) { status[counter] = ALSIUS; counter++; } if (data.matches(".*_syrtis.gif.*")) { status[counter] = SYRTIS; counter++; } if (data.matches(".*_ignis.gif.*")) { status[counter] = IGNIS; counter++; } } } catch (Exception exc) { for (int i = 0; i < status.length; i++) status[i] = UNKNOWN; } }
11
Code Sample 1: @Test public void testCopy_readerToOutputStream_Encoding_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null, "UTF16"); fail(); } catch (NullPointerException ex) { } } Code Sample 2: @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
00
Code Sample 1: public boolean copy(Class<?> subCls, String subCol, long id) { boolean bool = false; this.result = null; Connection conn = null; Object vo = null; try { conn = ConnectUtil.getConnect(); conn.setAutoCommit(false); PojoParser parser = PojoParser.getInstances(); String sql = SqlUtil.getInsertSql(this.getCls()); vo = this.findById(conn, "select * from " + parser.getTableName(cls) + " where " + parser.getPriamryKey(cls) + "=" + id); String pk = parser.getPriamryKey(cls); this.getCls().getMethod("set" + SqlUtil.getFieldName(pk), new Class[] { long.class }).invoke(vo, new Object[] { 0 }); PreparedStatement ps = conn.prepareStatement(sql); setPsParams(ps, vo); ps.executeUpdate(); ps.close(); long key = this.id; parser = PojoParser.getInstances(); sql = SqlUtil.getInsertSql(subCls); Class<?> clses = this.cls; this.cls = subCls; ps = conn.prepareStatement("select * from " + parser.getTableName(subCls) + " where " + subCol + "=" + id); this.assembleObjToList(ps); ps = conn.prepareStatement(sql); ids = new long[orgList.size()]; Method m = subCls.getMethod("set" + SqlUtil.getFieldName(subCol), new Class[] { long.class }); for (int i = 0; i < orgList.size(); ++i) { Object obj = orgList.get(i); subCls.getMethod("set" + SqlUtil.getFieldName(parser.getPriamryKey(subCls)), new Class[] { long.class }).invoke(obj, new Object[] { 0 }); m.invoke(obj, new Object[] { key }); setPsParams(ps, obj); ps.addBatch(); if ((i % 100) == 0) ps.executeBatch(); ids[i] = this.id; } ps.executeBatch(); ps.close(); conn.commit(); this.cls = clses; this.id = key; bool = true; } catch (Exception e) { try { conn.rollback(); } catch (Exception ex) { ex.printStackTrace(); } this.result = e.getMessage(); } finally { this.closeConnectWithTransaction(conn); } return bool; } Code Sample 2: public static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); InputStream is = CheckAvailability.class.getResourceAsStream("/isbns.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String isbn = null; HttpGet get = null; while ((isbn = br.readLine().split(" ")[0]) != null) { System.out.println("Target url: \n\t" + String.format(isbnSearchUrl, isbn)); get = new HttpGet(String.format(isbnSearchUrl, isbn)); HttpResponse resp = httpclient.execute(get); Scanner s = new Scanner(resp.getEntity().getContent()); String pattern = s.findWithinHorizon("((\\d*) hold[s]? on first copy returned of (\\d*) )?[cC]opies", 0); if (pattern != null) { MatchResult match = s.match(); if (match.groupCount() == 3) { if (match.group(2) == null) { System.out.println(isbn + ": copies available"); } else { System.out.println(isbn + ": " + match.group(2) + " holds on " + match.group(3) + " copies"); } } } else { System.out.println(isbn + ": no match"); } get.abort(); } }
11
Code Sample 1: private void handleSSI(HttpData data) throws HttpError, IOException { File tempFile = TempFileHandler.getTempFile(); FileOutputStream out = new FileOutputStream(tempFile); BufferedReader in = new BufferedReader(new FileReader(data.realPath)); String[] env = getEnvironmentVariables(data); if (ssi == null) { ssi = new BSssi(); } ssi.addEnvironment(env); if (data.resp == null) { SimpleResponse resp = new SimpleResponse(); resp.setHeader("Content-Type", "text/html"); moreHeaders(resp); resp.setHeader("Connection", "close"); data.resp = resp; resp.write(data.out); } String t; int start; Enumeration en; boolean anIfCondition = true; while ((t = in.readLine()) != null) { if ((start = t.indexOf("<!--#")) > -1) { if (anIfCondition) out.write(t.substring(0, start).getBytes()); try { en = ssi.parse(t.substring(start)).elements(); SSICommand command; while (en.hasMoreElements()) { command = (SSICommand) en.nextElement(); logger.fine("Command=" + command); switch(command.getCommand()) { case BSssi.CMD_IF_TRUE: anIfCondition = true; break; case BSssi.CMD_IF_FALSE: anIfCondition = false; break; case BSssi.CMD_CGI: out.flush(); if (command.getFileType() != null && command.getFileType().startsWith("shtm")) { HttpData d = newHttpData(data); d.out = out; d.realPath = HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()); new SsiHandler(d, ssi).perform(); } else { String application = getExtension(command.getFileType()); if (application == null) { writePaused(new FileInputStream(HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl())), out, pause); } else { String parameter = ""; if (command.getMessage().indexOf("php") >= 0) { parameter = "-f "; } Process p = Runtime.getRuntime().exec(application + " " + parameter + HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl())); BufferedReader pIn = new BufferedReader(new InputStreamReader(p.getInputStream())); String aLine; while ((aLine = pIn.readLine()) != null) out.write((aLine + "\n").getBytes()); pIn.close(); } } break; case BSssi.CMD_EXEC: Process p = Runtime.getRuntime().exec(command.getMessage()); BufferedReader pIn = new BufferedReader(new InputStreamReader(p.getInputStream())); String aLine; while ((aLine = pIn.readLine()) != null) out.write((aLine + "\n").getBytes()); BufferedReader pErr = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((aLine = pErr.readLine()) != null) out.write((aLine + "\n").getBytes()); pIn.close(); pErr.close(); p.destroy(); break; case BSssi.CMD_INCLUDE: File incFile = HttpThread.getMappedFilename(command.getMessage()); if (incFile.exists() && incFile.canRead()) { writePaused(new FileInputStream(incFile), out, pause); } break; case BSssi.CMD_FILESIZE: long sizeBytes = HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()).length(); double smartSize; String unit = "bytes"; if (command.getFileType().trim().equals("abbrev")) { if (sizeBytes > 1000000) { smartSize = sizeBytes / 1024000.0; unit = "M"; } else if (sizeBytes > 1000) { smartSize = sizeBytes / 1024.0; unit = "K"; } else { smartSize = sizeBytes; unit = "bytes"; } NumberFormat numberFormat = new DecimalFormat("#,##0", new DecimalFormatSymbols(Locale.ENGLISH)); out.write((numberFormat.format(smartSize) + "" + unit).getBytes()); } else { NumberFormat numberFormat = new DecimalFormat("#,###,##0", new DecimalFormatSymbols(Locale.ENGLISH)); out.write((numberFormat.format(sizeBytes) + " " + unit).getBytes()); } break; case BSssi.CMD_FLASTMOD: out.write(ssi.format(new Date(HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()).lastModified()), TimeZone.getTimeZone("GMT")).getBytes()); break; case BSssi.CMD_NOECHO: break; case BSssi.CMD_ECHO: default: out.write(command.getMessage().getBytes()); break; } } } catch (Exception e) { e.printStackTrace(); out.write((ssi.getErrorMessage() + " " + e.getMessage()).getBytes()); } if (anIfCondition) out.write("\n".getBytes()); } else { if (anIfCondition) out.write((t + "\n").getBytes()); } out.flush(); } in.close(); out.close(); data.fileData.setContentType("text/html"); data.fileData.setFile(tempFile); writePaused(new FileInputStream(tempFile), data.out, pause); logger.fine("HandleSSI done for " + data.resp); } Code Sample 2: public void run(IProgressMonitor runnerMonitor) throws CoreException { try { Map<String, File> projectFiles = new HashMap<String, File>(); IPath basePath = new Path("/"); for (File nextLocation : filesToZip) { projectFiles.putAll(getFilesToZip(nextLocation, basePath, fileFilter)); } if (projectFiles.isEmpty()) { PlatformActivator.logDebug("Zip file (" + zipFileName + ") not created because there were no files to zip"); return; } IPath resultsPath = PlatformActivator.getDefault().getResultsPath(); File copyRoot = resultsPath.toFile(); copyRoot.mkdirs(); IPath zipFilePath = resultsPath.append(new Path(finalZip)); String zipFileName = zipFilePath.toPortableString(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); try { out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String filePath : projectFiles.keySet()) { File nextFile = projectFiles.get(filePath); FileInputStream fin = new FileInputStream(nextFile); try { out.putNextEntry(new ZipEntry(filePath)); try { byte[] bin = new byte[4096]; int bread = fin.read(bin, 0, 4096); while (bread != -1) { out.write(bin, 0, bread); bread = fin.read(bin, 0, 4096); } } finally { out.closeEntry(); } } finally { fin.close(); } } } finally { out.close(); } } catch (FileNotFoundException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } catch (IOException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } }
00
Code Sample 1: public HashCash(String cash) throws NoSuchAlgorithmException { myToken = cash; String[] parts = cash.split(":"); myVersion = Integer.parseInt(parts[0]); if (myVersion < 0 || myVersion > 1) throw new IllegalArgumentException("Only supported versions are 0 and 1"); if ((myVersion == 0 && parts.length != 6) || (myVersion == 1 && parts.length != 7)) throw new IllegalArgumentException("Improperly formed HashCash"); try { int index = 1; if (myVersion == 1) myValue = Integer.parseInt(parts[index++]); else myValue = 0; SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString); Calendar tempCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); tempCal.setTime(dateFormat.parse(parts[index++])); myResource = parts[index++]; myExtensions = deserializeExtensions(parts[index++]); MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(cash.getBytes()); byte[] tempBytes = md.digest(); int tempValue = numberOfLeadingZeros(tempBytes); if (myVersion == 0) myValue = tempValue; else if (myVersion == 1) myValue = (tempValue > myValue ? myValue : tempValue); } catch (java.text.ParseException ex) { throw new IllegalArgumentException("Improperly formed HashCash", ex); } } Code Sample 2: protected URLConnection openConnection(URL url) throws IOException { if (bundleEntry != null) return (new BundleURLConnection(url, bundleEntry)); String bidString = url.getHost(); if (bidString == null) { throw new IOException(NLS.bind(AdaptorMsg.URL_NO_BUNDLE_ID, url.toExternalForm())); } AbstractBundle bundle = null; long bundleID; try { bundleID = Long.parseLong(bidString); } catch (NumberFormatException nfe) { throw new MalformedURLException(NLS.bind(AdaptorMsg.URL_INVALID_BUNDLE_ID, bidString)); } bundle = (AbstractBundle) context.getBundle(bundleID); if (!url.getAuthority().equals(SECURITY_AUTHORIZED)) { checkAdminPermission(bundle); } if (bundle == null) { throw new IOException(NLS.bind(AdaptorMsg.URL_NO_BUNDLE_FOUND, url.toExternalForm())); } return (new BundleURLConnection(url, findBundleEntry(url, bundle))); }
00
Code Sample 1: public Object run() { if (type == GET_THEME_DIR) { String sep = File.separator; String[] dirs = new String[] { userHome + sep + ".themes", System.getProperty("swing.metacitythemedir"), "/usr/share/themes", "/usr/gnome/share/themes", "/opt/gnome2/share/themes" }; URL themeDir = null; for (int i = 0; i < dirs.length; i++) { if (dirs[i] == null) { continue; } File dir = new File(dirs[i] + sep + arg + sep + "metacity-1"); if (new File(dir, "metacity-theme-1.xml").canRead()) { try { themeDir = dir.toURL(); } catch (MalformedURLException ex) { themeDir = null; } break; } } if (themeDir == null) { String filename = "resources/metacity/" + arg + "/metacity-1/metacity-theme-1.xml"; URL url = getClass().getResource(filename); if (url != null) { String str = url.toString(); try { themeDir = new URL(str.substring(0, str.lastIndexOf('/')) + "/"); } catch (MalformedURLException ex) { themeDir = null; } } } return themeDir; } else if (type == GET_USER_THEME) { try { userHome = System.getProperty("user.home"); String theme = System.getProperty("swing.metacitythemename"); if (theme != null) { return theme; } URL url = new URL(new File(userHome).toURL(), ".gconf/apps/metacity/general/%25gconf.xml"); Reader reader = new InputStreamReader(url.openStream(), "ISO-8859-1"); char[] buf = new char[1024]; StringBuffer strBuf = new StringBuffer(); int n; while ((n = reader.read(buf)) >= 0) { strBuf.append(buf, 0, n); } reader.close(); String str = strBuf.toString(); if (str != null) { String strLowerCase = str.toLowerCase(); int i = strLowerCase.indexOf("<entry name=\"theme\""); if (i >= 0) { i = strLowerCase.indexOf("<stringvalue>", i); if (i > 0) { i += "<stringvalue>".length(); int i2 = str.indexOf("<", i); return str.substring(i, i2); } } } } catch (MalformedURLException ex) { } catch (IOException ex) { } return null; } else if (type == GET_IMAGE) { return new ImageIcon((URL) arg).getImage(); } else { return null; } } Code Sample 2: public static String crypt(String strPassword, String strSalt) { try { StringTokenizer st = new StringTokenizer(strSalt, "$"); st.nextToken(); byte[] abyPassword = strPassword.getBytes(); byte[] abySalt = st.nextToken().getBytes(); MessageDigest _md = MessageDigest.getInstance("MD5"); _md.update(abyPassword); _md.update(MAGIC.getBytes()); _md.update(abySalt); MessageDigest md2 = MessageDigest.getInstance("MD5"); md2.update(abyPassword); md2.update(abySalt); md2.update(abyPassword); byte[] abyFinal = md2.digest(); for (int n = abyPassword.length; n > 0; n -= 16) { _md.update(abyFinal, 0, n > 16 ? 16 : n); } abyFinal = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; for (int j = 0, i = abyPassword.length; i != 0; i >>>= 1) { if ((i & 1) == 1) _md.update(abyFinal, j, 1); else _md.update(abyPassword, j, 1); } StringBuffer sbPasswd = new StringBuffer(); sbPasswd.append(MAGIC); sbPasswd.append(new String(abySalt)); sbPasswd.append('$'); abyFinal = _md.digest(); for (int n = 0; n < 1000; n++) { MessageDigest md3 = MessageDigest.getInstance("MD5"); if ((n & 1) != 0) md3.update(abyPassword); else md3.update(abyFinal); if ((n % 3) != 0) md3.update(abySalt); if ((n % 7) != 0) md3.update(abyPassword); if ((n & 1) != 0) md3.update(abyFinal); else md3.update(abyPassword); abyFinal = md3.digest(); } int[] anFinal = new int[] { (abyFinal[0] & 0x7f) | (abyFinal[0] & 0x80), (abyFinal[1] & 0x7f) | (abyFinal[1] & 0x80), (abyFinal[2] & 0x7f) | (abyFinal[2] & 0x80), (abyFinal[3] & 0x7f) | (abyFinal[3] & 0x80), (abyFinal[4] & 0x7f) | (abyFinal[4] & 0x80), (abyFinal[5] & 0x7f) | (abyFinal[5] & 0x80), (abyFinal[6] & 0x7f) | (abyFinal[6] & 0x80), (abyFinal[7] & 0x7f) | (abyFinal[7] & 0x80), (abyFinal[8] & 0x7f) | (abyFinal[8] & 0x80), (abyFinal[9] & 0x7f) | (abyFinal[9] & 0x80), (abyFinal[10] & 0x7f) | (abyFinal[10] & 0x80), (abyFinal[11] & 0x7f) | (abyFinal[11] & 0x80), (abyFinal[12] & 0x7f) | (abyFinal[12] & 0x80), (abyFinal[13] & 0x7f) | (abyFinal[13] & 0x80), (abyFinal[14] & 0x7f) | (abyFinal[14] & 0x80), (abyFinal[15] & 0x7f) | (abyFinal[15] & 0x80) }; to64(sbPasswd, anFinal[0] << 16 | anFinal[6] << 8 | anFinal[12], 4); to64(sbPasswd, anFinal[1] << 16 | anFinal[7] << 8 | anFinal[13], 4); to64(sbPasswd, anFinal[2] << 16 | anFinal[8] << 8 | anFinal[14], 4); to64(sbPasswd, anFinal[3] << 16 | anFinal[9] << 8 | anFinal[15], 4); to64(sbPasswd, anFinal[4] << 16 | anFinal[10] << 8 | anFinal[5], 4); to64(sbPasswd, anFinal[11], 2); return sbPasswd.toString(); } catch (NoSuchAlgorithmException e) { return null; } }
11
Code Sample 1: public void constructAssociationView() { String className; String methodName; String field; boolean foundRead = false; boolean foundWrite = false; boolean classWritten = false; try { AssocView = new BufferedWriter(new FileWriter("InfoFiles/AssociationView.txt")); FileInputStream fstreamPC = new FileInputStream("InfoFiles/PrincipleClassGroup.txt"); DataInputStream inPC = new DataInputStream(fstreamPC); BufferedReader PC = new BufferedReader(new InputStreamReader(inPC)); while ((field = PC.readLine()) != null) { className = field; AssocView.write(className); AssocView.newLine(); classWritten = true; while ((methodName = PC.readLine()) != null) { if (methodName.contentEquals("EndOfClass")) break; AssocView.write("StartOfMethod"); AssocView.newLine(); AssocView.write(methodName); AssocView.newLine(); for (int i = 0; i < readFileCount && foundRead == false; i++) { if (methodName.compareTo(readArray[i]) == 0) { foundRead = true; for (int j = 1; readArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (readArray[i + j].indexOf(".") > 0) { field = readArray[i + j].substring(0, readArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(readArray[i + j]); AssocView.newLine(); } } } } } for (int i = 0; i < writeFileCount && foundWrite == false; i++) { if (methodName.compareTo(writeArray[i]) == 0) { foundWrite = true; for (int j = 1; writeArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (writeArray[i + j].indexOf(".") > 0) { field = writeArray[i + j].substring(0, writeArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(writeArray[i + j]); AssocView.newLine(); } } } } } AssocView.write("EndOfMethod"); AssocView.newLine(); foundRead = false; foundWrite = false; } if (classWritten == true) { AssocView.write("EndOfClass"); AssocView.newLine(); classWritten = false; } } PC.close(); AssocView.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public String insertBuilding() { homeMap = homeMapDao.getHomeMapById(homeMap.getId()); homeBuilding.setHomeMap(homeMap); Integer id = homeBuildingDao.saveHomeBuilding(homeBuilding); String dir = "E:\\ganymede_workspace\\training01\\web\\user_buildings\\"; FileOutputStream fos; try { fos = new FileOutputStream(dir + id); IOUtils.copy(new FileInputStream(imageFile), fos); IOUtils.closeQuietly(fos); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return execute(); }
11
Code Sample 1: public void removeGames(List<Game> games) throws SQLException { Connection conn = ConnectionManager.getManager().getConnection(); PreparedStatement stm = null; conn.setAutoCommit(false); try { for (Game game : games) { stm = conn.prepareStatement(Statements.DELETE_GAME); stm.setInt(1, game.getGameID()); stm.executeUpdate(); } } catch (SQLException e) { conn.rollback(); throw e; } finally { if (stm != null) stm.close(); } conn.commit(); conn.setAutoCommit(true); } Code Sample 2: private void runUpdate(String sql, boolean transactional) { log().info("Vacuumd executing statement: " + sql); Connection dbConn = null; boolean commitRequired = false; boolean autoCommitFlag = !transactional; try { dbConn = getDataSourceFactory().getConnection(); dbConn.setAutoCommit(autoCommitFlag); PreparedStatement stmt = dbConn.prepareStatement(sql); int count = stmt.executeUpdate(); stmt.close(); if (log().isDebugEnabled()) { log().debug("Vacuumd: Ran update " + sql + ": this affected " + count + " rows"); } commitRequired = transactional; } catch (SQLException ex) { log().error("Vacuumd: Database error execuating statement " + sql, ex); } finally { if (dbConn != null) { try { if (commitRequired) { dbConn.commit(); } else if (transactional) { dbConn.rollback(); } } catch (SQLException ex) { } finally { if (dbConn != null) { try { dbConn.close(); } catch (Exception e) { } } } } } }
11
Code Sample 1: public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); HttpSession session = request.getSession(); String session_id = session.getId(); File session_fileDir = new File(destinationDir + java.io.File.separator + session_id); session_fileDir.mkdir(); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(1 * 1024 * 1024); fileItemFactory.setRepository(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); String pathToFile = new String(); try { List items = uploadHandler.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { ; } else { pathToFile = getServletContext().getRealPath("/") + "files" + java.io.File.separator + session_id; File file = new File(pathToFile + java.io.File.separator + item.getName()); item.write(file); getContents(file, pathToFile); ComtorStandAlone.setMode(Mode.CLOUD); Comtor.start(pathToFile); } } try { File reportFile = new File(pathToFile + java.io.File.separator + "comtorReport.txt"); String reportURLString = AWSServices.storeReportS3(reportFile, session_id).toString(); if (reportURLString.startsWith("https")) reportURLString = reportURLString.replaceFirst("https", "http"); String requestURL = request.getRequestURL().toString(); String url = requestURL.substring(0, requestURL.lastIndexOf("/")); out.println("<html><head/><body>"); out.println("<a href=\"" + url + "\">Return to home</a>&nbsp;&nbsp;"); out.println("<a href=\"" + reportURLString + "\">Report URL</a><br/><hr/>"); Scanner scan = new Scanner(reportFile); out.println("<pre>"); while (scan.hasNextLine()) out.println(scan.nextLine()); out.println("</pre><hr/>"); out.println("<a href=\"" + url + "\">Return to home</a>&nbsp;&nbsp;"); out.println("<a href=\"" + reportURLString + "\">Report URL</a><br/>"); out.println("</body></html>"); } catch (Exception ex) { System.err.println(ex); } } catch (FileUploadException ex) { System.err.println("Error encountered while parsing the request" + ex); } catch (Exception ex) { System.err.println("Error encountered while uploading file" + ex); } } Code Sample 2: public void write(File file) throws Exception { if (getGEDCOMFile() != null) { size = getGEDCOMFile().length(); if (!getGEDCOMFile().renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(getGEDCOMFile())); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } }
11
Code Sample 1: public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GUnzip source"); return; } String zipname, source; if (args[0].endsWith(".gz")) { zipname = args[0]; source = args[0].substring(0, args[0].length() - 3); } else { zipname = args[0] + ".gz"; source = args[0]; } GZIPInputStream zipin; try { FileInputStream in = new FileInputStream(zipname); zipin = new GZIPInputStream(in); } catch (IOException e) { System.out.println("Couldn't open " + zipname + "."); return; } byte[] buffer = new byte[sChunk]; try { FileOutputStream out = new FileOutputStream(source); int length; while ((length = zipin.read(buffer, 0, sChunk)) != -1) out.write(buffer, 0, length); out.close(); } catch (IOException e) { System.out.println("Couldn't decompress " + args[0] + "."); } try { zipin.close(); } catch (IOException e) { } } Code Sample 2: public OutputStream getAsOutputStream() throws IOException { OutputStream out; if (contentStream != null) { File tmp = File.createTempFile(getId(), null); out = new FileOutputStream(tmp); IOUtils.copy(contentStream, out); } else { out = new ByteArrayOutputStream(); out.write(getContent()); } return out; }
11
Code Sample 1: public void save() { final JFileChooser fc = new JFileChooser(); fc.setFileFilter(new FileFilter() { public String getDescription() { return "PDF File"; } public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".pdf"); } }); if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) { return; } File targetFile = fc.getSelectedFile(); if (!targetFile.getName().toLowerCase().endsWith(".pdf")) { targetFile = new File(targetFile.getParentFile(), targetFile.getName() + ".pdf"); } if (targetFile.exists()) { if (JOptionPane.showConfirmDialog(this, "Do you want to overwrite the file?") != JOptionPane.YES_OPTION) { return; } } try { final InputStream is = new FileInputStream(filename); try { final OutputStream os = new FileOutputStream(targetFile); try { final byte[] buffer = new byte[32768]; for (int read; (read = is.read(buffer)) != -1; ) { os.write(buffer, 0, read); } } finally { os.close(); } } finally { is.close(); } } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: private void copy(File source, File destination) { if (!destination.exists()) { destination.mkdir(); } File files[] = source.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { copy(files[i], new File(destination, files[i].getName())); } else { try { FileChannel srcChannel = new FileInputStream(files[i]).getChannel(); FileChannel dstChannel = new FileOutputStream(new File(destination, files[i].getName())).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { log.error("Could not write to " + destination.getAbsolutePath(), ioe); } } } } }
00
Code Sample 1: public synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new Exception(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: public void ftpUpload() { FTPClient ftpclient = null; InputStream is = null; try { ftpclient = new FTPClient(); ftpclient.connect(host, port); if (logger.isDebugEnabled()) { logger.debug("FTP连接远程服务器:" + host); } ftpclient.login(user, password); if (logger.isDebugEnabled()) { logger.debug("登陆用户:" + user); } ftpclient.setFileType(FTP.BINARY_FILE_TYPE); ftpclient.changeWorkingDirectory(remotePath); is = new FileInputStream(localPath + File.separator + filename); ftpclient.storeFile(filename, is); logger.info("上传文件结束...路径:" + remotePath + ",文件名:" + filename); is.close(); ftpclient.logout(); } catch (IOException e) { logger.error("上传文件失败", e); } finally { if (ftpclient.isConnected()) { try { ftpclient.disconnect(); } catch (IOException e) { logger.error("断开FTP出错", e); } } ftpclient = null; } }
00
Code Sample 1: public StringBuffer getReturn(String url_address) { StringBuffer message = new StringBuffer(); try { URL url = new URL(url_address); try { HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.connect(); InputStreamReader insr = new InputStreamReader(httpConnection.getInputStream()); BufferedReader in = new BufferedReader(insr); String temp = in.readLine(); while (temp != null) { message.append(temp + "\n"); temp = in.readLine(); } in.close(); } catch (IOException e) { System.out.println("httpConnecter:Error[" + e + "]"); message.append("Connect error [" + url_address + "]"); } } catch (MalformedURLException e) { message.append("Connect error [" + url_address + "]"); System.out.println("httpConneter:Error[" + e.getMessage() + "]"); } catch (Exception e) { message.append("Connect error [" + url_address + "]"); System.out.println("httpConneter:Error[" + e.getMessage() + "]"); } return message; } Code Sample 2: public static Image load(final InputStream input, String format, Point dimension) throws CoreException { MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null); File dotInput = null, dotOutput = null; ByteArrayOutputStream dotContents = new ByteArrayOutputStream(); try { dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION); dotOutput = File.createTempFile(TMP_FILE_PREFIX, "." + format); dotOutput.delete(); FileOutputStream tmpDotOutputStream = null; try { IOUtils.copy(input, dotContents); tmpDotOutputStream = new FileOutputStream(dotInput); IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream); } finally { IOUtils.closeQuietly(tmpDotOutputStream); } IStatus result = runDot(format, dimension, dotInput, dotOutput); status.add(result); status.add(logInput(dotContents)); if (dotOutput.isFile()) { if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status); ImageLoader loader = new ImageLoader(); ImageData[] imageData = loader.load(dotOutput.getAbsolutePath()); return new Image(Display.getDefault(), imageData[0]); } } catch (SWTException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } catch (IOException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } finally { dotInput.delete(); dotOutput.delete(); IOUtils.closeQuietly(input); } throw new CoreException(status); }
11
Code Sample 1: protected void writePage(final CacheItem entry, final TranslationResponse response, ModifyTimes times) throws IOException { if (entry == null) { return; } Set<ResponseHeader> headers = new TreeSet<ResponseHeader>(); for (ResponseHeader h : entry.getHeaders()) { if (TranslationResponse.ETAG.equals(h.getName())) { if (!times.isFileLastModifiedKnown()) { headers.add(new ResponseHeaderImpl(h.getName(), doETagStripWeakMarker(h.getValues()))); } } else { headers.add(h); } } response.addHeaders(headers); if (!times.isFileLastModifiedKnown()) { response.setLastModified(entry.getLastModified()); } response.setTranslationCount(entry.getTranslationCount()); response.setFailCount(entry.getFailCount()); OutputStream output = response.getOutputStream(); try { InputStream input = entry.getContentAsStream(); try { IOUtils.copy(input, output); } finally { input.close(); } } finally { response.setEndState(ResponseStateOk.getInstance()); } } Code Sample 2: public static void fastBackup(File file) { FileChannel in = null; FileChannel out = null; FileInputStream fin = null; FileOutputStream fout = null; try { in = (fin = new FileInputStream(file)).getChannel(); out = (fout = new FileOutputStream(file.getAbsolutePath() + ".bak")).getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { Logging.getErrorLog().reportError("Fast backup failure (" + file.getAbsolutePath() + "): " + e.getMessage()); } finally { if (fin != null) { try { fin.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file input stream", e); } } if (fout != null) { try { fout.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file output stream", e); } } if (in != null) { try { in.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file channel", e); } } if (out != null) { try { out.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file channel", e); } } } }
00
Code Sample 1: public void doActionOn(TomcatProject prj) throws Exception { String path = TomcatLauncherPlugin.getDefault().getManagerAppUrl(); try { path += "/reload?path=" + prj.getWebPath(); URL url = new URL(path); Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { String user = TomcatLauncherPlugin.getDefault().getManagerAppUser(); String password = TomcatLauncherPlugin.getDefault().getManagerAppPassword(); return new PasswordAuthentication(user, password.toCharArray()); } }); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.getContent(); connection.disconnect(); Authenticator.setDefault(null); } catch (Exception e) { throw new Exception("The following url was used : \n" + path + "\n\nCheck manager app settings (username and password)\n\n"); } } Code Sample 2: private static void salvarArtista(Artista artista) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "insert into artista VALUES (?,?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setInt(1, artista.getNumeroInscricao()); ps.setString(2, artista.getNome()); ps.setBoolean(3, artista.isSexo()); ps.setString(4, artista.getEmail()); ps.setString(5, artista.getObs()); ps.setString(6, artista.getTelefone()); ps.setNull(7, Types.INTEGER); ps.executeUpdate(); salvarEndereco(conn, ps, artista); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } }
00
Code Sample 1: private void getViolationsReportByProductOfferIdYearMonthDay() throws IOException { String xmlFile9Send = System.getenv("SLASOI_HOME") + System.getProperty("file.separator") + "Integration" + System.getProperty("file.separator") + "soap" + System.getProperty("file.separator") + "getViolationsReportByProductOfferIdYearMonthDay.xml"; URL url9; url9 = new URL(bmReportingWSUrl); URLConnection connection9 = url9.openConnection(); HttpURLConnection httpConn9 = (HttpURLConnection) connection9; FileInputStream fin9 = new FileInputStream(xmlFile9Send); ByteArrayOutputStream bout9 = new ByteArrayOutputStream(); SOAPClient4XG.copy(fin9, bout9); fin9.close(); byte[] b9 = bout9.toByteArray(); httpConn9.setRequestProperty("Content-Length", String.valueOf(b9.length)); httpConn9.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); httpConn9.setRequestProperty("SOAPAction", soapAction); httpConn9.setRequestMethod("POST"); httpConn9.setDoOutput(true); httpConn9.setDoInput(true); OutputStream out9 = httpConn9.getOutputStream(); out9.write(b9); out9.close(); InputStreamReader isr9 = new InputStreamReader(httpConn9.getInputStream()); BufferedReader in9 = new BufferedReader(isr9); String inputLine9; StringBuffer response9 = new StringBuffer(); while ((inputLine9 = in9.readLine()) != null) { response9.append(inputLine9); } in9.close(); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "Component Name: Business Manager\n" + "Interface Name: getReport\n" + "Operation Name: " + "getViolationsReportByProductOfferIdYearMonthDay\n" + "Input" + "ProductOfferID-1\n" + "PartyID-1\n" + "\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "######################################## RESPONSE" + "############################################\n\n"); System.out.println("--------------------------------"); System.out.println("Response\n" + response9.toString()); } Code Sample 2: public void testOptionalSections() throws Exception { final File implementationDirectory = this.getTestSourcesDirectory(); final File specificationDirectory = this.getTestSourcesDirectory(); IOUtils.copy(this.getClass().getResourceAsStream("ImplementationWithoutConstructorsSection.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("ImplementationWithoutDefaultConstructorSection.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("ImplementationWithoutDocumentationSection.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("ImplementationWithoutLicenseSection.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("SpecificationWithoutDocumentationSection.java.txt"), new FileOutputStream(new File(specificationDirectory, "Specification.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("SpecificationWithoutLicenseSection.java.txt"), new FileOutputStream(new File(specificationDirectory, "Specification.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); }
00
Code Sample 1: @Override public void run() { File file = new File(LogHandler.path); FileFilter filter = new FileFilter() { @Override public boolean accept(File file) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date()); cal.add(GregorianCalendar.DAY_OF_YEAR, -1); String oldTime = LogHandler.dateFormat.format(cal.getTime()); return file.getName().toLowerCase().startsWith(oldTime); } }; File[] list = file.listFiles(filter); if (list.length > 0) { FileInputStream in; int read = 0; byte[] data = new byte[1024]; for (int i = 0; i < list.length; i++) { try { in = new FileInputStream(LogHandler.path + list[i].getName()); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(LogHandler.path + list[i].getName() + ".temp")); while ((read = in.read(data, 0, 1024)) != -1) out.write(data, 0, read); in.close(); out.close(); new File(LogHandler.path + list[i].getName() + ".temp").renameTo(new File(LogHandler.path + list[i].getName() + ".gz")); list[i].delete(); } catch (FileNotFoundException e) { TrackingServer.incExceptionCounter(); e.printStackTrace(); } catch (IOException ioe) { } } } } Code Sample 2: @Test(expected = GadgetException.class) public void badFetchServesCached() throws Exception { HttpRequest firstRequest = createCacheableRequest(); expect(pipeline.execute(firstRequest)).andReturn(new HttpResponse(LOCAL_SPEC_XML)).once(); HttpRequest secondRequest = createIgnoreCacheRequest(); expect(pipeline.execute(secondRequest)).andReturn(HttpResponse.error()).once(); replay(pipeline); GadgetSpec original = specFactory.getGadgetSpec(createContext(SPEC_URL, false)); GadgetSpec cached = specFactory.getGadgetSpec(createContext(SPEC_URL, true)); assertEquals(original.getUrl(), cached.getUrl()); assertEquals(original.getChecksum(), cached.getChecksum()); }
00
Code Sample 1: protected void handleUrl(URL url) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String s; boolean moreResults = false; while ((s = in.readLine()) != null) { if (s.indexOf("<h1>Search Results</h1>") > -1) { System.err.println("found severals result"); moreResults = true; } else if (s.indexOf("Download <a href=") > -1) { if (s.indexOf("in JCAMP-DX format.") > -1) { System.err.println("download masspec"); super.handleUrl(new URL((url.getProtocol() + "://" + url.getHost() + s.substring(s.indexOf("\"") + 1, s.lastIndexOf("\""))).replaceAll("amp;", ""))); } moreResults = false; } if (moreResults == true) { if (s.indexOf("<li><a href=\"/cgi/cbook.cgi?ID") > -1) { System.err.println("\tdownloading new url " + new URL((url.getProtocol() + "://" + url.getHost() + s.substring(s.indexOf("\"") + 1, s.lastIndexOf("\""))).replaceAll("amp;", ""))); this.handleUrl(new URL((url.getProtocol() + "://" + url.getHost() + s.substring(s.indexOf("\"") + 1, s.lastIndexOf("\""))).replaceAll("amp;", ""))); } } } } Code Sample 2: public static Channel getChannelFromXML(String channelURL) throws SAXException, IOException { channel = new Channel(channelURL); downloadedItems = new LinkedList<Item>(); URL url = new URL(channelURL); XMLReader xr = XMLReaderFactory.createXMLReader(); ChannelFactory handler = new ChannelFactory(); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.parse(new InputSource(url.openStream())); channel.setUnreadItemsCount(downloadedItems.size()); return channel; }
00
Code Sample 1: public void backup(File source) throws BackupException { try { int index = source.getAbsolutePath().lastIndexOf("."); if (index == -1) return; File dest = new File(source.getAbsolutePath().substring(0, index) + ".bak"); FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception ex) { throw new BackupException(ex.getMessage(), ex, source); } } Code Sample 2: public static String replace(URL url, Replacer replacer) throws Exception { URLConnection con = url.openConnection(); InputStreamReader reader = new InputStreamReader(con.getInputStream()); StringWriter wr = new StringWriter(); int c; StringBuffer token = null; while ((c = reader.read()) != -1) { if (c == '@') { if (token == null) { token = new StringBuffer(); } else { String val = replacer.replace(token.toString()); if (val != null) { wr.write(val); token = null; } else { wr.write('@'); wr.write(token.toString()); token.delete(0, token.length()); } } } else { if (token == null) { wr.write((char) c); } else { token.append((char) c); } } } if (token != null) { wr.write('@'); wr.write(token.toString()); } return wr.toString(); }
11
Code Sample 1: public static void copyFiles(String strPath, String trgPath) { File src = new File(strPath); File trg = new File(trgPath); if (src.isDirectory()) { if (trg.exists() != true) trg.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { String strPath_1 = src.getAbsolutePath() + SEPARATOR + list[i]; String trgPath_1 = trg.getAbsolutePath() + SEPARATOR + list[i]; copyFiles(strPath_1, trgPath_1); } } else { try { FileChannel srcChannel = new FileInputStream(strPath).getChannel(); FileChannel dstChannel = new FileOutputStream(trgPath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (FileNotFoundException e) { System.out.println("[Error] File not found: " + e.getMessage()); } catch (IOException e) { System.out.println("[Error] " + e.getMessage()); } } } Code Sample 2: PackageFileImpl(PackageDirectoryImpl dir, String name, InputStream data) throws IOException { this.dir = dir; this.name = name; this.updates = dir.getUpdates(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); IOUtils.copy(data, stream); updates.setNewData(getFullName(), stream.toByteArray()); stream.close(); }
00
Code Sample 1: public String encrypt(String password) { String encrypted_pass = ""; ByteArrayOutputStream output = null; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte byte_array[] = md.digest(); output = new ByteArrayOutputStream(byte_array.length); output.write(byte_array); encrypted_pass = output.toString("UTF-8"); System.out.println("password: " + encrypted_pass); } catch (Exception e) { System.out.println("Exception thrown: " + e.getMessage()); } return encrypted_pass; } Code Sample 2: public void access() { Authenticator.setDefault(new MyAuthenticator()); try { URL url = new URL("http://localhost/ws/test"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
00
Code Sample 1: private void getViolationsReportByProductOfferIdYearMonthDay() throws IOException { String xmlFile9Send = System.getenv("SLASOI_HOME") + System.getProperty("file.separator") + "Integration" + System.getProperty("file.separator") + "soap" + System.getProperty("file.separator") + "getViolationsReportByProductOfferIdYearMonthDay.xml"; URL url9; url9 = new URL(bmReportingWSUrl); URLConnection connection9 = url9.openConnection(); HttpURLConnection httpConn9 = (HttpURLConnection) connection9; FileInputStream fin9 = new FileInputStream(xmlFile9Send); ByteArrayOutputStream bout9 = new ByteArrayOutputStream(); SOAPClient4XG.copy(fin9, bout9); fin9.close(); byte[] b9 = bout9.toByteArray(); httpConn9.setRequestProperty("Content-Length", String.valueOf(b9.length)); httpConn9.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); httpConn9.setRequestProperty("SOAPAction", soapAction); httpConn9.setRequestMethod("POST"); httpConn9.setDoOutput(true); httpConn9.setDoInput(true); OutputStream out9 = httpConn9.getOutputStream(); out9.write(b9); out9.close(); InputStreamReader isr9 = new InputStreamReader(httpConn9.getInputStream()); BufferedReader in9 = new BufferedReader(isr9); String inputLine9; StringBuffer response9 = new StringBuffer(); while ((inputLine9 = in9.readLine()) != null) { response9.append(inputLine9); } in9.close(); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "Component Name: Business Manager\n" + "Interface Name: getReport\n" + "Operation Name: " + "getViolationsReportByProductOfferIdYearMonthDay\n" + "Input" + "ProductOfferID-1\n" + "PartyID-1\n" + "\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "######################################## RESPONSE" + "############################################\n\n"); System.out.println("--------------------------------"); System.out.println("Response\n" + response9.toString()); } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public static void copy(File source, File target) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(target).getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER); while (in.read(buffer) != -1) { buffer.flip(); while (buffer.hasRemaining()) { out.write(buffer); } buffer.clear(); } } catch (IOException ex) { throw new RuntimeException(ex); } finally { close(in); close(out); } } Code Sample 2: public static boolean insert(final Funcionario objFuncionario) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into funcionario " + "(nome, cpf, telefone, email, senha, login, id_cargo)" + " values (?, ?, ?, ?, ?, ?, ?)"; pst = c.prepareStatement(sql); pst.setString(1, objFuncionario.getNome()); pst.setString(2, objFuncionario.getCpf()); pst.setString(3, objFuncionario.getTelefone()); pst.setString(4, objFuncionario.getEmail()); pst.setString(5, objFuncionario.getSenha()); pst.setString(6, objFuncionario.getLogin()); pst.setLong(7, (objFuncionario.getCargo()).getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { System.out.println("[FuncionarioDAO.insert] Erro ao inserir -> " + e1.getMessage()); } System.out.println("[FuncionarioDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
11
Code Sample 1: private void trainSRLParser(byte flag, JarArchiveOutputStream zout) throws Exception { AbstractSRLParser labeler = null; AbstractDecoder[] decoder = null; if (flag == SRLParser.FLAG_TRAIN_LEXICON) { System.out.println("\n* Save lexica"); labeler = new SRLParser(flag, s_featureXml); } else if (flag == SRLParser.FLAG_TRAIN_INSTANCE) { System.out.println("\n* Print training instances"); System.out.println("- loading lexica"); labeler = new SRLParser(flag, t_xml, s_lexiconFiles); } else if (flag == SRLParser.FLAG_TRAIN_BOOST) { System.out.println("\n* Train boost"); decoder = new AbstractDecoder[m_model.length]; for (int i = 0; i < decoder.length; i++) decoder[i] = new OneVsAllDecoder((OneVsAllModel) m_model[i]); labeler = new SRLParser(flag, t_xml, t_map, decoder); } AbstractReader<DepNode, DepTree> reader = new SRLReader(s_trainFile, true); DepTree tree; int n; labeler.setLanguage(s_language); reader.setLanguage(s_language); for (n = 0; (tree = reader.nextTree()) != null; n++) { labeler.parse(tree); if (n % 1000 == 0) System.out.printf("\r- parsing: %dK", n / 1000); } System.out.println("\r- labeling: " + n); if (flag == SRLParser.FLAG_TRAIN_LEXICON) { System.out.println("- labeling"); labeler.saveTags(s_lexiconFiles); t_xml = labeler.getSRLFtrXml(); } else if (flag == SRLParser.FLAG_TRAIN_INSTANCE || flag == SRLParser.FLAG_TRAIN_BOOST) { a_yx = labeler.a_trans; zout.putArchiveEntry(new JarArchiveEntry(ENTRY_FEATURE)); IOUtils.copy(new FileInputStream(s_featureXml), zout); zout.closeArchiveEntry(); for (String lexicaFile : s_lexiconFiles) { zout.putArchiveEntry(new JarArchiveEntry(lexicaFile)); IOUtils.copy(new FileInputStream(lexicaFile), zout); zout.closeArchiveEntry(); } if (flag == SRLParser.FLAG_TRAIN_INSTANCE) t_map = labeler.getSRLFtrMap(); } } Code Sample 2: public static void entering(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.readClass(new BufferedInputStream(new FileInputStream(args[0]))); int constantIndex = writer.getStringConstantIndex("Entering "); int fieldRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;"); int printlnRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); int printRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "print", "(Ljava/lang/String;)V"); for (Iterator i = writer.getMethods().iterator(); i.hasNext(); ) { MethodInfo method = (MethodInfo) i.next(); if (method.getName().equals("readConstant")) continue; CodeAttribute attribute = method.getCodeAttribute(); ArrayList instructions = new ArrayList(10); byte[] operands; operands = new byte[2]; NetByte.intToPair(fieldRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("getstatic"), 0, operands, false)); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("dup"), 0, null, false)); instructions.add(Instruction.appropriateLdc(constantIndex, false)); operands = new byte[2]; NetByte.intToPair(printRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); instructions.add(Instruction.appropriateLdc(writer.getStringConstantIndex(method.getName()), false)); operands = new byte[2]; NetByte.intToPair(printlnRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); attribute.insertInstructions(0, 0, instructions); attribute.codeCheck(); } BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(args[1])); writer.writeClass(outStream); outStream.close(); }
11
Code Sample 1: public boolean clonarFichero(String rutaFicheroOrigen, String rutaFicheroDestino) { System.out.println(""); System.out.println("*********** DENTRO DE 'clonarFichero' ***********"); boolean estado = false; try { FileInputStream entrada = new FileInputStream(rutaFicheroOrigen); FileOutputStream salida = new FileOutputStream(rutaFicheroDestino); FileChannel canalOrigen = entrada.getChannel(); FileChannel canalDestino = salida.getChannel(); canalOrigen.transferTo(0, canalOrigen.size(), canalDestino); entrada.close(); salida.close(); estado = true; } catch (IOException e) { System.out.println("No se encontro el archivo"); e.printStackTrace(); estado = false; } return estado; } Code Sample 2: private void copyReportFile(ServletRequest req, String reportName, Report report) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException, FileNotFoundException, IOException { String reportFileName = (String) Class.forName("org.eclipse.birt.report.utility.ParameterAccessor").getMethod("getReport", new Class[] { HttpServletRequest.class, String.class }).invoke(null, new Object[] { req, reportName }); ByteArrayInputStream bais = new ByteArrayInputStream(report.getReportContent()); FileOutputStream fos = new FileOutputStream(new File(reportFileName)); IOUtils.copy(bais, fos); bais.close(); fos.close(); }
11
Code Sample 1: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } } Code Sample 2: public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); }
11
Code Sample 1: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); } Code Sample 2: public void launchJob(final String workingDir, final AppConfigType appConfig) throws FaultType { logger.info("called for job: " + jobID); MessageContext mc = MessageContext.getCurrentContext(); HttpServletRequest req = (HttpServletRequest) mc.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); String clientDN = (String) req.getAttribute(GSIConstants.GSI_USER_DN); if (clientDN != null) { logger.info("Client's DN: " + clientDN); } else { clientDN = "Unknown client"; } String remoteIP = req.getRemoteAddr(); SOAPService service = mc.getService(); String serviceName = service.getName(); if (serviceName == null) { serviceName = "Unknown service"; } if (appConfig.isParallel()) { if (AppServiceImpl.drmaaInUse) { if (AppServiceImpl.drmaaPE == null) { logger.error("drmaa.pe property must be specified in opal.properties " + "for parallel execution using DRMAA"); throw new FaultType("drmaa.pe property must be specified in opal.properties " + "for parallel execution using DRMAA"); } if (AppServiceImpl.mpiRun == null) { logger.error("mpi.run property must be specified in opal.properties " + "for parallel execution using DRMAA"); throw new FaultType("mpi.run property must be specified in " + "opal.properties for parallel execution " + "using DRMAA"); } } else if (!AppServiceImpl.globusInUse) { if (AppServiceImpl.mpiRun == null) { logger.error("mpi.run property must be specified in opal.properties " + "for parallel execution without using Globus"); throw new FaultType("mpi.run property must be specified in " + "opal.properties for parallel execution " + "without using Globus"); } } if (jobIn.getNumProcs() == null) { logger.error("Number of processes unspecified for parallel job"); throw new FaultType("Number of processes unspecified for parallel job"); } else if (jobIn.getNumProcs().intValue() > AppServiceImpl.numProcs) { logger.error("Processors required - " + jobIn.getNumProcs() + ", available - " + AppServiceImpl.numProcs); throw new FaultType("Processors required - " + jobIn.getNumProcs() + ", available - " + AppServiceImpl.numProcs); } } try { status.setCode(GramJob.STATUS_PENDING); status.setMessage("Launching executable"); status.setBaseURL(new URI(AppServiceImpl.tomcatURL + jobID)); } catch (MalformedURIException mue) { logger.error("Cannot convert base_url string to URI - " + mue.getMessage()); throw new FaultType("Cannot convert base_url string to URI - " + mue.getMessage()); } if (!AppServiceImpl.dbInUse) { AppServiceImpl.statusTable.put(jobID, status); } else { Connection conn = null; try { conn = DriverManager.getConnection(AppServiceImpl.dbUrl, AppServiceImpl.dbUser, AppServiceImpl.dbPasswd); } catch (SQLException e) { logger.error("Cannot connect to database - " + e.getMessage()); throw new FaultType("Cannot connect to database - " + e.getMessage()); } String time = new SimpleDateFormat("MMM d, yyyy h:mm:ss a", Locale.US).format(new Date()); String sqlStmt = "insert into job_status(job_id, code, message, base_url, " + "client_dn, client_ip, service_name, start_time, last_update) " + "values ('" + jobID + "', " + status.getCode() + ", " + "'" + status.getMessage() + "', " + "'" + status.getBaseURL() + "', " + "'" + clientDN + "', " + "'" + remoteIP + "', " + "'" + serviceName + "', " + "'" + time + "', " + "'" + time + "');"; try { Statement stmt = conn.createStatement(); stmt.executeUpdate(sqlStmt); conn.close(); } catch (SQLException e) { logger.error("Cannot insert job status into database - " + e.getMessage()); throw new FaultType("Cannot insert job status into database - " + e.getMessage()); } } String args = appConfig.getDefaultArgs(); if (args == null) { args = jobIn.getArgList(); } else { String userArgs = jobIn.getArgList(); if (userArgs != null) args += " " + userArgs; } if (args != null) { args = args.trim(); } logger.debug("Argument list: " + args); if (AppServiceImpl.drmaaInUse) { String cmd = null; String[] argsArray = null; if (appConfig.isParallel()) { cmd = "/bin/sh"; String newArgs = AppServiceImpl.mpiRun + " -machinefile $TMPDIR/machines" + " -np " + jobIn.getNumProcs() + " " + appConfig.getBinaryLocation(); if (args != null) { args = newArgs + " " + args; } else { args = newArgs; } logger.debug("CMD: " + args); argsArray = new String[] { "-c", args }; } else { cmd = appConfig.getBinaryLocation(); if (args == null) args = ""; logger.debug("CMD: " + cmd + " " + args); argsArray = args.split(" "); } try { logger.debug("Working directory: " + workingDir); JobTemplate jt = session.createJobTemplate(); if (appConfig.isParallel()) jt.setNativeSpecification("-pe " + AppServiceImpl.drmaaPE + " " + jobIn.getNumProcs()); jt.setRemoteCommand(cmd); jt.setArgs(argsArray); jt.setJobName(jobID); jt.setWorkingDirectory(workingDir); jt.setErrorPath(":" + workingDir + "/stderr.txt"); jt.setOutputPath(":" + workingDir + "/stdout.txt"); drmaaJobID = session.runJob(jt); logger.info("DRMAA job has been submitted with id " + drmaaJobID); session.deleteJobTemplate(jt); } catch (Exception ex) { logger.error(ex); status.setCode(GramJob.STATUS_FAILED); status.setMessage("Error while running executable via DRMAA - " + ex.getMessage()); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } return; } status.setCode(GramJob.STATUS_ACTIVE); status.setMessage("Execution in progress"); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } } else if (AppServiceImpl.globusInUse) { String rsl = null; if (appConfig.isParallel()) { rsl = "&(directory=" + workingDir + ")" + "(executable=" + appConfig.getBinaryLocation() + ")" + "(count=" + jobIn.getNumProcs() + ")" + "(jobtype=mpi)" + "(stdout=stdout.txt)" + "(stderr=stderr.txt)"; } else { rsl = "&(directory=" + workingDir + ")" + "(executable=" + appConfig.getBinaryLocation() + ")" + "(stdout=stdout.txt)" + "(stderr=stderr.txt)"; } if (args != null) { args = "\"" + args + "\""; args = args.replaceAll("[\\s]+", "\" \""); rsl += "(arguments=" + args + ")"; } logger.debug("RSL: " + rsl); try { job = new GramJob(rsl); GlobusCredential globusCred = new GlobusCredential(AppServiceImpl.serviceCertPath, AppServiceImpl.serviceKeyPath); GSSCredential gssCred = new GlobusGSSCredentialImpl(globusCred, GSSCredential.INITIATE_AND_ACCEPT); job.setCredentials(gssCred); job.addListener(this); job.request(AppServiceImpl.gatekeeperContact); } catch (Exception ge) { logger.error(ge); status.setCode(GramJob.STATUS_FAILED); status.setMessage("Error while running executable via Globus - " + ge.getMessage()); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } return; } } else { String cmd = null; if (appConfig.isParallel()) { cmd = new String(AppServiceImpl.mpiRun + " " + "-np " + jobIn.getNumProcs() + " " + appConfig.getBinaryLocation()); } else { cmd = new String(appConfig.getBinaryLocation()); } if (args != null) { cmd += " " + args; } logger.debug("CMD: " + cmd); try { logger.debug("Working directory: " + workingDir); proc = Runtime.getRuntime().exec(cmd, null, new File(workingDir)); stdoutThread = writeStdOut(proc, workingDir); stderrThread = writeStdErr(proc, workingDir); } catch (IOException ioe) { logger.error(ioe); status.setCode(GramJob.STATUS_FAILED); status.setMessage("Error while running executable via fork - " + ioe.getMessage()); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } return; } status.setCode(GramJob.STATUS_ACTIVE); status.setMessage("Execution in progress"); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } } new Thread() { public void run() { try { waitForCompletion(); } catch (FaultType f) { logger.error(f); synchronized (status) { status.notifyAll(); } return; } if (AppServiceImpl.drmaaInUse || !AppServiceImpl.globusInUse) { done = true; status.setCode(GramJob.STATUS_STAGE_OUT); status.setMessage("Writing output metadata"); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update status database after finish - " + e.getMessage()); logger.error(e); synchronized (status) { status.notifyAll(); } return; } } } try { if (!AppServiceImpl.drmaaInUse && !AppServiceImpl.globusInUse) { try { logger.debug("Waiting for all outputs to be written out"); stdoutThread.join(); stderrThread.join(); logger.debug("All outputs successfully written out"); } catch (InterruptedException ignore) { } } File stdOutFile = new File(workingDir + File.separator + "stdout.txt"); if (!stdOutFile.exists()) { throw new IOException("Standard output missing for execution"); } File stdErrFile = new File(workingDir + File.separator + "stderr.txt"); if (!stdErrFile.exists()) { throw new IOException("Standard error missing for execution"); } if (AppServiceImpl.archiveData) { logger.debug("Archiving output files"); File f = new File(workingDir); File[] outputFiles = f.listFiles(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(workingDir + File.separator + jobID + ".zip")); byte[] buf = new byte[1024]; try { for (int i = 0; i < outputFiles.length; i++) { FileInputStream in = new FileInputStream(outputFiles[i]); out.putNextEntry(new ZipEntry(outputFiles[i].getName())); int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } out.close(); } catch (IOException e) { logger.error(e); logger.error("Error not fatal - moving on"); } } File f = new File(workingDir); File[] outputFiles = f.listFiles(); OutputFileType[] outputFileObj = new OutputFileType[outputFiles.length - 2]; int j = 0; for (int i = 0; i < outputFiles.length; i++) { if (outputFiles[i].getName().equals("stdout.txt")) { outputs.setStdOut(new URI(AppServiceImpl.tomcatURL + jobID + "/stdout.txt")); } else if (outputFiles[i].getName().equals("stderr.txt")) { outputs.setStdErr(new URI(AppServiceImpl.tomcatURL + jobID + "/stderr.txt")); } else { OutputFileType next = new OutputFileType(); next.setName(outputFiles[i].getName()); next.setUrl(new URI(AppServiceImpl.tomcatURL + jobID + "/" + outputFiles[i].getName())); outputFileObj[j++] = next; } } outputs.setOutputFile(outputFileObj); } catch (IOException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot retrieve outputs after finish - " + e.getMessage()); logger.error(e); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException se) { logger.error(se); } } synchronized (status) { status.notifyAll(); } return; } if (!AppServiceImpl.dbInUse) { AppServiceImpl.outputTable.put(jobID, outputs); } else { Connection conn = null; try { conn = DriverManager.getConnection(AppServiceImpl.dbUrl, AppServiceImpl.dbUser, AppServiceImpl.dbPasswd); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot connect to database after finish - " + e.getMessage()); logger.error(e); synchronized (status) { status.notifyAll(); } return; } String sqlStmt = "insert into job_output(job_id, std_out, std_err) " + "values ('" + jobID + "', " + "'" + outputs.getStdOut().toString() + "', " + "'" + outputs.getStdErr().toString() + "');"; Statement stmt = null; try { stmt = conn.createStatement(); stmt.executeUpdate(sqlStmt); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update job output database after finish - " + e.getMessage()); logger.error(e); try { updateStatusInDatabase(jobID, status); } catch (SQLException se) { logger.error(se); } synchronized (status) { status.notifyAll(); } return; } OutputFileType[] outputFile = outputs.getOutputFile(); for (int i = 0; i < outputFile.length; i++) { sqlStmt = "insert into output_file(job_id, name, url) " + "values ('" + jobID + "', " + "'" + outputFile[i].getName() + "', " + "'" + outputFile[i].getUrl().toString() + "');"; try { stmt = conn.createStatement(); stmt.executeUpdate(sqlStmt); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update output_file DB after finish - " + e.getMessage()); logger.error(e); try { updateStatusInDatabase(jobID, status); } catch (SQLException se) { logger.error(se); } synchronized (status) { status.notifyAll(); } return; } } } if (terminatedOK()) { status.setCode(GramJob.STATUS_DONE); status.setMessage("Execution complete - " + "check outputs to verify successful execution"); } else { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Execution failed"); } if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update status database after finish - " + e.getMessage()); logger.error(e); synchronized (status) { status.notifyAll(); } return; } } AppServiceImpl.jobTable.remove(jobID); synchronized (status) { status.notifyAll(); } logger.info("Execution complete for job: " + jobID); } }.start(); }
00
Code Sample 1: public void reload() throws SAXException, IOException { if (url != null) { java.io.InputStream is = url.openStream(); configDoc = builder.parse(is); is.close(); System.out.println("XML config file read correctly from " + url); } else { configDoc = builder.parse(configFile); System.out.println("XML config file read correctly from " + configFile); } } Code Sample 2: public static boolean copyFile(File from, File to) { try { FileChannel fromChannel = new FileInputStream(from).getChannel(); FileChannel toChannel = new FileOutputStream(to).getChannel(); toChannel.transferFrom(fromChannel, 0, fromChannel.size()); fromChannel.close(); toChannel.close(); } catch (IOException e) { log.error("failed to copy " + from.getAbsolutePath() + " to " + to.getAbsolutePath() + ": caught exception", e); return false; } return true; }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static void copyFile(File source, File destination) throws IOException { FileInputStream fis = new FileInputStream(source); FileOutputStream fos = null; try { fos = new FileOutputStream(destination); FileChannel sourceChannel = fis.getChannel(); FileChannel destinationChannel = fos.getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); destinationChannel.close(); sourceChannel.close(); } finally { if (fos != null) fos.close(); fis.close(); } }
11
Code Sample 1: private boolean copyFiles(File sourceDir, File destinationDir) { boolean result = false; try { if (sourceDir != null && destinationDir != null && sourceDir.exists() && destinationDir.exists() && sourceDir.isDirectory() && destinationDir.isDirectory()) { File sourceFiles[] = sourceDir.listFiles(); if (sourceFiles != null && sourceFiles.length > 0) { File destFiles[] = destinationDir.listFiles(); if (destFiles != null && destFiles.length > 0) { for (int i = 0; i < destFiles.length; i++) { if (destFiles[i] != null) { destFiles[i].delete(); } } } for (int i = 0; i < sourceFiles.length; i++) { if (sourceFiles[i] != null && sourceFiles[i].exists() && sourceFiles[i].isFile()) { String fileName = destFiles[i].getName(); File destFile = new File(destinationDir.getAbsolutePath() + "/" + fileName); if (!destFile.exists()) destFile.createNewFile(); FileInputStream in = new FileInputStream(sourceFiles[i]); FileOutputStream out = new FileOutputStream(destFile); FileChannel fcIn = in.getChannel(); FileChannel fcOut = out.getChannel(); fcIn.transferTo(0, fcIn.size(), fcOut); } } } } result = true; } catch (Exception e) { System.out.println("Exception in copyFiles Method : " + e); } return result; } Code Sample 2: private void putAlgosFromJar(File jarfile, AlgoDir dir, Model model) throws FileNotFoundException, IOException { URLClassLoader urlLoader = new URLClassLoader(new URL[] { jarfile.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(jarfile)); JarEntry entry = jis.getNextJarEntry(); String name = null; String tmpdir = System.getProperty("user.dir") + File.separator + Application.getProperty("dir.tmp") + File.separator; byte[] buffer = new byte[1000]; while (entry != null) { name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); try { Class<?> cls = urlLoader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && ((cls.getModifiers() & Modifier.ABSTRACT) == 0)) { dir.addAlgorithm(cls); model.putClass(cls.getName(), cls); } else if (ISerializable.class.isAssignableFrom(cls)) { model.putClass(cls.getName(), cls); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else if (Constants.isAllowedImageType(name)) { int lastSep = name.lastIndexOf("/"); if (lastSep != -1) { String dirs = tmpdir + name.substring(0, lastSep); File d = new File(dirs); if (!d.exists()) d.mkdirs(); } String filename = tmpdir + name; File f = new File(filename); if (!f.exists()) { f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); int read = -1; while ((read = jis.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.close(); } } entry = jis.getNextJarEntry(); } }
00
Code Sample 1: private void loginImageShack() throws Exception { loginsuccessful = false; HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); NULogger.getLogger().info("Trying to log in to imageshack.us"); HttpPost httppost = new HttpPost("http://imageshack.us/auth.php"); httppost.setHeader("Referer", "http://www.uploading.com/"); httppost.setHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); httppost.setHeader("Cookie", newcookie + ";" + phpsessioncookie + ";" + imgshckcookie + ";" + uncookie + ";" + latestcookie + ";" + langcookie); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("username", getUsername())); formparams.add(new BasicNameValuePair("password", getPassword())); formparams.add(new BasicNameValuePair("stay_logged_in", "")); formparams.add(new BasicNameValuePair("format", "json")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); HttpEntity en = httpresponse.getEntity(); uploadresponse = EntityUtils.toString(en); NULogger.getLogger().log(Level.INFO, "Upload response : {0}", uploadresponse); NULogger.getLogger().info("Getting cookies........"); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); if (escookie.getName().equalsIgnoreCase("myid")) { myidcookie = escookie.getValue(); NULogger.getLogger().info(myidcookie); loginsuccessful = true; } if (escookie.getName().equalsIgnoreCase("myimages")) { myimagescookie = escookie.getValue(); NULogger.getLogger().info(myimagescookie); } if (escookie.getName().equalsIgnoreCase("isUSER")) { usercookie = escookie.getValue(); NULogger.getLogger().info(usercookie); } } if (loginsuccessful) { NULogger.getLogger().info("ImageShack Login Success"); loginsuccessful = true; username = getUsername(); password = getPassword(); } else { NULogger.getLogger().info("ImageShack Login failed"); loginsuccessful = false; username = ""; password = ""; JOptionPane.showMessageDialog(NeembuuUploader.getInstance(), "<html><b>" + HOSTNAME + "</b> " + TranslationProvider.get("neembuuuploader.accounts.loginerror") + "</html>", HOSTNAME, JOptionPane.WARNING_MESSAGE); AccountsManager.getInstance().setVisible(true); } } Code Sample 2: private void sort() { for (int i = 0; i < density.length; i++) { for (int j = density.length - 2; j >= i; j--) { if (density[j] > density[j + 1]) { KDNode n = nonEmptyNodesArray[j]; nonEmptyNodesArray[j] = nonEmptyNodesArray[j + 1]; nonEmptyNodesArray[j + 1] = n; double d = density[j]; density[j] = density[j + 1]; density[j + 1] = d; } } } }
11
Code Sample 1: public void sendContent(OutputStream out, Range range, Map map, String string) throws IOException, NotAuthorizedException, BadRequestException { System.out.println("sendContent " + file); RFileInputStream in = new RFileInputStream(file); try { IOUtils.copyLarge(in, out); } finally { in.close(); } } Code Sample 2: public static void main(String[] args) { try { String completePath = null; String predictionFileName = null; if (args.length == 2) { completePath = args[0]; predictionFileName = args[1]; } else { System.out.println("Please provide complete path to training_set parent folder as an argument. EXITING"); System.exit(0); } File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); MovieLimitsTHash = new TShortObjectHashMap(17770, 1); int i = 0, totalcount = 0; short movie; int startIndex, endIndex; TIntArrayList a; while (mappedfile.hasRemaining()) { movie = mappedfile.getShort(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); MovieLimitsTHash.put(movie, a); } inC.close(); mappedfile = null; System.out.println("Loaded movie index hash"); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); MoviesAndRatingsPerCustomer = InitializeMovieRatingsForCustomerHashMap(completePath, CustomerLimitsTHash); System.out.println("Populated MoviesAndRatingsPerCustomer hashmap"); File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionFileName); FileChannel out = new FileOutputStream(outfile, true).getChannel(); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "formattedProbeData.txt"); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); int custAndRatingSize = 0; TIntByteHashMap custsandratings = new TIntByteHashMap(); int ignoreProcessedRows = 0; int movieViewershipSize = 0; while (probemappedfile.hasRemaining()) { short testmovie = probemappedfile.getShort(); int testCustomer = probemappedfile.getInt(); if ((CustomersAndRatingsPerMovie != null) && (CustomersAndRatingsPerMovie.containsKey(testmovie))) { } else { CustomersAndRatingsPerMovie = InitializeCustomerRatingsForMovieHashMap(completePath, testmovie); custsandratings = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(testmovie); custAndRatingSize = custsandratings.size(); } TShortByteHashMap testCustMovieAndRatingsMap = (TShortByteHashMap) MoviesAndRatingsPerCustomer.get(testCustomer); short[] testCustMovies = testCustMovieAndRatingsMap.keys(); float finalPrediction = 0; finalPrediction = predictRating(testCustomer, testmovie, custsandratings, custAndRatingSize, testCustMovies, testCustMovieAndRatingsMap); System.out.println("prediction for movie: " + testmovie + " for customer " + testCustomer + " is " + finalPrediction); ByteBuffer buf = ByteBuffer.allocate(11); buf.putShort(testmovie); buf.putInt(testCustomer); buf.putFloat(finalPrediction); buf.flip(); out.write(buf); buf = null; testCustMovieAndRatingsMap = null; testCustMovies = null; } } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: protected static String getFileContentAsString(URL url, String encoding) throws IOException { InputStream input = null; StringWriter sw = new StringWriter(); try { System.out.println("Free mem :" + Runtime.getRuntime().freeMemory()); input = url.openStream(); IOUtils.copy(input, sw, encoding); System.out.println("Free mem :" + Runtime.getRuntime().freeMemory()); } finally { if (input != null) { input.close(); System.gc(); input = null; System.out.println("Free mem :" + Runtime.getRuntime().freeMemory()); } } return sw.toString(); } Code Sample 2: public void testRevcounter() throws ServiceException, IOException { JCRNodeSource emptySource = loadTestSource(); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } System.out.println(emptySource.getLatestSourceRevision()); } String testSourceUri = BASE_URL + "users/lars.trieloff?revision=1.1"; JCRNodeSource secondSource = (JCRNodeSource) resolveSource(testSourceUri); System.out.println("Created at: " + secondSource.getSourceRevision()); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } System.out.println(emptySource.getLatestSourceRevision()); } System.out.println("Read again at:" + secondSource.getSourceRevision()); assertNotNull(emptySource.getSourceRevision()); }
11
Code Sample 1: void copyFile(String from, String to) throws IOException { File destFile = new File(to); if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(from).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public void unzip(String zipFileName, String outputDirectory) throws Exception { ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName)); ZipEntry z; while ((z = in.getNextEntry()) != null) { System.out.println("unziping " + z.getName()); if (z.isDirectory()) { String name = z.getName(); name = name.substring(0, name.length() - 1); File f = new File(outputDirectory + File.separator + name); f.mkdir(); System.out.println("mkdir " + outputDirectory + File.separator + name); } else { File f = new File(outputDirectory + File.separator + z.getName()); f.createNewFile(); FileOutputStream out = new FileOutputStream(f); int b; while ((b = in.read()) != -1) out.write(b); out.close(); } } in.close(); }
11
Code Sample 1: private void copyOneFile(String oldPath, String newPath) { File copiedFile = new File(newPath); try { FileInputStream source = new FileInputStream(oldPath); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.printStackTrace(); } } Code Sample 2: public void runDynusT() { final String[] exeFiles = new String[] { "DynusT.exe", "DLL_ramp.dll", "Ramp_Meter_Fixed_CDLL.dll", "Ramp_Meter_Feedback_CDLL.dll", "Ramp_Meter_Feedback_FDLL.dll", "libifcoremd.dll", "libmmd.dll", "Ramp_Meter_Fixed_FDLL.dll", "libiomp5md.dll" }; final String[] modelFiles = new String[] { "network.dat", "scenario.dat", "control.dat", "ramp.dat", "incident.dat", "movement.dat", "vms.dat", "origin.dat", "destination.dat", "StopCap4Way.dat", "StopCap2Way.dat", "YieldCap.dat", "WorkZone.dat", "GradeLengthPCE.dat", "leftcap.dat", "system.dat", "output_option.dat", "bg_demand_adjust.dat", "xy.dat", "TrafficFlowModel.dat", "parameter.dat" }; log.info("Creating iteration-directory..."); File iterDir = new File(this.tmpDir); if (!iterDir.exists()) { iterDir.mkdir(); } log.info("Copying application files to iteration-directory..."); for (String filename : exeFiles) { log.info(" Copying " + filename); IOUtils.copyFile(new File(this.dynusTDir + "/" + filename), new File(this.tmpDir + "/" + filename)); } log.info("Copying model files to iteration-directory..."); for (String filename : modelFiles) { log.info(" Copying " + filename); IOUtils.copyFile(new File(this.modelDir + "/" + filename), new File(this.tmpDir + "/" + filename)); } String logfileName = this.tmpDir + "/dynus-t.log"; String cmd = this.tmpDir + "/DynusT.exe"; log.info("running command: " + cmd); int timeout = 14400; int exitcode = ExeRunner.run(cmd, logfileName, timeout); if (exitcode != 0) { throw new RuntimeException("There was a problem running Dynus-T. exit code: " + exitcode); } }
00
Code Sample 1: public static String getPasswordHash(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes()); byte[] byteData = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { logger.log(Level.SEVERE, "Unknow error in hashing password", e); return "Unknow error, check system log"; } } Code Sample 2: public void delete(DeleteInterceptorChain chain, DistinguishedName dn, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + "LDAPBaseServer"); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); int id = getId(dn, con); HashMap<String, String> db2ldap = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_DB2LDAP + "LDAPBaseServer"); PreparedStatement ps = con.prepareStatement("DELETE FROM users WHERE id=?"); ps.setInt(1, id); ps.executeUpdate(); ps = con.prepareStatement("DELETE FROM locationmap WHERE person=?"); ps.setInt(1, id); ps.executeUpdate(); ps.close(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } }
00
Code Sample 1: public static Image getPluginImage(final Object plugin, final String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; } Code Sample 2: public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { InputStream urlStream = url.openStream(); AudioFileFormat fileFormat = null; try { fileFormat = getFMT(urlStream, false); } finally { if (fileFormat == null) { urlStream.close(); } } return new AudioInputStream(urlStream, fileFormat.getFormat(), fileFormat.getFrameLength()); }
00
Code Sample 1: public boolean ponerFlotantexRonda(int idJugadorDiv, int idRonda, int dato) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET flotante = " + dato + " WHERE jugadorxDivision_idJugadorxDivision = " + idJugadorDiv + " AND ronda_numeroRonda = " + idRonda; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); } Code Sample 2: public boolean openConnection(String url, Properties props) throws SQLException { try { Class.forName(RunConfig.getInstance().getDriverNameJDBC()); if (url == null) url = RunConfig.getInstance().getConnectionUrlJDBC(); connection = DriverManager.getConnection(url, props); if (statementTable == null) statementTable = new Hashtable<String, PreparedStatement>(); if (resultTable == null) resultTable = new Hashtable<String, ResultSet>(); clearStatus(); return true; } catch (Exception e) { setStatus(e); return false; } }
00
Code Sample 1: @Override protected HttpResponse<HttpURLConnection> execute(HttpRequest<HttpURLConnection> con) throws HttpRequestException { HttpURLConnection unwrap = con.unwrap(); try { unwrap.connect(); } catch (IOException e) { throw new HttpRequestException(e); } return new UrlHttpResponse(unwrap); } Code Sample 2: @Override public void download(String remoteFilePath, String localFilePath) { InputStream remoteStream = null; try { remoteStream = client.get(remoteFilePath); } catch (IOException e) { e.printStackTrace(); } OutputStream localStream = null; try { localStream = new FileOutputStream(new File(localFilePath)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } try { IOUtils.copy(remoteStream, localStream); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: protected String getOldHash(String text) { String hash = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte[] digestedBytes = md.digest(); hash = HexUtils.convert(digestedBytes); } catch (NoSuchAlgorithmException e) { log.log(Level.SEVERE, "Error creating SHA password hash:" + e.getMessage()); hash = text; } catch (UnsupportedEncodingException e) { log.log(Level.SEVERE, "UTF-8 not supported!?!"); } return hash; } Code Sample 2: private void loadNumberFormats() { String fileToLocate = "/" + FILENAME_NUMBER_FMT; URL url = getClass().getClassLoader().getResource(fileToLocate); if (url == null) { return; } List<String> lines; try { lines = IOUtils.readLines(url.openStream()); } catch (IOException e) { throw new ConfigurationException("Problem loading file " + fileToLocate, e); } for (String line : lines) { if (line.startsWith("#") || StringUtils.isBlank(line)) { continue; } String[] parts = StringUtils.split(line, "="); addFormat(parts[0], new DecimalFormat(parts[1])); } }
00
Code Sample 1: public void registerSchema(String newSchemaName, String objectControlller, long boui, String expression, String schema) throws SQLException { Connection cndef = null; PreparedStatement pstm = null; try { cndef = this.getRepositoryConnection(p_ctx.getApplication(), "default", 2); String friendlyName = "Schema created by object [" + objectControlller + "] with boui [" + boui + "]"; pstm = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? and objecttype='S'"); pstm.setString(1, newSchemaName); pstm.executeUpdate(); pstm.close(); pstm = cndef.prepareStatement("INSERT INTO NGTDIC (\"SCHEMA\",OBJECTNAME,OBJECTTYPE,TABLENAME, " + "FRIENDLYNAME, EXPRESSION) VALUES (" + "?,?,?,?,?,?)"); pstm.setString(1, schema); pstm.setString(2, newSchemaName); pstm.setString(3, "S"); pstm.setString(4, newSchemaName); pstm.setString(5, friendlyName); pstm.setString(6, expression); pstm.executeUpdate(); pstm.close(); cndef.commit(); } catch (Exception e) { cndef.rollback(); e.printStackTrace(); throw new SQLException(e.getMessage()); } finally { if (pstm != null) { try { pstm.close(); } catch (Exception e) { } } } } Code Sample 2: public void run() { result.setValid(false); try { final HttpResponse response = client.execute(method, context); result.setValid(ArrayUtils.contains(validCodes, response.getStatusLine().getStatusCode())); result.setResult(response.getStatusLine().getStatusCode()); } catch (final ClientProtocolException e) { LOGGER.error(e); result.setValid(false); } catch (final IOException e) { LOGGER.error(e); result.setValid(false); } }
11
Code Sample 1: public static String hashMD5(String passw) { String passwHash = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(passw.getBytes()); byte[] result = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < result.length; i++) { String tmpStr = "0" + Integer.toHexString((0xff & result[i])); sb.append(tmpStr.substring(tmpStr.length() - 2)); } passwHash = sb.toString(); } catch (NoSuchAlgorithmException ecc) { log.error("Errore algoritmo " + ecc); } return passwHash; } Code Sample 2: public static String hash(String password) { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.update(password.getBytes(charset)); byte[] rawHash = digest.digest(); return new String(Hex.encodeHex(rawHash)); } catch (Exception e) { throw new RuntimeException(e); } }
00
Code Sample 1: public void initResources() throws XAwareException { final String methodName = "initResources"; if (!initialized) { String host = channelObject.getProperty(XAwareConstants.BIZDRIVER_HOST); if (host == null || host.trim().length() == 0) { throw new XAwareException("xa:host must be specified."); } String portString = channelObject.getProperty(XAwareConstants.BIZDRIVER_PORT); if (portString == null || portString.trim().length() == 0) { throw new XAwareException("xa:port must be specified."); } int port = 0; try { port = Integer.parseInt(portString); } catch (Exception exception) { throw new XAwareException("xa:port must be numeric."); } String remoteVerification = channelObject.getProperty(XAwareConstants.XAWARE_FTP_REMOTE_VERIFICATION); String userName = channelObject.getProperty(XAwareConstants.BIZDRIVER_USER); String password = channelObject.getProperty(XAwareConstants.BIZDRIVER_PWD); String proxyUser = channelObject.getProperty(XAwareConstants.BIZCOMPONENT_ATTR_PROXYUSER); String proxyPassword = channelObject.getProperty(XAwareConstants.BIZCOMPONENT_ATTR_PROXYPASSWORD); ftpClient = new FTPClient(); logger.finest("Connecting to host:" + host + " Port:" + port, className, methodName); try { ftpClient.connect(host, port); if (remoteVerification != null && remoteVerification.trim().equals(XAwareConstants.XAWARE_YES)) { ftpClient.setRemoteVerificationEnabled(true); } else { ftpClient.setRemoteVerificationEnabled(false); } final int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); String errorMessage = "FTP server refused connection. Error Code:" + reply; logger.severe(errorMessage, className, methodName); throw new XAwareException(errorMessage); } logger.finest("Logging in User:" + userName + " PWD:" + password, className, methodName); if (!ftpClient.login(userName, password)) { ftpClient.logout(); String errorMessage = "Error logging into server. Please check credentials."; logger.severe(errorMessage, className, methodName); throw new XAwareException(errorMessage); } if (proxyUser != null && proxyUser.trim().length() > 0) { logger.finest("Logging in again proxy UID:" + proxyUser + " proxy password:" + proxyPassword, className, methodName); if (!ftpClient.login(proxyUser, proxyPassword)) { ftpClient.logout(); String errorMessage = "Error logging using proxy user/pwd. Please check proxy credentials."; logger.severe(errorMessage, className, methodName); throw new XAwareException(errorMessage); } } } catch (SocketException e) { String errorMessage = "SocketException: " + ExceptionMessageHelper.getExceptionMessage(e); logger.severe(errorMessage, className, methodName); throw new XAwareException(errorMessage, e); } catch (IOException e) { String errorMessage = "IOException: " + ExceptionMessageHelper.getExceptionMessage(e); logger.severe(errorMessage, className, methodName); throw new XAwareException(errorMessage, e); } logger.finest("Connected to host:" + host + " Port:" + port, className, methodName); initialized = true; } } Code Sample 2: protected void createGraphicalViewer(Composite parent) { final RulerComposite rc = new RulerComposite(parent, SWT.NONE); viewer = new ScrollingGraphicalViewer(); viewer.createControl(rc); editDomain.addViewer(viewer); rc.setGraphicalViewer(viewer); viewer.getControl().setBackground(ColorConstants.white); viewer.setEditPartFactory(new EditPartFactory() { public EditPart createEditPart(EditPart context, Object model) { return new RecorderEditPart(TopLevelModel.getRecorderModel()); } }); viewer.setContents(TopLevelModel.getRecorderModel()); Control control = viewer.getControl(); System.out.println("widget: " + control); DropTarget dt = new DropTarget(control, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_DEFAULT); dt.setTransfer(new Transfer[] { TextTransfer.getInstance() }); dt.addDropListener(new SensorTransferDropTargetListener(viewer)); }
11
Code Sample 1: public File createReadmeFile(File dir, MavenProject mavenProject) throws IOException { InputStream is = getClass().getResourceAsStream("README.template"); StringWriter sw = new StringWriter(); IOUtils.copy(is, sw); String content = sw.getBuffer().toString(); content = StringUtils.replace(content, "{project_name}", mavenProject.getArtifactId()); File readme = new File(dir, "README.TXT"); FileUtils.writeStringToFile(readme, content); return readme; } Code Sample 2: public static File insertFileInto(File zipFile, File toInsert, String targetPath) { Zip64File zip64File = null; try { boolean compress = false; zip64File = new Zip64File(zipFile); FileEntry testEntry = getFileEntry(zip64File, targetPath); if (testEntry != null && testEntry.getMethod() == FileEntry.iMETHOD_DEFLATED) { compress = true; } processAndCreateFolderEntries(zip64File, parseTargetPath(targetPath, toInsert), compress); if (testEntry != null) { log.info("[insertFileInto] Entry exists: " + testEntry.getName()); log.info("[insertFileInto] Will delete this entry before inserting: " + toInsert.getName()); if (!testEntry.isDirectory()) { zip64File.delete(testEntry.getName()); } else { log.info("[insertFileInto] Entry is a directory. " + "Will delete all files contained in this entry and insert " + toInsert.getName() + "and all nested files."); if (!targetPath.contains("/")) { targetPath = targetPath + "/"; } deleteFileEntry(zip64File, testEntry); log.info("[insertFileInto] Entry successfully deleted."); } log.info("[insertFileInto] Writing new Entry: " + targetPath); EntryOutputStream out = null; if (!compress) { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_STORED, new Date(toInsert.lastModified())); } else { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_DEFLATED, new Date(toInsert.lastModified())); } if (toInsert.isDirectory()) { out.flush(); out.close(); log.info("[insertFileInto] Finished writing entry: " + targetPath); List<String> containedPaths = normalizePaths(toInsert); List<File> containedFiles = listAllFilesAndFolders(toInsert, new ArrayList<File>()); log.info("[insertFileInto] Added entry is a folder."); log.info("[insertFileInto] Adding all nested files: "); for (int i = 0; i < containedPaths.size(); i++) { File currentFile = containedFiles.get(i); String currentPath = targetPath.replace("/", "") + File.separator + containedPaths.get(i); EntryOutputStream loop_out = null; if (!compress) { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_STORED, new Date(currentFile.lastModified())); } else { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_DEFLATED, new Date(currentFile.lastModified())); } if (currentFile.isFile()) { InputStream loop_in = new FileInputStream(currentFile); IOUtils.copyLarge(loop_in, loop_out); loop_in.close(); } log.info("[insertFileInto] Added: " + currentPath); loop_out.flush(); loop_out.close(); } } else { InputStream in = new FileInputStream(toInsert); IOUtils.copyLarge(in, out); in.close(); out.flush(); out.close(); } } else { EntryOutputStream out = null; if (!compress) { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_STORED, new Date(toInsert.lastModified())); } else { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_DEFLATED, new Date(toInsert.lastModified())); } if (toInsert.isDirectory()) { out.flush(); out.close(); log.info("[insertFileInto] Finished writing entry: " + targetPath); List<String> containedPaths = normalizePaths(toInsert); List<File> containedFiles = listAllFilesAndFolders(toInsert, new ArrayList<File>()); log.info("[insertFileInto] Added entry is a folder."); log.info("[insertFileInto] Adding all nested files: "); for (int i = 0; i < containedPaths.size(); i++) { File currentFile = containedFiles.get(i); String currentPath = targetPath.replace("/", "") + File.separator + containedPaths.get(i); EntryOutputStream loop_out = null; if (!compress) { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_STORED, new Date(currentFile.lastModified())); } else { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_DEFLATED, new Date(currentFile.lastModified())); } if (currentFile.isFile()) { InputStream loop_in = new FileInputStream(currentFile); IOUtils.copyLarge(loop_in, loop_out); loop_in.close(); } log.info("[insertFileInto] Added: " + currentPath); loop_out.flush(); loop_out.close(); } } else { InputStream in = new FileInputStream(toInsert); IOUtils.copyLarge(in, out); in.close(); out.flush(); out.close(); } } log.info("[insertFileInto] Done! Added " + toInsert.getName() + " to zip."); zip64File.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return new File(zip64File.getDiskFile().getFileName()); }
11
Code Sample 1: private String getStoreName() { try { final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(protectionDomain.getBytes()); final byte[] bs = digest.digest(); final StringBuffer sb = new StringBuffer(bs.length * 2); for (int i = 0; i < bs.length; i++) { final String s = Integer.toHexString(bs[i] & 0xff); if (s.length() < 2) sb.append('0'); sb.append(s); } return sb.toString(); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Can't save credentials: digest method MD5 unavailable."); } } Code Sample 2: public synchronized String encrypt(String p_plainText) throws ServiceUnavailableException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new ServiceUnavailableException(e.getMessage()); } try { md.update(p_plainText.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new ServiceUnavailableException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
11
Code Sample 1: private void readFromFile1() throws DException { URL url1 = null; if (url == null) { url = getClass().getResource("/com/daffodilwoods/daffodildb/utils/parser/parser.schema"); try { url = new URL(url.getProtocol() + ":" + url.getPath().substring(0, url.getPath().indexOf("/parser.schema"))); } catch (MalformedURLException ex2) { ex2.printStackTrace(); throw new DException("DSE0", new Object[] { ex2 }); } try { url1 = new URL(url.getProtocol() + ":" + url.getPath() + "/parser.schema"); } catch (MalformedURLException ex) { throw new DException("DSE0", new Object[] { ex }); } if (url1 == null) { throw new DException("DSE0", new Object[] { "Parser.schema file is missing in classpath." }); } } else { try { url1 = new URL(url.getProtocol() + ":" + url.getPath() + "/parser.schema"); } catch (MalformedURLException ex) { throw new DException("DSE0", new Object[] { ex }); } } ArrayList arr1 = null; StringBuffer rule = null; try { LineNumberReader raf = new LineNumberReader(new BufferedReader(new InputStreamReader(url1.openStream()))); arr1 = new ArrayList(); rule = new StringBuffer(""); while (true) { String str1 = raf.readLine(); if (str1 == null) { break; } String str = str1.trim(); if (str.length() == 0) { if (rule.length() > 0) { arr1.add(rule.toString()); } rule = new StringBuffer(""); } else { rule.append(" ").append(str); } } raf.close(); } catch (IOException ex1) { ex1.printStackTrace(); throw new DException("DSE0", new Object[] { ex1 }); } if (rule.length() > 0) arr1.add(rule.toString()); for (int i = 0; i < arr1.size(); i++) { String str = (String) arr1.get(i); int index = str.indexOf("::="); if (index == -1) { P.pln("Error " + str); throw new DException("DSE0", new Object[] { "Rule is missing from parser.schema" }); } String key = str.substring(0, index).trim(); String value = str.substring(index + 3).trim(); Object o = fileEntries.put(key, value); if (o != null) { new Exception("Duplicate Defination for Rule [" + key + "] Value [" + value + "] Is Replaced By [" + o + "]").printStackTrace(); } } } Code Sample 2: public int doEndTag() throws JspException { HttpSession session = pageContext.getSession(); try { IntactUserI user = (IntactUserI) session.getAttribute(Constants.USER_KEY); String urlStr = user.getSourceURL(); if (urlStr == null) { return EVAL_PAGE; } URL url = null; try { url = new URL(urlStr); } catch (MalformedURLException me) { String decodedUrl = URLDecoder.decode(urlStr, "UTF-8"); pageContext.getOut().write("The source is malformed : <a href=\"" + decodedUrl + "\" target=\"_blank\">" + decodedUrl + "</a>"); return EVAL_PAGE; } StringBuffer httpContent = new StringBuffer(); httpContent.append("<!-- URL : " + urlStr + "-->"); String tmpLine; try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((tmpLine = reader.readLine()) != null) { httpContent.append(tmpLine); } reader.close(); } catch (IOException ioe) { user.resetSourceURL(); String decodedUrl = URLDecoder.decode(urlStr, "UTF-8"); pageContext.getOut().write("Unable to display the source at : <a href=\"" + decodedUrl + "\" target=\"_blank\">" + decodedUrl + "</a>"); return EVAL_PAGE; } pageContext.getOut().write(httpContent.toString()); } catch (Exception e) { e.printStackTrace(); throw new JspException("Error when trying to get HTTP content"); } return EVAL_PAGE; }
11
Code Sample 1: private void addAuditDatastream() throws ObjectIntegrityException, StreamIOException { if (m_obj.getAuditRecords().size() == 0) { return; } String dsId = m_pid.toURI() + "/AUDIT"; String dsvId = dsId + "/" + DateUtility.convertDateToString(m_obj.getCreateDate()); Entry dsEntry = m_feed.addEntry(); dsEntry.setId(dsId); dsEntry.setTitle("AUDIT"); dsEntry.setUpdated(m_obj.getCreateDate()); dsEntry.addCategory(MODEL.STATE.uri, "A", null); dsEntry.addCategory(MODEL.CONTROL_GROUP.uri, "X", null); dsEntry.addCategory(MODEL.VERSIONABLE.uri, "false", null); dsEntry.addLink(dsvId, Link.REL_ALTERNATE); Entry dsvEntry = m_feed.addEntry(); dsvEntry.setId(dsvId); dsvEntry.setTitle("AUDIT.0"); dsvEntry.setUpdated(m_obj.getCreateDate()); ThreadHelper.addInReplyTo(dsvEntry, m_pid.toURI() + "/AUDIT"); dsvEntry.addCategory(MODEL.FORMAT_URI.uri, AUDIT1_0.uri, null); dsvEntry.addCategory(MODEL.LABEL.uri, "Audit Trail for this object", null); if (m_format.equals(ATOM_ZIP1_1)) { String name = "AUDIT.0.xml"; try { m_zout.putNextEntry(new ZipEntry(name)); Reader r = new StringReader(DOTranslationUtility.getAuditTrail(m_obj)); IOUtils.copy(r, m_zout, m_encoding); m_zout.closeEntry(); r.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); dsvEntry.setSummary("AUDIT.0"); dsvEntry.setContent(iri, "text/xml"); } else { dsvEntry.setContent(DOTranslationUtility.getAuditTrail(m_obj), "text/xml"); } } Code Sample 2: public static void copyFile4(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copy(in, out); in.close(); out.close(); }
11
Code Sample 1: private void copyFile(File src_file, File dest_file) { InputStream src_stream = null; OutputStream dest_stream = null; try { int b; src_stream = new BufferedInputStream(new FileInputStream(src_file)); dest_stream = new BufferedOutputStream(new FileOutputStream(dest_file)); while ((b = src_stream.read()) != -1) dest_stream.write(b); } catch (Exception e) { XRepository.getLogger().warning(this, "Error on copying the plugin file!"); XRepository.getLogger().warning(this, e); } finally { try { src_stream.close(); dest_stream.close(); } catch (Exception ex2) { } } } Code Sample 2: public static void copyFile(String fromPath, String toPath) { try { File inputFile = new File(fromPath); String dirImg = (new File(toPath)).getParent(); File tmp = new File(dirImg); if (!tmp.exists()) { tmp.mkdir(); } File outputFile = new File(toPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); } }
00
Code Sample 1: public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void doGet(HttpServletRequest request_, HttpServletResponse response) throws IOException, ServletException { Writer out = null; DatabaseAdapter dbDyn = null; PreparedStatement st = null; try { RenderRequest renderRequest = null; RenderResponse renderResponse = null; ContentTypeTools.setContentType(response, ContentTypeTools.CONTENT_TYPE_UTF8); out = response.getWriter(); AuthSession auth_ = (AuthSession) renderRequest.getUserPrincipal(); if (auth_ == null) { throw new IllegalStateException("You have not enough right to execute this operation"); } PortletSession session = renderRequest.getPortletSession(); dbDyn = DatabaseAdapter.getInstance(); String index_page = PortletService.url("mill.price.index", renderRequest, renderResponse); Long id_shop = null; if (renderRequest.getParameter(ShopPortlet.NAME_ID_SHOP_PARAM) != null) { id_shop = PortletService.getLong(renderRequest, ShopPortlet.NAME_ID_SHOP_PARAM); } else { Long id_ = (Long) session.getAttribute(ShopPortlet.ID_SHOP_SESSION); if (id_ == null) { response.sendRedirect(index_page); return; } id_shop = id_; } session.removeAttribute(ShopPortlet.ID_SHOP_SESSION); session.setAttribute(ShopPortlet.ID_SHOP_SESSION, id_shop); if (auth_.isUserInRole("webmill.edit_price_list")) { Long id_item = PortletService.getLong(renderRequest, "id_item"); if (id_item == null) throw new IllegalArgumentException("id_item not initialized"); if (RequestTools.getString(renderRequest, "action").equals("update")) { dbDyn.getConnection().setAutoCommit(false); String sql_ = "delete from WM_PRICE_ITEM_DESCRIPTION a " + "where exists " + " ( select null from WM_PRICE_LIST b " + " where b.id_shop = ? and b.id_item = ? and " + " a.id_item=b.id_item ) "; try { st = dbDyn.prepareStatement(sql_); RsetTools.setLong(st, 1, id_shop); RsetTools.setLong(st, 2, id_item); st.executeUpdate(); } catch (Exception e0001) { dbDyn.rollback(); out.write("Error #1 - " + ExceptionTools.getStackTrace(e0001, 20, "<br>")); return; } finally { DatabaseManager.close(st); st = null; } sql_ = "insert into WM_PRICE_ITEM_DESCRIPTION " + "(ID_PRICE_ITEM_DESCRIPTION, ID_ITEM, TEXT)" + "(select seq_WM_PRICE_ITEM_DESCRIPTION.nextval, ID_ITEM, ? " + " from WM_PRICE_LIST b where b.ID_SHOP = ? and b.ID_ITEM = ? )"; try { int idx = 0; int offset = 0; int j = 0; byte[] b = StringTools.getBytesUTF(RequestTools.getString(renderRequest, "n")); st = dbDyn.prepareStatement(sql_); while ((idx = StringTools.getStartUTF(b, 2000, offset)) != -1) { st.setString(1, new String(b, offset, idx - offset, "utf-8")); RsetTools.setLong(st, 2, id_shop); RsetTools.setLong(st, 3, id_item); st.addBatch(); offset = idx; if (j > 10) break; j++; } int[] updateCounts = st.executeBatch(); if (log.isDebugEnabled()) log.debug("Number of updated records - " + updateCounts); dbDyn.commit(); } catch (Exception e0) { dbDyn.rollback(); out.write("Error #2 - " + ExceptionTools.getStackTrace(e0, 20, "<br>")); return; } finally { dbDyn.getConnection().setAutoCommit(true); if (st != null) { DatabaseManager.close(st); st = null; } } } if (RequestTools.getString(renderRequest, "action").equals("new_image") && renderRequest.getParameter("id_image") != null) { Long id_image = PortletService.getLong(renderRequest, "id_image"); dbDyn.getConnection().setAutoCommit(false); String sql_ = "delete from WM_IMAGE_PRICE_ITEMS a " + "where exists " + " ( select null from WM_PRICE_LIST b " + "where b.id_shop = ? and b.id_item = ? and " + "a.id_item=b.id_item ) "; try { st = dbDyn.prepareStatement(sql_); RsetTools.setLong(st, 1, id_shop); RsetTools.setLong(st, 2, id_item); st.executeUpdate(); } catch (Exception e0001) { dbDyn.rollback(); out.write("Error #3 - " + ExceptionTools.getStackTrace(e0001, 20, "<br>")); return; } finally { DatabaseManager.close(st); st = null; } sql_ = "insert into WM_IMAGE_PRICE_ITEMS " + "(id_IMAGE_PRICE_ITEMS, id_item, ID_IMAGE_DIR)" + "(select seq_WM_IMAGE_PRICE_ITEMS.nextval, id_item, ? " + " from WM_PRICE_LIST b where b.id_shop = ? and b.id_item = ? )"; try { st = dbDyn.prepareStatement(sql_); RsetTools.setLong(st, 1, id_image); RsetTools.setLong(st, 2, id_shop); RsetTools.setLong(st, 3, id_item); int updateCounts = st.executeUpdate(); if (log.isDebugEnabled()) log.debug("Number of updated records - " + updateCounts); dbDyn.commit(); } catch (Exception e0) { dbDyn.rollback(); log.error("Error insert image", e0); out.write("Error #4 - " + ExceptionTools.getStackTrace(e0, 20, "<br>")); return; } finally { dbDyn.getConnection().setAutoCommit(true); DatabaseManager.close(st); st = null; } } if (true) throw new Exception("Need refactoring"); } } catch (Exception e) { log.error(e); out.write(ExceptionTools.getStackTrace(e, 20, "<br>")); } finally { DatabaseManager.close(dbDyn, st); st = null; dbDyn = null; } }
11
Code Sample 1: public static String scramble(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (byte b : md.digest()) sb.append(Integer.toString(b & 0xFF, 16)); return sb.toString(); } catch (UnsupportedEncodingException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } } Code Sample 2: public void setContentMD5() { MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); contentMD5 = null; } messagedigest.update(content.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } contentMD5 = chk; }
11
Code Sample 1: public void testAddFiles() throws Exception { File original = ZipPlugin.getFileInPlugin(new Path("testresources/test.zip")); File copy = new File(original.getParentFile(), "1test.zip"); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(original); out = new FileOutputStream(copy); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } ArchiveFile archive = new ArchiveFile(ZipPlugin.createArchive(copy.getPath())); archive.addFiles(new String[] { ZipPlugin.getFileInPlugin(new Path("testresources/add.txt")).getPath() }, new NullProgressMonitor()); IArchive[] children = archive.getChildren(); boolean found = false; for (IArchive child : children) { if (child.getLabel(IArchive.NAME).equals("add.txt")) found = true; } assertTrue(found); copy.delete(); } Code Sample 2: public void run(IProgressMonitor runnerMonitor) throws CoreException { try { Map<String, File> projectFiles = new HashMap<String, File>(); IPath basePath = new Path("/"); for (File nextLocation : filesToZip) { projectFiles.putAll(getFilesToZip(nextLocation, basePath, fileFilter)); } if (projectFiles.isEmpty()) { PlatformActivator.logDebug("Zip file (" + zipFileName + ") not created because there were no files to zip"); return; } IPath resultsPath = PlatformActivator.getDefault().getResultsPath(); File copyRoot = resultsPath.toFile(); copyRoot.mkdirs(); IPath zipFilePath = resultsPath.append(new Path(finalZip)); String zipFileName = zipFilePath.toPortableString(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); try { out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String filePath : projectFiles.keySet()) { File nextFile = projectFiles.get(filePath); FileInputStream fin = new FileInputStream(nextFile); try { out.putNextEntry(new ZipEntry(filePath)); try { byte[] bin = new byte[4096]; int bread = fin.read(bin, 0, 4096); while (bread != -1) { out.write(bin, 0, bread); bread = fin.read(bin, 0, 4096); } } finally { out.closeEntry(); } } finally { fin.close(); } } } finally { out.close(); } } catch (FileNotFoundException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } catch (IOException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } }
11
Code Sample 1: public void run() { String s; s = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + word); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while (((str = in.readLine()) != null) && (!stopped)) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("Main Entry:.+?<br>(.+?)</td>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); java.io.StringWriter wr = new java.io.StringWriter(); HTMLDocument doc = null; HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit(); try { doc = (HTMLDocument) editor.getDocument(); } catch (Exception e) { } System.out.println(wr); editor.setContentType("text/html"); if (matcher.find()) try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR>" + matcher.group(1) + "<HR>", 0, 0, null); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } else try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR><FONT COLOR='RED'>NOT FOUND!!</FONT><HR>", 0, 0, null); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } button.setEnabled(true); } Code Sample 2: public static String read(URL url) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringWriter res = new StringWriter(); PrintWriter writer = new PrintWriter(new BufferedWriter(res)); String line; while ((line = reader.readLine()) != null) { writer.println(line); } reader.close(); writer.close(); return res.toString(); }
11
Code Sample 1: public void format(File source, File target) { if (!source.exists()) { throw new IllegalArgumentException("Source '" + source + " doesn't exist"); } if (!source.isFile()) { throw new IllegalArgumentException("Source '" + source + " is not a file"); } target.mkdirs(); String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1); String _target = source.getName().replace(fileExtension, "html"); target = new File(target.getPath() + "/" + _target); try { Reader reader = new FileReader(source); Writer writer = new FileWriter(target); this.format(reader, writer); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void createZipCopy(IUIContext ui, final String zipFileName, final File[] filesToZip, final FilenameFilter fileFilter, Timestamp timestamp) { TestCase.assertNotNull(ui); TestCase.assertNotNull(zipFileName); TestCase.assertFalse(zipFileName.trim().length() == 0); TestCase.assertNotNull(filesToZip); TestCase.assertNotNull(timestamp); String nameCopy = zipFileName; if (nameCopy.endsWith(".zip")) { nameCopy = nameCopy.substring(0, zipFileName.length() - 4); } nameCopy = nameCopy + "_" + timestamp.toString() + ".zip"; final String finalZip = nameCopy; IWorkspaceRunnable noResourceChangedEventsRunner = new IWorkspaceRunnable() { public void run(IProgressMonitor runnerMonitor) throws CoreException { try { Map<String, File> projectFiles = new HashMap<String, File>(); IPath basePath = new Path("/"); for (File nextLocation : filesToZip) { projectFiles.putAll(getFilesToZip(nextLocation, basePath, fileFilter)); } if (projectFiles.isEmpty()) { PlatformActivator.logDebug("Zip file (" + zipFileName + ") not created because there were no files to zip"); return; } IPath resultsPath = PlatformActivator.getDefault().getResultsPath(); File copyRoot = resultsPath.toFile(); copyRoot.mkdirs(); IPath zipFilePath = resultsPath.append(new Path(finalZip)); String zipFileName = zipFilePath.toPortableString(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); try { out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String filePath : projectFiles.keySet()) { File nextFile = projectFiles.get(filePath); FileInputStream fin = new FileInputStream(nextFile); try { out.putNextEntry(new ZipEntry(filePath)); try { byte[] bin = new byte[4096]; int bread = fin.read(bin, 0, 4096); while (bread != -1) { out.write(bin, 0, bread); bread = fin.read(bin, 0, 4096); } } finally { out.closeEntry(); } } finally { fin.close(); } } } finally { out.close(); } } catch (FileNotFoundException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } catch (IOException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } } }; try { IWorkspace workspace = ResourcesPlugin.getWorkspace(); workspace.run(noResourceChangedEventsRunner, workspace.getRoot(), IWorkspace.AVOID_UPDATE, new NullProgressMonitor()); } catch (CoreException ce) { PlatformActivator.logException(ce); } }
11
Code Sample 1: public String getScenarioData(String urlForSalesData) throws IOException, Exception { InputStream inputStream = null; BufferedReader bufferedReader = null; DataInputStream input = null; StringBuffer sBuf = new StringBuffer(); Proxy proxy; if (httpWebProxyServer != null && Integer.toString(httpWebProxyPort) != null) { SocketAddress address = new InetSocketAddress(httpWebProxyServer, httpWebProxyPort); proxy = new Proxy(Proxy.Type.HTTP, address); } else { proxy = null; } proxy = null; URL url; try { url = new URL(urlForSalesData); HttpURLConnection httpUrlConnection; if (proxy != null) httpUrlConnection = (HttpURLConnection) url.openConnection(proxy); else httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setDoInput(true); httpUrlConnection.setRequestMethod("GET"); String name = rb.getString("WRAP_NAME"); String password = rb.getString("WRAP_PASSWORD"); Credentials simpleAuthCrentials = new Credentials(TOKEN_TYPE.SimpleApiAuthToken, name, password); ACSTokenProvider tokenProvider = new ACSTokenProvider(httpWebProxyServer, httpWebProxyPort, simpleAuthCrentials); String requestUriStr1 = "https://" + solutionName + "." + acmHostName + "/" + serviceName; String appliesTo1 = rb.getString("SIMPLEAPI_APPLIES_TO"); String token = tokenProvider.getACSToken(requestUriStr1, appliesTo1); httpUrlConnection.addRequestProperty("token", "WRAPv0.9 " + token); httpUrlConnection.addRequestProperty("solutionName", solutionName); httpUrlConnection.connect(); if (httpUrlConnection.getResponseCode() == HttpServletResponse.SC_UNAUTHORIZED) { List<TestSalesOrderService> salesOrderServiceBean = new ArrayList<TestSalesOrderService>(); TestSalesOrderService response = new TestSalesOrderService(); response.setResponseCode(HttpServletResponse.SC_UNAUTHORIZED); response.setResponseMessage(httpUrlConnection.getResponseMessage()); salesOrderServiceBean.add(response); } inputStream = httpUrlConnection.getInputStream(); input = new DataInputStream(inputStream); bufferedReader = new BufferedReader(new InputStreamReader(input)); String str; while (null != ((str = bufferedReader.readLine()))) { sBuf.append(str); } String responseString = sBuf.toString(); return responseString; } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } } Code Sample 2: public DatabaseDefinitionFactory(final DBIf db, final String adapter) throws IOException { _db = db; LOG.debug("Loading adapter: " + adapter); final URL url = getClass().getClassLoader().getResource("adapter/" + adapter + ".properties"); _props = new Properties(); _props.load(url.openStream()); if (adapter.equals("mysql")) { _modifier = new MySQLModifier(this); } else if (adapter.equals("postgresql")) { _modifier = new PostgresModifier(this); } else if (adapter.equals("hypersonic")) { _modifier = new HSQLModifier(this); } else if (adapter.equals("oracle")) { _modifier = new OracleModifier(this); } else if (adapter.equals("mssql")) { _modifier = new MSSQLModifier(this); } else { _modifier = null; } }
00
Code Sample 1: public void saveDraft(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint, String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml, String charset, InternetHeaders headers, String priority) throws MailException { try { if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } if ((body == null) || body.trim().equals("")) { body = " "; } Email email = null; if (isHtml) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(charset); Users user = getUser(hsession, repositoryName); Identity identity = getIdentity(hsession, ideIdint, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null); InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null); InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if ((_to != null) && (_to.length > 0)) { HashSet aux = new HashSet(_to.length); Collections.addAll(aux, _to); email.setTo(aux); } if ((_cc != null) && (_cc.length > 0)) { HashSet aux = new HashSet(_cc.length); Collections.addAll(aux, _cc); email.setCc(aux); } if ((_bcc != null) && (_bcc.length > 0)) { HashSet aux = new HashSet(_bcc.length); Collections.addAll(aux, _bcc); email.setBcc(aux); } email.setSubject(subject); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } if ((attachments != null) && (attachments.size() > 0)) { for (int i = 0; i < attachments.size(); i++) { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { MailPartObj obj = (MailPartObj) attachments.get(i); File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); if (email instanceof MultiPartEmail) { ((MultiPartEmail) email).attach(attachment); } } catch (Exception ex) { } finally { IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } } } if (headers != null) { Header xheader; Enumeration xe = headers.getAllHeaders(); for (; xe.hasMoreElements(); ) { xheader = (Header) xe.nextElement(); if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) { email.addHeader(xheader.getName(), xheader.getValue()); } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) { email.addHeader(xheader.getName(), xheader.getValue()); } } } if (priority != null) { if (priority.equals("high")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "1"); } else if (priority.equals("low")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "5"); } } if (email instanceof HtmlEmail) { ((HtmlEmail) email).setHtmlMsg(body); } else { email.setMsg(body); } email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeDraftMessage(getId(), mime, user); } catch (MailException e) { throw e; } catch (Exception e) { throw new MailException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new MailException(ex); } catch (Throwable e) { throw new MailException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } } Code Sample 2: private static String executeQueryWithSaxon(String queryFile) throws XPathException, FileNotFoundException, IOException, URISyntaxException { URL url = DocumentTableTest.class.getResource(queryFile); URI uri = url.toURI(); String query = IOUtils.toString(url.openStream()); Configuration config = new Configuration(); config.setHostLanguage(Configuration.XQUERY); StaticQueryContext staticContext = new StaticQueryContext(config); staticContext.setBaseURI(uri.toString()); XQueryExpression exp = staticContext.compileQuery(query); Properties props = new Properties(); props.setProperty(SaxonOutputKeys.WRAP, "no"); props.setProperty(OutputKeys.INDENT, "no"); props.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter res_sw = new StringWriter(); DynamicQueryContext dynamicContext = new DynamicQueryContext(config); exp.run(dynamicContext, new StreamResult(res_sw), props); return res_sw.toString(); }
00
Code Sample 1: public static String sendGetRequest(String urlStr) { String result = null; try { URL url = new URL(urlStr); System.out.println(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line = ""; System.out.println("aa" + line); while ((line = rd.readLine()) != null) { System.out.println("aa" + line); sb.append(line); } rd.close(); result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } return result; } Code Sample 2: public static boolean verify(String password, String encryptedPassword) { MessageDigest digest = null; int size = 0; String base64 = null; if (encryptedPassword.regionMatches(true, 0, "{CRYPT}", 0, 7)) { throw new InternalError("Not implemented"); } else if (encryptedPassword.regionMatches(true, 0, "{SHA}", 0, 5)) { size = 20; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SSHA}", 0, 6)) { size = 20; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{MD5}", 0, 5)) { size = 16; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SMD5}", 0, 6)) { size = 16; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else { return false; } byte[] data = Base64.decode(base64.toCharArray()); byte[] orig = new byte[size]; System.arraycopy(data, 0, orig, 0, size); digest.reset(); digest.update(password.getBytes()); if (data.length > size) { digest.update(data, size, data.length - size); } return MessageDigest.isEqual(digest.digest(), orig); }
00
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("image/png"); OutputStream outStream; outStream = resp.getOutputStream(); InputStream is; String name = req.getParameter("name"); if (name == null) { is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png"); } else { ImageRecord imageRecord = imageBean.getFile(name); if (imageRecord != null) { is = new BufferedInputStream(new FileInputStream(imageRecord.getThumbnailFile())); } else { is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png"); } } IOUtils.copy(is, outStream); outStream.close(); outStream.flush(); } Code Sample 2: @Override public String compute_hash(String plaintext) { MessageDigest d; try { d = MessageDigest.getInstance(get_algorithm_name()); d.update(plaintext.getBytes()); byte[] hash = d.digest(); StringBuffer sb = new StringBuffer(); for (byte b : hash) sb.append(String.format("%02x", b)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
11
Code Sample 1: private static void recurseFiles(File root, File file, TarArchiveOutputStream taos, boolean absolute) throws IOException { if (file.isDirectory()) { File[] files = file.listFiles(); for (File file2 : files) { recurseFiles(root, file2, taos, absolute); } } else if ((!file.getName().endsWith(".tar")) && (!file.getName().endsWith(".TAR"))) { String filename = null; if (absolute) { filename = file.getAbsolutePath().substring(root.getAbsolutePath().length()); } else { filename = file.getName(); } TarArchiveEntry tae = new TarArchiveEntry(filename); tae.setSize(file.length()); taos.putArchiveEntry(tae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, taos); taos.closeArchiveEntry(); } } 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: protected HttpResponse executeRequest(AbstractHttpRequest request) throws ConnectionException, RequestCancelledException { try { HttpResponse response = getHttpClient().execute(request); if (!response.is2xxSuccess()) { throw new ConnectionException(); } return response; } catch (IOException ex) { throw new ConnectionException(); } catch (TimeoutException ex) { throw new ConnectionException(); } } Code Sample 2: public String uploadVideo(String ticketId, String filePath) { TreeMap<String, String> uploadParams = new TreeMap<String, String>(); String url = "http://www.vimeo.com/services/upload/"; uploadParams.put("api_key", apiKey); uploadParams.put("auth_token", this.TEMP_AUTH_TOKEN); uploadParams.put("ticket_id", ticketId); uploadParams.put("format", "json"); String signature = this.generateAppSignature(uploadParams); uploadParams.put("api_sig", signature); ClientHttpRequest request = null; try { request = new ClientHttpRequest(new URL(url).openConnection()); } catch (IOException e) { e.printStackTrace(); } for (Entry<String, String> param : uploadParams.entrySet()) { try { request.setParameter(param.getKey(), param.getValue()); } catch (IOException e) { e.printStackTrace(); } } InputStream videoInput = null; try { videoInput = new FileInputStream(filePath); } catch (FileNotFoundException e) { e.printStackTrace(); } try { request.setParameter("video", filePath, videoInput); } catch (IOException e) { e.printStackTrace(); } InputStream response = null; try { response = request.post(); } catch (IOException e) { e.printStackTrace(); } try { InputStreamReader inR = new InputStreamReader(response); BufferedReader buf = new BufferedReader(inR); String line; try { while ((line = buf.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return "hey"; }
11
Code Sample 1: public static void readFile(FOUserAgent ua, String uri, Writer output, String encoding) throws IOException { InputStream in = getURLInputStream(ua, uri); try { StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, encoding); } finally { IOUtils.closeQuietly(in); } } Code Sample 2: File exportCommunityData(Community community) throws CommunityNotActiveException, FileNotFoundException, IOException, CommunityNotFoundException { try { String communityId = community.getId(); if (!community.isActive()) { log.error("The community with id " + communityId + " is inactive"); throw new CommunityNotActiveException("The community with id " + communityId + " is inactive"); } new File(CommunityManagerImpl.EXPORTED_COMMUNITIES_PATH).mkdirs(); String communityName = community.getName(); String communityType = community.getType(); String communityTitle = I18NUtils.localize(community.getTitle()); File zipOutFilename; if (community.isPersonalCommunity()) { zipOutFilename = new File(CommunityManagerImpl.EXPORTED_COMMUNITIES_PATH + communityName + ".zip"); } else { zipOutFilename = new File(CommunityManagerImpl.EXPORTED_COMMUNITIES_PATH + MANUAL_EXPORTED_COMMUNITY_PREFIX + communityTitle + ".zip"); } ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipOutFilename)); File file = File.createTempFile("exported-community", null); TemporaryFilesHandler.register(null, file); FileOutputStream fos = new FileOutputStream(file); String contentPath = JCRUtil.getNodeById(communityId).getPath(); JCRUtil.currentSession().exportSystemView(contentPath, fos, false, false); fos.close(); File propertiesFile = File.createTempFile("exported-community-properties", null); TemporaryFilesHandler.register(null, propertiesFile); FileOutputStream fosProperties = new FileOutputStream(propertiesFile); fosProperties.write(("communityId=" + communityId).getBytes()); fosProperties.write(";".getBytes()); fosProperties.write(("externalId=" + community.getExternalId()).getBytes()); fosProperties.write(";".getBytes()); fosProperties.write(("title=" + communityTitle).getBytes()); fosProperties.write(";".getBytes()); fosProperties.write(("communityType=" + communityType).getBytes()); fosProperties.write(";".getBytes()); fosProperties.write(("communityName=" + communityName).getBytes()); fosProperties.close(); FileInputStream finProperties = new FileInputStream(propertiesFile); byte[] bufferProperties = new byte[4096]; out.putNextEntry(new ZipEntry("properties")); int readProperties = 0; while ((readProperties = finProperties.read(bufferProperties)) > 0) { out.write(bufferProperties, 0, readProperties); } finProperties.close(); FileInputStream fin = new FileInputStream(file); byte[] buffer = new byte[4096]; out.putNextEntry(new ZipEntry("xmlData")); int read = 0; while ((read = fin.read(buffer)) > 0) { out.write(buffer, 0, read); } fin.close(); out.close(); community.setActive(Boolean.FALSE); communityPersister.saveCommunity(community); Collection<Community> duplicatedPersonalCommunities = communityPersister.searchCommunitiesByName(communityName); if (CommunityManager.PERSONAL_COMMUNITY_TYPE.equals(communityType)) { for (Community currentCommunity : duplicatedPersonalCommunities) { if (currentCommunity.isActive()) { currentCommunity.setActive(Boolean.FALSE); communityPersister.saveCommunity(currentCommunity); } } } return zipOutFilename; } catch (RepositoryException e) { log.error("Error getting community with id " + community.getId()); throw new GroupwareRuntimeException("Error getting community with id " + community.getId(), e.getCause()); } }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public static int[] sortDescending(int input[]) { int[] order = new int[input.length]; for (int i = 0; i < order.length; i++) order[i] = i; for (int i = input.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (input[j] < input[j + 1]) { int mem = input[j]; input[j] = input[j + 1]; input[j + 1] = mem; int id = order[j]; order[j] = order[j + 1]; order[j + 1] = id; } } } return order; }
00
Code Sample 1: public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GUnzip source"); return; } String zipname, source; if (args[0].endsWith(".gz")) { zipname = args[0]; source = args[0].substring(0, args[0].length() - 3); } else { zipname = args[0] + ".gz"; source = args[0]; } GZIPInputStream zipin; try { FileInputStream in = new FileInputStream(zipname); zipin = new GZIPInputStream(in); } catch (IOException e) { System.out.println("Couldn't open " + zipname + "."); return; } byte[] buffer = new byte[sChunk]; try { FileOutputStream out = new FileOutputStream(source); int length; while ((length = zipin.read(buffer, 0, sChunk)) != -1) out.write(buffer, 0, length); out.close(); } catch (IOException e) { System.out.println("Couldn't decompress " + args[0] + "."); } try { zipin.close(); } catch (IOException e) { } } Code Sample 2: public String decrypt(String text, String passphrase, int keylen) { RC2ParameterSpec parm = new RC2ParameterSpec(keylen); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes(getCharset())); SecretKeySpec skeySpec = new SecretKeySpec(md.digest(), "RC2"); Cipher cipher = Cipher.getInstance("RC2/ECB/NOPADDING"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, parm); byte[] dString = Base64.decode(text); byte[] d = cipher.doFinal(dString); String clearTextNew = decodeBytesNew(d); return clearTextNew; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
11
Code Sample 1: public static java.io.ByteArrayOutputStream getFileByteStream(URL _url) { java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream(); try { InputStream input = _url.openStream(); IOUtils.copy(input, buffer); IOUtils.closeQuietly(input); } catch (Exception err) { throw new RuntimeException(err); } return buffer; } Code Sample 2: public void execute() { File sourceFile = new File(oarfilePath); File destinationFile = new File(deploymentDirectory + File.separator + sourceFile.getName()); try { FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(destinationFile); byte[] readArray = new byte[2048]; while (fis.read(readArray) != -1) { fos.write(readArray); } fis.close(); fos.flush(); fos.close(); } catch (IOException ioe) { logger.severe("failed to copy the file:" + ioe); } }
00
Code Sample 1: public void loadXML(URL flux, int status, File file) { try { SAXBuilder sbx = new SAXBuilder(); try { if (file.exists()) { file.delete(); } if (!file.exists()) { URLConnection conn = flux.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(10000); InputStream is = conn.getInputStream(); OutputStream out = new FileOutputStream(file); byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) out.write(buf, 0, len); out.close(); is.close(); } } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "Exeption retrieving XML", e); } try { document = sbx.build(new FileInputStream(file)); } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "xml error ", e); } } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "TsukiQueryError", e); } if (document != null) { root = document.getRootElement(); PopulateDatabase(root, status); } } Code Sample 2: public static String postServiceContent(String serviceURL, String text) throws IOException { URL url = new URL(serviceURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.connect(); int code = connection.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); byte[] buffer = null; String stringBuffer = ""; buffer = new byte[4096]; int totBytes, bytes, sumBytes = 0; totBytes = connection.getContentLength(); while (true) { bytes = is.read(buffer); if (bytes <= 0) break; stringBuffer = stringBuffer + new String(buffer); } return stringBuffer; } return null; }
00
Code Sample 1: public static String createStringFromHtml(MyUrl url) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.getUrl().openStream(), "UTF-8")); String line; String xmlAsString = ""; while ((line = reader.readLine()) != null) { xmlAsString += line; } reader.close(); return xmlAsString; } catch (Exception e) { return null; } } 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: private String sha1(String s) { String encrypt = s; try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(s.getBytes()); byte[] digest = sha.digest(); final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { final byte b = digest[i]; final int value = (b & 0x7F) + (b < 0 ? 128 : 0); buffer.append(value < 16 ? "0" : ""); buffer.append(Integer.toHexString(value)); } encrypt = buffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encrypt; } Code Sample 2: @Override public InputStream getInputStream() throws IOException { if (dfos == null) { int deferredOutputStreamThreshold = Config.getInstance().getDeferredOutputStreamThreshold(); dfos = new DeferredFileOutputStream(deferredOutputStreamThreshold, Definitions.PROJECT_NAME, "." + Definitions.TMP_EXTENSION); try { IOUtils.copy(is, dfos); } finally { dfos.close(); } } return dfos.getDeferredInputStream(); }
00
Code Sample 1: private void pushResource(String peerId, String communityId, String resourceFilePath, List<String> attachmentFilePaths) throws IOException { String urlString = "http://" + peerId + "/upload"; HttpURLConnection uploadConnection = null; DataOutputStream connOutput = null; FileInputStream fileInput = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "232404jkg4220957934FW"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; try { File resourceFile = new File(resourceFilePath); if (!resourceFile.exists()) { LOG.error("JTellaAdapter: Resource file could not be found for push: " + resourceFilePath); return; } List<File> attachments = new ArrayList<File>(); for (String attachmentPath : attachmentFilePaths) { File attachFile = new File(attachmentPath); if (!attachFile.exists()) { LOG.error("JTellaAdapter: Attachment file could not be found for push: " + attachmentPath); return; } attachments.add(attachFile); } LOG.debug("JTellaAdapter: Initiating push to: " + urlString); URL url = new URL(urlString); uploadConnection = (HttpURLConnection) url.openConnection(); uploadConnection.setDoInput(true); uploadConnection.setDoOutput(true); uploadConnection.setUseCaches(false); uploadConnection.setRequestMethod("POST"); uploadConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); uploadConnection.setRequestProperty("Connection", "Keep-Alive"); uploadConnection.setRequestProperty("User-Agent", "UP2P"); uploadConnection.setRequestProperty("Accept", "[star]/[star]"); connOutput = new DataOutputStream(uploadConnection.getOutputStream()); connOutput.writeBytes(twoHyphens + boundary + lineEnd); connOutput.writeBytes("Content-Disposition: form-data; name=\"up2p:community\"" + lineEnd + lineEnd); connOutput.writeBytes(communityId + lineEnd); connOutput.writeBytes(twoHyphens + boundary + lineEnd); connOutput.writeBytes("Content-Disposition: form-data; name=\"up2p:pushupload\"" + lineEnd + lineEnd + "true" + lineEnd); connOutput.writeBytes(twoHyphens + boundary + lineEnd); boolean fileWriteComplete = false; boolean resourceFileWritten = false; File nextFile = null; while (!fileWriteComplete) { if (!resourceFileWritten) { nextFile = resourceFile; } else { nextFile = attachments.remove(0); } LOG.debug("JTellaAdapter: PUSHing file: " + nextFile.getAbsolutePath()); connOutput.writeBytes("Content-Disposition: form-data; name=\"up2p:filename\";" + " filename=\"" + nextFile.getName() + "\"" + lineEnd); connOutput.writeBytes(lineEnd); fileInput = new FileInputStream(nextFile); bytesAvailable = fileInput.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInput.read(buffer, 0, bufferSize); while (bytesRead > 0) { connOutput.write(buffer, 0, bufferSize); bytesAvailable = fileInput.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInput.read(buffer, 0, bufferSize); } connOutput.writeBytes(lineEnd); if (attachments.isEmpty()) { connOutput.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); } else { connOutput.writeBytes(twoHyphens + boundary + lineEnd); } resourceFileWritten = true; if (attachments.isEmpty()) { fileWriteComplete = true; } } BufferedReader inStream = new BufferedReader(new InputStreamReader(uploadConnection.getInputStream())); while (inStream.readLine() != null) ; inStream.close(); LOG.debug("JTellaAdapter: Push upload was succesful."); } catch (MalformedURLException ex) { LOG.error("JTellaAdapter: pushResource Malformed URL: " + ex); throw new IOException("pushResource failed for URL: " + urlString); } catch (IOException ioe) { LOG.error("JTellaAdapter: pushResource IOException: " + ioe); throw new IOException("pushResource failed for URL: " + urlString); } finally { try { if (fileInput != null) { fileInput.close(); } if (connOutput != null) { connOutput.flush(); } if (connOutput != null) { connOutput.close(); } if (uploadConnection != null) { uploadConnection.disconnect(); } } catch (IOException e) { LOG.error("JTellaAdapter: pushResource failed to close connection streams."); } } } Code Sample 2: public static Status checkUpdate() { Status updateStatus = Status.FAILURE; URL url; InputStream is; InputStreamReader isr; BufferedReader r; String line; try { url = new URL(updateURL); is = url.openStream(); isr = new InputStreamReader(is); r = new BufferedReader(isr); String variable, value; while ((line = r.readLine()) != null) { if (!line.equals("") && line.charAt(0) != '/') { variable = line.substring(0, line.indexOf('=')); value = line.substring(line.indexOf('=') + 1); if (variable.equals("Latest Version")) { variable = value; value = variable.substring(0, variable.indexOf(" ")); variable = variable.substring(variable.indexOf(" ") + 1); latestGameVersion = value; latestModifier = variable; if (Float.parseFloat(value) > Float.parseFloat(gameVersion)) updateStatus = Status.NOT_CURRENT; else updateStatus = Status.CURRENT; } else if (variable.equals("Download URL")) downloadURL = value; } } return updateStatus; } catch (MalformedURLException e) { return Status.URL_NOT_FOUND; } catch (IOException e) { return Status.FAILURE; } }
11
Code Sample 1: public void zipUp() throws PersistenceException { ZipOutputStream out = null; try { if (!backup.exists()) backup.createNewFile(); out = new ZipOutputStream(new FileOutputStream(backup)); out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String file : backupDirectory.list()) { logger.debug("Deflating: " + file); FileInputStream in = null; try { in = new FileInputStream(new File(backupDirectory, file)); out.putNextEntry(new ZipEntry(file)); IOUtils.copy(in, out); } finally { out.closeEntry(); if (null != in) in.close(); } } FileUtils.deleteDirectory(backupDirectory); } catch (Exception ex) { logger.error("Unable to ZIP the backup {" + backupDirectory.getAbsolutePath() + "}.", ex); throw new PersistenceException(ex); } finally { try { if (null != out) out.close(); } catch (IOException e) { logger.error("Unable to close ZIP output stream.", e); } } } Code Sample 2: public void install(Session session) throws Exception { String cfgPath = ConfigurationFactory.getConfigSonInstance().getConfigurationPath(); File setupKson = new File(cfgPath, "setup.kson"); InputStream is = null; if (setupKson.exists()) { log.debug("Reagind kson from " + setupKson.getAbsolutePath()); is = new FileInputStream(setupKson); } else { String ksonCp = "/org/chon/cms/core/setup/setup.kson"; is = Setup.class.getResourceAsStream(ksonCp); log.info("Creating initial setup.kson in " + setupKson.getAbsolutePath()); IOUtils.copy(is, new FileOutputStream(setupKson)); is = new FileInputStream(setupKson); } BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); List<String> lines = new ArrayList<String>(); while (true) { String line = br.readLine(); if (line == null) break; lines.add(line); } List<NodeCreation> ncList = readKSon(lines.toArray(new String[lines.size()])); for (NodeCreation nc : ncList) { try { createNode(session, nc); } catch (Exception e) { System.err.println("error crating node " + nc.path + " -> " + e.getMessage()); } } session.save(); }
11
Code Sample 1: public void zipFile(String baseDir, String fileName, boolean encrypt) throws Exception { List fileList = getSubFiles(new File(baseDir)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fileName + ".temp")); ZipEntry ze = null; byte[] buf = new byte[BUFFER]; byte[] encrypByte = new byte[encrypLength]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { if (stopZipFile) { zos.close(); File zipFile = new File(fileName + ".temp"); if (zipFile.exists()) zipFile.delete(); break; } File f = (File) fileList.get(i); if (f.getAbsoluteFile().equals(fileName + ".temp")) continue; ze = new ZipEntry(getAbsFileName(baseDir, f)); ze.setSize(f.length()); ze.setTime(f.lastModified()); zos.putNextEntry(ze); InputStream is = new BufferedInputStream(new FileInputStream(f)); readLen = is.read(buf, 0, BUFFER); if (encrypt) { if (readLen >= encrypLength) { System.arraycopy(buf, 0, encrypByte, 0, encrypLength); } else if (readLen > 0) { Arrays.fill(encrypByte, (byte) 0); System.arraycopy(buf, 0, encrypByte, 0, readLen); readLen = encrypLength; } byte[] temp = CryptionControl.getInstance().encryptoECB(encrypByte, rootKey); System.arraycopy(temp, 0, buf, 0, encrypLength); } while (readLen != -1) { zos.write(buf, 0, readLen); readLen = is.read(buf, 0, BUFFER); } is.close(); } zos.close(); File zipFile = new File(fileName + ".temp"); if (zipFile.exists()) zipFile.renameTo(new File(fileName + ".zip")); } Code Sample 2: public static boolean copyFile(String fromfile, String tofile) { File from = new File(fromfile); File to = new File(tofile); if (!from.exists()) return false; if (to.exists()) { log.error(tofile + "exists already"); return false; } BufferedInputStream in = null; BufferedOutputStream out = null; FileInputStream fis = null; FileOutputStream ois = null; boolean flag = true; try { to.createNewFile(); fis = new FileInputStream(from); ois = new FileOutputStream(to); in = new BufferedInputStream(fis); out = new BufferedOutputStream(ois); byte[] buf = new byte[2048]; int readBytes = 0; while ((readBytes = in.read(buf, 0, buf.length)) != -1) { out.write(buf, 0, readBytes); } } catch (IOException e) { log.error(e); flag = false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { log.error(e); flag = false; } } return flag; }
00
Code Sample 1: @SuppressWarnings("finally") private void compress(File src) throws IOException { if (this.switches.contains(Switch.test)) return; checkSourceFile(src); if (src.getPath().endsWith(".bz2")) { this.log.println("WARNING: skipping file because it already has .bz2 suffix:").println(src); return; } final File dst = new File(src.getPath() + ".bz2").getAbsoluteFile(); if (!checkDestFile(dst)) return; FileChannel inChannel = null; FileChannel outChannel = null; FileOutputStream fileOut = null; BZip2OutputStream bzOut = null; FileLock inLock = null; FileLock outLock = null; try { inChannel = new FileInputStream(src).getChannel(); final long inSize = inChannel.size(); inLock = inChannel.tryLock(0, inSize, true); if (inLock == null) throw error("source file locked by another process: " + src); fileOut = new FileOutputStream(dst); outChannel = fileOut.getChannel(); bzOut = new BZip2OutputStream( new BufferedXOutputStream(fileOut, 8192), Math.min( (this.blockSize == -1) ? BZip2OutputStream.MAX_BLOCK_SIZE : this.blockSize, BZip2OutputStream.chooseBlockSize(inSize) ) ); outLock = outChannel.tryLock(); if (outLock == null) throw error("destination file locked by another process: " + dst); final boolean showProgress = this.switches.contains(Switch.showProgress); long pos = 0; int progress = 0; if (showProgress || this.verbose) { this.log.print("source: " + src).print(": size=").println(inSize); this.log.println("target: " + dst); } while (true) { final long maxStep = showProgress ? Math.max(8192, (inSize - pos) / MAX_PROGRESS) : (inSize - pos); if (maxStep <= 0) { if (showProgress) { for (int i = progress; i < MAX_PROGRESS; i++) this.log.print('#'); this.log.println(" done"); } break; } else { final long step = inChannel.transferTo(pos, maxStep, bzOut); if ((step == 0) && (inChannel.size() != inSize)) throw error("file " + src + " has been modified concurrently by another process"); pos += step; if (showProgress) { final double p = (double) pos / (double) inSize; final int newProgress = (int) (MAX_PROGRESS * p); for (int i = progress; i < newProgress; i++) this.log.print('#'); progress = newProgress; } } } inLock.release(); inChannel.close(); bzOut.closeInstance(); final long outSize = outChannel.position(); outChannel.truncate(outSize); outLock.release(); fileOut.close(); if (this.verbose) { final double ratio = (inSize == 0) ? (outSize * 100) : ((double) outSize / (double) inSize); this.log.print("raw size: ").print(inSize) .print("; compressed size: ").print(outSize) .print("; compression ratio: ").print(ratio).println('%'); } if (!this.switches.contains(Switch.keep)) { if (!src.delete()) throw error("unable to delete sourcefile: " + src); } } catch (final IOException ex) { IO.tryClose(inChannel); IO.tryClose(bzOut); IO.tryClose(fileOut); IO.tryRelease(inLock); IO.tryRelease(outLock); try { this.log.println(); } finally { throw ex; } } } Code Sample 2: private URL retrieveFirstURL(URL url, RSLink link) { link.setStatus(RSLink.STATUS_WAITING); URL result = null; HttpURLConnection httpConn = null; BufferedReader inr = null; Pattern formStartPattern = Pattern.compile("<form.+action=\""); Pattern freeUserPattern = Pattern.compile("input type=\"submit\" value=\"Free user\""); Pattern formEndPattern = Pattern.compile("</form>"); Pattern urlString = Pattern.compile("http://[a-zA-Z0-9\\.\\-/_]+"); try { httpConn = (HttpURLConnection) url.openConnection(); httpConn.setDoOutput(false); httpConn.setDoInput(true); inr = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); String line = null; String urlLine = null; boolean freeUser = false; Matcher matcher = null; while ((line = inr.readLine()) != null) { if (urlLine == null) { matcher = formStartPattern.matcher(line); if (matcher.find()) { urlLine = line; } } else { matcher = formEndPattern.matcher(line); if (matcher.find()) { urlLine = null; } else { matcher = freeUserPattern.matcher(line); if (matcher.find()) { freeUser = true; break; } } } } if (freeUser) { matcher = urlString.matcher(urlLine); if (matcher.find()) { result = new URL(matcher.group()); } } } catch (MalformedURLException ex) { log("Malformed URL Exception!"); } catch (IOException ex) { log("I/O Exception!"); } finally { try { if (inr != null) inr.close(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Can not close some connections:\n" + ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE); } if (httpConn != null) httpConn.disconnect(); link.setStatus(RSLink.STATUS_NOTHING); return result; } }
11
Code Sample 1: private void copy(File fin, File fout) throws IOException { FileOutputStream out = new FileOutputStream(fout); FileInputStream in = new FileInputStream(fin); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } in.close(); out.close(); } Code Sample 2: public static int copy(File src, int amount, File dst) { final int BUFFER_SIZE = 1024; int amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { if (in != null) try { in.close(); } catch (IOException e) { } if (out != null) { try { out.flush(); } catch (IOException e) { } try { out.close(); } catch (IOException e) { } } } return amount - amountToRead; }
00
Code Sample 1: public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { InputStream urlStream = url.openStream(); AudioFileFormat fileFormat = null; try { fileFormat = getFMT(urlStream, false); } finally { if (fileFormat == null) { urlStream.close(); } } return new AudioInputStream(urlStream, fileFormat.getFormat(), fileFormat.getFrameLength()); } Code Sample 2: public void Copy() throws IOException { if (!FileDestination.exists()) { FileDestination.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(FileSource).getChannel(); destination = new FileOutputStream(FileDestination).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
00
Code Sample 1: public static void copyFile(final FileInputStream in, final File out) throws IOException { final FileChannel inChannel = 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(); } } Code Sample 2: byte[] loadUrlByteArray(String szName, int offset, int size) { byte[] baBuffer = new byte[size]; try { URL url = new URL(waba.applet.Applet.currentApplet.getCodeBase(), szName); try { InputStream file = url.openStream(); if (size == 0) { int n = file.available(); baBuffer = new byte[n - offset]; } DataInputStream dataFile = new DataInputStream(file); try { dataFile.skip(offset); dataFile.readFully(baBuffer); } catch (EOFException e) { System.err.print(e.getMessage()); } file.close(); } catch (IOException e) { System.err.print(e.getMessage()); } } catch (MalformedURLException e) { System.err.print(e.getMessage()); } return baBuffer; }
00
Code Sample 1: public void run() { if (saveAsDialog == null) { saveAsDialog = new FileDialog(window.getShell(), SWT.SAVE); saveAsDialog.setFilterExtensions(saveAsTypes); } String outputFile = saveAsDialog.open(); if (outputFile != null) { Object inputFile = DataSourceSingleton.getInstance().getContainer().getWrapped(); InputStream in; try { if (inputFile instanceof URL) in = ((URL) inputFile).openStream(); else in = new FileInputStream((File) inputFile); OutputStream out = new FileOutputStream(outputFile); if (outputFile.endsWith("xml")) { int c; while ((c = in.read()) != -1) out.write(c); } else { PrintWriter pw = new PrintWriter(out); Element data = DataSourceSingleton.getInstance().getRawData(); writeTextFile(data, pw, -1); pw.close(); } in.close(); out.close(); } catch (MalformedURLException e1) { } catch (IOException e) { } } } Code Sample 2: public String getShortToken(String md5Str) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.update(md5Str.getBytes(JspRunConfig.charset)); } catch (Exception e) { e.printStackTrace(); } StringBuffer token = toHex(md5.digest()); return token.substring(8, 24); }
11
Code Sample 1: protected void unZip() throws PersistenceException { boolean newZip = false; try { if (null == backup) { mode = (String) context.get(Context.MODE); if (null == mode) mode = Context.MODE_NAME_RESTORE; backupDirectory = (File) context.get(Context.BACKUP_DIRECTORY); logger.debug("Got backup directory {" + backupDirectory.getAbsolutePath() + "}"); if (!backupDirectory.exists() && mode.equals(Context.MODE_NAME_BACKUP)) { newZip = true; backupDirectory.mkdirs(); } else if (!backupDirectory.exists()) { throw new PersistenceException("Backup directory {" + backupDirectory.getAbsolutePath() + "} does not exist."); } backup = new File(backupDirectory + "/" + getBackupName() + ".zip"); logger.debug("Got zip file {" + backup.getAbsolutePath() + "}"); } File _explodedDirectory = File.createTempFile("exploded-" + backup.getName() + "-", ".zip"); _explodedDirectory.mkdirs(); _explodedDirectory.delete(); backupDirectory = new File(_explodedDirectory.getParentFile(), _explodedDirectory.getName()); backupDirectory.mkdirs(); logger.debug("Created exploded directory {" + backupDirectory.getAbsolutePath() + "}"); if (!backup.exists() && mode.equals(Context.MODE_NAME_BACKUP)) { newZip = true; backup.createNewFile(); } else if (!backup.exists()) { throw new PersistenceException("Backup file {" + backup.getAbsolutePath() + "} does not exist."); } if (newZip) return; ZipFile zip = new ZipFile(backup); Enumeration zipFileEntries = zip.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); logger.debug("Inflating: " + entry); File destFile = new File(backupDirectory, currentEntry); File destinationParent = destFile.getParentFile(); destinationParent.mkdirs(); if (!entry.isDirectory()) { InputStream in = null; OutputStream out = null; try { in = zip.getInputStream(entry); out = new FileOutputStream(destFile); IOUtils.copy(in, out); } finally { if (null != out) out.close(); if (null != in) in.close(); } } } } catch (IOException e) { logger.error("Unable to unzip {" + backup + "}", e); throw new PersistenceException(e); } } Code Sample 2: protected static IFile createTempFile(CodeFile codeFile) { IPath path = Util.getAbsolutePathFromCodeFile(codeFile); File file = new File(path.toOSString()); String[] parts = codeFile.getName().split("\\."); String extension = parts[parts.length - 1]; IPath ext = path.addFileExtension(extension); File tempFile = new File(ext.toOSString()); if (tempFile.exists()) { boolean deleted = tempFile.delete(); System.out.println("deleted: " + deleted); } try { boolean created = tempFile.createNewFile(); if (created) { FileOutputStream fos = new FileOutputStream(tempFile); FileInputStream fis = new FileInputStream(file); while (fis.available() > 0) { fos.write(fis.read()); } fis.close(); fos.close(); IFile iFile = Util.getFileFromPath(ext); return iFile; } } catch (IOException e) { e.printStackTrace(); } return null; }
00
Code Sample 1: public void testDecode1000BinaryStore() throws Exception { EXISchema corpus = EXISchemaFactoryTestUtil.getEXISchema("/DataStore/DataStore.xsd", getClass(), m_compilerErrors); Assert.assertEquals(0, m_compilerErrors.getTotalCount()); GrammarCache grammarCache = new GrammarCache(corpus, GrammarOptions.STRICT_OPTIONS); String[] base64Values100 = { "R0lGODdhWALCov////T09M7Ozqampn19fVZWVi0tLQUFBSxYAsJAA/8Iutz+MMpJq7046827/2Ao\n", "/9j/4BBKRklGAQEBASwBLP/hGlZFeGlmTU0qF5ZOSUtPTiBDT1JQT1JBVElPTk5J", "R0lGODlhHh73KSkpOTk5QkJCSkpKUlJSWlpaY2Nja2trc3Nze3t7hISEjIyMlJSUnJycpaWlra2t\n" + "tbW1vb29xsbGzs7O1tbW3t7e5+fn7+/v//////////8=", "/9j/4BBKRklGAQEBAf/bQwYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBc=", "R0lGODlhHh73M2aZzP8zMzNmM5kzzDP/M2YzZmZmmWbM", "/9j/4BBKRklGAQEBAf/bQwYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsj\n" + "HBYWICwgIyYnKSopGR8tMC0oMCUoKSj/20M=", "R0lGODdhWAK+ov////j4+NTU1JOTk0tLSx8fHwkJCSxYAr5AA/8IMkzjrEEmahy23SpC", "R0lGODdh4QIpAncJIf4aU29mdHdhcmU6IE1pY3Jvc29mdCBPZmZpY2Us4QIpAof//////8z//5n/\n", "R0lGODdhWAK+ov////v7++fn58DAwI6Ojl5eXjExMQMDAyxYAr5AA/8Iutz+MMpJq7046827/2Ao\n" + "jmRpnmiqPsKxvg==", "R0lGODdh4QIpAncJIf4aU29mdHdhcmU6IE1pY3Jvc29mdCBPZmZpY2Us4QIpAob//////8z//5n/\nzP//zMw=" }; AlignmentType alignment = AlignmentType.bitPacked; Transmogrifier encoder = new Transmogrifier(); encoder.setEXISchema(grammarCache); encoder.setAlignmentType(alignment); ByteArrayOutputStream baos = new ByteArrayOutputStream(); encoder.setOutputStream(baos); URL url = resolveSystemIdAsURL("/DataStore/instance/1000BinaryStore.xml"); encoder.encode(new InputSource(url.openStream())); byte[] bts = baos.toByteArray(); Scanner scanner; int n_texts; EXIDecoder decoder = new EXIDecoder(999); decoder.setEXISchema(grammarCache); decoder.setAlignmentType(alignment); decoder.setInputStream(new ByteArrayInputStream(bts)); scanner = decoder.processHeader(); EXIEvent exiEvent; n_texts = 0; while ((exiEvent = scanner.nextEvent()) != null) { if (exiEvent.getEventVariety() == EXIEvent.EVENT_CH) { if (++n_texts % 100 == 0) { String expected = base64Values100[(n_texts / 100) - 1]; String val = exiEvent.getCharacters().makeString(); Assert.assertEquals(expected, val); } } } Assert.assertEquals(1000, n_texts); } Code Sample 2: InputStream selectSource(String item) { if (item.endsWith(".pls")) { item = fetch_pls(item); if (item == null) return null; } else if (item.endsWith(".m3u")) { item = fetch_m3u(item); if (item == null) return null; } if (!item.endsWith(".ogg")) { return null; } InputStream is = null; URLConnection urlc = null; try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), item); else url = new URL(item); urlc = url.openConnection(); is = urlc.getInputStream(); current_source = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + url.getFile(); } catch (Exception ee) { System.err.println(ee); } if (is == null && !running_as_applet) { try { is = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + item); current_source = null; } catch (Exception ee) { System.err.println(ee); } } if (is == null) return null; System.out.println("Select: " + item); { boolean find = false; for (int i = 0; i < cb.getItemCount(); i++) { String foo = (String) (cb.getItemAt(i)); if (item.equals(foo)) { find = true; break; } } if (!find) { cb.addItem(item); } } int i = 0; String s = null; String t = null; udp_port = -1; udp_baddress = null; while (urlc != null && true) { s = urlc.getHeaderField(i); t = urlc.getHeaderFieldKey(i); if (s == null) break; i++; if (t != null && t.equals("udp-port")) { try { udp_port = Integer.parseInt(s); } catch (Exception ee) { System.err.println(ee); } } else if (t != null && t.equals("udp-broadcast-address")) { udp_baddress = s; } } return is; }
00
Code Sample 1: private String httpGet(String urlString, boolean postStatus) throws Exception { URL url; URLConnection conn; String answer = ""; try { if (username.equals("") || password.equals("")) throw new AuthNotProvidedException(); url = new URL(urlString); conn = url.openConnection(); conn.setRequestProperty("Authorization", "Basic " + getAuthentificationString()); if (postStatus) { conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream das = new DataOutputStream(conn.getOutputStream()); String content = "status=" + URLEncoder.encode(statusMessage, "UTF-8") + "&source=" + URLEncoder.encode("sametimetwitterclient", "UTF-8"); das.writeBytes(content); das.flush(); das.close(); } InputStream is = (InputStream) conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { answer += line + "\n"; } br.close(); } catch (FileNotFoundException ex) { System.out.println(ex.toString()); throw new RuntimeException("Page not Found. Maybe Twitter-API has changed."); } catch (UnknownHostException ex) { System.out.println(ex.toString()); throw new RuntimeException("Network connection problems. Could not find twitter.com"); } catch (IOException ex) { System.out.println("IO-Exception"); if (ex.getMessage().indexOf("401") > -1) { authenthicated = AUTH_BAD; throw new AuthNotAcceptedException(); } System.out.println(ex.toString()); } if (checkForError(answer) != null) { throw new RuntimeException(checkForError(answer)); } authenthicated = AUTH_OK; return answer; } Code Sample 2: public void compressImage(InputStream input, OutputStream output, DjatokaEncodeParam params) throws DjatokaException { if (params == null) params = new DjatokaEncodeParam(); File inputFile = null; try { inputFile = File.createTempFile("tmp", ".tif"); IOUtils.copyStream(input, new FileOutputStream(inputFile)); if (params.getLevels() == 0) { ImageRecord dim = ImageRecordUtils.getImageDimensions(inputFile.getAbsolutePath()); params.setLevels(ImageProcessingUtils.getLevelCount(dim.getWidth(), dim.getHeight())); dim = null; } } catch (IOException e1) { logger.error("Unexpected file format; expecting uncompressed TIFF", e1); throw new DjatokaException("Unexpected file format; expecting uncompressed TIFF"); } String out = STDOUT; File winOut = null; if (isWindows) { try { winOut = File.createTempFile("pipe_", ".jp2"); } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } out = winOut.getAbsolutePath(); } String command = getKduCompressCommand(inputFile.getAbsolutePath(), out, params); logger.debug("compressCommand: " + command); Runtime rt = Runtime.getRuntime(); try { final Process process = rt.exec(command, envParams, new File(env)); if (out.equals(STDOUT)) { IOUtils.copyStream(process.getInputStream(), output); } else if (isWindows) { FileInputStream fis = new FileInputStream(out); IOUtils.copyStream(fis, output); fis.close(); } process.waitFor(); if (process != null) { String errorCheck = null; try { errorCheck = new String(IOUtils.getByteArray(process.getErrorStream())); } catch (Exception e1) { logger.error(e1, e1); } process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); process.destroy(); if (errorCheck != null) throw new DjatokaException(errorCheck); } } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } catch (InterruptedException e) { logger.error(e, e); throw new DjatokaException(e); } if (inputFile != null) inputFile.delete(); if (winOut != null) winOut.delete(); }
00
Code Sample 1: private InputStream getManifestAsResource() { ClassLoader cl = getClass().getClassLoader(); try { Enumeration manifests = cl != null ? cl.getResources(Constants.OSGI_BUNDLE_MANIFEST) : ClassLoader.getSystemResources(Constants.OSGI_BUNDLE_MANIFEST); while (manifests.hasMoreElements()) { URL url = (URL) manifests.nextElement(); try { Headers headers = Headers.parseManifest(url.openStream()); if ("true".equals(headers.get(Constants.ECLIPSE_SYSTEMBUNDLE))) return url.openStream(); } catch (BundleException e) { } } } catch (IOException e) { } return null; } Code Sample 2: protected void createFile(File sourceActionDirectory, File destinationActionDirectory, LinkedList<String> segments) throws DuplicateActionFileException { File currentSrcDir = sourceActionDirectory; File currentDestDir = destinationActionDirectory; String segment = ""; for (int i = 0; i < segments.size() - 1; i++) { segment = segments.get(i); currentSrcDir = new File(currentSrcDir, segment); currentDestDir = new File(currentDestDir, segment); } if (currentSrcDir != null && currentDestDir != null) { File srcFile = new File(currentSrcDir, segments.getLast()); if (srcFile.exists()) { File destFile = new File(currentDestDir, segments.getLast()); if (destFile.exists()) { throw new DuplicateActionFileException(srcFile.toURI().toASCIIString()); } try { FileChannel srcChannel = new FileInputStream(srcFile).getChannel(); FileChannel destChannel = new FileOutputStream(destFile).getChannel(); ByteBuffer buffer = ByteBuffer.allocate((int) srcChannel.size()); while (srcChannel.position() < srcChannel.size()) { srcChannel.read(buffer); } srcChannel.close(); buffer.rewind(); destChannel.write(buffer); destChannel.close(); } catch (Exception ex) { ex.printStackTrace(); } } } }
00
Code Sample 1: public void sendMessage(Message m) throws IOException { URL url = new URL(strURL); urlcon = (HttpURLConnection) url.openConnection(); urlcon.setUseCaches(false); urlcon.setDefaultUseCaches(false); urlcon.setDoOutput(true); urlcon.setDoInput(true); urlcon.setRequestProperty("Content-type", "application/octet-stream"); urlcon.setAllowUserInteraction(false); HttpURLConnection.setDefaultAllowUserInteraction(false); urlcon.setRequestMethod("POST"); ObjectOutputStream oos = new ObjectOutputStream(urlcon.getOutputStream()); oos.writeObject(m); oos.flush(); oos.close(); } Code Sample 2: public GEItem lookup(final int itemID) { try { URL url = new URL(GrandExchange.HOST + GrandExchange.GET + itemID); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String input; boolean exists = false; int i = 0; double[] values = new double[4]; String name = "", examine = ""; while ((input = br.readLine()) != null) { if (input.contains("<div class=\"brown_box main_ge_page") && !exists) { if (!input.contains("vertically_spaced")) { return null; } exists = true; br.readLine(); br.readLine(); name = br.readLine(); } else if (input.contains("<img id=\"item_image\" src=\"")) { examine = br.readLine(); } else if (input.matches("(?i).+ (price|days):</b> .+")) { values[i] = parse(input); i++; } else if (input.matches("<div id=\"legend\">")) break; } return new GEItem(name, examine, itemID, values); } catch (IOException ignore) { } return null; }
11
Code Sample 1: public void processDeleteCompany(Company companyBean, AuthSession authSession) { if (authSession == null) { return; } DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (companyBean.getId() == null) throw new IllegalArgumentException("companyId is null"); String sql = "update WM_LIST_COMPANY set is_deleted = 1 " + "where ID_FIRM = ? and ID_FIRM in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedCompanyId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_FIRM from v$_read_list_firm z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, companyBean.getId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(2, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete company"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } Code Sample 2: public int instantiate(int objectId, String description) throws FidoDatabaseException, ObjectNotFoundException, ClassLinkTypeNotFoundException { try { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { String sql = "insert into Objects (Description) " + "values ('" + description + "')"; conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); if (contains(stmt, objectId) == false) throw new ObjectNotFoundException(objectId); stmt.executeUpdate(sql); int id; sql = "select currval('objects_objectid_seq')"; rs = stmt.executeQuery(sql); if (rs.next() == false) throw new SQLException("No rows returned from select currval() query"); else id = rs.getInt(1); ObjectLinkTable objectLinkList = new ObjectLinkTable(); objectLinkList.linkObjects(stmt, id, "instance", objectId); conn.commit(); return id; } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
11
Code Sample 1: private void copyOutResource(String dstPath, InputStream in) throws FileNotFoundException, IOException { FileOutputStream out = null; try { dstPath = this.outputDir + dstPath; File file = new File(dstPath); file.getParentFile().mkdirs(); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } } } Code Sample 2: private static void copy(String sourceName, String destName) throws IOException { File source = new File(sourceName); File dest = new File(destName); FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
11
Code Sample 1: FileCacheInputStreamFountain(FileCacheInputStreamFountainFactory factory, InputStream in) throws IOException { file = factory.createFile(); OutputStream out = new FileOutputStream(file); IOUtils.copy(in, out); in.close(); out.close(); } Code Sample 2: public static File unGzip(File infile, boolean deleteGzipfileOnSuccess) throws IOException { GZIPInputStream gin = new GZIPInputStream(new FileInputStream(infile)); File outFile = new File(infile.getParent(), infile.getName().replaceAll("\\.gz$", "")); FileOutputStream fos = new FileOutputStream(outFile); byte[] buf = new byte[100000]; int len; while ((len = gin.read(buf)) > 0) fos.write(buf, 0, len); gin.close(); fos.close(); if (deleteGzipfileOnSuccess) infile.delete(); return outFile; }