label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: protected static final void copyFile(String from, String to) throws SeleniumException { try { java.io.File fileFrom = new File(from); java.io.File fileTo = new File(to); FileReader in = new FileReader(fileFrom); FileWriter out = new FileWriter(fileTo); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { throw new SeleniumException("Failed to copy new file : " + from + " to : " + to, e); } } Code Sample 2: private JButton getButtonImagen() { if (buttonImagen == null) { buttonImagen = new JButton(); buttonImagen.setText("Cargar Imagen"); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetree.png"))); buttonImagen.addActionListener(new java.awt.event.ActionListener() { 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 { } } }); } return buttonImagen; }
00
Code Sample 1: public static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); file = new File("H:\\FileServeUploader.java"); HttpPost httppost = new HttpPost(postURL); httppost.setHeader("Cookie", uprandcookie + ";" + autologincookie); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart("MAX_FILE_SIZE", new StringBody("2097152000")); mpEntity.addPart("UPLOAD_IDENTIFIER", new StringBody(uid)); mpEntity.addPart("go", new StringBody("1")); mpEntity.addPart("files", cbFile); httppost.setEntity(mpEntity); System.out.println("Now uploading your file into depositfiles..........................."); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); downloadlink = parseResponse(uploadresponse, "ud_download_url = '", "'"); deletelink = parseResponse(uploadresponse, "ud_delete_url = '", "'"); System.out.println("download link : " + downloadlink); System.out.println("delete link : " + deletelink); } } Code Sample 2: public static void joinFiles(FileValidator validator, File target, File[] sources) { FileOutputStream fos = null; try { if (!validator.verifyFile(target)) return; fos = new FileOutputStream(target); FileInputStream fis = null; byte[] bytes = new byte[512]; for (int i = 0; i < sources.length; i++) { fis = new FileInputStream(sources[i]); int nbread = 0; try { while ((nbread = fis.read(bytes)) > -1) { fos.write(bytes, 0, nbread); } } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { fis.close(); } } } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } }
11
Code Sample 1: public static void parseString(String str, String name) { BufferedReader reader; String zeile = null; boolean firstL = true; int lambda; float intens; int l_b = 0; int l_e = 0; HashMap<Integer, Float> curve = new HashMap<Integer, Float>(); String[] temp; try { File f = File.createTempFile("tempFile", null); URL url = new URL(str); InputStream is = url.openStream(); FileOutputStream os = new FileOutputStream(f); byte[] buffer = new byte[0xFFFF]; for (int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len); is.close(); os.close(); reader = new BufferedReader(new FileReader(f)); zeile = reader.readLine(); lambda = 0; while (zeile != null) { if (!(zeile.length() > 0 && zeile.charAt(0) == '#')) { zeile = reader.readLine(); break; } zeile = reader.readLine(); } while (zeile != null) { if (zeile.length() > 0) { temp = zeile.split(" "); lambda = Integer.parseInt(temp[0]); intens = Float.parseFloat(temp[1]); if (firstL) { firstL = false; l_b = lambda; } curve.put(lambda, intens); } zeile = reader.readLine(); } l_e = lambda; } catch (IOException e) { System.err.println("Error2 :" + e); } try { String tempV; File file = new File("C:/spectralColors/" + name + ".sd"); FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); bw.write("# COLOR: " + name + " Auto generated File: 02/09/2009; From " + l_b + " to " + l_e); bw.newLine(); bw.write(l_b + ""); bw.newLine(); for (int i = l_b; i <= l_e; i++) { if (curve.containsKey(i)) { tempV = i + " " + curve.get(i); bw.write(tempV); bw.newLine(); } } bw.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: private static void copy(File src, File dst) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public HSSFWorkbook callRules(URL urlOfExcelDataFile, RuleSource ruleSource, String excelLogSheet) throws DroolsParserException, IOException, ClassNotFoundException { InputStream inputFromExcel = null; try { log.info("Looking for url:" + urlOfExcelDataFile); inputFromExcel = urlOfExcelDataFile.openStream(); log.info("found url:" + urlOfExcelDataFile); } catch (MalformedURLException e) { log.log(Level.SEVERE, "Malformed URL Exception Loading rules", e); throw e; } catch (IOException e) { log.log(Level.SEVERE, "IO Exception Loading rules", e); throw e; } return callRules(inputFromExcel, ruleSource, excelLogSheet); } Code Sample 2: public static void readConfigFromResource(String resname) throws Exception { URL url = ConfigXMLReader.class.getClassLoader().getResource(resname); if (url == null) throw new FileNotFoundException("Couldn't find the config resource:" + resname); System.out.println("Reading config from resource: " + url.toString()); readConfig(url.openStream()); }
11
Code Sample 1: private static void copyFile(String fromFile, String toFile) throws Exception { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: private void copyPhoto(final IPhoto photo, final Map.Entry<String, Integer> size) { final File fileIn = new File(storageService.getPhotoPath(photo, storageService.getOriginalDir())); final File fileOut = new File(storageService.getPhotoPath(photo, size.getKey())); InputStream fileInputStream; OutputStream fileOutputStream; try { fileInputStream = new FileInputStream(fileIn); fileOutputStream = new FileOutputStream(fileOut); IOUtils.copy(fileInputStream, fileOutputStream); fileInputStream.close(); fileOutputStream.close(); } catch (final IOException e) { log.error("file io exception", e); return; } } Code Sample 2: private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { GTLogger.getInstance().error(e); } } catch (FileNotFoundException e) { GTLogger.getInstance().error(e); } }
11
Code Sample 1: public void transform(File inputMatrixFile, MatrixIO.Format inputFormat, File outputMatrixFile) throws IOException { FileChannel original = new FileInputStream(inputMatrixFile).getChannel(); FileChannel copy = new FileOutputStream(outputMatrixFile).getChannel(); copy.transferFrom(original, 0, original.size()); original.close(); copy.close(); } Code Sample 2: public static void copyFile(File source, File destination) throws IOException { FileInputStream fis = new FileInputStream(source); FileOutputStream fos = new FileOutputStream(destination); FileChannel inCh = fis.getChannel(); FileChannel outCh = fos.getChannel(); inCh.transferTo(0, inCh.size(), outCh); inCh.close(); fis.close(); outCh.close(); fos.flush(); fos.close(); }
11
Code Sample 1: public boolean authenticate(String plaintext) throws NoSuchAlgorithmException { String[] passwordParts = this.password.split("\\$"); md = MessageDigest.getInstance("SHA-1"); md.update(passwordParts[1].getBytes()); isAuthenticated = toHex(md.digest(plaintext.getBytes())).equalsIgnoreCase(passwordParts[2]); return isAuthenticated; } Code Sample 2: public static String md5(String text) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } try { msgDigest.update(text.getBytes(AlipayConfig.CharSet)); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("System doesn't support your EncodingException."); } byte[] bytes = msgDigest.digest(); String md5Str = new String(encodeHex(bytes)); return md5Str; }
00
Code Sample 1: public static String[] parsePLS(String strURL, Context c) { URL url; URLConnection urlConn = null; String TAG = "parsePLS"; Vector<String> radio = new Vector<String>(); final String filetoken = "file"; final String SPLITTER = "="; try { url = new URL(strURL); urlConn = url.openConnection(); Log.d(TAG, "Got data"); } catch (IOException ioe) { Log.e(TAG, "Could not connect to " + strURL); } try { DataInputStream in = new DataInputStream(urlConn.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { String temp = strLine.toLowerCase(); Log.d(TAG, strLine); if (temp.startsWith(filetoken)) { String[] s = Pattern.compile(SPLITTER).split(temp); radio.add(s[1]); Log.d(TAG, "Found audio " + s[1]); } } br.close(); in.close(); } catch (Exception e) { Log.e(TAG, "Trouble reading file: " + e.getMessage()); } String[] t = new String[0]; String[] r = null; if (radio.size() != 0) { r = (String[]) radio.toArray(t); Log.d(TAG, "Found total: " + String.valueOf(r.length)); } return r; } Code Sample 2: public static void copy(File from, File to) { if (from.getAbsolutePath().equals(to.getAbsolutePath())) { return; } FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(from); os = new FileOutputStream(to); int read = -1; byte[] buffer = new byte[10000]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } } catch (Exception e) { throw new RuntimeException(); } finally { try { is.close(); } catch (Exception e) { } try { os.close(); } catch (Exception e) { } } }
00
Code Sample 1: public Certificate(URL url) throws CertificateException { try { URLConnection con = url.openConnection(); InputStream in2 = con.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(in2)); String inputLine; StringBuffer cert = new StringBuffer(); while ((inputLine = in.readLine()) != null) { cert.append(inputLine); cert.append("\n"); } in.close(); this.certificate = cert.toString(); } catch (IOException ex) { throw new CertificateException("Unable to read in credential: " + ex.getMessage(), ex); } loadCredential(this.certificate); } Code Sample 2: public final InputStream getStreamFromUrl(final URL url) { try { if (listener != null) { listener.openedStream(url); } return url.openStream(); } catch (IOException e) { listener.exceptionThrown(e); return null; } }
11
Code Sample 1: public File addFile(File file, String suffix) throws IOException { if (file.exists() && file.isFile()) { File nf = File.createTempFile(prefix, "." + suffix, workdir); nf.delete(); if (!file.renameTo(nf)) { IOUtils.copy(file, nf); } synchronized (fileList) { fileList.add(nf); } if (log.isDebugEnabled()) { log.debug("Add file [" + file.getPath() + "] -> [" + nf.getPath() + "]"); } return nf; } return file; } Code Sample 2: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
00
Code Sample 1: public String getDataAsString(String url) throws RuntimeException { try { String responseBody = ""; URLConnection urlc; if (!url.toUpperCase().startsWith("HTTP://") && !url.toUpperCase().startsWith("HTTPS://")) { urlc = tryOpenConnection(url); } else { urlc = new URL(url).openConnection(); } urlc.setUseCaches(false); urlc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlc.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-GB; rv:1.9.1.9) Gecko/20100414 Iceweasel/3.5.9 (like Firefox/3.5.9)"); urlc.setRequestProperty("Accept-Encoding", "gzip"); InputStreamReader re = new InputStreamReader(urlc.getInputStream()); BufferedReader rd = new BufferedReader(re); String line = ""; while ((line = rd.readLine()) != null) { responseBody += line; responseBody += "\n"; line = null; } rd.close(); re.close(); return responseBody; } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: static InputStream getUrlStream(String url) throws IOException { System.out.print("getting : " + url + " ... "); long start = System.currentTimeMillis(); URLConnection c = new URL(url).openConnection(); InputStream is = c.getInputStream(); System.out.print((System.currentTimeMillis() - start) + "ms\n"); return is; }
00
Code Sample 1: @Override public void run() { String src = null; try { src = File.readText(srcFile); if (Char.isValidate(src)) { java.net.URL url = new java.net.URL(ConsEnv.HOMEPAGE + "code/code0001.ashx"); java.util.HashMap<String, String> params = new java.util.HashMap<String, String>(); String ext = File.getExtension(srcFile.getName()); if (Char.isValidate(ext) && ext.charAt(0) == '.') { ext = ext.substring(1); } params.put("l", ext); params.put("i", "1"); params.put("n", ck_LineNbr.isSelected() ? "1" : "0"); params.put("u", ck_LinkUri.isSelected() ? "1" : "0"); params.put("t", cb_TagStyle.getSelectedItem() + ""); String tab = tf_TabCount.getText().trim(); if (java.util.regex.Pattern.matches("^\\d+$", tab)) { tab = "4"; } params.put("s", tab); params.put("o", "html"); params.put("c", src); java.net.HttpURLConnection con = (java.net.HttpURLConnection) url.openConnection(); java.io.InputStream stream = Http.post(con, params); ep_CodeView.setContentType(con.getContentType()); src = File.readText(stream); stream.close(); con.disconnect(); java.io.File tmpFile = java.io.File.createTempFile("src_", ".html"); tmpFile.deleteOnExit(); File.saveText(tmpFile, src); ep_CodeView.setPage(tmpFile.toURI().toURL()); ep_CodeView.setFont(ep_CodeView.getFont().deriveFont(20f)); } } catch (Exception exp) { Logs.exception(exp); } } Code Sample 2: protected void assignListeners() { groupsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent event) { refreshInfo(); } }); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JFileChooser fileDialog = new JFileChooser("."); fileDialog.setFileFilter(ReaderData.mkExtensionFileFilter(".grp", "Group Files")); int outcome = fileDialog.showSaveDialog((Frame) null); if (outcome == JFileChooser.APPROVE_OPTION) { assert (fileDialog.getCurrentDirectory() != null); assert (fileDialog.getSelectedFile() != null); String fileName = fileDialog.getCurrentDirectory().toString() + File.separator + fileDialog.getSelectedFile().getName(); try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); ReaderWriterGroup.write(out, writer); System.err.println("Wrote groups informations to output '" + fileName + "'."); out.close(); } catch (IOException e) { System.err.println("error while writing (GroupManager.saveClt):"); e.printStackTrace(); } } else if (outcome == JFileChooser.CANCEL_OPTION) { } } }); loadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { JFileChooser fileDialog = new JFileChooser("."); fileDialog.setFileFilter(ReaderData.mkExtensionFileFilter(".grp", "Group Files")); int outcome = fileDialog.showOpenDialog((Frame) null); if (outcome == JFileChooser.APPROVE_OPTION) { assert (fileDialog.getCurrentDirectory() != null); assert (fileDialog.getSelectedFile() != null); String fileName = fileDialog.getCurrentDirectory().toString() + File.separator + fileDialog.getSelectedFile().getName(); BufferedReader fileReader = null; try { fileReader = new BufferedReader(new FileReader(fileName)); ReaderWriterGroup.read(fileReader, writer); fileReader.close(); } catch (Exception e) { System.err.println("Exception while reading from file '" + fileName + "'."); System.err.println(e); } } else if (outcome == JFileChooser.CANCEL_OPTION) { } } }); ItemListener propItemListener = new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { int[] indices = groupsList.getSelectedIndices(); for (int index : indices) { Group group = getGroupFromListIndex(index); if (group != null) { if (event.getSource() instanceof JComboBox) { JComboBox eventSource = (JComboBox) event.getSource(); if (eventSource == colorComboBox) { Color color = colorComboBox.getSelectedColor(); assert (color != null); group.setColor(color); shapeComboBox.setColor(color); } else if (eventSource == shapeComboBox) { Shape shape = shapeComboBox.getSelectedShape(); assert (shape != null); group.setShape(shape); } } else if (event.getSource() instanceof JCheckBox) { JCheckBox eventSource = (JCheckBox) event.getSource(); if (eventSource == showGroupCheckBox) { group.visible = showGroupCheckBox.isSelected(); } else if (eventSource == showGraphicInfoCheckBox) { group.info = showGraphicInfoCheckBox.isSelected(); } } } } graph.notifyAboutGroupsChange(null); } }; colorComboBox.addItemListener(propItemListener); shapeComboBox.addItemListener(propItemListener); showGroupCheckBox.addItemListener(propItemListener); showGraphicInfoCheckBox.addItemListener(propItemListener); showGroupfreeNodesCheckBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { graph.getGroup(0).visible = showGroupfreeNodesCheckBox.isSelected(); graph.notifyAboutGroupsChange(null); } }); ActionListener propActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JButton botton = (JButton) event.getSource(); Group group = getGroupFromListIndex(groupsList.getSelectedIndex()); if (group != null) { for (GraphVertex graphVertex : group) { if (botton == showLabelsButton) { graphVertex.setShowName(NameVisibility.Priority.GROUPS, true); } else if (botton == hideLabelsButton) { graphVertex.setShowName(NameVisibility.Priority.GROUPS, false); } } graph.notifyAboutGroupsChange(null); } } }; showLabelsButton.addActionListener(propActionListener); hideLabelsButton.addActionListener(propActionListener); newButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { String newGroupName = JOptionPane.showInputDialog(null, "Enter a name", "Name of the new group", JOptionPane.QUESTION_MESSAGE); if (newGroupName != null) { if (graph.getGroup(newGroupName) == null) { graph.addGroup(new Group(newGroupName, graph)); } } } }); editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { Group group = getGroupFromListIndex(groupsList.getSelectedIndex()); if (group != null) { DialogEditGroup dialog = new DialogEditGroup(graph, group); dialog.setModal(true); dialog.setVisible(true); } } }); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index > 0 && index < graph.getNumberOfGroups() - 1) { graph.removeGroup(index); } } }); upButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index < graph.getNumberOfGroups() - 1) { graph.moveGroupUp(index); groupsList.setSelectedIndex(index - 1); } } }); downButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index < graph.getNumberOfGroups() - 1) { graph.moveGroupDown(index); groupsList.setSelectedIndex(index + 1); } } }); }
11
Code Sample 1: public void copyFile(final File sourceFile, final File destinationFile) throws FileIOException { final FileChannel sourceChannel; try { sourceChannel = new FileInputStream(sourceFile).getChannel(); } catch (FileNotFoundException exception) { final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile; LOGGER.fatal(message); throw fileIOException(message, sourceFile, exception); } final FileChannel destinationChannel; try { destinationChannel = new FileOutputStream(destinationFile).getChannel(); } catch (FileNotFoundException exception) { final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile; LOGGER.fatal(message); throw fileIOException(message, destinationFile, exception); } try { destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (Exception exception) { final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile; LOGGER.fatal(message); throw fileIOException(message, null, exception); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException exception) { LOGGER.error("closing source", exception); } } if (destinationChannel != null) { try { destinationChannel.close(); } catch (IOException exception) { LOGGER.error("closing destination", exception); } } } } Code Sample 2: protected void initGame() { try { for (File fonte : files) { String absolutePath = outputDir.getAbsolutePath(); String separator = System.getProperty("file.separator"); String name = fonte.getName(); String destName = name.substring(0, name.length() - 3); File destino = new File(absolutePath + separator + destName + "jme"); FileInputStream reader = new FileInputStream(fonte); OutputStream writer = new FileOutputStream(destino); conversor.setProperty("mtllib", fonte.toURL()); conversor.convert(reader, writer); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } super.finish(); }
00
Code Sample 1: protected void convertInternal(InputStream inputStream, DocumentFormat inputFormat, OutputStream outputStream, DocumentFormat outputFormat) { File inputFile = null; File outputFile = null; try { inputFile = File.createTempFile("document", "." + inputFormat.getFileExtension()); OutputStream inputFileStream = null; try { inputFileStream = new FileOutputStream(inputFile); IOUtils.copy(inputStream, inputFileStream); } finally { IOUtils.closeQuietly(inputFileStream); } outputFile = File.createTempFile("document", "." + outputFormat.getFileExtension()); convert(inputFile, inputFormat, outputFile, outputFormat); InputStream outputFileStream = null; try { outputFileStream = new FileInputStream(outputFile); IOUtils.copy(outputFileStream, outputStream); } finally { IOUtils.closeQuietly(outputFileStream); } } catch (IOException ioException) { throw new OpenOfficeException("conversion failed", ioException); } finally { if (inputFile != null) { inputFile.delete(); } if (outputFile != null) { outputFile.delete(); } } } Code Sample 2: public void delete(DeleteInterceptorChain chain, DistinguishedName dn, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue(); PreparedStatement ps = con.prepareStatement(this.deleteSQL); ps.setString(1, uid); ps.executeUpdate(); 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); } }
11
Code Sample 1: public static void downloadJars(IProject project, String repositoryUrl, String jarDirectory, String[] jars) { try { File tmpFile = null; for (String jar : jars) { try { tmpFile = File.createTempFile("tmpPlugin_", ".zip"); URL url = new URL(repositoryUrl + jarDirectory + jar); String destFilename = new File(url.getFile()).getName(); File destFile = new File(project.getLocation().append("lib").append(jarDirectory).toFile(), destFilename); InputStream inputStream = null; FileOutputStream outputStream = null; try { URLConnection urlConnection = url.openConnection(); inputStream = urlConnection.getInputStream(); outputStream = new FileOutputStream(tmpFile); IOUtils.copy(inputStream, outputStream); } finally { if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } } } catch (Exception ex) { ex.printStackTrace(); } } Code Sample 2: private void writeToFile(Body b, File mime4jFile) throws FileNotFoundException, IOException { if (b instanceof TextBody) { String charset = CharsetUtil.toJavaCharset(b.getParent().getCharset()); if (charset == null) { charset = "ISO8859-1"; } OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((TextBody) b).getReader(), out, charset); } else { OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((BinaryBody) b).getInputStream(), out); } }
11
Code Sample 1: @Override public String fetchElectronicEdition(Publication pub) { final String url = baseURL + pub.getKey() + ".html"; logger.info("fetching pub ee from local cache at: " + url); HttpMethod method = null; String responseBody = ""; method = new GetMethod(url); method.setFollowRedirects(true); try { if (StringUtils.isNotBlank(method.getURI().getScheme())) { InputStream is = null; StringWriter writer = new StringWriter(); try { client.executeMethod(method); Header contentType = method.getResponseHeader("Content-Type"); if (contentType != null && StringUtils.isNotBlank(contentType.getValue()) && contentType.getValue().indexOf("text/html") >= 0) { is = method.getResponseBodyAsStream(); IOUtils.copy(is, writer); responseBody = writer.toString(); } else { logger.info("ignoring non-text/html response from page: " + url + " content-type:" + contentType); } } catch (HttpException he) { logger.error("Http error connecting to '" + url + "'"); logger.error(he.getMessage()); } catch (IOException ioe) { logger.error("Unable to connect to '" + url + "'"); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(writer); } } } catch (URIException e) { logger.error(e); } finally { method.releaseConnection(); } return responseBody; } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { URL url; URLConnection urlConn; DataOutputStream dos; DataInputStream dis; monitor.beginTask("Uploading log to placelab.org", 100); StringBuffer dfsb = new SimpleDateFormat("M/dd/yyyy").format(new java.util.Date(), new StringBuffer(), new FieldPosition(0)); String dateStr = dfsb.toString(); monitor.subTask("Connecting"); if (monitor.isCanceled()) throw new InterruptedException(); url = new URL(urlString); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); dos = new DataOutputStream(urlConn.getOutputStream()); monitor.worked(10); monitor.subTask("Encoding headers"); if (monitor.isCanceled()) throw new InterruptedException(); String args = "username=" + URLEncoder.encode(username) + "&" + "passwd=" + URLEncoder.encode(passwd) + "&" + "readDisclaimer=agree&" + "cvt_to_ns=true&" + "trace_device=" + URLEncoder.encode(device) + "&" + "trace_descr=" + URLEncoder.encode(description) + "&" + "mailBack=on&" + "simple_output=true&" + "trace_date=" + URLEncoder.encode(dateStr) + "&" + "trace_data="; if (header != null) { args = args + URLEncoder.encode(header); } System.out.println("upload args = " + args); dos.writeBytes(args); monitor.worked(5); monitor.subTask("Sending log"); if (monitor.isCanceled()) throw new InterruptedException(); File f = new File(file); long numBytes = f.length(); FileInputStream is = new FileInputStream(file); boolean done = false; byte[] buf = new byte[1024]; while (!done) { int cnt = is.read(buf, 0, buf.length); if (cnt == -1) { done = true; } else { if (monitor.isCanceled()) throw new InterruptedException(); dos.writeBytes(URLEncoder.encode(new String(buf, 0, cnt))); Logger.println(URLEncoder.encode(new String(buf, 0, cnt)), Logger.HIGH); monitor.worked((int) (((double) cnt / (double) numBytes) * 80)); } } is.close(); dos.flush(); dos.close(); monitor.subTask("getting response from placelab.org"); if (monitor.isCanceled()) throw new InterruptedException(); dis = new DataInputStream(urlConn.getInputStream()); StringBuffer sb = new StringBuffer(); done = false; while (!done) { int read = dis.read(buf, 0, buf.length); if (read == -1) { done = true; } else { sb.append(new String(buf, 0, read)); } } String s = sb.toString(); dis.close(); Logger.println("Got back " + s, Logger.LOW); if (s.equals("SUCCESS")) { Logger.println("Whoo!!!", Logger.HIGH); } else { Logger.println("Post Error!", Logger.HIGH); throw new InvocationTargetException(new PlacelabOrgFailure(s)); } monitor.worked(5); monitor.done(); } catch (InterruptedException ie) { throw new InterruptedException(); } catch (Exception e) { throw new InvocationTargetException(e); } }
11
Code Sample 1: private File prepareFileForUpload(File source, String s3key) throws IOException { File tmp = File.createTempFile("dirsync", ".tmp"); tmp.deleteOnExit(); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(source); out = new DeflaterOutputStream(new CryptOutputStream(new FileOutputStream(tmp), cipher, getDataEncryptionKey())); IOUtils.copy(in, out); in.close(); out.close(); return tmp; } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } Code Sample 2: 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(); } }
11
Code Sample 1: public String generateFilename() { MessageDigest md; byte[] sha1hash = new byte[40]; Random r = new Random(); String fileName = ""; String token = ""; while (true) { token = Long.toString(Math.abs(r.nextLong()), 36) + Long.toString(System.currentTimeMillis()); try { md = MessageDigest.getInstance("SHA-1"); md.update(token.getBytes("iso-8859-1"), 0, token.length()); sha1hash = md.digest(); } catch (Exception e) { log.log(Level.WARNING, e.getMessage(), e); } fileName = convertToHex(sha1hash); if (!new File(Configuration.ImageUploadPath + fileName).exists()) { break; } } return fileName; } Code Sample 2: public static String md5(String texto) { String resultado; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(texto.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); resultado = hash.toString(16); if (resultado.length() < 32) { char chars[] = new char[32 - resultado.length()]; Arrays.fill(chars, '0'); resultado = new String(chars) + resultado; } } catch (NoSuchAlgorithmException e) { resultado = e.toString(); } return resultado; }
00
Code Sample 1: public static String getImportFileBody(String fileName, HttpSession session) { FTPClient ftp = new FTPClient(); CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user"); String fileTransferFolder = CofaxToolsServlet.fileTransferFolder; String importFTPServer = (String) user.workingPubConfigElementsHash.get("IMPORTFTPSERVER"); String importFTPLogin = (String) user.workingPubConfigElementsHash.get("IMPORTFTPLOGIN"); String importFTPPassword = (String) user.workingPubConfigElementsHash.get("IMPORTFTPPASSWORD"); String importFTPFilePath = (String) user.workingPubConfigElementsHash.get("IMPORTFTPFILEPATH"); String body = (""); try { int reply; ftp.connect(importFTPServer); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody connecting to server " + importFTPServer); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return ("CofaxToolsFTP getImportFileBody ERROR: FTP server refused connection."); } else { ftp.login(importFTPLogin, importFTPPassword); } try { boolean change = ftp.changeWorkingDirectory(importFTPFilePath); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody changing to directory: " + importFTPFilePath); CofaxToolsUtil.log("Results: " + change); OutputStream output; output = new FileOutputStream(fileTransferFolder + fileName); boolean retrieve = ftp.retrieveFile(fileName, output); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody retrieving file: " + fileName); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody results: " + change); output.close(); body = CofaxToolsUtil.readFile(fileTransferFolder + fileName, true); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody deleting remote file: " + importFTPFilePath + fileName); boolean delete = ftp.deleteFile(importFTPFilePath + fileName); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody results: " + delete); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody disconnecting from server:" + importFTPServer); ftp.logout(); ftp.disconnect(); } catch (java.io.IOException e) { return ("CofaxToolsFTP getImportFileBody ERROR: cannot write file: " + fileName); } } catch (IOException e) { return ("CofaxToolsFTP getImportFileBody ERROR: could not connect to server: " + e); } return (body); } Code Sample 2: public static Element postMessage() throws Exception { final URL theUrl = getHostURL(); lf.debug("url = " + theUrl.toExternalForm()); final HttpURLConnection urlConn = (HttpURLConnection) (theUrl).openConnection(); urlConn.setRequestMethod("POST"); urlConn.setDoInput(true); urlConn.setDoOutput(true); final BufferedOutputStream bos = new BufferedOutputStream(urlConn.getOutputStream()); final InputStream bis = urlConn.getInputStream(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int count = 0; while ((count = bis.read(buffer)) > -1) { baos.write(buffer, 0, count); } final SAXBuilder sb = new SAXBuilder(); lf.debug("Received XML response from server: " + baos.toString()); return sb.build(new StringReader(baos.toString())).getRootElement(); }
00
Code Sample 1: private void findFile() throws SchedulerException { java.io.InputStream f = null; String furl = null; File file = new File(getFileName()); if (!file.exists()) { URL url = classLoadHelper.getResource(getFileName()); if (url != null) { try { furl = URLDecoder.decode(url.getPath(), "UTF-8"); file = new File(furl); f = url.openStream(); } catch (java.io.UnsupportedEncodingException uee) { } catch (IOException ignor) { } } } else { try { f = new java.io.FileInputStream(file); } catch (FileNotFoundException e) { } } if (f == null && isFailOnFileNotFound()) { throw new SchedulerException("File named '" + getFileName() + "' does not exist. f == null && isFailOnFileNotFound()"); } else if (f == null) { getLog().warn("File named '" + getFileName() + "' does not exist. f == null"); } else { fileFound = true; try { if (furl != null) this.filePath = furl; else this.filePath = file.getAbsolutePath(); f.close(); } catch (IOException ioe) { getLog().warn("Error closing jobs file " + getFileName(), ioe); } } } 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: private void detachFile(File file, Block b) throws IOException { File tmpFile = volume.createDetachFile(b, file.getName()); try { IOUtils.copyBytes(new FileInputStream(file), new FileOutputStream(tmpFile), 16 * 1024, true); if (file.length() != tmpFile.length()) { throw new IOException("Copy of file " + file + " size " + file.length() + " into file " + tmpFile + " resulted in a size of " + tmpFile.length()); } FileUtil.replaceFile(tmpFile, file); } catch (IOException e) { boolean done = tmpFile.delete(); if (!done) { DataNode.LOG.info("detachFile failed to delete temporary file " + tmpFile); } throw e; } } Code Sample 2: public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { URL url; URLConnection urlConn; DataOutputStream dos; DataInputStream dis; monitor.beginTask("Uploading log to placelab.org", 100); StringBuffer dfsb = new SimpleDateFormat("M/dd/yyyy").format(new java.util.Date(), new StringBuffer(), new FieldPosition(0)); String dateStr = dfsb.toString(); monitor.subTask("Connecting"); if (monitor.isCanceled()) throw new InterruptedException(); url = new URL(urlString); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); dos = new DataOutputStream(urlConn.getOutputStream()); monitor.worked(10); monitor.subTask("Encoding headers"); if (monitor.isCanceled()) throw new InterruptedException(); String args = "username=" + URLEncoder.encode(username) + "&" + "passwd=" + URLEncoder.encode(passwd) + "&" + "readDisclaimer=agree&" + "cvt_to_ns=true&" + "trace_device=" + URLEncoder.encode(device) + "&" + "trace_descr=" + URLEncoder.encode(description) + "&" + "mailBack=on&" + "simple_output=true&" + "trace_date=" + URLEncoder.encode(dateStr) + "&" + "trace_data="; if (header != null) { args = args + URLEncoder.encode(header); } System.out.println("upload args = " + args); dos.writeBytes(args); monitor.worked(5); monitor.subTask("Sending log"); if (monitor.isCanceled()) throw new InterruptedException(); File f = new File(file); long numBytes = f.length(); FileInputStream is = new FileInputStream(file); boolean done = false; byte[] buf = new byte[1024]; while (!done) { int cnt = is.read(buf, 0, buf.length); if (cnt == -1) { done = true; } else { if (monitor.isCanceled()) throw new InterruptedException(); dos.writeBytes(URLEncoder.encode(new String(buf, 0, cnt))); Logger.println(URLEncoder.encode(new String(buf, 0, cnt)), Logger.HIGH); monitor.worked((int) (((double) cnt / (double) numBytes) * 80)); } } is.close(); dos.flush(); dos.close(); monitor.subTask("getting response from placelab.org"); if (monitor.isCanceled()) throw new InterruptedException(); dis = new DataInputStream(urlConn.getInputStream()); StringBuffer sb = new StringBuffer(); done = false; while (!done) { int read = dis.read(buf, 0, buf.length); if (read == -1) { done = true; } else { sb.append(new String(buf, 0, read)); } } String s = sb.toString(); dis.close(); Logger.println("Got back " + s, Logger.LOW); if (s.equals("SUCCESS")) { Logger.println("Whoo!!!", Logger.HIGH); } else { Logger.println("Post Error!", Logger.HIGH); throw new InvocationTargetException(new PlacelabOrgFailure(s)); } monitor.worked(5); monitor.done(); } catch (InterruptedException ie) { throw new InterruptedException(); } catch (Exception e) { throw new InvocationTargetException(e); } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void copyFile(File 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 static String getHashedPassword(String password) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); BigInteger hashedInt = new BigInteger(1, digest.digest()); return String.format("%1$032X", hashedInt); } catch (NoSuchAlgorithmException nsae) { System.err.println(nsae.getMessage()); } return ""; } Code Sample 2: public Document getSdlDomResource(String aResourceName) throws SdlException { InputStream in = null; try { URL url = getDeploymentContext().getResourceURL(aResourceName); if (url == null) { return null; } else { in = url.openStream(); return getSdlParser().loadSdlDocument(in, null); } } catch (Throwable t) { logger.error("Error: unable to load: " + aResourceName + " from " + getDeploymentContext().getDeploymentLocation()); throw new SdlDeploymentException(MessageFormat.format("unable to load: {0} from {1}", new Object[] { aResourceName, getDeploymentContext().getDeploymentLocation() }), t); } finally { SdlCloser.close(in); } }
11
Code Sample 1: @Override public void run() { try { File[] inputFiles = new File[this.previousFiles != null ? this.previousFiles.length + 1 : 1]; File copiedInput = new File(this.randomFolder, this.inputFile.getName()); IOUtils.copyFile(this.inputFile, copiedInput); inputFiles[inputFiles.length - 1] = copiedInput; if (previousFiles != null) { for (int i = 0; i < this.previousFiles.length; i++) { File prev = this.previousFiles[i]; File copiedPrev = new File(this.randomFolder, prev.getName()); IOUtils.copyFile(prev, copiedPrev); inputFiles[i] = copiedPrev; } } org.happycomp.radiog.Activator activator = org.happycomp.radiog.Activator.getDefault(); if (this.exportedMP3File != null) { EncodingUtils.encodeToWavAndThenMP3(inputFiles, this.exportedWavFile, this.exportedMP3File, this.deleteOnExit, this.randomFolder, activator.getCommandsMap()); } else { EncodingUtils.encodeToWav(inputFiles, this.exportedWavFile, randomFolder, activator.getCommandsMap()); } if (encodeMonitor != null) { encodeMonitor.setEncodingFinished(true); } } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } Code Sample 2: private static void serveHTML() throws Exception { Bus bus = BusFactory.getDefaultBus(); DestinationFactoryManager dfm = bus.getExtension(DestinationFactoryManager.class); DestinationFactory df = dfm.getDestinationFactory("http://cxf.apache.org/transports/http/configuration"); EndpointInfo ei = new EndpointInfo(); ei.setAddress("http://localhost:8080/test.html"); Destination d = df.getDestination(ei); d.setMessageObserver(new MessageObserver() { public void onMessage(Message message) { try { ExchangeImpl ex = new ExchangeImpl(); ex.setInMessage(message); Conduit backChannel = message.getDestination().getBackChannel(message, null, null); MessageImpl res = new MessageImpl(); res.put(Message.CONTENT_TYPE, "text/html"); backChannel.prepare(res); OutputStream out = res.getContent(OutputStream.class); FileInputStream is = new FileInputStream("test.html"); IOUtils.copy(is, out, 2048); out.flush(); out.close(); is.close(); backChannel.close(res); } catch (Exception e) { e.printStackTrace(); } } }); }
11
Code Sample 1: public static void fileCopy(File sourceFile, File destFile) throws IOException { FileChannel source = null; FileChannel destination = null; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(sourceFile); fos = new FileOutputStream(destFile); source = fis.getChannel(); destination = fos.getChannel(); destination.transferFrom(source, 0, source.size()); } finally { fis.close(); fos.close(); if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public void addEntry(InputStream jis, JarEntry entry) throws IOException, URISyntaxException { File target = new File(this.target.getPath() + entry.getName()).getAbsoluteFile(); if (!target.exists()) { target.createNewFile(); } if ((new File(this.source.toURI())).isDirectory()) { File sourceEntry = new File(this.source.getPath() + entry.getName()); FileInputStream fis = new FileInputStream(sourceEntry); byte[] classBytes = new byte[fis.available()]; fis.read(classBytes); (new FileOutputStream(target)).write(classBytes); } else { readwriteStreams(jis, (new FileOutputStream(target))); } }
00
Code Sample 1: private void inject(int x, int y) throws IOException { Tag source = data.getTag(); Log.event(Log.DEBUG_INFO, "source: " + source.getString()); if (source == Tag.ORGANISM) { String seed = data.readString(); data.readTag(Tag.STREAM); injectCodeTape(data.getIn(), seed, x, y); } else if (source == Tag.URL) { String url = data.readString(); String seed = url.substring(url.lastIndexOf('.') + 1); BufferedReader urlIn = null; try { urlIn = new BufferedReader(new InputStreamReader(new URL(url).openStream())); injectCodeTape(urlIn, seed, x, y); } finally { if (urlIn != null) urlIn.close(); } } else data.writeString("unknown organism source: " + source.getString()); } Code Sample 2: public static String filtraDoc(HttpServletRequest request, String resource, Repository rep, String template) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader br = null; int sec = 0; try { URL url = rep.getResource(request, resource); if (url == null) { return "Documento " + rep.dir + "/" + resource + " no encontrado"; } br = new BufferedReader(new InputStreamReader(url.openStream(), rep.encoding)); String line = br.readLine(); while (line != null) { int pos = line.indexOf("KAttach("); if (pos > -1) { sb.append(attach(request, ++sec, line, pos, template)); } else { line = line.replaceAll("%20", "-"); sb.append(new String(line.getBytes(rep.encoding), Config.getMng().getEncoding())).append("\n"); } line = br.readLine(); } } finally { if (br != null) br.close(); } return sb.toString(); }
00
Code Sample 1: private List<File> ungzipFile(File directory, File compressedFile) throws IOException { List<File> files = new ArrayList<File>(); TarArchiveInputStream in = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(compressedFile))); try { TarArchiveEntry entry = in.getNextTarEntry(); while (entry != null) { if (entry.isDirectory()) { log.warn("TAR archive contains directories which are being ignored"); entry = in.getNextTarEntry(); continue; } String fn = new File(entry.getName()).getName(); if (fn.startsWith(".")) { log.warn("TAR archive contains a hidden file which is being ignored"); entry = in.getNextTarEntry(); continue; } File targetFile = new File(directory, fn); if (targetFile.exists()) { log.warn("TAR archive contains duplicate filenames, only the first is being extracted"); entry = in.getNextTarEntry(); continue; } files.add(targetFile); log.debug("Extracting file: " + entry.getName() + " to: " + targetFile.getAbsolutePath()); OutputStream fout = new BufferedOutputStream(new FileOutputStream(targetFile)); InputStream entryIn = new FileInputStream(entry.getFile()); IOUtils.copy(entryIn, fout); fout.close(); entryIn.close(); } } finally { in.close(); } return files; } Code Sample 2: protected void configure() { Enumeration<URL> resources = null; try { resources = classLoader.getResources(resourceName); } catch (IOException e) { binder().addError(e.getMessage(), e); return; } int resourceCount = 0; while (resources.hasMoreElements()) { URL url = resources.nextElement(); log.debug(url + " ..."); try { InputStream stream = url.openStream(); Properties props = new Properties(); props.load(stream); resourceCount++; addComponentsFromProperties(props, classLoader); } catch (IOException e) { binder().addError(e.getMessage(), e); } } log.info("Added components from " + resourceCount + " resources."); }
11
Code Sample 1: public static String getBiopaxId(Reaction reaction) { String id = null; if (reaction.getId() > Reaction.NO_ID_ASSIGNED) { id = reaction.getId().toString(); } else { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(reaction.getTextualRepresentation().getBytes()); byte[] digestBytes = md.digest(); StringBuilder digesterSb = new StringBuilder(32); for (int i = 0; i < digestBytes.length; i++) { int intValue = digestBytes[i] & 0xFF; if (intValue < 0x10) digesterSb.append('0'); digesterSb.append(Integer.toHexString(intValue)); } id = digesterSb.toString(); } catch (NoSuchAlgorithmException e) { } } return id; } Code Sample 2: public Attributes getAttributes() throws SchemaViolationException, NoSuchAlgorithmException, UnsupportedEncodingException { BasicAttributes outAttrs = new BasicAttributes(true); BasicAttribute oc = new BasicAttribute("objectclass", "inetOrgPerson"); oc.add("organizationalPerson"); oc.add("person"); outAttrs.put(oc); if (lastName != null && firstName != null) { outAttrs.put("sn", lastName); outAttrs.put("givenName", firstName); outAttrs.put("cn", firstName + " " + lastName); } else { throw new SchemaViolationException("user must have surname"); } if (password != null) { MessageDigest sha = MessageDigest.getInstance("md5"); sha.reset(); sha.update(password.getBytes("utf-8")); byte[] digest = sha.digest(); String hash = Base64.encodeBase64String(digest); outAttrs.put("userPassword", "{MD5}" + hash); } if (email != null) { outAttrs.put("mail", email); } return (Attributes) outAttrs; }
11
Code Sample 1: public void testRenderRules() { try { MappingManager manager = new MappingManager(); OWLOntologyManager omanager = OWLManager.createOWLOntologyManager(); OWLOntology srcOntology; OWLOntology targetOntology; manager.loadMapping(rulesDoc.toURL()); srcOntology = omanager.loadOntologyFromPhysicalURI(srcURI); targetOntology = omanager.loadOntologyFromPhysicalURI(targetURI); manager.setSourceOntology(srcOntology); manager.setTargetOntology(targetOntology); Graph srcGraph = manager.getSourceGraph(); Graph targetGraph = manager.getTargetGraph(); System.out.println("Starting to render..."); FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.BLUES); factory.visit(srcGraph); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); System.out.println("View updated with graph..."); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); System.out.println("Finished writing"); writer.close(); System.out.println("Finished render... XML is:"); System.out.println(writer.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (OWLOntologyCreationException e) { e.printStackTrace(); } } Code Sample 2: private InputStream open(String url) throws IOException { debug(url); if (!useCache) { return new URL(url).openStream(); } File f = new File(System.getProperty("java.io.tmpdir", "."), Digest.SHA1.encrypt(url) + ".xml"); debug("Cache : " + f); if (f.exists()) { return new FileInputStream(f); } InputStream in = new URL(url).openStream(); OutputStream out = new FileOutputStream(f); IOUtils.copyTo(in, out); out.flush(); out.close(); in.close(); return new FileInputStream(f); }
00
Code Sample 1: public File mergeDoc(URL urlDoc, File fOutput, boolean bMulti) throws Exception { if (s_log.isTraceEnabled()) trace(0, "Copying from " + urlDoc.toString() + " to " + fOutput.toString()); File fOut = null; InputStream is = null; try { is = urlDoc.openStream(); fOut = mergeDoc(is, fOutput, bMulti); } finally { is.close(); } return fOut; } Code Sample 2: public static Vector getVectorForm(String u, String usr, String pwd) { Vector response = new Vector(); logger.debug("Attempting to call: " + u); logger.debug("Creating Authenticator: usr=" + usr + ", pwd=" + pwd); Authenticator.setDefault(new CustomAuthenticator(usr, pwd)); try { URL url = new URL(u); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { response.add(str); } in.close(); logger.debug("Response: " + response.toString()); } catch (MalformedURLException e) { logger.error(e); logger.trace(e, e); } catch (IOException e) { logger.error(e); logger.trace(e, e); } return response; }
00
Code Sample 1: public void checkAndDownload(String statsUrl, RDFStatsUpdatableModelExt stats, Date lastDownload, boolean onlyIfNewer) throws DataSourceMonitorException { if (log.isInfoEnabled()) log.info("Checking if update required for statistics of " + ds + "..."); HttpURLConnection urlConnection; try { URL url = new URL(statsUrl); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(CONNECT_TIMEOUT); urlConnection.setReadTimeout(READ_TIMEOUT); int statusCode = urlConnection.getResponseCode(); if (statusCode / 100 != 2) { String msg = urlConnection.getResponseMessage(); throw new DataSourceMonitorException(statsUrl + " returned HTTP " + statusCode + (msg != null ? msg : "") + "."); } } catch (Exception e) { throw new DataSourceMonitorException("Failed to connect to " + statsUrl + ".", e); } long lastModified = urlConnection.getLastModified(); boolean newer = lastDownload == null || lastModified == 0 || lastModified - TIMING_GAP > lastDownload.getTime(); if (newer || !onlyIfNewer) { Model newStats = retrieveModelData(urlConnection, ds); Date retrievedTimestamp = Calendar.getInstance().getTime(); Date modifiedTimestamp = (urlConnection.getLastModified() > 0) ? new Date(urlConnection.getLastModified()) : null; if (log.isInfoEnabled()) log.info("Attempt to import up-to-date " + ((modifiedTimestamp != null) ? "(from " + modifiedTimestamp + ") " : "") + "statistics for " + ds + "."); try { if (stats.updateFrom(RDFStatsModelFactory.create(newStats), onlyIfNewer)) stats.setLastDownload(ds.getSPARQLEndpointURL(), retrievedTimestamp); } catch (Exception e) { throw new DataSourceMonitorException("Failed to import statistics and set last download for " + ds + ".", e); } } else { if (log.isInfoEnabled()) log.info("Statistics for " + ds + " are up-to-date" + ((lastDownload != null) ? " (" + lastDownload + ")" : "")); } } Code Sample 2: public static Dimension getJPEGDimension(String urls) throws IOException { URL url; Dimension d = null; try { url = new URL(urls); InputStream fis = url.openStream(); if (fis.read() != 255 || fis.read() != 216) throw new RuntimeException("SOI (Start Of Image) marker 0xff 0xd8 missing"); while (fis.read() == 255) { int marker = fis.read(); int len = fis.read() << 8 | fis.read(); if (marker == 192) { fis.skip(1); int height = fis.read() << 8 | fis.read(); int width = fis.read() << 8 | fis.read(); d = new Dimension(width, height); break; } fis.skip(len - 2); } fis.close(); } catch (MalformedURLException e) { e.printStackTrace(); } return d; }
00
Code Sample 1: public static void main(String args[]) { String midletClass = null; ; File appletInputFile = null; File deviceInputFile = null; File midletInputFile = null; File htmlOutputFile = null; File appletOutputFile = null; File deviceOutputFile = null; File midletOutputFile = null; List params = new ArrayList(); for (int i = 0; i < args.length; i++) { params.add(args[i]); } Iterator argsIterator = params.iterator(); while (argsIterator.hasNext()) { String arg = (String) argsIterator.next(); argsIterator.remove(); if ((arg.equals("--help")) || (arg.equals("-help"))) { System.out.println(usage()); System.exit(0); } else if (arg.equals("--midletClass")) { midletClass = (String) argsIterator.next(); argsIterator.remove(); } else if (arg.equals("--appletInput")) { appletInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--deviceInput")) { deviceInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--midletInput")) { midletInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--htmlOutput")) { htmlOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--appletOutput")) { appletOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--deviceOutput")) { deviceOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--midletOutput")) { midletOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } } if (midletClass == null || appletInputFile == null || deviceInputFile == null || midletInputFile == null || htmlOutputFile == null || appletOutputFile == null || deviceOutputFile == null || midletOutputFile == null) { System.out.println(usage()); System.exit(0); } try { DeviceImpl device = null; String descriptorLocation = null; JarFile jar = new JarFile(deviceInputFile); for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorLocation = entry; break; } } if (descriptorLocation != null) { EmulatorContext context = new EmulatorContext() { private DisplayComponent displayComponent = new NoUiDisplayComponent(); private InputMethod inputMethod = new J2SEInputMethod(); private DeviceDisplay deviceDisplay = new J2SEDeviceDisplay(this); private FontManager fontManager = new J2SEFontManager(); private DeviceComponent deviceComponent = new SwingDeviceComponent(true); public DisplayComponent getDisplayComponent() { return displayComponent; } public InputMethod getDeviceInputMethod() { return inputMethod; } public DeviceDisplay getDeviceDisplay() { return deviceDisplay; } public FontManager getDeviceFontManager() { return fontManager; } public InputStream getResourceAsStream(String name) { return MIDletBridge.getCurrentMIDlet().getClass().getResourceAsStream(name); } public DeviceComponent getDeviceComponent() { return deviceComponent; } }; URL[] urls = new URL[1]; urls[0] = deviceInputFile.toURI().toURL(); ClassLoader classLoader = new ExtensionsClassLoader(urls, urls.getClass().getClassLoader()); device = DeviceImpl.create(context, classLoader, descriptorLocation, J2SEDevice.class); } if (device == null) { System.out.println("Error parsing device package: " + descriptorLocation); System.exit(0); } createHtml(htmlOutputFile, device, midletClass, midletOutputFile, appletOutputFile, deviceOutputFile); createMidlet(midletInputFile.toURI().toURL(), midletOutputFile); IOUtils.copyFile(appletInputFile, appletOutputFile); IOUtils.copyFile(deviceInputFile, deviceOutputFile); } catch (IOException ex) { ex.printStackTrace(); } System.exit(0); } Code Sample 2: private synchronized void resetUserDictionary() { if (this.fChecker == null) return; if (this.fUserDictionary != null) { this.fChecker.removeDictionary(this.fUserDictionary); this.fUserDictionary.unload(); this.fUserDictionary = null; } IPreferenceStore store = SpellActivator.getDefault().getPreferenceStore(); String filePath = store.getString(PreferenceConstants.SPELLING_USER_DICTIONARY); IStringVariableManager variableManager = VariablesPlugin.getDefault().getStringVariableManager(); try { filePath = variableManager.performStringSubstitution(filePath); } catch (CoreException e) { SpellActivator.log(e); return; } if (filePath.length() > 0) { try { File file = new File(filePath); if (!file.exists() && !file.createNewFile()) return; final URL url = new URL("file", null, filePath); InputStream stream = url.openStream(); if (stream != null) { try { this.fUserDictionary = new PersistentSpellDictionary(url); this.fChecker.addDictionary(this.fUserDictionary); } finally { stream.close(); } } } catch (MalformedURLException exception) { } catch (IOException exception) { } } }
11
Code Sample 1: public static void fixEol(File fin) throws IOException { File fout = File.createTempFile(fin.getName(), ".fixEol", fin.getParentFile()); FileChannel in = new FileInputStream(fin).getChannel(); if (0 != in.size()) { FileChannel out = new FileOutputStream(fout).getChannel(); byte[] eol = AStringUtilities.systemNewLine.getBytes(); ByteBuffer bufOut = ByteBuffer.allocateDirect(1024 * eol.length); boolean previousIsCr = false; ByteBuffer buf = ByteBuffer.allocateDirect(1024); while (in.read(buf) > 0) { buf.limit(buf.position()); buf.position(0); while (buf.remaining() > 0) { byte b = buf.get(); if (b == '\r') { previousIsCr = true; bufOut.put(eol); } else { if (b == '\n') { if (!previousIsCr) bufOut.put(eol); } else bufOut.put(b); previousIsCr = false; } } bufOut.limit(bufOut.position()); bufOut.position(0); out.write(bufOut); bufOut.clear(); buf.clear(); } out.close(); } in.close(); fin.delete(); fout.renameTo(fin); } Code Sample 2: private void copyFile(File source, File destination) throws IOException { FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); fileOutputStream = new FileOutputStream(destination); int bufferLength = 1024; byte[] buffer = new byte[bufferLength]; int readCount = 0; while ((readCount = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, readCount); } } finally { if (fileInputStream != null) { fileInputStream.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } } }
11
Code Sample 1: public static List<String> extract(String zipFilePath, String destDirPath) throws IOException { List<String> list = null; ZipFile zip = new ZipFile(zipFilePath); try { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File destFile = new File(destDirPath, entry.getName()); if (entry.isDirectory()) { destFile.mkdirs(); } else { InputStream in = zip.getInputStream(entry); OutputStream out = new FileOutputStream(destFile); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); try { out.close(); } catch (IOException ioe) { ioe.getMessage(); } try { in.close(); } catch (IOException ioe) { ioe.getMessage(); } } } if (list == null) { list = new ArrayList<String>(); } list.add(destFile.getAbsolutePath()); } return list; } finally { try { zip.close(); } catch (Exception e) { e.getMessage(); } } } Code Sample 2: public void xtest7() throws Exception { System.out.println("Lowagie"); FileInputStream inputStream = new FileInputStream("C:/Temp/arquivo.pdf"); PDFBoxManager manager = new PDFBoxManager(); InputStream[] images = manager.toImage(inputStream, "jpeg"); int count = 0; for (InputStream image : images) { FileOutputStream outputStream = new FileOutputStream("C:/Temp/arquivo_" + count + ".jpg"); IOUtils.copy(image, outputStream); count++; outputStream.close(); } inputStream.close(); }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void copyFile(String original, String destination) throws Exception { File original_file = new File(original); File destination_file = new File(destination); if (!original_file.exists()) throw new Exception("File with path " + original + " does not exist."); if (destination_file.exists()) throw new Exception("File with path " + destination + " already exists."); FileReader in = new FileReader(original_file); FileWriter out = new FileWriter(destination_file); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
11
Code Sample 1: @RequestMapping(value = "/privatefiles/{file_name}") public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response, Principal principal) { try { Boolean validUser = false; final String currentUser = principal.getName(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!auth.getPrincipal().equals(new String("anonymousUser"))) { MetabolightsUser metabolightsUser = (MetabolightsUser) auth.getPrincipal(); if (metabolightsUser != null && metabolightsUser.isCurator()) validUser = true; } if (currentUser != null) { Study study = studyService.getBiiStudy(fileName, true); Collection<User> users = study.getUsers(); Iterator<User> iter = users.iterator(); while (iter.hasNext()) { User user = iter.next(); if (user.getUserName().equals(currentUser)) { validUser = true; break; } } } if (!validUser) throw new RuntimeException(PropertyLookup.getMessage("Entry.notAuthorised")); try { InputStream is = new FileInputStream(privateFtpDirectory + fileName + ".zip"); response.setContentType("application/zip"); IOUtils.copy(is, response.getOutputStream()); } catch (Exception e) { throw new RuntimeException(PropertyLookup.getMessage("Entry.fileMissing")); } response.flushBuffer(); } catch (IOException ex) { logger.info("Error writing file to output stream. Filename was '" + fileName + "'"); throw new RuntimeException("IOError writing file to output stream"); } } Code Sample 2: public void doCompress(File[] files, File out, List<String> excludedKeys) { Map<String, File> map = new HashMap<String, File>(); String parent = FilenameUtils.getBaseName(out.getName()); for (File f : files) { CompressionUtil.list(f, parent, map, excludedKeys); } if (!map.isEmpty()) { FileOutputStream fos = null; ArchiveOutputStream aos = null; InputStream is = null; try { fos = new FileOutputStream(out); aos = getArchiveOutputStream(fos); for (Map.Entry<String, File> entry : map.entrySet()) { File file = entry.getValue(); ArchiveEntry ae = getArchiveEntry(file, entry.getKey()); aos.putArchiveEntry(ae); if (file.isFile()) { IOUtils.copy(is = new FileInputStream(file), aos); IOUtils.closeQuietly(is); is = null; } aos.closeArchiveEntry(); } aos.finish(); } catch (IOException ex) { ex.printStackTrace(); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(aos); IOUtils.closeQuietly(fos); } } }
11
Code Sample 1: public FileInputStream execute() { FacesContext faces = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse(); String pdfPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/pdf"); try { FileOutputStream outputStream = new FileOutputStream(pdfPath + "/driveTogether.pdf"); PdfWriter writer = PdfWriter.getInstance(doc, outputStream); doc.open(); String pfad = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/pdf/template.pdf"); logger.info("Loading PDF-Template: " + pfad); PdfReader reader = new PdfReader(pfad); PdfImportedPage page = writer.getImportedPage(reader, 1); PdfContentByte cb = writer.getDirectContent(); cb.addTemplate(page, 0, 0); doHeader(); doParagraph(trip, forUser); doc.close(); fis = new FileInputStream(pdfPath + "/driveTogether.pdf"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return fis; } Code Sample 2: private ByteBuffer getByteBuffer(String resource) throws IOException { ClassLoader classLoader = this.getClass().getClassLoader(); InputStream in = classLoader.getResourceAsStream(resource); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); return ByteBuffer.wrap(out.toByteArray()); }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void extract(final File destDir, final Collection<ZipEntryInfo> entryInfos) throws IOException { if (destDir == null || CollectionUtils.isEmpty(entryInfos)) throw new IllegalArgumentException("One or parameter is null or empty!"); if (!destDir.exists()) destDir.mkdirs(); for (ZipEntryInfo entryInfo : entryInfos) { ZipEntry entry = entryInfo.getZipEntry(); InputStream in = entryInfo.getInputStream(); File entryDest = new File(destDir, entry.getName()); entryDest.getParentFile().mkdirs(); if (!entry.isDirectory()) { OutputStream out = new FileOutputStream(new File(destDir, entry.getName())); try { IOUtils.copy(in, out); out.flush(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } }
00
Code Sample 1: public static byte[] readUrl(URL url) { BufferedInputStream in = null; try { class Part { byte[] partData; int len; } in = new BufferedInputStream(url.openStream()); LinkedList<Part> parts = new LinkedList<Part>(); int len = 1; while (len > 0) { byte[] data = new byte[1024]; len = in.read(data); if (len > 0) { Part part = new Part(); part.partData = data; part.len = len; parts.add(part); } } int length = 0; for (Part part : parts) length += part.len; byte[] result = new byte[length]; int pos = 0; for (Part part : parts) { System.arraycopy(part.partData, 0, result, pos, part.len); pos += part.len; } return result; } catch (IOException e) { return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: public void copy(final File source, final File target) throws FileSystemException { LogHelper.logMethod(log, toObjectString(), "copy(), source = " + source + ", target = " + target); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); sourceChannel.transferTo(0L, sourceChannel.size(), targetChannel); log.info("Copied " + source + " to " + target); } catch (FileNotFoundException e) { throw new FileSystemException("Unexpected FileNotFoundException while copying a file", e); } catch (IOException e) { throw new FileSystemException("Unexpected IOException while copying a file", e); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException e) { log.error("IOException during source channel close after copy", e); } } if (targetChannel != null) { try { targetChannel.close(); } catch (IOException e) { log.error("IOException during target channel close after copy", e); } } } } Code Sample 2: public Controller(String m_hostname, String team, boolean m_shouldexit) throws InternalException { m_received_messages = new ConcurrentLinkedQueue<ReceivedMessage>(); m_fragmsgs = new ArrayList<String>(); m_customizedtaunts = new HashMap<Integer, String>(); m_nethandler = new CachingNetHandler(); m_drawingpanel = GLDrawableFactory.getFactory().createGLCanvas(new GLCapabilities()); m_user = System.getProperty("user.name"); m_chatbuffer = new StringBuffer(); this.m_shouldexit = m_shouldexit; isChatPaused = false; isRunning = true; m_lastbullet = 0; try { BufferedReader in = new BufferedReader(new FileReader(HogsConstants.FRAGMSGS_FILE)); String str; while ((str = in.readLine()) != null) { m_fragmsgs.add(str); } in.close(); } catch (IOException e) { e.printStackTrace(); } String newFile = PathFinder.getCustsFile(); boolean exists = (new File(newFile)).exists(); Reader reader = null; if (exists) { try { reader = new FileReader(newFile); } catch (FileNotFoundException e3) { e3.printStackTrace(); } } else { Object[] options = { "Yes, create a .hogsrc file", "No, use default taunts" }; int n = JOptionPane.showOptionDialog(m_window, "You do not have customized taunts in your home\n " + "directory. Would you like to create a customizable file?", "Hogs Customization", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if (n == 0) { try { FileChannel srcChannel = new FileInputStream(HogsConstants.CUSTS_TEMPLATE).getChannel(); FileChannel dstChannel; dstChannel = new FileOutputStream(newFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); reader = new FileReader(newFile); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { try { reader = new FileReader(HogsConstants.CUSTS_TEMPLATE); } catch (FileNotFoundException e3) { e3.printStackTrace(); } } } try { m_netengine = NetEngine.forHost(m_user, m_hostname, 1820, m_nethandler); m_netengine.start(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (NetException e) { e.printStackTrace(); } m_gamestate = m_netengine.getCurrentState(); m_gamestate.setInChatMode(false); m_gamestate.setController(this); try { readFromFile(reader); } catch (NumberFormatException e3) { e3.printStackTrace(); } catch (IOException e3) { e3.printStackTrace(); } catch (InternalException e3) { e3.printStackTrace(); } GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice m_graphicsdevice = ge.getDefaultScreenDevice(); m_window = new GuiFrame(m_drawingpanel, m_gamestate); m_graphics = null; try { m_graphics = new GraphicsEngine(m_drawingpanel, m_gamestate); } catch (InternalException e1) { e1.printStackTrace(); System.exit(0); } m_drawingpanel.addGLEventListener(m_graphics); m_physics = new Physics(); if (team == null) { team = HogsConstants.TEAM_NONE; } if (!(team.toLowerCase().equals(HogsConstants.TEAM_NONE) || team.toLowerCase().equals(HogsConstants.TEAM_RED) || team.toLowerCase().equals(HogsConstants.TEAM_BLUE))) { throw new InternalException("Invalid team name!"); } String orig_team = team; Craft local_craft = m_gamestate.getLocalCraft(); if (m_gamestate.getNumCrafts() == 0) { local_craft.setTeamname(team); } else if (m_gamestate.isInTeamMode()) { if (team == HogsConstants.TEAM_NONE) { int red_craft = m_gamestate.getNumOnTeam(HogsConstants.TEAM_RED); int blue_craft = m_gamestate.getNumOnTeam(HogsConstants.TEAM_BLUE); String new_team; if (red_craft > blue_craft) { new_team = HogsConstants.TEAM_BLUE; } else if (red_craft < blue_craft) { new_team = HogsConstants.TEAM_RED; } else { new_team = Math.random() > 0.5 ? HogsConstants.TEAM_BLUE : HogsConstants.TEAM_RED; } m_gamestate.getLocalCraft().setTeamname(new_team); } else { local_craft.setTeamname(team); } } else { local_craft.setTeamname(HogsConstants.TEAM_NONE); if (orig_team != null) { m_window.displayText("You cannot join a team, this is an individual game."); } } if (!local_craft.getTeamname().equals(HogsConstants.TEAM_NONE)) { m_window.displayText("You are joining the " + local_craft.getTeamname() + " team."); } m_drawingpanel.setSize(m_drawingpanel.getWidth(), m_drawingpanel.getHeight()); m_middlepos = new java.awt.Point(m_drawingpanel.getWidth() / 2, m_drawingpanel.getHeight() / 2); m_curpos = new java.awt.Point(m_drawingpanel.getWidth() / 2, m_drawingpanel.getHeight() / 2); GuiKeyListener k_listener = new GuiKeyListener(); GuiMouseListener m_listener = new GuiMouseListener(); m_window.addKeyListener(k_listener); m_drawingpanel.addKeyListener(k_listener); m_window.addMouseListener(m_listener); m_drawingpanel.addMouseListener(m_listener); m_window.addMouseMotionListener(m_listener); m_drawingpanel.addMouseMotionListener(m_listener); m_drawingpanel.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { m_window.setMouseTrapped(false); m_window.returnMouseToCenter(); } }); m_window.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { m_window.setMouseTrapped(false); m_window.returnMouseToCenter(); } }); m_window.requestFocus(); }
11
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 int delete(BusinessObject o) throws DAOException { int delete = 0; Item item = (Item) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_ITEM")); pst.setInt(1, item.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; }
11
Code Sample 1: public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new SoundFilter()); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.17")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "sonidos/" + file.getName(); String rutaRelativa = rutaDatos + "sonidos/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setSonidoURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonSonido.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); gui.getAudio().reproduceAudio(imagen); } catch (IOException ex) { ex.printStackTrace(); } } else { } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static List<ReactomeBean> getUrlData(URL url) throws IOException { List<ReactomeBean> beans = new ArrayList<ReactomeBean>(256); log.debug("Retreiving content for: " + url); StringBuffer content = new StringBuffer(4096); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { if (str.startsWith("#")) { continue; } StringTokenizer stringTokenizer = new StringTokenizer(str, "\t"); String InteractionAc = stringTokenizer.nextToken(); String reactomeId = stringTokenizer.nextToken(); ReactomeBean reactomeBean = new ReactomeBean(); reactomeBean.setReactomeID(reactomeId); reactomeBean.setInteractionAC(InteractionAc); beans.add(reactomeBean); } in.close(); return beans; } Code Sample 2: private void handleInterfaceReparented(String ipAddr, Parms eventParms) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (log.isDebugEnabled()) log.debug("interfaceReparented event received..."); if (ipAddr == null || eventParms == null) { log.warn(EventConstants.INTERFACE_REPARENTED_EVENT_UEI + " ignored - info incomplete - ip/parms: " + ipAddr + "/" + eventParms); return; } long oldNodeId = -1; long newNodeId = -1; String parmName = null; Value parmValue = null; String parmContent = null; Enumeration parmEnum = eventParms.enumerateParm(); while (parmEnum.hasMoreElements()) { Parm parm = (Parm) parmEnum.nextElement(); parmName = parm.getParmName(); parmValue = parm.getValue(); if (parmValue == null) continue; else parmContent = parmValue.getContent(); if (parmName.equals(EventConstants.PARM_OLD_NODEID)) { try { oldNodeId = Integer.valueOf(parmContent).intValue(); } catch (NumberFormatException nfe) { log.warn("Parameter " + EventConstants.PARM_OLD_NODEID + " cannot be non-numeric"); oldNodeId = -1; } } else if (parmName.equals(EventConstants.PARM_NEW_NODEID)) { try { newNodeId = Integer.valueOf(parmContent).intValue(); } catch (NumberFormatException nfe) { log.warn("Parameter " + EventConstants.PARM_NEW_NODEID + " cannot be non-numeric"); newNodeId = -1; } } } if (newNodeId == -1 || oldNodeId == -1) { log.warn("Unable to process 'interfaceReparented' event, invalid event parm."); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement reparentOutagesStmt = dbConn.prepareStatement(OutageConstants.DB_REPARENT_OUTAGES); reparentOutagesStmt.setLong(1, newNodeId); reparentOutagesStmt.setLong(2, oldNodeId); reparentOutagesStmt.setString(3, ipAddr); int count = reparentOutagesStmt.executeUpdate(); try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("Reparented " + count + " outages - ip: " + ipAddr + " reparented from " + oldNodeId + " to " + newNodeId); } catch (SQLException se) { log.warn("Rolling back transaction, reparent outages failed for newNodeId/ipAddr: " + newNodeId + "/" + ipAddr); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } reparentOutagesStmt.close(); } catch (SQLException se) { log.warn("SQL exception while handling \'interfaceReparented\'", se); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); try { FileChannel destinationChannel = new FileOutputStream(out).getChannel(); try { sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { destinationChannel.close(); } } finally { sourceChannel.close(); } } Code Sample 2: public static void main(String[] args) { FileInputStream fr = null; FileOutputStream fw = null; BufferedInputStream br = null; BufferedOutputStream bw = null; try { fr = new FileInputStream("D:/5.xls"); fw = new FileOutputStream("c:/Dxw.java"); br = new BufferedInputStream(fr); bw = new BufferedOutputStream(fw); int read = br.read(); while (read != -1) { bw.write(read); read = br.read(); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
00
Code Sample 1: private HashMap<String, GCVote> getVotes(ArrayList<String> waypoints, boolean blnSleepBeforeDownload) { if (blnSleepBeforeDownload) { try { Thread.sleep(PACKET_SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } final String strWaypoints = this.join(waypoints, ","); try { String strParameters = URLEncoder.encode("waypoints", "UTF-8") + "=" + URLEncoder.encode(strWaypoints, "UTF-8"); if (this.mstrUsername.length() > 0) { strParameters += "&" + URLEncoder.encode("userName", "UTF-8") + "=" + URLEncoder.encode(this.mstrUsername, "UTF-8"); if (this.mstrPassword.length() > 0) { strParameters += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(this.mstrPassword, "UTF-8"); } } final URL url = new URL(BASE_URL_GET_VOTE); URLConnection conn = url.openConnection(); conn.setDoOutput(true); final OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream()); osw.write(strParameters); osw.flush(); final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(false); saxParserFactory.setNamespaceAware(true); final SAXParser saxParser = saxParserFactory.newSAXParser(); final XMLReader xmlReader = saxParser.getXMLReader(); final GCVoteHandler gcVoteHandler = new GCVoteHandler(); xmlReader.setContentHandler(gcVoteHandler); xmlReader.parse(new InputSource(new InputStreamReader(conn.getInputStream()))); return gcVoteHandler.getVotes(); } catch (Exception e) { e.printStackTrace(); return null; } } Code Sample 2: private static void loadListFromRecouces(String category, URL url, DataSetArray<DataSetList> list, final StatusLineManager slm) { i = 0; try { if (url == null) return; InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF8")); String strLine; while ((strLine = br.readLine()) != null) { strLine = strLine.trim(); i++; if (slm != null) { Display.getDefault().syncExec(new Runnable() { public void run() { slm.setMessage(_("Importing country code " + i)); } }); } if (!strLine.isEmpty() && !strLine.startsWith("#")) { String parts[] = strLine.split("=", 2); if (parts.length == 2) { String key = parts[0].trim(); String value = parts[1].trim(); key = DataUtils.replaceAllAccentedChars(key).toUpperCase(); DataSetList newListEntry = new DataSetList(category, key, value); list.addNewDataSetIfNew(newListEntry); } } } in.close(); } catch (IOException e) { Logger.logError(e, "Error loading " + url.getFile()); } }
11
Code Sample 1: private void modifyDialog(boolean fileExists) { if (fileExists) { if (vars.containsKey(EnvironmentalVariables.WEBDAV_REVOCATION_LOCATION)) { RevLocation = ((String) vars.get(EnvironmentalVariables.WEBDAV_REVOCATION_LOCATION)); } if (vars.containsKey(EnvironmentalVariables.WEBDAV_CERTIFICATE_LOCATION)) { CertLocation = ((String) vars.get(EnvironmentalVariables.WEBDAV_CERTIFICATE_LOCATION)); } if (vars.containsKey(EnvironmentalVariables.HOLDER_NAME_STRING)) { jHolderName.setText((String) vars.get(EnvironmentalVariables.HOLDER_NAME_STRING)); } else jHolderName.setText("<EMPTY>"); if (vars.containsKey(EnvironmentalVariables.LDAP_HOLDER_EDITOR_UTILITY)) { if (vars.containsKey(EnvironmentalVariables.HOLDER_EDITOR_UTILITY_SERVER)) { jProviderURL.setText((String) vars.get(EnvironmentalVariables.HOLDER_EDITOR_UTILITY_SERVER)); } } if (vars.containsKey(EnvironmentalVariables.SERIAL_NUMBER_STRING)) { serialNumber = (String) vars.get(EnvironmentalVariables.SERIAL_NUMBER_STRING); } else serialNumber = "<EMPTY>"; if (vars.containsKey(EnvironmentalVariables.VALIDITY_PERIOD_STRING)) { jValidityPeriod.setText((String) vars.get(EnvironmentalVariables.VALIDITY_PERIOD_STRING)); } else jValidityPeriod.setText("<EMPTY>"); if (vars.containsKey(LDAPSavingUtility.LDAP_SAVING_UTILITY_AC_TYPE)) { String acType = (String) vars.get(LDAPSavingUtility.LDAP_SAVING_UTILITY_AC_TYPE); if ((!acType.equals("")) && (!acType.equals("<EMPTY>"))) jACType.setText((String) vars.get(LDAPSavingUtility.LDAP_SAVING_UTILITY_AC_TYPE)); else jACType.setText("attributeCertificateAttribute"); } if (utils.containsKey("issrg.acm.extensions.SimpleSigningUtility")) { if (vars.containsKey(DefaultSecurity.DEFAULT_FILE_STRING)) { jDefaultProfile.setText((String) vars.get(DefaultSecurity.DEFAULT_FILE_STRING)); } else jDefaultProfile.setText("<EMPTY>"); jCHEntrust.setSelected(true); } else { jCHEntrust.setSelected(false); jDefaultProfile.setEnabled(false); } if (utils.containsKey("issrg.acm.extensions.ACMDISSigningUtility")) { if (vars.containsKey("DefaultDIS")) { jDISAddress.setText((String) vars.get("DefaultDIS")); } else jDISAddress.setText("<EMPTY>"); jDIS.setSelected(true); jCHEntrust.setSelected(true); jDefaultProfile.setEnabled(true); if (vars.containsKey(DefaultSecurity.DEFAULT_FILE_STRING)) { jDefaultProfile.setText((String) vars.get(DefaultSecurity.DEFAULT_FILE_STRING)); } else jDefaultProfile.setText("permis.p12"); } else { jDIS.setSelected(false); jDISAddress.setEnabled(false); } if (vars.containsKey(EnvironmentalVariables.AAIA_LOCATION)) { jaaia[0].setSelected(true); } if (vars.containsKey(EnvironmentalVariables.NOREV_LOCATION)) { jnorev[0].setSelected(true); jdavrev[0].setEnabled(false); jdavrev[1].setEnabled(false); jdavrev[1].setSelected(false); } if (vars.containsKey(EnvironmentalVariables.DAVREV_LOCATION)) { jdavrev[0].setSelected(true); jnorev[0].setEnabled(false); jnorev[1].setEnabled(false); jnorev[1].setSelected(true); } if (vars.containsKey("LDAPSavingUtility.ProviderURI")) { jProviderURL.setText((String) vars.get("LDAPSavingUtility.ProviderURI")); } else jProviderURL.setText("<EMPTY>"); if (vars.containsKey("LDAPSavingUtility.Login")) { jProviderLogin.setText((String) vars.get("LDAPSavingUtility.Login")); } else jProviderLogin.setText("<EMPTY>"); if (vars.containsKey("LDAPSavingUtility.Password")) { jProviderPassword.setText((String) vars.get("LDAPSavingUtility.Password")); } else jProviderPassword.setText("<EMPTY>"); if ((!vars.containsKey(EnvironmentalVariables.TRUSTSTORE)) || (((String) vars.get(EnvironmentalVariables.TRUSTSTORE)).equals(""))) { vars.put(EnvironmentalVariables.TRUSTSTORE, "truststorefile"); } if (vars.containsKey(EnvironmentalVariables.WEBDAV_HOST)) { jWebDAVHost.setText((String) vars.get(EnvironmentalVariables.WEBDAV_HOST)); } else { jWebDAVHost.setText("<EMPTY>"); } if (vars.containsKey(EnvironmentalVariables.WEBDAV_PORT)) { jWebDAVPort.setText((String) vars.get(EnvironmentalVariables.WEBDAV_PORT)); } else { jWebDAVPort.setText("<EMPTY>"); } if (vars.containsKey(EnvironmentalVariables.WEBDAV_PROTOCOL)) { if (vars.get(EnvironmentalVariables.WEBDAV_PROTOCOL).equals("HTTPS")) { jWebDAVHttps.setSelected(true); jWebDAVSelectP12.setEnabled(true); jWebDAVP12Filename.setEnabled(true); jWebDAVP12Password.setEnabled(true); jWebDAVSSL.setEnabled(true); addWebDAVSSL.setEnabled(true); } else { jWebDAVHttps.setSelected(false); jWebDAVSelectP12.setEnabled(false); jWebDAVP12Filename.setEnabled(false); jWebDAVP12Password.setEnabled(false); jWebDAVSSL.setEnabled(false); addWebDAVSSL.setEnabled(false); } } else { jWebDAVHttps.setSelected(false); } if (vars.containsKey(EnvironmentalVariables.WEBDAV_P12FILENAME)) { jWebDAVP12Filename.setText((String) vars.get(EnvironmentalVariables.WEBDAV_P12FILENAME)); } else { jWebDAVP12Filename.setText("<EMPTY>"); } if (vars.containsKey(EnvironmentalVariables.WEBDAV_P12PASSWORD)) { jWebDAVP12Password.setText((String) vars.get(EnvironmentalVariables.WEBDAV_P12PASSWORD)); } else { jWebDAVP12Password.setText("<EMPTY>"); } if (vars.containsKey(EnvironmentalVariables.WEBDAV_SSLCERTIFICATE)) { jWebDAVSSL.setText((String) vars.get(EnvironmentalVariables.WEBDAV_SSLCERTIFICATE)); } else { jWebDAVSSL.setText("<EMPTY>"); } } else { jHolderName.setText("cn=A Permis Test User, o=PERMIS, c=gb"); try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(new Date().toString().getBytes()); byte[] result = md.digest(); BigInteger bi = new BigInteger(result); bi = bi.abs(); serialNumber = bi.toString(16); } catch (Exception e) { serialNumber = "<EMPTY>"; } jValidityPeriod.setText("<EMPTY>"); jDefaultProfile.setText("permis.p12"); jCHEntrust.setSelected(true); jProviderURL.setText("ldap://sec.cs.kent.ac.uk/c=gb"); jProviderLogin.setText(""); jProviderPassword.setText(""); jWebDAVHost.setText(""); jWebDAVPort.setText("443"); jWebDAVP12Filename.setText(""); jACType.setText("attributeCertificateAttribute"); vars.put(EnvironmentalVariables.TRUSTSTORE, "truststorefile"); saveChanges(); } } Code Sample 2: public static String getMdPsw(String passwd) throws Exception { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(passwd.getBytes("iso-8859-1"), 0, passwd.length()); md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: @Test public void test00_reinitData() throws Exception { Logs.logMethodName(); init(); Db db = DbConnection.defaultCieDbRW(); try { db.begin(); PreparedStatement pst = db.prepareStatement("TRUNCATE e_module;"); pst.executeUpdate(); pst = db.prepareStatement("TRUNCATE e_application_version;"); pst.executeUpdate(); ModuleHelper.synchronizeDbWithModuleList(db); ModuleHelper.declareNewVersion(db); ModuleHelper.updateModuleVersions(db); esisId = com.entelience.directory.PeopleFactory.lookupUserName(db, "esis"); assertNotNull(esisId); guestId = com.entelience.directory.PeopleFactory.lookupUserName(db, "guest"); assertNotNull(guestId); extenId = com.entelience.directory.PeopleFactory.lookupUserName(db, "exten"); assertNotNull(extenId); db.commit(); } catch (Exception e) { db.rollback(); throw e; } } Code Sample 2: public Object construct() { Object result; try { if (getParameter("data") != null && getParameter("data").length() > 0) { NanoXMLDOMInput domi = new NanoXMLDOMInput(new UMLFigureFactory(), new StringReader(getParameter("data"))); result = domi.readObject(0); } else if (getParameter("datafile") != null) { InputStream in = null; try { URL url = new URL(getDocumentBase(), getParameter("datafile")); in = url.openConnection().getInputStream(); NanoXMLDOMInput domi = new NanoXMLDOMInput(new UMLFigureFactory(), in); result = domi.readObject(0); } finally { if (in != null) in.close(); } } else { result = null; } } catch (Throwable t) { result = t; } return result; }
00
Code Sample 1: public void storeModule(OWLModuleManager manager, Module module, URI physicalURI, OWLModuleFormat moduleFormat) throws ModuleStorageException, UnknownModuleException { try { OutputStream os; if (!physicalURI.isAbsolute()) { throw new ModuleStorageException("Physical URI must be absolute: " + physicalURI); } if (physicalURI.getScheme().equals("file")) { File file = new File(physicalURI); file.getParentFile().mkdirs(); os = new FileOutputStream(file); } else { URL url = physicalURI.toURL(); URLConnection conn = url.openConnection(); os = conn.getOutputStream(); } Writer w = new BufferedWriter(new OutputStreamWriter(os)); storeModule(manager, module, w, moduleFormat); } catch (IOException e) { throw new ModuleStorageException(e); } } Code Sample 2: public boolean refresh() { try { URLConnection conn = url.openConnection(); conn.setUseCaches(false); if (credential != null) conn.setRequestProperty("Authorization", credential); conn.connect(); int status = ((HttpURLConnection) conn).getResponseCode(); if (status == 401 || status == 403) errorMessage = (credential == null ? PASSWORD_MISSING : PASSWORD_INCORRECT); else if (status == 404) errorMessage = NOT_FOUND; else if (status != 200) errorMessage = COULD_NOT_RETRIEVE; else { InputStream in = conn.getInputStream(); byte[] httpData = TinyWebServer.slurpContents(in, true); synchronized (this) { data = httpData; dataProvider = null; } errorMessage = null; refreshDate = new Date(); String owner = conn.getHeaderField(OWNER_HEADER_FIELD); if (owner != null) setLocalAttr(OWNER_ATTR, owner); store(); return true; } } catch (UnknownHostException uhe) { errorMessage = NO_SUCH_HOST; } catch (ConnectException ce) { errorMessage = COULD_NOT_CONNECT; } catch (IOException ioe) { errorMessage = COULD_NOT_RETRIEVE; } return false; }
00
Code Sample 1: public static Vector getMetaKeywordsFromURL(String p_url) throws Exception { URL x_url = new URL(p_url); URLConnection x_conn = x_url.openConnection(); InputStreamReader x_is_reader = new InputStreamReader(x_conn.getInputStream()); BufferedReader x_reader = new BufferedReader(x_is_reader); String x_line = null; String x_lc_line = null; int x_body = -1; String x_keyword_list = null; int x_keywords = -1; String[] x_meta_keywords = null; while ((x_line = x_reader.readLine()) != null) { x_lc_line = x_line.toLowerCase(); x_keywords = x_lc_line.indexOf("<meta name=\"keywords\" content=\""); if (x_keywords != -1) { x_keywords = "<meta name=\"keywords\" content=\"".length(); x_keyword_list = x_line.substring(x_keywords, x_line.indexOf("\">", x_keywords)); x_keyword_list = x_keyword_list.replace(',', ' '); x_meta_keywords = Parser.extractWordsFromSpacedList(x_keyword_list); } x_body = x_lc_line.indexOf("<body"); if (x_body != -1) break; } Vector x_vector = new Vector(x_meta_keywords.length); for (int i = 0; i < x_meta_keywords.length; i++) x_vector.add(x_meta_keywords[i]); return x_vector; } Code Sample 2: public void constructFundamentalView() { String className; String methodName; String field; boolean foundRead = false; boolean foundWrite = false; boolean classWritten = false; try { FundView = new BufferedWriter(new FileWriter("InfoFiles/FundamentalView.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; FundView.write(className); FundView.newLine(); classWritten = true; while ((methodName = PC.readLine()) != null) { if (methodName.contentEquals("EndOfClass")) break; FundView.write("StartOfMethod"); FundView.newLine(); FundView.write(methodName); FundView.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 (field.compareTo(className) == 0) { FundView.write(readArray[i + j]); FundView.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 (field.compareTo(className) == 0) { FundView.write(writeArray[i + j]); FundView.newLine(); } } } } } FundView.write("EndOfMethod"); FundView.newLine(); foundRead = false; foundWrite = false; } if (classWritten == true) { FundView.write("EndOfClass"); FundView.newLine(); classWritten = false; } } PC.close(); FundView.close(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } } Code Sample 2: public void testIsVersioned() throws ServiceException, IOException { JCRNodeSource emptySource = loadTestSource(); assertTrue(emptySource.isVersioned()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } assertTrue(emptySource.isVersioned()); }
00
Code Sample 1: public static void fileCopy(File sourceFile, File destFile) throws IOException { FileChannel source = null; FileChannel destination = null; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(sourceFile); fos = new FileOutputStream(destFile); source = fis.getChannel(); destination = fos.getChannel(); destination.transferFrom(source, 0, source.size()); } finally { fis.close(); fos.close(); if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public void visit(AuthenticationMD5Password message) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(((String) properties.get("password") + (String) properties.get("user")).getBytes("iso8859-1")); String newValue = toHexString(md5.digest()) + new String(message.getSalt(), "iso8859-1"); md5.reset(); md5.update(newValue.getBytes("iso8859-1")); newValue = toHexString(md5.digest()); PasswordMessage mes = new PasswordMessage("md5" + newValue); byte[] data = encoder.encode(mes); out.write(data); } catch (Exception e) { e.printStackTrace(); } }
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 void copyCompletely(InputStream input, OutputStream output) throws IOException { if ((output instanceof FileOutputStream) && (input instanceof FileInputStream)) { try { FileChannel target = ((FileOutputStream) output).getChannel(); FileChannel source = ((FileInputStream) input).getChannel(); source.transferTo(0, Integer.MAX_VALUE, target); source.close(); target.close(); return; } catch (Exception e) { } } byte[] buf = new byte[8192]; while (true) { int length = input.read(buf); if (length < 0) break; output.write(buf, 0, length); } try { input.close(); } catch (IOException ignore) { } try { output.close(); } catch (IOException ignore) { } }
11
Code Sample 1: public static void copyFile(String source, String dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(new File(source)).getChannel(); out = new FileOutputStream(new File(dest)).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } 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 { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: protected void addAssetResources(MimeMultipart pkg, MarinerPageContext context) throws PackagingException { boolean includeFullyQualifiedURLs = context.getBooleanDevicePolicyValue("protocol.mime.fully.qualified.urls"); MarinerRequestContext requestContext = context.getRequestContext(); ApplicationContext ac = ContextInternals.getApplicationContext(requestContext); PackageResources pr = ac.getPackageResources(); List encodedURLs = pr.getEncodedURLs(); Map assetURLMap = pr.getAssetURLMap(); Iterator iterator; String encodedURL; PackageResources.Asset asset; String assetURL = null; BodyPart assetPart; if (encodedURLs != null) { iterator = encodedURLs.iterator(); } else { iterator = assetURLMap.keySet().iterator(); } while (iterator.hasNext()) { encodedURL = (String) iterator.next(); asset = (PackageResources.Asset) assetURLMap.get(encodedURL); assetURL = asset.getValue(); if (includeFullyQualifiedURLs || !isFullyQualifiedURL(assetURL)) { if (isToBeAdded(assetURL, context)) { assetPart = new MimeBodyPart(); try { if (!asset.getOnClientSide()) { URL url = null; URLConnection connection; try { url = context.getAbsoluteURL(new MarinerURL(assetURL)); connection = url.openConnection(); if (connection != null) { connection.setDoInput(true); connection.setDoOutput(false); connection.setAllowUserInteraction(false); connection.connect(); connection.getInputStream(); assetPart.setDataHandler(new DataHandler(url)); assetPart.setHeader("Content-Location", assetURL); pkg.addBodyPart(assetPart); } } catch (MalformedURLException e) { if (logger.isDebugEnabled()) { logger.debug("Ignoring asset with malformed URL: " + url.toString()); } } catch (IOException e) { if (logger.isDebugEnabled()) { logger.debug("Ignoring asset with URL that doesn't " + "exist: " + assetURL + " (" + url.toString() + ")"); } } } else { assetPart.setHeader("Content-Location", "file://" + assetURL); } } catch (MessagingException e) { throw new PackagingException(exceptionLocalizer.format("could-not-add-asset", encodedURL), e); } } } } } Code Sample 2: protected int doWork() { SAMFileReader reader = new SAMFileReader(IoUtil.openFileForReading(INPUT)); reader.getFileHeader().setSortOrder(SORT_ORDER); SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), false, OUTPUT); Iterator<SAMRecord> iterator = reader.iterator(); while (iterator.hasNext()) writer.addAlignment(iterator.next()); reader.close(); writer.close(); return 0; }
00
Code Sample 1: public boolean loadFile(String inpfile) { if (osmlContainer == null) return false; hApdx.clear(); try { BufferedReader in = null; if (inpfile.indexOf("http://") >= 0) { URL url = null; url = new URL(inpfile); URLConnection conn = url.openConnection(); conn.setUseCaches(false); InputStreamReader is = new InputStreamReader(conn.getInputStream()); in = new BufferedReader(is); } else { in = new BufferedReader(new FileReader(inpfile)); } String pline = null; while ((pline = in.readLine()) != null) { StringTokenizer tok = new StringTokenizer(pline, "\t\n\r"); if (tok.countTokens() < 2) continue; String name = tok.nextToken(); String apdx = tok.nextToken(); String note = ""; if (tok.countTokens() > 0) note = tok.nextToken(); if (name.length() == 0 || apdx.length() == 0) continue; OmicElementContainer element = (OmicElementContainer) OmicElementContainer.createContainer(); element.setName(name); element.setNote(note); element.addAppendix(apdx); String keys[] = commaPattern.split(apdx); for (int j = 0; j < keys.length; j++) { ArrayList v = (ArrayList) hApdx.get(keys[j]); if (v == null) v = new ArrayList(); v.add(element); hApdx.put(keys[j], v); } } in.close(); } catch (MalformedURLException mfe) { System.out.println("MalformedURLException"); return false; } catch (IOException ioe) { System.out.println("IOException"); return false; } System.out.println("appendix name list size " + hApdx.size()); if (bElementDirected) { int nCount = 0; ArrayList<OmicElementContainer> omicElementList = osmlContainer.getAllOmicElementContainers(); for (OmicElementContainer element : omicElementList) { String name = element.getName(); String apdx = element.getAppendix(); if (name.length() == 0) continue; String names[] = commaPattern.split(name); String apdxs[] = commaPattern.split(apdx); String list[] = new String[names.length + apdxs.length]; for (int j = 0; j < names.length; j++) list[j] = names[j]; for (int j = 0; j < apdxs.length; j++) list[j + names.length] = apdxs[j]; for (int j = 0; j < list.length; j++) { ArrayList v = (ArrayList) hApdx.get(list[j]); if (v == null) continue; for (int k = 0; k < v.size(); k++) { OmicElementContainer appendix = (OmicElementContainer) v.get(k); element.addAppendix(appendix.getName()); nCount++; } } } System.out.println("match appendix element " + nCount + " items"); } if (bFunctionDirected) { int nCount = 0; FunctionalClassContainer functions[] = osmlContainer.getFunctionalClassContainer("[@container=all]"); ArrayList vFunction = new ArrayList(); for (int i = 0; i < functions.length; i++) { if (!vFunction.contains(functions[i])) vFunction.add(functions[i]); } for (int i = 0; i < vFunction.size(); i++) { FunctionalClassContainer function = (FunctionalClassContainer) vFunction.get(i); String name = function.getName(); if (name.length() == 0) continue; String names[] = name.split(","); for (int j = 0; j < names.length; j++) { ArrayList v = (ArrayList) hApdx.get(names[j]); if (v == null) continue; for (int k = 0; k < v.size(); k++) { OmicElementContainer appendix = (OmicElementContainer) v.get(k); functions[i].addOmicElementContainer(appendix); nCount++; } } } System.out.println("match appendix function " + nCount + " items"); } return true; } Code Sample 2: public boolean crear() { int result = 0; String sql = "insert into divisionxTorneo" + "(torneo_idTorneo, tipoTorneo_idTipoTorneo, nombreDivision, descripcion, numJugadores, numFechas, terminado, tipoDesempate, rondaActual, ptosxbye)" + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement(); result = 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 (result > 0); }
00
Code Sample 1: public int create(BusinessObject o) throws DAOException { int insert = 0; int id = 0; Account acc = (Account) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_ACCOUNT")); pst.setString(1, acc.getName()); pst.setString(2, acc.getAddress()); pst.setInt(3, acc.getCurrency()); pst.setInt(4, acc.getMainContact()); insert = pst.executeUpdate(); if (insert <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (insert > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select max(id) from account"); rs.next(); id = rs.getInt(1); connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return id; } Code Sample 2: private static String format(String check) throws NoSuchAlgorithmException, UnsupportedEncodingException { check = check.replaceAll(" ", ""); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(check.getBytes("ISO-8859-1")); byte[] end = md5.digest(); String digest = ""; for (int i = 0; i < end.length; i++) { digest += ((end[i] & 0xff) < 16 ? "0" : "") + Integer.toHexString(end[i] & 0xff); } return digest; }
00
Code Sample 1: public Object mapRow(ResultSet rs, int i) throws SQLException { Blob blob = rs.getBlob(1); if (rs.wasNull()) return null; try { InputStream inputStream = blob.getBinaryStream(); if (length > 0) IOUtils.copy(inputStream, outputStream, offset, length); else IOUtils.copy(inputStream, outputStream); inputStream.close(); } catch (IOException e) { } return null; } Code Sample 2: private void harvest() throws IOException, XMLStreamException { String api_url = "http://search.twitter.com/search.atom?q=+%23" + hashtag + "+to%3A" + account; System.err.println(api_url); URL url = new URL(api_url); URLConnection con = url.openConnection(); String basic = this.login + ":" + new String(this.password); con.setRequestProperty("Authorization", "Basic " + Base64.encode(basic)); XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true); factory.setProperty(XMLInputFactory.IS_VALIDATING, false); factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); XMLEventReader reader = factory.createXMLEventReader(con.getInputStream()); boolean inEntry = false; boolean inAuthor = false; String published = null; String title = null; String foafName = null; String foafURI = null; String link = null; while (reader.hasNext()) { XMLEvent evt = reader.nextEvent(); if (evt.isStartElement()) { StartElement e = evt.asStartElement(); QName qName = e.getName(); if (!inEntry && Atom.NS.equals(qName.getNamespaceURI()) && qName.getLocalPart().equals("entry")) { inEntry = true; } else if (inEntry) { String local = qName.getLocalPart(); if (local.equals("published")) { published = reader.getElementText(); } else if (local.equals("title")) { title = reader.getElementText(); } else if (link == null && local.equals("link")) { Attribute att = e.getAttributeByName(new QName("type")); if (att != null && att.getValue().equals("text/html")) { att = e.getAttributeByName(new QName("href")); if (att != null) { link = att.getValue(); } } } else if (local.equals("author")) { inAuthor = true; } else if (inAuthor && local.equals("name")) { foafName = reader.getElementText(); } else if (inAuthor && local.equals("uri")) { foafURI = reader.getElementText(); } } } else if (evt.isEndElement()) { EndElement e = evt.asEndElement(); QName qName = e.getName(); if (inEntry && Atom.NS.equals(qName.getNamespaceURI())) { String local = qName.getLocalPart(); if (local.equals("entry")) { Protein p1 = null; Protein p2 = null; PubmedEntry pubmed = null; boolean valid = title != null && published != null; String tokens[] = title == null ? new String[0] : title.trim().split("[ \t\n\r]+"); if (valid && tokens.length != 5) { System.err.println("Ignoring " + title); valid = false; } if (valid && !tokens[0].equals("@" + account)) { System.err.println("Ignoring " + title + " doesn't start with @" + account); valid = false; } if (valid && !(tokens[1].startsWith("gi:") && Cast.Integer.isA(tokens[1].substring(3)))) { System.err.println("Ignoring " + title + " not a gi:###"); valid = false; } if (valid && (p1 = fetchProtein(Integer.parseInt(tokens[1].substring(3)))) == null) { valid = false; } if (valid && !(tokens[2].startsWith("gi:") && Cast.Integer.isA(tokens[2].substring(3)))) { System.err.println("Ignoring " + title + " not a gi:###"); valid = false; } if (valid && (p2 = fetchProtein(Integer.parseInt(tokens[2].substring(3)))) == null) { valid = false; } if (valid && !(tokens[3].startsWith("pmid:") && Cast.Integer.isA(tokens[3].substring(5)))) { System.err.println("Ignoring " + title + " not a pmid:###"); valid = false; } if (valid && (pubmed = fetchPubmedEntry(Integer.parseInt(tokens[3].substring(5)))) == null) { valid = false; } if (valid && !tokens[4].equals("#" + hashtag)) { System.err.println("Ignoring " + title + " doesn't end with #" + hashtag); valid = false; } if (valid && p1 != null && p2 != null && pubmed != null && foafName != null && foafURI != null) { exportFoaf(foafName, foafURI); exportGi(p1); exportGi(p2); exportPubmed(pubmed); System.out.println("<Interaction rdf:about=\"" + link + "\">"); System.out.println(" <interactor rdf:resource=\"lsid:ncbi.nlm.nih.gov:protein:" + p1.gi + "\"/>"); System.out.println(" <interactor rdf:resource=\"lsid:ncbi.nlm.nih.gov:protein:" + p2.gi + "\"/>"); System.out.println(" <reference rdf:resource=\"http://www.ncbi.nlm.nih.gov/pubmed/" + pubmed.pmid + "\"/>"); System.out.println(" <dc:creator rdf:resource=\"" + foafURI + "\"/>"); System.out.println(" <dc:date>" + escape(published) + "</dc:date>"); System.out.println("</Interaction>"); } inEntry = false; title = null; foafName = null; foafURI = null; inAuthor = false; published = null; link = null; } else if (inAuthor && local.equals("author")) { inAuthor = false; } } } } reader.close(); }
11
Code Sample 1: public static File copy(String inFileName, String outFileName) throws IOException { File inputFile = new File(inFileName); File outputFile = new File(outFileName); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return outputFile; } Code Sample 2: public static URL toFileUrl(URL location) throws IOException { String protocol = location.getProtocol().intern(); if (protocol != "jar") throw new IOException("cannot explode " + location); JarURLConnection juc = (JarURLConnection) location.openConnection(); String path = juc.getEntryName(); String parentPath = parentPathOf(path); File tempDir = createTempDir("jartemp"); JarFile jarFile = juc.getJarFile(); for (Enumeration<JarEntry> en = jarFile.entries(); en.hasMoreElements(); ) { ZipEntry entry = en.nextElement(); if (entry.isDirectory()) continue; String entryPath = entry.getName(); if (entryPath.startsWith(parentPath)) { File dest = new File(tempDir, entryPath); dest.getParentFile().mkdirs(); InputStream in = jarFile.getInputStream(entry); OutputStream out = new FileOutputStream(dest); IOUtils.copy(in, out); dest.deleteOnExit(); } } File realFile = new File(tempDir, path); return realFile.toURL(); }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void main(String[] args) { JFileChooser askDir = new JFileChooser(); askDir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); askDir.setMultiSelectionEnabled(false); int returnVal = askDir.showOpenDialog(null); if (returnVal == JFileChooser.CANCEL_OPTION) { System.exit(returnVal); } File startDir = askDir.getSelectedFile(); ArrayList<File> files = new ArrayList<File>(); goThrough(startDir, files); SearchClient client = new SearchClient("VZFo5W5i"); MyID3 singleton = new MyID3(); for (File song : files) { try { MusicMetadataSet set = singleton.read(song); IMusicMetadata meta = set.getSimplified(); String qu = song.getName(); if (meta.getAlbum() != null) { qu = meta.getAlbum(); } else if (meta.getArtist() != null) { qu = meta.getArtist(); } if (qu.length() > 2) { ImageSearchRequest req = new ImageSearchRequest(qu); ImageSearchResults res = client.imageSearch(req); if (res.getTotalResultsAvailable().doubleValue() > 1) { System.out.println("Downloading " + res.listResults()[0].getUrl()); URL url = new URL(res.listResults()[0].getUrl()); URLConnection con = url.openConnection(); con.setConnectTimeout(10000); int realSize = con.getContentLength(); if (realSize > 0) { String mime = con.getContentType(); InputStream stream = con.getInputStream(); byte[] realData = new byte[realSize]; for (int i = 0; i < realSize; i++) { stream.read(realData, i, 1); } stream.close(); ImageData imgData = new ImageData(realData, mime, qu, 0); meta.addPicture(imgData); File temp = File.createTempFile("tempsong", "mp3"); singleton.write(song, temp, set, meta); FileChannel inChannel = new FileInputStream(temp).getChannel(); FileChannel outChannel = new FileOutputStream(song).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } temp.delete(); } } } } catch (ID3ReadException e) { } catch (MalformedURLException e) { } catch (UnsupportedEncodingException e) { } catch (ID3WriteException e) { } catch (IOException e) { } catch (SearchException e) { } } }
11
Code Sample 1: public String excute(String targetUrl, String params, String type) { URL url; HttpURLConnection connection = null; try { url = new URL(targetUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(type); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length)); connection.setRequestProperty("Content-Language", CHAR_SET); connection.setRequestProperty("Connection", "close"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); if (params != null) { if (params.length() > 0) { DataOutputStream wr; wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(params); wr.flush(); wr.close(); } } InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, CHAR_SET)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append("\r\n"); } rd.close(); return response.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } Code Sample 2: private void run(String[] args) throws Throwable { ArgParser parser = new ArgParser("Run an experiment"); parser.addOptions(this, true); args = parser.matchAllArgs(args, 0, ArgParserOption.EXIT_ON_ERROR, ArgParserOption.STOP_FIRST_UNMATCHED); if (log4jFile != null) { logger.info("Using another log4j configuration: %s", log4jFile); PropertyConfigurator.configure(log4jFile.getAbsolutePath()); } final TreeMap<TaskName, Class<Task>> tasks = GenericHelper.newTreeMap(); final Enumeration<URL> e = About.class.getClassLoader().getResources(EXPERIMENT_PACKAGES); while (e.hasMoreElements()) { final URL url = e.nextElement(); logger.debug("Got URL %s", url); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { String packageName = line; getTasks(url, tasks, packageName); } } getTasks(null, tasks, getClass().getPackage().getName()); if (tasks.isEmpty()) { logger.fatal("I did not find any valid experiment (service bpiwowar.experiments.ExperimentListProvider)"); System.exit(1); } if (args.length == 0 || args[0].equals("list")) { System.out.format("Available experiments:%n"); TreeMapArray<PackageName, String> map = TreeMapArray.newInstance(); for (Entry<TaskName, Class<Task>> entry : tasks.entrySet()) { TaskName task = entry.getKey(); if (showClassNames) map.add(task.packageName, String.format("%s (%s)", task.name, entry.getValue().toString())); else map.add(task.packageName, task.name); } Stack<PackageName> ancestors = new Stack<PackageName>(); for (Entry<PackageName, ArrayList<String>> entry : map.entrySet()) { final PackageName key = entry.getKey(); while (!ancestors.isEmpty() && key.commonPrefixLength(ancestors.peek()) != ancestors.peek().getLength()) ancestors.pop(); int nbAncestors = ancestors.size(); int c = nbAncestors > 0 ? ancestors.peek().getLength() : 0; StringBuilder s = new StringBuilder(); for (int i = 0; i < c; i++) s.append("|"); for (int i = c; i < key.getLength(); i++) { s.append("|"); ancestors.add(new PackageName(key, i + 1)); System.out.format("%s%n", s); System.out.format("%s+ [%s]%n", s, ancestors.peek()); nbAncestors++; } String prefix = s.toString(); for (String task : entry.getValue()) System.out.format("%s|- %s%n", prefix, task); ancestors.add(key); } return; } else if (args[0].equals(SEARCH_COMMAND)) { final class Options { @OrderedArgument(required = true) String search; } Options options = new Options(); ArgParser ap = new ArgParser(SEARCH_COMMAND); ap.addOptions(options); ap.matchAllArgs(args, 1); logger.info("Searching for %s", options.search); for (Entry<TaskName, Class<Task>> entry : tasks.entrySet()) { TaskName taskname = entry.getKey(); if (taskname.name.contains(options.search)) { System.err.format("[*] %s - %s%n %s%n", taskname, entry.getValue(), entry.getValue().getAnnotation(TaskDescription.class).description()); } } return; } String taskName = args[0]; args = Arrays.copyOfRange(args, 1, args.length); ArrayList<Class<Task>> matching = GenericHelper.newArrayList(); for (Entry<TaskName, Class<Task>> entry : tasks.entrySet()) { if (entry.getKey().name.equals(taskName)) matching.add(entry.getValue()); } if (matching.isEmpty()) { System.err.println("No task match " + taskName); System.exit(1); } if (matching.size() > 1) { System.err.println("Too many tasks match " + taskName); System.exit(1); } Class<Task> taskClass = matching.get(0); logger.info("Running experiment " + taskClass.getCanonicalName()); Task task = taskClass.newInstance(); int errorCode = 0; try { task.init(args); if (xstreamOutput != null) { OutputStream out; if (xstreamOutput.toString().equals("-")) out = System.out; else out = new FileOutputStream(xstreamOutput); logger.info("Serializing the object into %s", xstreamOutput); new XStream().toXML(task, out); out.close(); } else { errorCode = task.run(); } logger.info("Finished task"); } catch (Throwable t) { if (t instanceof InvocationTargetException && t.getCause() != null) { t = t.getCause(); } logger.error("Exception thrown while executing the action:%n%s%n", t); errorCode = 2; } System.exit(errorCode); }
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); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new OutputStream() { @Override public void write(byte[] b, int off, int len) { } @Override public void write(int b) { } @Override public void write(byte[] b) throws IOException { } }); } finally { IOUtils.closeQuietly(in); } return checksum; }
00
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public final String encrypt(String input) throws Exception { try { MessageDigest messageDigest = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); messageDigest.reset(); messageDigest.update(input.getBytes()); String output = convert(messageDigest.digest()); return output; } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Fatal Error while digesting input string", ex); } } return input; }
00
Code Sample 1: public void run() { if (_plot == null) { _plot = newPlot(); } getContentPane().add(plot(), BorderLayout.NORTH); int width; int height; String widthspec = getParameter("width"); if (widthspec != null) { width = Integer.parseInt(widthspec); } else { width = 400; } String heightspec = getParameter("height"); if (heightspec != null) { height = Integer.parseInt(heightspec); } else { height = 400; } _setPlotSize(width, height); plot().setButtons(true); Color background = Color.white; String colorspec = getParameter("background"); if (colorspec != null) { background = PlotBox.getColorByName(colorspec); } setBackground(background); plot().setBackground(background); getContentPane().setBackground(background); Color foreground = Color.black; colorspec = getParameter("foreground"); if (colorspec != null) { foreground = PlotBox.getColorByName(colorspec); } setForeground(foreground); plot().setForeground(foreground); plot().setVisible(true); String dataurlspec = getParameter("dataurl"); if (dataurlspec != null) { try { showStatus("Reading data"); URL dataurl = new URL(getDocumentBase(), dataurlspec); InputStream in = dataurl.openStream(); _read(in); showStatus("Done"); } catch (MalformedURLException e) { System.err.println(e.toString()); } catch (FileNotFoundException e) { System.err.println("PlotApplet: file not found: " + e); } catch (IOException e) { System.err.println("PlotApplet: error reading input file: " + e); } } } Code Sample 2: public String post() { if (content == null || content.equals("")) return "Type something to publish!!"; OutputStreamWriter wr = null; BufferedReader rd = null; try { String data = URLEncoder.encode("api", "UTF-8") + "=" + URLEncoder.encode(apiKey, "UTF-8"); data += "&" + URLEncoder.encode("content", "UTF-8") + "=" + URLEncoder.encode(content, "UTF-8"); data += "&" + URLEncoder.encode("description", "UTF-8") + "=" + URLEncoder.encode(descriptionTextArea.getText() + description_suffix, "UTF-8"); data += "&" + URLEncoder.encode("expiry", "UTF-8") + "=" + URLEncoder.encode((String) expiryComboBox.getSelectedItem(), "UTF-8"); data += "&" + URLEncoder.encode("type", "UTF-8") + "=" + URLEncoder.encode(type, "UTF-8"); data += "&" + URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(nameTextBox.getText(), "UTF-8"); URL url = new URL("http://pastebin.ca/quiet-paste.php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; line = rd.readLine(); if (line == null || line.length() < 8 || !line.substring(0, 8).equals("SUCCESS:")) return "Unknown error in publishing the post"; else return "*Publish successful.! The link to your post is.: " + "http://pastebin.ca/" + line.substring(8); } catch (IOException ex) { return "Unable to connect to http://pastebin.ca/\nPlease check your internet connection"; } finally { try { if (wr != null) wr.close(); if (rd != null) rd.close(); } catch (IOException ex) { } } }
11
Code Sample 1: private void writeGif(String filename, String outputFile) throws IOException { File file = new File(filename); InputStream in = new FileInputStream(file); FileOutputStream fout = new FileOutputStream(outputFile); int totalRead = 0; int readBytes = 0; int blockSize = 65000; long fileLen = file.length(); byte b[] = new byte[blockSize]; while ((long) totalRead < fileLen) { readBytes = in.read(b, 0, blockSize); totalRead += readBytes; fout.write(b, 0, readBytes); } in.close(); fout.close(); } Code Sample 2: public void close() { try { if (writer != null) { BufferedReader reader; writer.close(); writer = new BufferedWriter(new FileWriter(fileName)); for (int i = 0; i < headers.size(); i++) writer.write(headers.get(i) + ","); writer.write("\n"); reader = new BufferedReader(new FileReader(file)); while (reader.ready()) writer.write(reader.readLine() + "\n"); reader.close(); writer.close(); file.delete(); } } catch (java.io.IOException e) { throw new RuntimeException(e); } }
00
Code Sample 1: public void apop(String user, char[] secret) throws IOException, POP3Exception { if (timestamp == null) { throw new CommandNotSupportedException("No timestamp from server - APOP not possible"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(timestamp.getBytes()); if (secret == null) secret = new char[0]; byte[] digest = md.digest(new String(secret).getBytes("ISO-8859-1")); mutex.lock(); sendCommand("APOP", new String[] { user, digestToString(digest) }); POP3Response response = readSingleLineResponse(); if (!response.isOK()) { throw new POP3Exception(response); } state = TRANSACTION; } catch (NoSuchAlgorithmException e) { throw new POP3Exception("Installed JRE doesn't support MD5 - APOP not possible"); } finally { mutex.release(); } } Code Sample 2: public void initialize(IProgressMonitor monitor) throws JETException { IProgressMonitor progressMonitor = monitor; progressMonitor.beginTask("", 10); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_GeneratingJETEmitterFor_message", new Object[] { getTemplateURI() })); final IWorkspace workspace = ResourcesPlugin.getWorkspace(); IJavaModel javaModel = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); try { final JETCompiler jetCompiler = getTemplateURIPath() == null ? new MyBaseJETCompiler(getTemplateURI(), getEncoding(), getClassLoader()) : new MyBaseJETCompiler(getTemplateURIPath(), getTemplateURI(), getEncoding(), getClassLoader()); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETParsing_message", new Object[] { jetCompiler.getResolvedTemplateURI() })); jetCompiler.parse(); progressMonitor.worked(1); String packageName = jetCompiler.getSkeleton().getPackageName(); if (getTemplateURIPath() != null) { URI templateURI = URI.createURI(getTemplateURIPath()[0]); URLClassLoader theClassLoader = null; if (templateURI.isPlatformResource()) { IProject project = workspace.getRoot().getProject(templateURI.segment(1)); if (JETNature.getRuntime(project) != null) { List<URL> urls = new ArrayList<URL>(); IJavaProject javaProject = JavaCore.create(project); urls.add(new File(project.getLocation() + "/" + javaProject.getOutputLocation().removeFirstSegments(1) + "/").toURI().toURL()); for (IClasspathEntry classpathEntry : javaProject.getResolvedClasspath(true)) { if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { IPath projectPath = classpathEntry.getPath(); IProject otherProject = workspace.getRoot().getProject(projectPath.segment(0)); IJavaProject otherJavaProject = JavaCore.create(otherProject); urls.add(new File(otherProject.getLocation() + "/" + otherJavaProject.getOutputLocation().removeFirstSegments(1) + "/").toURI().toURL()); } } theClassLoader = AccessController.doPrivileged(new GetURLClassLoaderSuperAction(urls)); } } else if (templateURI.isPlatformPlugin()) { final Bundle bundle = Platform.getBundle(templateURI.segment(1)); if (bundle != null) { theClassLoader = AccessController.doPrivileged(new GetURLClassLoaderBundleAction(bundle)); } } if (theClassLoader != null) { String className = (packageName.length() == 0 ? "" : packageName + ".") + jetCompiler.getSkeleton().getClassName(); if (className.endsWith("_")) { className = className.substring(0, className.length() - 1); } try { Class<?> theClass = theClassLoader.loadClass(className); Class<?> theOtherClass = null; try { theOtherClass = getClassLoader().loadClass(className); } catch (ClassNotFoundException exception) { } if (theClass != theOtherClass) { String methodName = jetCompiler.getSkeleton().getMethodName(); Method[] methods = theClass.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (methods[i].getName().equals(methodName)) { jetEmitter.setMethod(methods[i]); break; } } return; } } catch (ClassNotFoundException exception) { } } } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); jetCompiler.generate(outputStream); final InputStream contents = new ByteArrayInputStream(outputStream.toByteArray()); if (!javaModel.isOpen()) { javaModel.open(new SubProgressMonitor(progressMonitor, 1)); } else { progressMonitor.worked(1); } final IProject project = workspace.getRoot().getProject(jetEmitter.getProjectName()); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETPreparingProject_message", new Object[] { project.getName() })); IJavaProject javaProject; if (!project.exists()) { progressMonitor.subTask("JET creating project " + project.getName()); project.create(new SubProgressMonitor(progressMonitor, 1)); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETCreatingProject_message", new Object[] { project.getName() })); IProjectDescription description = workspace.newProjectDescription(project.getName()); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); description.setLocation(null); project.open(new SubProgressMonitor(progressMonitor, 1)); project.setDescription(description, new SubProgressMonitor(progressMonitor, 1)); } else { project.open(new SubProgressMonitor(progressMonitor, 5)); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); project.setDescription(description, new SubProgressMonitor(progressMonitor, 1)); } javaProject = JavaCore.create(project); List<IClasspathEntry> classpath = new UniqueEList<IClasspathEntry>(Arrays.asList(javaProject.getRawClasspath())); for (int i = 0, len = classpath.size(); i < len; i++) { IClasspathEntry entry = classpath.get(i); if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE && ("/" + project.getName()).equals(entry.getPath().toString())) { classpath.remove(i); } } progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETInitializingProject_message", new Object[] { project.getName() })); IClasspathEntry classpathEntry = JavaCore.newSourceEntry(new Path("/" + project.getName() + "/src")); IClasspathEntry jreClasspathEntry = JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")); classpath.add(classpathEntry); classpath.add(jreClasspathEntry); classpath.addAll(getClassPathEntries()); IFolder sourceFolder = project.getFolder(new Path("src")); if (!sourceFolder.exists()) { sourceFolder.create(false, true, new SubProgressMonitor(progressMonitor, 1)); } IFolder runtimeFolder = project.getFolder(new Path("bin")); if (!runtimeFolder.exists()) { runtimeFolder.create(false, true, new SubProgressMonitor(progressMonitor, 1)); } javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[classpath.size()]), new SubProgressMonitor(progressMonitor, 1)); javaProject.setOutputLocation(new Path("/" + project.getName() + "/bin"), new SubProgressMonitor(progressMonitor, 1)); javaProject.close(); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETOpeningJavaProject_message", new Object[] { project.getName() })); javaProject.open(new SubProgressMonitor(progressMonitor, 1)); IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots(); IPackageFragmentRoot sourcePackageFragmentRoot = null; for (int j = 0; j < packageFragmentRoots.length; ++j) { IPackageFragmentRoot packageFragmentRoot = packageFragmentRoots[j]; if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) { sourcePackageFragmentRoot = packageFragmentRoot; break; } } StringTokenizer stringTokenizer = new StringTokenizer(packageName, "."); IProgressMonitor subProgressMonitor = new SubProgressMonitor(progressMonitor, 1); subProgressMonitor.beginTask("", stringTokenizer.countTokens() + 4); subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_CreateTargetFile_message")); IContainer sourceContainer = sourcePackageFragmentRoot == null ? project : (IContainer) sourcePackageFragmentRoot.getCorrespondingResource(); while (stringTokenizer.hasMoreElements()) { String folderName = stringTokenizer.nextToken(); sourceContainer = sourceContainer.getFolder(new Path(folderName)); if (!sourceContainer.exists()) { ((IFolder) sourceContainer).create(false, true, new SubProgressMonitor(subProgressMonitor, 1)); } } IFile targetFile = sourceContainer.getFile(new Path(jetCompiler.getSkeleton().getClassName() + ".java")); if (!targetFile.exists()) { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETCreating_message", new Object[] { targetFile.getFullPath() })); targetFile.create(contents, true, new SubProgressMonitor(subProgressMonitor, 1)); } else { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETUpdating_message", new Object[] { targetFile.getFullPath() })); targetFile.setContents(contents, true, true, new SubProgressMonitor(subProgressMonitor, 1)); } subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETBuilding_message", new Object[] { project.getName() })); project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, new SubProgressMonitor(subProgressMonitor, 1)); boolean errors = hasErrors(subProgressMonitor, targetFile); if (!errors) { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETLoadingClass_message", new Object[] { jetCompiler.getSkeleton().getClassName() + ".class" })); List<URL> urls = new ArrayList<URL>(); urls.add(new File(project.getLocation() + "/" + javaProject.getOutputLocation().removeFirstSegments(1) + "/").toURI().toURL()); final Set<Bundle> bundles = new HashSet<Bundle>(); LOOP: for (IClasspathEntry jetEmitterClasspathEntry : jetEmitter.getClasspathEntries()) { IClasspathAttribute[] classpathAttributes = jetEmitterClasspathEntry.getExtraAttributes(); if (classpathAttributes != null) { for (IClasspathAttribute classpathAttribute : classpathAttributes) { if (classpathAttribute.getName().equals(CodeGenUtil.EclipseUtil.PLUGIN_ID_CLASSPATH_ATTRIBUTE_NAME)) { Bundle bundle = Platform.getBundle(classpathAttribute.getValue()); if (bundle != null) { bundles.add(bundle); continue LOOP; } } } } urls.add(new URL("platform:/resource" + jetEmitterClasspathEntry.getPath() + "/")); } URLClassLoader theClassLoader = AccessController.doPrivileged(new GetURLClassLoaderSuperBundlesAction(bundles, urls)); Class<?> theClass = theClassLoader.loadClass((packageName.length() == 0 ? "" : packageName + ".") + jetCompiler.getSkeleton().getClassName()); String methodName = jetCompiler.getSkeleton().getMethodName(); Method[] methods = theClass.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (methods[i].getName().equals(methodName)) { jetEmitter.setMethod(methods[i]); break; } } } subProgressMonitor.done(); } catch (CoreException exception) { throw new JETException(exception); } catch (Exception exception) { throw new JETException(exception); } finally { progressMonitor.done(); } }
00
Code Sample 1: public static long getLastModified(URL url) throws IOException { if ("file".equals(url.getProtocol())) { String externalForm = url.toExternalForm(); File file = new File(externalForm.substring(5)); return file.lastModified(); } else { URLConnection connection = url.openConnection(); long modified = connection.getLastModified(); try { InputStream is = connection.getInputStream(); if (is != null) is.close(); } catch (UnknownServiceException use) { } catch (IOException ioe) { } return modified; } } Code Sample 2: public static GenericDocumentTransformer<? extends GenericDocument> getTranformer(URL url) throws IOException { setDefaultImplementation(); if ("text/xml".equals(url.openConnection().getContentType()) || "application/xml".equals(url.openConnection().getContentType())) { return null; } else if ("text/html".equals(url.openConnection().getContentType())) { return null; } return null; }
00
Code Sample 1: public static void copyFile(File inputFile, File outputFile) throws IOException { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(inputFile).getChannel(); outChannel = new FileOutputStream(outputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { try { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } catch (IOException e) { throw e; } } } Code Sample 2: protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { ChallengeAction challengeAction; ManagerResponse challengeResponse; String challenge; String key; LoginAction loginAction; ManagerResponse loginResponse; if (socket == null) { connect(); } if (!socket.isConnected()) { connect(); } synchronized (protocolIdentifier) { if (protocolIdentifier.value == null) { try { protocolIdentifier.wait(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (protocolIdentifier.value == null) { disconnect(); if (reader != null && reader.getTerminationException() != null) { throw reader.getTerminationException(); } else { throw new TimeoutException("Timeout waiting for protocol identifier"); } } } challengeAction = new ChallengeAction("MD5"); try { challengeResponse = sendAction(challengeAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send challenge action", e); } if (challengeResponse instanceof ChallengeResponse) { challenge = ((ChallengeResponse) challengeResponse).getChallenge(); } else { disconnect(); throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + challengeResponse.getMessage()); } try { MessageDigest md; md = MessageDigest.getInstance("MD5"); if (challenge != null) { md.update(challenge.getBytes()); } if (password != null) { md.update(password.getBytes()); } key = ManagerUtil.toHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { disconnect(); throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } loginAction = new LoginAction(username, "MD5", key, eventMask); try { loginResponse = sendAction(loginAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send login action", e); } if (loginResponse instanceof ManagerError) { disconnect(); throw new AuthenticationFailedException(loginResponse.getMessage()); } version = determineVersion(); writer.setTargetVersion(version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); }
00
Code Sample 1: public static String md5(String texto) { String resultado; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(texto.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); resultado = hash.toString(16); if (resultado.length() < 32) { char chars[] = new char[32 - resultado.length()]; Arrays.fill(chars, '0'); resultado = new String(chars) + resultado; } } catch (NoSuchAlgorithmException e) { resultado = e.toString(); } return resultado; } Code Sample 2: private String getData(String myurl) throws Exception { URL url = new URL(myurl); uc = (HttpURLConnection) url.openConnection(); br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String temp = "", k = ""; while ((temp = br.readLine()) != null) { k += temp; } br.close(); return k; }
11
Code Sample 1: public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getName()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getName()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getName()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: private void fileCopy(final File src, final File dest) throws IOException { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
11
Code Sample 1: public static void main(String[] args) throws Exception { String linesep = System.getProperty("line.separator"); FileOutputStream fos = new FileOutputStream(new File("lib-licenses.txt")); fos.write(new String("JCP contains the following libraries. Please read this for comments on copyright etc." + linesep + linesep).getBytes()); fos.write(new String("Chemistry Development Kit, master version as of " + new Date().toString() + " (http://cdk.sf.net)" + linesep).getBytes()); fos.write(new String("Copyright 1997-2009 The CDK Development Team" + linesep).getBytes()); fos.write(new String("License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)" + linesep).getBytes()); fos.write(new String("Download: https://sourceforge.net/projects/cdk/files/" + linesep).getBytes()); fos.write(new String("Source available at: http://sourceforge.net/scm/?type=git&group_id=20024" + linesep + linesep).getBytes()); File[] files = new File(args[0]).listFiles(new JarFileFilter()); for (int i = 0; i < files.length; i++) { if (new File(files[i].getPath() + ".meta").exists()) { Map<String, Map<String, String>> metaprops = readProperties(new File(files[i].getPath() + ".meta")); Iterator<String> itsect = metaprops.keySet().iterator(); while (itsect.hasNext()) { String section = itsect.next(); fos.write(new String(metaprops.get(section).get("Library") + " " + metaprops.get(section).get("Version") + " (" + metaprops.get(section).get("Homepage") + ")" + linesep).getBytes()); fos.write(new String("Copyright " + metaprops.get(section).get("Copyright") + linesep).getBytes()); fos.write(new String("License: " + metaprops.get(section).get("License") + " (" + metaprops.get(section).get("LicenseURL") + ")" + linesep).getBytes()); fos.write(new String("Download: " + metaprops.get(section).get("Download") + linesep).getBytes()); fos.write(new String("Source available at: " + metaprops.get(section).get("SourceCode") + linesep + linesep).getBytes()); } } if (new File(files[i].getPath() + ".extra").exists()) { fos.write(new String("The author says:" + linesep).getBytes()); FileInputStream in = new FileInputStream(new File(files[i].getPath() + ".extra")); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } fos.write(linesep.getBytes()); } fos.close(); } Code Sample 2: 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(); } } }
11
Code Sample 1: public static byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(frase.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { return null; } } Code Sample 2: public String encryptLdapPassword(String algorithm) { String sEncrypted = _password; if ((_password != null) && (_password.length() > 0)) { algorithm = Val.chkStr(algorithm); boolean bMD5 = algorithm.equalsIgnoreCase("MD5"); boolean bSHA = algorithm.equalsIgnoreCase("SHA") || algorithm.equalsIgnoreCase("SHA1") || algorithm.equalsIgnoreCase("SHA-1"); if (bSHA || bMD5) { String sAlgorithm = "MD5"; if (bSHA) { sAlgorithm = "SHA"; } try { MessageDigest md = MessageDigest.getInstance(sAlgorithm); md.update(getPassword().getBytes("UTF-8")); sEncrypted = "{" + sAlgorithm + "}" + (new BASE64Encoder()).encode(md.digest()); } catch (NoSuchAlgorithmException e) { sEncrypted = null; e.printStackTrace(System.err); } catch (UnsupportedEncodingException e) { sEncrypted = null; e.printStackTrace(System.err); } } } return sEncrypted; }
11
Code Sample 1: public long getMD5Hash(String str) { MessageDigest m = null; try { m = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(str.getBytes(), 0, str.length()); return new BigInteger(1, m.digest()).longValue(); } Code Sample 2: public ChatClient registerPlayer(int playerId, String playerLogin) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.reset(); md.update(playerLogin.getBytes("UTF-8"), 0, playerLogin.length()); byte[] accountToken = md.digest(); byte[] token = generateToken(accountToken); ChatClient chatClient = new ChatClient(playerId, token); players.put(playerId, chatClient); return chatClient; }
00
Code Sample 1: private static void addFile(File file, ZipArchiveOutputStream zaos) throws IOException { String filename = null; filename = file.getName(); ZipArchiveEntry zae = new ZipArchiveEntry(filename); zae.setSize(file.length()); zaos.putArchiveEntry(zae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, zaos); zaos.closeArchiveEntry(); } Code Sample 2: protected String contentString() { String result = null; URL url; String encoding = null; try { url = url(); URLConnection connection = url.openConnection(); connection.setDoInput(true); connection.setDoOutput(false); connection.setUseCaches(false); for (Enumeration e = bindingKeys().objectEnumerator(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); if (key.startsWith("?")) { connection.setRequestProperty(key.substring(1), valueForBinding(key).toString()); } } if (connection.getContentEncoding() != null) { encoding = connection.getContentEncoding(); } if (encoding == null) { encoding = (String) valueForBinding("encoding"); } if (encoding == null) { encoding = "UTF-8"; } InputStream stream = connection.getInputStream(); byte bytes[] = ERXFileUtilities.bytesFromInputStream(stream); stream.close(); result = new String(bytes, encoding); } catch (IOException ex) { throw NSForwardException._runtimeExceptionForThrowable(ex); } return result; }
00
Code Sample 1: public Result search(Object object) { if (object == null || !(object instanceof String)) { return null; } String query = (String) object; Result hitResult = new Result(); Set<Hit> hits = new HashSet<Hit>(8); try { query = URLEncoder.encode(query, "UTF-8"); URL url = new URL("http://ajax.googleapis.com/ajax/services/search/web?start=0&rsz=large&v=1.0&q=" + query); URLConnection connection = url.openConnection(); connection.addRequestProperty("Referer", HTTP_REFERER); String line; StringBuilder builder = new StringBuilder(); InputStream input = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); while ((line = reader.readLine()) != null) { builder.append(line); } input.close(); String response = builder.toString(); JSONObject json = new JSONObject(response); LOGGER.debug(json.getString("responseData")); int count = json.getJSONObject("responseData").getJSONObject("cursor").getInt("estimatedResultCount"); hitResult.setEstimatedCount(count); JSONArray ja = json.getJSONObject("responseData").getJSONArray("results"); for (int i = 0; i < ja.length(); i++) { JSONObject j = ja.getJSONObject(i); Hit hit = new Hit(); String result = j.getString("titleNoFormatting"); hit.setTitle(result == null || result.equals("") ? "${EMPTY}" : result); result = j.getString("url"); hit.setUrl(new URL(result)); hits.add(hit); } } catch (Exception e) { e.printStackTrace(); LOGGER.error("Something went wrong..." + e.getMessage()); } hitResult.setHits(hits); return hitResult; } Code Sample 2: protected static byte[] hashPassword(byte[] saltBytes, String plaintextPassword) throws AssertionError { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw (AssertionError) new AssertionError("No MD5 message digest supported.").initCause(ex); } digest.update(saltBytes); try { digest.update(plaintextPassword.getBytes("utf-8")); } catch (UnsupportedEncodingException ex) { throw (AssertionError) new AssertionError("No UTF-8 encoding supported.").initCause(ex); } byte[] passwordBytes = digest.digest(); return passwordBytes; }
00
Code Sample 1: public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(File.separator) + 1, path.length())); String name = imageName.substring(0, imageName.lastIndexOf('.')); String extension = imageName.substring(imageName.lastIndexOf('.') + 1, imageName.length()); File imageFile = new File(path); directoryPath = "images" + File.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName; File newFile = new File(imagePath); if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.REPLACE_IMAGE"))) { Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name); if (aux.size() != 0) { int idImage = TIGDataBase.imageKeySearchName(name); TIGDataBase.deleteAsociatedOfImage(idImage); } } if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.ADD_IMAGE"))) { int i = 1; while (newFile.exists()) { imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); name = name + "_" + i; newFile = new File(imagePath); i++; } } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); imageName = name + "." + extension; try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } TIGDataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { createThumbnail(); } } } } Code Sample 2: public ResourceBundle getResources() { if (resources == null) { String lang = userProps.getProperty("language"); lang = "en"; try { URL myurl = getResource("Resources_" + lang.trim() + ".properties"); InputStream in = myurl.openStream(); resources = new PropertyResourceBundle(in); in.close(); } catch (Exception ex) { System.err.println("Error loading Resources"); return null; } } return resources; }
00
Code Sample 1: private void connectAndLogin() throws SocketException, IOException, ClassNotFoundException, SQLException, FileNotFoundException { lastOperationTime = System.currentTimeMillis(); exit(); ftp = new FTPClient(); ftp.connect(SERVER); ftp.login(USERNAME, PASSWORD); ftp.enterLocalPassiveMode(); ftp.setFileType(FTP.BINARY_FILE_TYPE); System.out.println("Connected to " + SERVER + "."); db = new DB(propertiesPath); } Code Sample 2: private void importUrl() throws ExtractaException { UITools.changeCursor(UITools.WAIT_CURSOR, this); try { m_sUrlString = m_urlTF.getText(); URL url = new URL(m_sUrlString); Document document = DomHelper.parseHtml(url.openStream()); m_inputPanel.setDocument(document); Edl edl = new Edl(); edl.addUrlDescriptor(new UrlDescriptor(m_sUrlString)); m_resultPanel.setContext(new ResultContext(edl, document, url)); setModified(true); } catch (IOException ex) { throw new ExtractaException("Can not open URL!", ex); } finally { UITools.changeCursor(UITools.DEFAULT_CURSOR, this); } }
00
Code Sample 1: @Override protected DefaultHttpClient doInBackground(Account... params) { AccountManager accountManager = AccountManager.get(mainActivity); Account account = params[0]; try { Bundle bundle = accountManager.getAuthToken(account, "ah", false, null, null).getResult(); Intent intent = (Intent) bundle.get(AccountManager.KEY_INTENT); if (intent != null) { mainActivity.startActivity(intent); } else { String auth_token = bundle.getString(AccountManager.KEY_AUTHTOKEN); http_client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); HttpGet http_get = new HttpGet("http://3dforandroid.appspot.com/_ah" + "/login?continue=http://localhost/&auth=" + auth_token); HttpResponse response = http_client.execute(http_get); if (response.getStatusLine().getStatusCode() != 302) return null; for (Cookie cookie : http_client.getCookieStore().getCookies()) { if (cookie.getName().equals("ACSID")) { authClient = http_client; String json = createJsonFile(Kind); initializeSQLite(); initializeServer(json); } } } } catch (OperationCanceledException e) { e.printStackTrace(); } catch (AuthenticatorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return http_client; } Code Sample 2: public static String executePost(String urlStr, String content) { StringBuffer result = new StringBuffer(); try { Authentication.doIt(); URL url = new URL(urlStr); System.out.println("Host: " + url.getHost()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); System.out.println("got connection "); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); connection.setRequestProperty("Content-Length", "" + content.length()); connection.setRequestProperty("SOAPAction", "\"http://niki-bt.act.cmis.csiro.org/SMSService/SendText\""); connection.setRequestMethod("POST"); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print(content); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { result.append(inputLine); } in.close(); out.close(); connection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String msg = result.toString(); if (msg != null) { int beginCut = msg.indexOf('>'); int endCut = msg.lastIndexOf('<'); if (beginCut != -1 && endCut != -1) { return msg.substring(beginCut + 1, endCut); } } return null; }
00
Code Sample 1: public static String getURL(String urlString, String getData, String postData) { try { if (getData != null) if (!getData.equals("")) urlString += "?" + getData; URL url = new URL(urlString); URLConnection connection = url.openConnection(); if (!postData.equals("")) { connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print(postData); out.close(); } BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); int inputLine; String output = ""; while ((inputLine = in.read()) != -1) output += (char) inputLine; in.close(); return output; } catch (Exception e) { return null; } } Code Sample 2: public static boolean downFile(String url, String username, String password, String remotePath, Date DBLastestDate, String localPath) { File dFile = new File(localPath); if (!dFile.exists()) { dFile.mkdir(); } boolean success = false; FTPClient ftp = new FTPClient(); ftp.setConnectTimeout(connectTimeout); System.out.println("FTP begin!!"); try { int reply; ftp.connect(url); ftp.login(username, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.changeWorkingDirectory(remotePath); String[] filesName = ftp.listNames(); if (DBLastestDate == null) { System.out.println(" 初次下载,全部下载 "); for (String string : filesName) { if (!string.matches("[0-9]{12}")) { continue; } File localFile = new File(localPath + "/" + string); OutputStream is = new FileOutputStream(localFile); ftp.retrieveFile(string, is); is.close(); } } else { System.out.println(" 加一下载 "); Date date = DBLastestDate; long ldate = date.getTime(); Date nowDate = new Date(); String nowDateStr = Constants.DatetoString(nowDate, Constants.Time_template_LONG); String fileName; do { ldate += 60 * 1000; Date converterDate = new Date(ldate); fileName = Constants.DatetoString(converterDate, Constants.Time_template_LONG); File localFile = new File(localPath + "/" + fileName); OutputStream is = new FileOutputStream(localFile); if (!ftp.retrieveFile(fileName, is)) { localFile.delete(); } is.close(); } while (fileName.compareTo(nowDateStr) < 0); } ftp.logout(); success = true; } catch (IOException e) { System.out.println("FTP timeout return"); e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; }
00
Code Sample 1: char[] DigestCalcHA1(String algorithm, String userName, String realm, String password, String nonce, String clientNonce) throws SaslException { byte[] hash; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(userName.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(realm.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(password.getBytes("UTF-8")); hash = md.digest(); if ("md5-sess".equals(algorithm)) { md.update(hash); md.update(":".getBytes("UTF-8")); md.update(nonce.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(clientNonce.getBytes("UTF-8")); hash = md.digest(); } } catch (NoSuchAlgorithmException e) { throw new SaslException("No provider found for MD5 hash", e); } catch (UnsupportedEncodingException e) { throw new SaslException("UTF-8 encoding not supported by platform.", e); } return convertToHex(hash); } 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: public synchronized String encrypt(String plaintext) throws PasswordException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new PasswordException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new PasswordException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new Base64Encoder()).encode(raw); return hash; } Code Sample 2: public static String getETag(final String uri, final long lastModified) { try { final MessageDigest dg = MessageDigest.getInstance("MD5"); dg.update(uri.getBytes("utf-8")); dg.update(new byte[] { (byte) ((lastModified >> 24) & 0xFF), (byte) ((lastModified >> 16) & 0xFF), (byte) ((lastModified >> 8) & 0xFF), (byte) (lastModified & 0xFF) }); return CBASE64Codec.encode(dg.digest()); } catch (final Exception ignore) { return uri + lastModified; } }
00
Code Sample 1: public static void initStaticStuff() { Enumeration<URL> urls = null; try { urls = Play.class.getClassLoader().getResources("play.static"); } catch (Exception e) { } while (urls != null && urls.hasMoreElements()) { URL url = urls.nextElement(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; while ((line = reader.readLine()) != null) { try { Class.forName(line); } catch (Exception e) { System.out.println("! Cannot init static : " + line); } } } catch (Exception ex) { Logger.error(ex, "Cannot load %s", url); } } } Code Sample 2: protected String readFileUsingFileUrl(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); InputStreamReader isr = new InputStreamReader(connection.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; }
00
Code Sample 1: private void doDissemTest(String what, boolean redirectOK) throws Exception { final int num = 30; System.out.println("Getting " + what + " " + num + " times..."); int i = 0; try { URL url = new URL(BASE_URL + "/get/" + what); for (i = 0; i < num; i++) { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream in = conn.getInputStream(); in.read(); in.close(); conn.disconnect(); } } catch (Exception e) { fail("Dissemination of " + what + " failed on iter " + i + ": " + e.getMessage()); } } Code Sample 2: public void createVendorSignature() { byte b; try { _vendorMessageDigest = MessageDigest.getInstance("MD5"); _vendorSig = Signature.getInstance("MD5/RSA/PKCS#1"); _vendorSig.initSign((PrivateKey) _vendorPrivateKey); _vendorMessageDigest.update(getBankString().getBytes()); _vendorMessageDigestBytes = _vendorMessageDigest.digest(); _vendorSig.update(_vendorMessageDigestBytes); _vendorSignatureBytes = _vendorSig.sign(); } catch (Exception e) { } ; }
00
Code Sample 1: public String generateKey(Message msg) { String text = msg.getDefaultMessage(); String meaning = msg.getMeaning(); if (text == null) { return null; } MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error initializing MD5", e); } try { md5.update(text.getBytes("UTF-8")); if (meaning != null) { md5.update(meaning.getBytes("UTF-8")); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 unsupported", e); } return StringUtils.toHexString(md5.digest()); } Code Sample 2: private Document getDocument(URL url) throws SAXException, IOException { InputStream is; try { is = url.openStream(); } catch (IOException io) { System.out.println("parameter error : The specified reading data is mistaken."); System.out.println(" Request URL is " + sourceUri); throw new IOException("\t" + io.toString()); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException pce) { System.out.println("error : The error of DocumentBuilder instance generation"); throw new RuntimeException(pce.toString()); } Document doc; try { doc = builder.parse(is); } catch (Exception e) { System.out.println("error : parse of reading data went wrong."); System.out.println(" Request URL is " + sourceUri); throw new RuntimeException(e.toString()); } return doc; }
11
Code Sample 1: public static String encryptPassword(String password) throws PasswordException { String hash = null; if (password != null && !password.equals("")) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); hash = (new BASE64Encoder()).encode(raw); } catch (NoSuchAlgorithmException nsae) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } catch (UnsupportedEncodingException uee) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } } return hash; } Code Sample 2: public static String createHash(String seed) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Can't happen!", e); } try { md.update(seed.getBytes(CHARSET)); md.update(String.valueOf(System.currentTimeMillis()).getBytes(CHARSET)); return toHexString(md.digest()); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Can't happen!", e); } }
11
Code Sample 1: private void simulate() throws Exception { BufferedWriter out = null; out = new BufferedWriter(new FileWriter(outFile)); out.write("#Thread\tReputation\tAction\n"); out.flush(); System.out.println("Simulate..."); File file = new File(trsDemoSimulationfile); ObtainUserReputation obtainUserReputationRequest = new ObtainUserReputation(); ObtainUserReputationResponse obtainUserReputationResponse; RateUser rateUserRequest; RateUserResponse rateUserResponse; FileInputStream fis = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String call = br.readLine(); while (call != null) { rateUserRequest = generateRateUserRequest(call); try { rateUserResponse = trsPort.rateUser(rateUserRequest); System.out.println("----------------R A T I N G-------------------"); System.out.println("VBE: " + rateUserRequest.getVbeId()); System.out.println("VO: " + rateUserRequest.getVoId()); System.out.println("USER: " + rateUserRequest.getUserId()); System.out.println("SERVICE: " + rateUserRequest.getServiceId()); System.out.println("ACTION: " + rateUserRequest.getActionId()); System.out.println("OUTCOME: " + rateUserResponse.isOutcome()); System.out.println("----------------------------------------------"); assertEquals("The outcome field of the rateUser should be true: MESSAGE=" + rateUserResponse.getMessage(), true, rateUserResponse.isOutcome()); } catch (RemoteException e) { fail(e.getMessage()); } obtainUserReputationRequest.setIoi(null); obtainUserReputationRequest.setServiceId(null); obtainUserReputationRequest.setUserId(rateUserRequest.getUserId()); obtainUserReputationRequest.setVbeId(rateUserRequest.getVbeId()); obtainUserReputationRequest.setVoId(null); try { obtainUserReputationResponse = trsPort.obtainUserReputation(obtainUserReputationRequest); System.out.println("-----------R E P U T A T I O N----------------"); System.out.println("VBE: " + obtainUserReputationRequest.getVbeId()); System.out.println("VO: " + obtainUserReputationRequest.getVoId()); System.out.println("USER: " + obtainUserReputationRequest.getUserId()); System.out.println("SERVICE: " + obtainUserReputationRequest.getServiceId()); System.out.println("IOI: " + obtainUserReputationRequest.getIoi()); System.out.println("REPUTATION: " + obtainUserReputationResponse.getReputation()); System.out.println("----------------------------------------------"); assertEquals("The outcome field of the obtainUserReputation should be true: MESSAGE=" + obtainUserReputationResponse.getMessage(), true, obtainUserReputationResponse.isOutcome()); assertEquals(0.0, obtainUserReputationResponse.getReputation(), 1.0); } catch (RemoteException e) { fail(e.getMessage()); } obtainUserReputationRequest.setIoi(null); obtainUserReputationRequest.setServiceId(null); obtainUserReputationRequest.setUserId(rateUserRequest.getUserId()); obtainUserReputationRequest.setVbeId(rateUserRequest.getVbeId()); obtainUserReputationRequest.setVoId(rateUserRequest.getVoId()); try { obtainUserReputationResponse = trsPort.obtainUserReputation(obtainUserReputationRequest); System.out.println("-----------R E P U T A T I O N----------------"); System.out.println("VBE: " + obtainUserReputationRequest.getVbeId()); System.out.println("VO: " + obtainUserReputationRequest.getVoId()); System.out.println("USER: " + obtainUserReputationRequest.getUserId()); System.out.println("SERVICE: " + obtainUserReputationRequest.getServiceId()); System.out.println("IOI: " + obtainUserReputationRequest.getIoi()); System.out.println("REPUTATION: " + obtainUserReputationResponse.getReputation()); System.out.println("----------------------------------------------"); assertEquals("The outcome field of the obtainUserReputation should be true: MESSAGE=" + obtainUserReputationResponse.getMessage(), true, obtainUserReputationResponse.isOutcome()); assertEquals(0.0, obtainUserReputationResponse.getReputation(), 1.0); } catch (RemoteException e) { fail(e.getMessage()); } call = br.readLine(); } fis.close(); br.close(); out.flush(); out.close(); } Code Sample 2: private static synchronized boolean doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { destFile = new File(destFile + FILE_SEPARATOR + srcFile.getName()); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } return destFile.exists(); }
00
Code Sample 1: public GGMunicipalities getListMunicipalities() throws IllegalStateException, GGException, Exception { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("method", "gg.photos.geo.getListMunicipality")); qparams.add(new BasicNameValuePair("key", this.key)); String url = REST_URL + "?" + URLEncodedUtils.format(qparams, "UTF-8"); URI uri = new URI(url); HttpGet httpget = new HttpGet(uri); HttpResponse response = httpClient.execute(httpget); int status = response.getStatusLine().getStatusCode(); errorCheck(response, status); InputStream content = response.getEntity().getContent(); GGMunicipalities municipalities = JAXB.unmarshal(content, GGMunicipalities.class); return municipalities; } Code Sample 2: public void create(String oid, Serializable obj) throws PersisterException { String key = getLock(oid); if (key != null) { throw new PersisterException("Object already exists: OID = " + oid); } Connection conn = null; PreparedStatement ps = null; try { byte[] data = serialize(obj); conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("insert into " + _table_name + "(" + _oid_col + "," + _data_col + "," + _ts_col + ") values (?,?,?)"); ps.setString(1, oid); ps.setBinaryStream(2, new ByteArrayInputStream(data), data.length); ps.setLong(3, System.currentTimeMillis()); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to create object: OID = " + oid, th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void guardarCantidad() { try { String can = String.valueOf(cantidadArchivos); File archivo = new File("cantidadArchivos.txt"); FileWriter fw = new FileWriter(archivo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter salida = new PrintWriter(bw); salida.print(can); salida.close(); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("cantidadArchivos.zip"); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[buffer]; File f = new File("cantidadArchivos.txt"); FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, buffer); ZipEntry entry = new ZipEntry("cantidadArchivos.txt"); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, buffer)) != -1) out.write(data, 0, count); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
00
Code Sample 1: private void copyFile(File srcFile, File destFile) throws IOException { if (!(srcFile.exists() && srcFile.isFile())) throw new IllegalArgumentException("Source file doesn't exist: " + srcFile.getAbsolutePath()); if (destFile.exists() && destFile.isDirectory()) throw new IllegalArgumentException("Destination file is directory: " + destFile.getAbsolutePath()); FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[4096]; int no = 0; try { while ((no = in.read(buffer)) != -1) out.write(buffer, 0, no); } finally { in.close(); out.close(); } } 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: protected URLConnection openConnection(URL url) throws IOException { URLConnection con = url.openConnection(); if ("HTTPS".equalsIgnoreCase(url.getProtocol())) { HttpsURLConnection scon = (HttpsURLConnection) con; try { scon.setSSLSocketFactory(SSLUtil.getSSLSocketFactory(ks, password, alias)); scon.setHostnameVerifier(SSLUtil.getHostnameVerifier(SSLUtil.HOSTCERT_MIN_CHECK)); } catch (GeneralException e) { throw new IOException(e.getMessage()); } catch (GeneralSecurityException e) { throw new IOException(e.getMessage()); } } return con; } Code Sample 2: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
11
Code Sample 1: public static void copyFile(File src, File dest) throws IOException { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; fIn = new FileInputStream(src); fOut = new FileOutputStream(dest); fIChan = fIn.getChannel(); fOChan = fOut.getChannel(); fSize = fIChan.size(); mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); fOChan.write(mBuf); fIChan.close(); fIn.close(); fOChan.close(); fOut.close(); } Code Sample 2: private BinaryDocument documentFor(String code, String type, int diagramIndex) { code = code.replaceAll("\n", "").replaceAll("\t", "").trim().replaceAll(" ", "%20"); StringBuilder builder = new StringBuilder("http://yuml.me/diagram/"); builder.append(type).append("/"); builder.append(code); URL url; try { url = new URL(builder.toString()); String name = "uml" + diagramIndex + ".png"; diagramIndex++; BinaryDocument pic = new BinaryDocument(name, "image/png"); IOUtils.copy(url.openStream(), pic.getContent().getOutputStream()); return pic; } catch (MalformedURLException e) { throw ManagedIOException.manage(e); } catch (IOException e) { throw ManagedIOException.manage(e); } }
00
Code Sample 1: public void delete(String user) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate("delete from Principals where PrincipalId = '" + user + "'"); stmt.executeUpdate("delete from Roles where PrincipalId = '" + user + "'"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: public boolean validateLogin(String username, String password) { boolean user_exists = false; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); String password_hash = hash.toString(16); statement = connect.prepareStatement("SELECT id from toepen.users WHERE username = ? AND password = ?"); statement.setString(1, username); statement.setString(2, password_hash); resultSet = statement.executeQuery(); while (resultSet.next()) { user_exists = true; } } catch (Exception ex) { System.out.println(ex); } finally { close(); return user_exists; } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: private Attachment setupSimpleAttachment(Context context, long messageId, boolean withBody) throws IOException { Attachment attachment = new Attachment(); attachment.mFileName = "the file.jpg"; attachment.mMimeType = "image/jpg"; attachment.mSize = 0; attachment.mContentId = null; attachment.mContentUri = "content://com.android.email/1/1"; attachment.mMessageKey = messageId; attachment.mLocation = null; attachment.mEncoding = null; if (withBody) { InputStream inStream = new ByteArrayInputStream(TEST_STRING.getBytes()); File cacheDir = context.getCacheDir(); File tmpFile = File.createTempFile("setupSimpleAttachment", "tmp", cacheDir); OutputStream outStream = new FileOutputStream(tmpFile); IOUtils.copy(inStream, outStream); attachment.mContentUri = "file://" + tmpFile.getAbsolutePath(); } return attachment; }
00
Code Sample 1: private String readHtmlFile(String htmlFileName) { StringBuffer buffer = new StringBuffer(); java.net.URL url = getClass().getClassLoader().getResource("freestyleLearning/homeCore/help/" + htmlFileName); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String string = " "; while (string != null) { string = reader.readLine(); if (string != null) buffer.append(string); } } catch (Exception exc) { System.out.println(exc); } return new String(buffer); } Code Sample 2: private Element makeRequest(String link) { try { URL url = new URL(link); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); InputStream in = conn.getInputStream(); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(in); Element element = document.getDocumentElement(); element.normalize(); if (checkRootTag(element)) { return element; } else { return null; } } catch (IOException e) { e.printStackTrace(); return null; } catch (ParserConfigurationException e) { e.printStackTrace(); return null; } catch (SAXException e) { e.printStackTrace(); return null; } }
00
Code Sample 1: public void run() { FileInputStream src; try { src = new FileInputStream(srcName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileOutputStream dest; FileChannel srcC = src.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(BUFFER_SIZE); try { int i = 1; int fileNo = 0; long maxByte = this.maxSize << 10; long nbByte = srcC.size(); long nbFile = (nbByte / maxByte) + 1; for (fileNo = 0; fileNo < nbFile; fileNo++) { long fileByte = 0; String destName = srcName + "_" + fileNo; dest = new FileOutputStream(destName); FileChannel destC = dest.getChannel(); while ((i > 0) && fileByte < maxByte) { i = srcC.read(buf); buf.flip(); fileByte += i; destC.write(buf); buf.compact(); } destC.close(); dest.close(); } } catch (IOException e1) { e1.printStackTrace(); return; } } Code Sample 2: public void handler(List<GoldenBoot> gbs, TargetPage target) { try { URL url = new URL(target.getUrl()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; String include = "Top Scorers"; while ((line = reader.readLine()) != null) { if (line.indexOf(include) != -1) { buildGildenBoot(line, gbs); break; } } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
00
Code Sample 1: public ResourceMigrator getCompletedResourceMigrator() { return new ResourceMigrator() { public void migrate(InputMetadata meta, InputStream inputStream, OutputCreator outputCreator) throws IOException, ResourceMigrationException { OutputStream outputStream = outputCreator.createOutputStream(); IOUtils.copy(inputStream, outputStream); } }; } Code Sample 2: public List<AnalyzerResult> analyze(LWComponent c, boolean tryFallback) { List<AnalyzerResult> results = new ArrayList<AnalyzerResult>(); try { URL url = new URL(DEFAULT_FLOW_URL + "?" + DEFAULT_INPUT + "=" + c.getLabel()); if (flow != null) { url = new URL(flow.getUrl() + "?" + flow.getInputList().get(0) + "=" + getSpecFromComponent(c)); } System.setProperty("javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl"); XMLDecoder decoder = new XMLDecoder(url.openStream()); Map map = (Map) decoder.readObject(); for (Object key : map.keySet()) { results.add(new AnalyzerResult(key.toString(), map.get(key).toString())); } } catch (Exception ex) { ex.printStackTrace(); VueUtil.alert("Can't Execute Flow on the node " + c.getLabel(), "Can't Execute Seasr flow"); } return results; }
11
Code Sample 1: public static void notify(String msg) throws Exception { String url = "http://api.clickatell.com/http/sendmsg?"; url = add(url, "user", user); url = add(url, "password", password); url = add(url, "api_id", apiId); url = add(url, "to", to); url = add(url, "text", msg); URL u = new URL(url); URLConnection c = u.openConnection(); InputStream is = c.getInputStream(); IOUtils.copy(is, System.out); IOUtils.closeQuietly(is); System.out.println(); } Code Sample 2: @Override public void run() { log.debug("Now running...."); log.debug("Current env. variables:"); try { this.infoNotifiers("Environment parameters after modifications:"); this.logEnvironment(); this.infoNotifiers("Dump thread will now run..."); this.endNotifiers(); this.process = this.pb.start(); this.process.waitFor(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } List<String> cmd = new LinkedList<String>(); cmd.add("gzip"); cmd.add(info.getDumpFileName()); File basePath = this.pb.directory(); this.pb = new ProcessBuilder(cmd); this.pb.directory(basePath); log.debug("Executing: " + StringUtils.join(cmd.iterator(), ' ')); this.process = this.pb.start(); this.process.waitFor(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump GZip Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } info.setDumpFileName(info.getDumpFileName() + ".gz"); info.setMD5SumFileName(info.getDumpFileName() + ".md5sum"); cmd = new LinkedList<String>(); cmd.add("md5sum"); cmd.add("-b"); cmd.add(info.getDumpFileName()); log.debug("Executing: " + StringUtils.join(cmd.iterator(), ' ')); this.pb = new ProcessBuilder(cmd); this.pb.directory(basePath); this.process = this.pb.start(); BufferedOutputStream md5sumFileOut = new BufferedOutputStream(new FileOutputStream(basePath.getAbsolutePath() + File.separatorChar + info.getMD5SumFileName())); IOUtils.copy(this.process.getInputStream(), md5sumFileOut); this.process.waitFor(); md5sumFileOut.flush(); md5sumFileOut.close(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump GZip MD5Sum Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } else { this.startNotifiers(); this.infoNotifiers("Dump, gzip and md5sum sucessfuly completed."); this.endNotifiers(); } } catch (IOException e) { String message = "IOException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } catch (InterruptedException e) { String message = "InterruptedException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } catch (IntegrationException e) { String message = "IntegrationException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } Code Sample 2: public static void convertEncoding(File infile, File outfile, String from, String to) throws IOException, UnsupportedEncodingException { InputStream in; if (infile != null) in = new FileInputStream(infile); else in = System.in; OutputStream out; outfile.createNewFile(); if (outfile != null) out = new FileOutputStream(outfile); else out = System.out; if (from == null) from = System.getProperty("file.encoding"); if (to == null) to = "Unicode"; Reader r = new BufferedReader(new InputStreamReader(in, from)); Writer w = new BufferedWriter(new OutputStreamWriter(out, to)); char[] buffer = new char[4096]; int len; while ((len = r.read(buffer)) != -1) w.write(buffer, 0, len); r.close(); w.close(); }
00
Code Sample 1: public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine, outputLine; inputLine = in.readLine(); String dist_metric = in.readLine(); File outFile = new File("data.txt"); FileWriter outw = new FileWriter(outFile); outw.write(inputLine); outw.close(); File sample_coords = new File("sample_coords.txt"); sample_coords.delete(); File sp_coords = new File("sp_coords.txt"); sp_coords.delete(); try { System.out.println("Running python script..."); System.out.println("Command: " + "python l19test.py " + "\"" + dist_metric + "\""); Process pr = Runtime.getRuntime().exec("python l19test.py " + dist_metric); BufferedReader br = new BufferedReader(new InputStreamReader(pr.getErrorStream())); String line; while ((line = br.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); System.out.println("Process Exit Value: " + exitVal); System.out.println("done."); } catch (Exception e) { System.out.println("Unable to run python script for PCoA analysis"); } File myFile = new File("sp_coords.txt"); byte[] mybytearray = new byte[(new Long(myFile.length())).intValue()]; FileInputStream fis = new FileInputStream(myFile); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); for (int i = 0; i < myFile.length(); i++) { out.writeByte(fis.read()); } myFile = new File("sample_coords.txt"); mybytearray = new byte[(int) myFile.length()]; fis = new FileInputStream(myFile); fis.read(mybytearray); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); out.write(mybytearray); myFile = new File("evals.txt"); mybytearray = new byte[(new Long(myFile.length())).intValue()]; fis = new FileInputStream(myFile); fis.read(mybytearray); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); out.write(mybytearray); out.flush(); out.close(); in.close(); clientSocket.close(); serverSocket.close(); } Code Sample 2: private static void checkForUpdates() { LOGGER.debug("Checking for Updates"); new Thread() { @Override public void run() { String lastVersion = null; try { URL projectSite = new URL("http://code.google.com/p/g15lastfm/"); URLConnection urlC = projectSite.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlC.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("<strong>Current version:")) { lastVersion = inputLine; break; } } in.close(); if (lastVersion != null && lastVersion.length() > 0) { lastVersion = lastVersion.substring(lastVersion.indexOf("Current version:") + 16); lastVersion = lastVersion.substring(0, lastVersion.indexOf("</strong>")).trim(); LOGGER.debug("last Version=" + lastVersion); } if (lastVersion.equals(getVersion())) LOGGER.debug("Not necessary to update"); else { LOGGER.debug("New update found!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (JOptionPane.showConfirmDialog(null, "New version of G15Lastfm is available to download!", "New Update for G15Lastfm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { LOGGER.debug("User choose to update, opening browser."); Desktop desktop = Desktop.getDesktop(); try { desktop.browse(new URI("http://code.google.com/p/g15lastfm/")); } catch (IOException e) { LOGGER.debug(e); } catch (URISyntaxException e) { LOGGER.debug(e); } } else { LOGGER.debug("User choose to not update."); } } }); } } catch (Exception e) { LOGGER.debug(e); } } }.start(); }