label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
11
|
Code Sample 1:
private void copyTemplate(String resource, OutputStream outputStream) throws IOException { URL url = Tools.getResource(resource); if (url == null) { throw new IOException("could not find resource"); } BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF-8"))); String line = null; do { line = reader.readLine(); if (line != null) { writer.write(line); writer.newLine(); } } while (line != null); reader.close(); writer.close(); }
Code Sample 2:
public List<String> query(String query) throws IOException { List<String> list = new LinkedList<String>(); query = URLEncoder.encode(query, "UTF-8"); String queryurl = baseurl + "?type=tuples&lang=itql&format=csv&query=" + query; URL url = new URL(queryurl); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = reader.readLine(); while (line != null) { list.add(line); line = reader.readLine(); } reader.close(); return list; }
|
11
|
Code Sample 1:
public void zipUp() throws PersistenceException { ZipOutputStream out = null; try { if (!backup.exists()) backup.createNewFile(); out = new ZipOutputStream(new FileOutputStream(backup)); out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String file : backupDirectory.list()) { logger.debug("Deflating: " + file); FileInputStream in = null; try { in = new FileInputStream(new File(backupDirectory, file)); out.putNextEntry(new ZipEntry(file)); IOUtils.copy(in, out); } finally { out.closeEntry(); if (null != in) in.close(); } } FileUtils.deleteDirectory(backupDirectory); } catch (Exception ex) { logger.error("Unable to ZIP the backup {" + backupDirectory.getAbsolutePath() + "}.", ex); throw new PersistenceException(ex); } finally { try { if (null != out) out.close(); } catch (IOException e) { logger.error("Unable to close ZIP output stream.", e); } } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
private 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 = 0L; 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 < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + 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!"); }
|
00
|
Code Sample 1:
private Document saveFile(Document document, File file) throws Exception { List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { preference = preferences.get(0); } SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); String repo = preference.getRepository(); Calendar calendar = Calendar.getInstance(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(sdf.format(calendar.getTime())); sbFolder.append(File.separator).append(calendar.get(Calendar.HOUR_OF_DAY)); File folder = new File(sbRepo.append(sbFolder).toString()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()); StringBuffer fname = new StringBuffer(document.getId().toString()); fname.append(".").append(document.getExt()); sbFile.append(File.separator).append(fname); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } return document; }
Code Sample 2:
public static ArrayList<Quote> fetchAllQuotes(String symbol, Date from, Date to) { try { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(from); String monthFrom = (new Integer(calendar.get(GregorianCalendar.MONTH))).toString(); String dayFrom = (new Integer(calendar.get(GregorianCalendar.DAY_OF_MONTH))).toString(); String yearFrom = (new Integer(calendar.get(GregorianCalendar.YEAR))).toString(); calendar.setTime(to); String monthTo = (new Integer(calendar.get(GregorianCalendar.MONTH))).toString(); String dayTo = (new Integer(calendar.get(GregorianCalendar.DAY_OF_MONTH))).toString(); String yearTo = (new Integer(calendar.get(GregorianCalendar.YEAR))).toString(); URL url = new URL("http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=" + monthFrom + "&b=" + dayFrom + "&c=" + yearFrom + "&d=" + monthTo + "&e=" + dayTo + "&f=" + yearTo + "&g=d&ignore=.csv"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; ArrayList<Quote> result = new ArrayList<Quote>(); reader.readLine(); while ((line = reader.readLine()) != null) { String[] values = line.split(","); String date = values[0]; Date dateQuote = new SimpleDateFormat("yyyy-MM-dd").parse(date); double open = Double.valueOf(values[1]); double high = Double.valueOf(values[2]); double low = Double.valueOf(values[3]); double close = Double.valueOf(values[4]); long volume = Long.valueOf(values[5]); double adjClose = Double.valueOf(values[6]); Quote q = new Quote(dateQuote, open, high, low, close, volume, adjClose); result.add(q); } reader.close(); Collections.reverse(result); return result; } catch (MalformedURLException e) { System.out.println("URL malformee"); } catch (IOException e) { System.out.println("Donnees illisibles"); } catch (ParseException e) { e.printStackTrace(); } return null; }
|
00
|
Code Sample 1:
public static Properties addAttributes(Node node, String[] names, Properties props, LogEvent evt) throws ConfigurationException { if (props == null) props = new Properties(); try { MessageDigest md = MessageDigest.getInstance("MD5"); for (int i = 0; i < names.length; i++) { String value = addProperty(names[i], props, node, evt); if (value != null) { md.update(names[i].getBytes()); md.update(value.getBytes()); } } byte[] digest = md.digest(); evt.addMessage("digest " + ISOUtil.hexString(digest)); props.put(DIGEST_PROPERTY, digest); } catch (NoSuchAlgorithmException e) { throw new ConfigurationException(e); } return props; }
Code Sample 2:
public void testReleaseOnEntityWriteTo() throws Exception { HttpParams params = defaultParams.copy(); ConnManagerParams.setMaxTotalConnections(params, 1); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1)); ThreadSafeClientConnManager mgr = createTSCCM(params, null); assertEquals(0, mgr.getConnectionsInPool()); DefaultHttpClient client = new DefaultHttpClient(mgr, params); HttpGet httpget = new HttpGet("/random/20000"); HttpHost target = getServerHttp(); HttpResponse response = client.execute(target, httpget); ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null); try { connreq.getConnection(250, TimeUnit.MILLISECONDS); fail("ConnectionPoolTimeoutException should have been thrown"); } catch (ConnectionPoolTimeoutException expected) { } HttpEntity e = response.getEntity(); assertNotNull(e); ByteArrayOutputStream outsteam = new ByteArrayOutputStream(); e.writeTo(outsteam); assertEquals(1, mgr.getConnectionsInPool()); connreq = mgr.requestConnection(new HttpRoute(target), null); ManagedClientConnection conn = connreq.getConnection(250, TimeUnit.MILLISECONDS); mgr.releaseConnection(conn, -1, null); mgr.shutdown(); }
|
11
|
Code Sample 1:
public static void zip(File srcDir, File destFile, FileFilter filter) throws IOException { ZipOutputStream out = null; try { out = new ZipOutputStream(new FileOutputStream(destFile)); Collection<File> files = FileUtils.listFiles(srcDir, TrueFileFilter.TRUE, TrueFileFilter.TRUE); for (File f : files) { if (filter == null || filter.accept(f)) { FileInputStream in = FileUtils.openInputStream(f); out.putNextEntry(new ZipEntry(Util.relativePath(srcDir, f).replace('\\', '/'))); IOUtils.copyLarge(in, out); out.closeEntry(); IOUtils.closeQuietly(in); } } IOUtils.closeQuietly(out); } catch (Throwable t) { throw new IOException("Failed to create zip file", t); } finally { if (out != null) { out.flush(); IOUtils.closeQuietly(out); } } }
Code Sample 2:
private void outputSignedOpenDocument(byte[] signatureData) throws IOException { LOG.debug("output signed open document"); OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream(); if (null == signedOdfOutputStream) { throw new NullPointerException("signedOpenDocumentOutputStream is null"); } ZipOutputStream zipOutputStream = new ZipOutputStream(signedOdfOutputStream); ZipInputStream zipInputStream = new ZipInputStream(this.getOpenDocumentURL().openStream()); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) { zipOutputStream.putNextEntry(zipEntry); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
|
00
|
Code Sample 1:
@Override @RemoteMethod public synchronized boolean copy(int idAnexo) { try { Anexo anexo = selectById(idAnexo); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Usuario usuario = (Usuario) auth.getPrincipal(); if (anexo.getAssinado() == 1 && anexo.getIdAssinadoPor() != usuario.getIdUsuario()) { deleteAnexoFromTemp(anexo); return false; } Carteira carteiraUsuario = carteiraService.selectById(usuario.getIdCarteira()); DocumentoDetalhes documentoDetalhes = anexo.getDocumentoDetalhes(); Set<Documento> documentos = documentoDetalhes.getDocumentosByCarteira(); boolean havePermission = false; for (Documento documento : documentos) { Carteira carteiraDocumento = documento.getCarteira(); if (carteiraDocumento != null) { if (carteiraDocumento.getIdCarteira() == carteiraUsuario.getIdCarteira()) { havePermission = true; System.out.println("tem permisssao: " + havePermission); break; } } } if (!havePermission) { System.out.println("Não tem permissao."); return false; } FileInputStream fis = new FileInputStream(new File(config.baseDir + "/temp/" + anexo.getAnexoCaminho())); FileOutputStream fos = new FileOutputStream(new File(config.baseDir + "/arquivos_upload_direto/" + anexo.getAnexoCaminho())); IOUtils.copy(fis, fos); String txtHistorico = "(Edição) -" + anexo.getAnexoNome() + "-"; txtHistorico += usuario.getUsuLogin(); Historico historico = new Historico(); historico.setCarteira(carteiraUsuario); historico.setDataHoraHistorico(new Date()); historico.setHistorico(txtHistorico); historico.setDocumentoDetalhes(documentoDetalhes); historico.setUsuario(usuario); historicoService.save(historico); return deleteAnexoFromTemp(anexo); } catch (FileNotFoundException e) { System.out.println("FileNotFoundException"); e.printStackTrace(); return false; } catch (IOException e) { System.out.println("IOException"); e.printStackTrace(); return false; } catch (Exception e) { System.out.println("AnexoServiceImpl.copy ERRO DESCONHECIDO"); e.printStackTrace(); return false; } }
Code Sample 2:
public static void main(String[] args) { try { URL url = new URL("http://www.lineadecodigo.com"); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); } catch (Throwable t) { } String inputLine; String inputText = ""; while ((inputLine = in.readLine()) != null) { inputText = inputText + inputLine; } System.out.println("El contenido de la URL es: " + inputText); in.close(); } catch (MalformedURLException me) { System.out.println("URL erronea"); } catch (IOException ioe) { System.out.println("Error IO"); } }
|
11
|
Code Sample 1:
public final boolean login(String user, String pass) { if (user == null || pass == null) return false; connectionInfo.setData("com.tensegrity.palojava.pass#" + user, pass); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); pass = asHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { throw new PaloException("Failed to create encrypted password for " + "user '" + user + "'!", ex); } connectionInfo.setUser(user); connectionInfo.setPassword(pass); return loginInternal(user, pass); }
Code Sample 2:
public static String sha1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("UTF-8"), 0, text.length()); byte[] sha1hash = md.digest(); return convertToHex(sha1hash); }
|
11
|
Code Sample 1:
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); } } }); }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
11
|
Code Sample 1:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
Code Sample 2:
public String getClass(EmeraldjbBean eb) throws EmeraldjbException { Entity entity = (Entity) eb; StringBuffer sb = new StringBuffer(); String myPackage = getPackageName(eb); sb.append("package " + myPackage + ";\n"); sb.append("\n"); DaoValuesGenerator valgen = new DaoValuesGenerator(); String values_class_name = valgen.getClassName(entity); sb.append("\n"); List importList = new Vector(); importList.add("java.io.FileOutputStream;"); importList.add("java.io.FileInputStream;"); importList.add("java.io.DataInputStream;"); importList.add("java.io.DataOutputStream;"); importList.add("java.io.IOException;"); importList.add("java.sql.Date;"); importList.add(valgen.getPackageName(eb) + "." + values_class_name + ";"); Iterator it = importList.iterator(); while (it.hasNext()) { String importName = (String) it.next(); sb.append("import " + importName + "\n"); } sb.append("\n"); String proto_version = entity.getPatternValue(GeneratorConst.PATTERN_STREAM_PROTO_VERSION, "1"); String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + "\n"); sb.append("{" + "\n public static final int PROTO_VERSION=" + proto_version + ";"); sb.append("\n\n"); StringBuffer f_writer = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); while (it.hasNext()) { Member member = (Member) it.next(); String nm = member.getName(); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToBinaryCode(pad, "dos", getter + "()")); f_reader.append(gen_type.getFromBinaryCode(pad, "din", setter)); } String reader_vars = ""; sb.append("\n public static void writeToFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileOutputStream fos = new FileOutputStream(file_nm);" + "\n DataOutputStream dos = new DataOutputStream(fos);" + "\n writeStream(dos, obj);" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileInputStream fis = new FileInputStream(file_nm);" + "\n DataInputStream dis = new DataInputStream(fis);" + "\n readStream(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeStream(DataOutputStream dos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n dos.writeByte(PROTO_VERSION);" + "\n " + f_writer + "\n } // end of writeStream" + "\n" + "\n public static void readStream(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + "\n int proto_version = din.readByte();" + "\n if (proto_version==" + proto_version + ") readStreamV1(din,obj);" + "\n } // end of readStream" + "\n" + "\n public static void readStreamV1(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + reader_vars + f_reader + "\n } // end of readStreamV1" + "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"); return sb.toString(); }
|
00
|
Code Sample 1:
public ViewedCandidatesIndex getAllViewedCandidates() throws BookKeeprCommunicationException { try { synchronized (httpClient) { HttpGet req = new HttpGet(remoteHost.getUrl() + "/cand/viewed"); req.setHeader("Accept-Encoding", "gzip"); HttpResponse resp = httpClient.execute(req); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { try { InputStream in = resp.getEntity().getContent(); Header hdr = resp.getFirstHeader("Content-Encoding"); String enc = ""; if (hdr != null) { enc = resp.getFirstHeader("Content-Encoding").getValue(); } if (enc.equals("gzip")) { in = new GZIPInputStream(in); } XMLAble xmlable = XMLReader.read(in); in.close(); if (xmlable instanceof ViewedCandidatesIndex) { ViewedCandidatesIndex p = (ViewedCandidatesIndex) xmlable; return p; } else { resp.getEntity().consumeContent(); throw new BookKeeprCommunicationException("BookKeepr returned the wrong thing for ViewedCandidatesIndex"); } } catch (SAXException ex) { Logger.getLogger(BookKeeprConnection.class.getName()).log(Level.WARNING, "Got a malformed message from the bookkeepr", ex); throw new BookKeeprCommunicationException(ex); } } else { throw new BookKeeprCommunicationException("Got a " + resp.getStatusLine().getStatusCode() + " from the BookKeepr"); } } } catch (HttpException ex) { throw new BookKeeprCommunicationException(ex); } catch (IOException ex) { throw new BookKeeprCommunicationException(ex); } catch (URISyntaxException ex) { throw new BookKeeprCommunicationException(ex); } }
Code Sample 2:
private boolean enregistreToi() { PrintWriter lEcrivain; String laDest = "./img_types/" + sonImage; if (!new File("./img_types").exists()) { new File("./img_types").mkdirs(); } try { FileChannel leFicSource = new FileInputStream(sonFichier).getChannel(); FileChannel leFicDest = new FileOutputStream(laDest).getChannel(); leFicSource.transferTo(0, leFicSource.size(), leFicDest); leFicSource.close(); leFicDest.close(); lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true)); lEcrivain.println(sonNom); lEcrivain.println(sonImage); if (sonOptionRadio1.isSelected()) { lEcrivain.println("0:?"); } if (sonOptionRadio2.isSelected()) { lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE)); } if (sonOptionRadio3.isSelected()) { lEcrivain.println("2:?"); } lEcrivain.close(); return true; } catch (Exception lException) { return false; } }
|
11
|
Code Sample 1:
private void loadInitialDbState() throws IOException { InputStream in = SchemaAndDataPopulator.class.getClassLoader().getResourceAsStream(resourceName); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer); for (String statement : writer.toString().split(SQL_STATEMENT_DELIMITER)) { logger.info("Executing SQL Statement {}", statement); template.execute(statement); } }
Code Sample 2:
public void setBckImg(String newPath) { try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = null; try { out = new FileOutputStream(outputFile); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); JOptionPane.showMessageDialog(null, ex1.getMessage().substring(0, Math.min(ex1.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } int c; if (out != null) { while ((c = in.read()) != -1) out.write(c); out.close(); } in.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } setPath(newPath); bckImg = new ImageIcon(getPath()); }
|
11
|
Code Sample 1:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[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 boolean copy(File in, File out) { try { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); FileChannel readableChannel = fis.getChannel(); FileChannel writableChannel = fos.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); fis.close(); fos.close(); return true; } catch (IOException ioe) { guiBuilder.showError("Copy Error", "IOException during copy", ioe.getMessage()); return false; } }
|
00
|
Code Sample 1:
@Override public void parse() throws IOException { URL url = new URL(getDataUrl()); URLConnection con = url.openConnection(); BufferedReader bStream = new BufferedReader(new InputStreamReader(con.getInputStream())); String s = bStream.readLine(); String[] tokens = s.split("</html>"); tokens = tokens[1].split("<br>"); for (String sToken : tokens) { String[] sTokens = sToken.split(";"); CurrencyUnit unit = new CurrencyUnit(sTokens[4], Float.valueOf(sTokens[9]), Integer.valueOf(sTokens[5])); this.set.add(unit); } }
Code Sample 2:
public static String[] listFilesInJar(String resourcesLstName, String dirPath, String ext) { try { dirPath = Tools.subString(dirPath, "\\", "/"); if (!dirPath.endsWith("/")) { dirPath = dirPath + "/"; } if (dirPath.startsWith("/")) { dirPath = dirPath.substring(1, dirPath.length()); } URL url = ResourceLookup.getClassResourceUrl(Tools.class, resourcesLstName); if (url == null) { String msg = "File not found " + resourcesLstName; Debug.signal(Debug.ERROR, null, msg); return new String[0]; } InputStream is = url.openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String name = in.readLine(); HashSet<String> list = new HashSet<String>(10); while (name != null) { name = in.readLine(); if (name == null) { continue; } if (ext != null && !name.endsWith(ext)) { continue; } if (name.indexOf('.') == -1 && !name.endsWith("/")) { name = name + "/"; } int index = name.indexOf(dirPath); if (index < 0) { continue; } index += dirPath.length(); if (index >= name.length() - 1) { continue; } index = name.indexOf("/", index); if (ext != null && (name.endsWith("/") || index >= 0)) { continue; } else if (ext == null && (index < 0 || index < name.length() - 1)) { continue; } list.add("/" + name); } is.close(); String[] toReturn = {}; return list.toArray(toReturn); } catch (IOException ioe) { String msg = "Error reading file " + resourcesLstName + " caused by " + ioe; Debug.signal(Debug.ERROR, null, msg); return new String[0]; } }
|
11
|
Code Sample 1:
@Override public void copyTo(ManagedFile other) throws ManagedIOException { try { if (other.getType() == ManagedFileType.FILE) { IOUtils.copy(this.getContent().getInputStream(), other.getContent().getOutputStream()); } else { ManagedFile newFile = other.retrive(this.getPath()); newFile.createFile(); IOUtils.copy(this.getContent().getInputStream(), newFile.getContent().getOutputStream()); } } catch (IOException ioe) { throw ManagedIOException.manage(ioe); } }
Code Sample 2:
public static void downloadFile(HttpServletResponse response, String file) throws IOException { response.setContentType(FileUtils.getContentType(file)); response.setContentLength(FileUtils.getContentLength(file)); response.setHeader("Content-type", ResponseUtils.DOWNLOAD_CONTENT_TYPE); response.setHeader("Content-Disposition", "attachment; filename=\"" + FileUtils.getFileName(file) + "\""); response.setHeader("Content-Length", Integer.toString(FileUtils.getContentLength(file))); InputStream input = new FileInputStream(file); OutputStream output = response.getOutputStream(); IOUtils.copy(input, output, true); }
|
00
|
Code Sample 1:
@SuppressWarnings("unchecked") private int syncCustomers() throws RemoteException, BasicException { dlintegration.syncCustomersBefore(); ArrayList<String> notToSync = new ArrayList<String>(); int step = 0; User[] remoteUsers; int cpt = 0; do { remoteUsers = externalsales.getUsersBySteps(step); step++; if (remoteUsers == null) { throw new BasicException(AppLocal.getIntString("message.returnnull") + " > Customers null"); } if (remoteUsers.length > 0) { String perms; for (User remoteUser : remoteUsers) { if (notToSync.contains(remoteUser.getLogin())) continue; cpt++; String name = externalsales.encodeString((remoteUser.getFirstname().trim() + " " + remoteUser.getLastname()).trim()); String firstname = externalsales.encodeString(remoteUser.getFirstname()); String lastname = externalsales.encodeString(remoteUser.getLastname()); String description = externalsales.encodeString(remoteUser.getDescription()); String address = externalsales.encodeString(remoteUser.getAddress()); String address2 = externalsales.encodeString(remoteUser.getAddress2()); String city = externalsales.encodeString(remoteUser.getCity()); String country = externalsales.encodeString(remoteUser.getCountry()); String phone = externalsales.encodeString(remoteUser.getPhone()); String mobile = externalsales.encodeString(remoteUser.getMobile()); String zipcode = externalsales.encodeString(remoteUser.getZipcode()); CustomerSync copyCustomer = new CustomerSync(remoteUser.getId()); if (firstname == null || firstname.equals("")) firstname = " "; copyCustomer.setFirstname(firstname.toUpperCase()); if (lastname == null || lastname.equals("")) lastname = " "; copyCustomer.setLastname(lastname.toUpperCase()); copyCustomer.setTaxid(remoteUser.getLogin()); copyCustomer.setSearchkey(remoteUser.getLogin() + name.toUpperCase()); if (name == null || name.equals("")) name = " "; copyCustomer.setName(name.toUpperCase()); if (description == null || description.equals("")) description = " "; copyCustomer.setNotes(description); copyCustomer.setEmail(remoteUser.getEmail()); if (address == null || address.equals("")) address = " "; copyCustomer.setAddress(address); if (address2 == null || address2.equals("")) address2 = " "; copyCustomer.setAddress2(address2); if (city == null || city.equals("")) city = "Brussels"; copyCustomer.setCity(city); if (country == null || country.equals("")) country = "Belgium"; copyCustomer.setCountry(country); copyCustomer.setMaxdebt(10000.0); if (phone == null || phone.equals("")) phone = " "; copyCustomer.setPhone(phone); if (mobile == null || mobile.equals("")) mobile = " "; copyCustomer.setPhone2(mobile); if (zipcode == null || zipcode.equals("")) zipcode = " "; copyCustomer.setPostal(zipcode); if (TicketInfo.isWS() && TicketInfo.getPayID() == 2 && remoteUser.getEmail().contains("@DONOTSENDME")) { notToSync.add(copyCustomer.getTaxid()); continue; } dlintegration.syncCustomer(copyCustomer); notToSync.add(copyCustomer.getTaxid()); } } } while (remoteUsers.length > 0); List<CustomerSync> localList = dlintegration.getCustomers(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (CustomerSync localCustomer : localList) { Date now = new Date(); if (notToSync.contains(localCustomer.getTaxid())) { continue; } cpt++; User userAdd = new User(); userAdd.setLogin(localCustomer.getTaxid()); userAdd.setId(localCustomer.getTaxid()); userAdd.setFirstname(" "); String tmpName = localCustomer.getName().trim(); tmpName = tmpName.replace("'", ""); while (tmpName.charAt(0) == ' ') { tmpName = tmpName.substring(1); } userAdd.setLastname(tmpName); char[] pw = new char[8]; int c = 'A'; int r1 = 0; for (int i = 0; i < 8; i++) { r1 = (int) (Math.random() * 3); switch(r1) { case 0: c = '0' + (int) (Math.random() * 10); break; case 1: c = 'a' + (int) (Math.random() * 26); break; case 2: c = 'A' + (int) (Math.random() * 26); break; } pw[i] = (char) c; } String clave = new String(pw); byte[] password = { 00 }; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(clave.getBytes()); password = md5.digest(); userAdd.setPassword(password.toString()); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UsersSync.class.getName()).log(Level.SEVERE, null, ex); userAdd.setPassword(clave); } userAdd.setTitle("M"); if (localCustomer.getEmail() == null || localCustomer.getEmail().trim().equals("") || localCustomer.getEmail().indexOf('@') <= 0) userAdd.setEmail(localCustomer.getTaxid() + defaultEmail); else userAdd.setEmail(localCustomer.getEmail()); userAdd.setDescription(localCustomer.getNotes() + ""); userAdd.setAddress(localCustomer.getAddress() + ""); userAdd.setAddress2(localCustomer.getAddress2() + ""); userAdd.setState_region(localCustomer.getRegion() + ""); userAdd.setCity(localCustomer.getCity() + ""); userAdd.setCountry(localCustomer.getCountry() + ""); userAdd.setZipcode(localCustomer.getPostal() + ""); userAdd.setPhone(localCustomer.getPhone() + ""); userAdd.setMobile(localCustomer.getPhone2() + ""); userAdd.setFax(" "); try { userAdd.setCdate(df.format(localCustomer.getCurdate())); } catch (NullPointerException nu) { userAdd.setCdate(df.format(now)); } userAdd.setPerms("shopper"); userAdd.setBank_account_nr(""); userAdd.setBank_account_holder(""); userAdd.setBank_account_type(""); userAdd.setBank_iban(""); userAdd.setBank_name(""); userAdd.setBank_sort_code(""); userAdd.setMdate(df.format(now)); userAdd.setShopper_group_id("1"); externalsales.addUser(userAdd); } return cpt; }
Code Sample 2:
public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } }
|
11
|
Code Sample 1:
public static String hash(String str) { if (str == null || str.length() == 0) { throw new CaptureSecurityException("String to encript cannot be null or zero length"); } StringBuilder hexString = new StringBuilder(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (byte element : hash) { if ((0xff & element) < 0x10) { hexString.append('0').append(Integer.toHexString((0xFF & element))); } else { hexString.append(Integer.toHexString(0xFF & element)); } } } catch (NoSuchAlgorithmException e) { throw new CaptureSecurityException(e); } return hexString.toString(); }
Code Sample 2:
protected Object getMethodKey(String methodName, Object[] args) { StringBuffer key = new StringBuffer(methodName.trim().replace(" ", ".")).append("."); for (Object o : args) { if (o != null) key.append(o.hashCode()); } LOGGER.info("Generation key ->" + key.toString()); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-512"); messageDigest.reset(); messageDigest.update(key.toString().getBytes(Charset.forName("UTF8"))); final byte[] resultByte = messageDigest.digest(); String hex = null; for (int i = 0; i < resultByte.length; i++) { hex = Integer.toHexString(0xFF & resultByte[i]); if (hex.length() < 2) { key.append("0"); } key.append(hex); } } catch (NoSuchAlgorithmException e) { LOGGER.severe("No hash generated for method key! " + StackTraceUtil.getStackTrace(e)); } LOGGER.info("Generation key ->" + key.toString()); return new String(key); }
|
11
|
Code Sample 1:
public static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); System.out.println("test"); URL url = new URL(addr); System.out.println("test2"); IOUtils.copy(url.openStream(), output); return output.toString(); }
Code Sample 2:
public static boolean copyFile(File sourceFile, File destFile) throws IOException { long flag = 0; if (!destFile.exists()) destFile.createNewFile(); FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); flag = destination.transferFrom(source, 0, source.size()); } catch (Exception e) { Logger.getLogger(FileUtils.class.getPackage().getName()).log(Level.WARNING, "ERROR: Problem copying file", e); } finally { if (source != null) source.close(); if (destination != null) destination.close(); } if (flag == 0) return false; else return true; }
|
11
|
Code Sample 1:
public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException fnfe) { Log.debug(fnfe); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
Code Sample 2:
public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
|
11
|
Code Sample 1:
public static String unsecureHashConstantSalt(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { password = SALT3 + password; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); password += convertToHex(md5.digest()) + SALT4; MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(password.getBytes("UTF-8"), 0, password.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
Code Sample 2:
public String plainStringToMD5(String input) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.exit(-1); } md.reset(); md.update(input.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); }
|
11
|
Code Sample 1:
public String getRssFeedUrl(boolean searchWeb) { String rssFeedUrl = null; if (entity.getNewsFeedUrl() != null & !entity.getUrl().equals("")) { return entity.getNewsFeedUrl(); } else if (entity.getUrl() == null || entity.getUrl().equals("")) { return entity.getNewsFeedUrl(); } else if (searchWeb) { HttpURLConnection con = null; InputStream is = null; try { URL url = new URL(entity.getUrl()); con = (HttpURLConnection) url.openConnection(); con.connect(); is = con.getInputStream(); InputStreamReader sr = new InputStreamReader(is); BufferedReader br = new BufferedReader(sr); String ln; StringBuffer sb = new StringBuffer(); while ((ln = br.readLine()) != null) { sb.append(ln + "\n"); } rssFeedUrl = extractRssFeedUrl(sb.toString()); } catch (Exception e) { log.error(e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { log.error(e); } } if (con != null) { con.disconnect(); } } } return rssFeedUrl; }
Code Sample 2:
public static BufferedReader getUserInfoStream(String name) throws IOException { BufferedReader in; try { URL url = new URL("http://www.spoj.pl/users/" + name.toLowerCase() + "/"); in = new BufferedReader(new InputStreamReader(url.openStream())); } catch (MalformedURLException e) { in = null; throw e; } return in; }
|
00
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
protected void doRestoreOrganizeTypeRelation() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strDelQuery = "DELETE FROM " + Common.ORGANIZE_TYPE_RELATION_TABLE; String strSelQuery = "SELECT parent_organize_type,child_organize_type " + "FROM " + Common.ORGANIZE_TYPE_RELATION_B_TABLE + " " + "WHERE version_no = ?"; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_RELATION_TABLE + " " + "(parent_organize_type,child_organize_type) " + "VALUES (?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strDelQuery); ps.executeUpdate(); ps = con.prepareStatement(strSelQuery); ps.setInt(1, this.versionNO); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setString(1, result.getString("parent_organize_type")); ps.setString(2, result.getString("child_organize_type")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): ERROR Inserting data " + "in T_SYS_ORGANIZE_TYPE_RELATION INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): SQLException while committing or rollback"); } }
|
00
|
Code Sample 1:
@Override public void save(File folder) { actInstance = instance; this.setProperty(EsomMapper.PROPERTY_INSTANCE, String.valueOf(actInstance)); log.debug("instance: " + this.getProperty(EsomMapper.PROPERTY_INSTANCE)); if (this.getProperty(EsomMapper.PROPERTY_LRN_RADIO_SELECTED) == EsomMapper.RADIO_LOAD_SELECTED) { File src = new File(this.getProperty(EsomMapper.PROPERTY_LRN_FILE)); if (src.getParent() != folder.getPath()) { log.debug("saving lrn file in save folder " + folder.getPath()); File dst = new File(folder.getAbsolutePath() + File.separator + src.getName() + String.valueOf(actInstance)); try { FileReader fr = new FileReader(src); BufferedReader br = new BufferedReader(fr); dst.createNewFile(); FileWriter fw = new FileWriter(dst); BufferedWriter bw = new BufferedWriter(fw); int i = 0; while ((i = br.read()) != -1) bw.write(i); bw.flush(); bw.close(); br.close(); fr.close(); } catch (FileNotFoundException e) { log.error("Error while opening lrn sourcefile! Saving wasn't possible!!!"); e.printStackTrace(); } catch (IOException e) { log.error("Error while creating lrn destfile! Creating wasn't possible!!!"); e.printStackTrace(); } this.setProperty(EsomMapper.PROPERTY_LRN_FILE, dst.getName()); log.debug("done saving lrn file"); } } if (this.getProperty(EsomMapper.PROPERTY_WTS_RADIO_SELECTED) == EsomMapper.RADIO_LOAD_SELECTED) { File src = new File(this.getProperty(EsomMapper.PROPERTY_WTS_FILE)); if (src.getParent() != folder.getPath()) { log.debug("saving wts file in save folder " + folder.getPath()); File dst = new File(folder.getAbsolutePath() + File.separator + src.getName() + String.valueOf(actInstance)); try { FileReader fr = new FileReader(src); BufferedReader br = new BufferedReader(fr); dst.createNewFile(); FileWriter fw = new FileWriter(dst); BufferedWriter bw = new BufferedWriter(fw); int i = 0; while ((i = br.read()) != -1) bw.write(i); bw.flush(); bw.close(); br.close(); fr.close(); } catch (FileNotFoundException e) { log.error("Error while opening wts sourcefile! Saving wasn't possible!!!"); e.printStackTrace(); } catch (IOException e) { log.error("Error while creating wts destfile! Creating wasn't possible!!!"); e.printStackTrace(); } this.setProperty(EsomMapper.PROPERTY_WTS_FILE, dst.getName()); log.debug("done saving wts file"); } } if (this.getProperty(EsomMapper.PROPERTY_LRN_RADIO_SELECTED) == EsomMapper.RADIO_SELECT_FROM_DATANAV_SELECTED) { this.setProperty(EsomMapper.PROPERTY_LRN_FILE, "EsomMapper" + this.actInstance + ".lrn"); File dst = new File(folder + File.separator + this.getProperty(EsomMapper.PROPERTY_LRN_FILE)); try { FileWriter fw = new FileWriter(dst); BufferedWriter bw = new BufferedWriter(fw); bw.write("# EsomMapper LRN save file\n"); bw.write("% " + this.inputVectors.getNumRows() + "\n"); bw.write("% " + this.inputVectors.getNumCols() + "\n"); bw.write("% 9"); for (IColumn col : this.inputVectors.getColumns()) { if (col.getType() == IClusterNumber.class) bw.write("\t2"); else if (col.getType() == String.class) bw.write("\t8"); else bw.write("\t1"); } bw.write("\n% Key"); for (IColumn col : this.inputVectors.getColumns()) { bw.write("\t" + col.getLabel()); } bw.write("\n"); int keyIterator = 0; for (Vector<Object> row : this.inputVectors.getGrid()) { bw.write(this.inputVectors.getKey(keyIterator++).toString()); for (Object point : row) bw.write("\t" + point.toString()); bw.write("\n"); } bw.flush(); fw.flush(); bw.close(); fw.close(); } catch (IOException e) { e.printStackTrace(); } this.setProperty(EsomMapper.PROPERTY_LRN_RADIO_SELECTED, EsomMapper.RADIO_LOAD_SELECTED); } if (this.getProperty(EsomMapper.PROPERTY_WTS_RADIO_SELECTED) == EsomMapper.RADIO_SELECT_FROM_DATANAV_SELECTED) { this.setProperty(EsomMapper.PROPERTY_WTS_FILE, "EsomMapper" + this.actInstance + ".wts"); MyRetina tempRetina = new MyRetina(this.outputRetina.getNumRows(), this.outputRetina.getNumCols(), this.outputRetina.getDim(), this.outputRetina.getDistanceFunction(), this.outputRetina.isToroid()); for (int row = 0; row < this.outputRetina.getNumRows(); row++) { for (int col = 0; col < this.outputRetina.getNumCols(); col++) { for (int dim = 0; dim < this.outputRetina.getDim(); dim++) { tempRetina.setNeuron(row, col, dim, this.outputRetina.getPointasDoubleArray(row, col)[dim]); } } } EsomIO.writeWTSFile(folder + File.separator + this.getProperty(EsomMapper.PROPERTY_WTS_FILE), tempRetina); this.setProperty(EsomMapper.PROPERTY_WTS_RADIO_SELECTED, EsomMapper.RADIO_LOAD_SELECTED); } EsomMapper.instance++; }
Code Sample 2:
private static Properties getProperties(String propFilename) { Properties properties = new Properties(); try { URL url = Loader.getResource(propFilename); properties.load(url.openStream()); } catch (Exception e) { log.debug("Cannot find SAML property file: " + propFilename); throw new RuntimeException("SAMLIssuerFactory: Cannot load properties: " + propFilename); } return properties; }
|
00
|
Code Sample 1:
public static String encryptPassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); byte[] hash = md.digest(); StringBuffer hashStringBuf = new StringBuffer(); String byteString; int byteLength; for (int index = 0; index < hash.length; index++) { byteString = String.valueOf(hash[index] + 128); byteLength = byteString.length(); switch(byteLength) { case 1: byteString = "00" + byteString; break; case 2: byteString = "0" + byteString; break; } hashStringBuf.append(byteString); } return hashStringBuf.toString(); } catch (NoSuchAlgorithmException nsae) { log.error("Error getting password hash - " + nsae.getMessage()); return null; } }
Code Sample 2:
public static void copyFile(File src, File dest, int bufSize, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file: " + dest.getName()); } } byte[] buffer = new byte[bufSize]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } }
|
11
|
Code Sample 1:
protected void zipDirectory(File dir, File zipfile) throws IOException, IllegalArgumentException { if (!dir.isDirectory()) throw new IllegalArgumentException("Compress: not a directory: " + dir); String[] entries = dir.list(); byte[] buffer = new byte[4096]; int bytes_read; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile)); for (int i = 0; i < entries.length; i++) { File f = new File(dir, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getPath()); out.putNextEntry(entry); while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); } out.close(); }
Code Sample 2:
public void includeJs(Group group, Writer out, PageContext pageContext) throws IOException { includeResource(pageContext, out, RetentionHelper.buildRootRetentionFilePath(group, ".js"), JS_BEGIN_TAG, JS_END_TAG); ByteArrayOutputStream outtmp = new ByteArrayOutputStream(); if (AbstractGroupBuilder.getInstance().buildGroupJsIfNeeded(group, outtmp, pageContext.getServletContext())) { FileOutputStream fileStream = new FileOutputStream(new File(RetentionHelper.buildFullRetentionFilePath(group, ".js"))); IOUtils.copy(new ByteArrayInputStream(outtmp.toByteArray()), fileStream); fileStream.close(); } }
|
11
|
Code Sample 1:
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(); } } }
Code Sample 2:
public static void main(String[] args) { for (int i = 0; i < args.length - 2; i++) { if (!CommonArguments.parseArguments(args, i, u)) { u.usage(); System.exit(1); } if (CommonParameters.startArg > (i + 1)) i = CommonParameters.startArg - 1; } if (args.length < CommonParameters.startArg + 2) { u.usage(); System.exit(1); } try { int readsize = 1024; ContentName argName = ContentName.fromURI(args[CommonParameters.startArg]); CCNHandle handle = CCNHandle.open(); File theFile = new File(args[CommonParameters.startArg + 1]); if (theFile.exists()) { System.out.println("Overwriting file: " + args[CommonParameters.startArg + 1]); } FileOutputStream output = new FileOutputStream(theFile); long starttime = System.currentTimeMillis(); CCNInputStream input; if (CommonParameters.unversioned) input = new CCNInputStream(argName, handle); else input = new CCNFileInputStream(argName, handle); if (CommonParameters.timeout != null) { input.setTimeout(CommonParameters.timeout); } byte[] buffer = new byte[readsize]; int readcount = 0; long readtotal = 0; while ((readcount = input.read(buffer)) != -1) { readtotal += readcount; output.write(buffer, 0, readcount); output.flush(); } if (CommonParameters.verbose) System.out.println("ccngetfile took: " + (System.currentTimeMillis() - starttime) + "ms"); System.out.println("Retrieved content " + args[CommonParameters.startArg + 1] + " got " + readtotal + " bytes."); System.exit(0); } catch (ConfigurationException e) { System.out.println("Configuration exception in ccngetfile: " + e.getMessage()); e.printStackTrace(); } catch (MalformedContentNameStringException e) { System.out.println("Malformed name: " + args[CommonParameters.startArg] + " " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println("Cannot write file or read content. " + e.getMessage()); e.printStackTrace(); } System.exit(1); }
|
00
|
Code Sample 1:
private boolean doDelete(String identifier) throws IOException, MalformedURLException { URL url = new URL(baseurl.toString() + "/" + identifier); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); huc.setRequestMethod("DELETE"); huc.connect(); if (huc.getResponseCode() == 200) { return true; } else return false; }
Code Sample 2:
public static void main(String[] args) { FileInputStream in; DeflaterOutputStream out; FileOutputStream fos; FileDialog fd; fd = new FileDialog(new Frame(), "Find a file to deflate", FileDialog.LOAD); fd.show(); if (fd.getFile() != null) { try { in = new FileInputStream(new File(fd.getDirectory(), fd.getFile())); fos = new FileOutputStream(new File("Deflated.out")); out = new DeflaterOutputStream(fos, new Deflater(Deflater.DEFLATED, true)); int bytes_read = 0; byte[] buffer = new byte[1024]; while ((bytes_read = in.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } fos.flush(); fos.close(); out.flush(); out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Done"); } }
|
11
|
Code Sample 1:
public static void invokeMvnArtifact(final IProject project, final IModuleExtension moduleExtension, final String location) throws CoreException, InterruptedException, IOException { final Properties properties = new Properties(); properties.put("archetypeGroupId", "org.nexopenframework.plugins"); properties.put("archetypeArtifactId", "openfrwk-archetype-webmodule"); final String version = org.maven.ide.eclipse.ext.Maven2Plugin.getArchetypeVersion(); properties.put("archetypeVersion", version); properties.put("artifactId", moduleExtension.getArtifact()); properties.put("groupId", moduleExtension.getGroup()); properties.put("version", moduleExtension.getVersion()); final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); final ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(LAUNCH_CONFIGURATION_TYPE_ID); final ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, "Creating WEB module using Apache Maven archetype"); File archetypePomDirectory = getDefaultArchetypePomDirectory(); try { final String dfPom = getPomFile(moduleExtension.getGroup(), moduleExtension.getArtifact()); final ByteArrayInputStream bais = new ByteArrayInputStream(dfPom.getBytes()); final File f = new File(archetypePomDirectory, "pom.xml"); OutputStream fous = null; try { fous = new FileOutputStream(f); IOUtils.copy(bais, fous); } finally { try { if (fous != null) { fous.close(); } if (bais != null) { bais.close(); } } catch (final IOException e) { } } String goalName = "archetype:create"; boolean offline = false; try { final Class clazz = Thread.currentThread().getContextClassLoader().loadClass("org.maven.ide.eclipse.Maven2Plugin"); final Maven2Plugin plugin = (Maven2Plugin) clazz.getMethod("getDefault", new Class[0]).invoke(null, new Object[0]); offline = plugin.getPreferenceStore().getBoolean("eclipse.m2.offline"); } catch (final ClassNotFoundException e) { Logger.logException("No class [org.maven.ide.eclipse.ext.Maven2Plugin] in classpath", e); } catch (final NoSuchMethodException e) { Logger.logException("No method getDefault", e); } catch (final Throwable e) { Logger.logException(e); } if (offline) { goalName = new StringBuffer(goalName).append(" -o").toString(); } if (!offline) { final IPreferenceStore ps = Maven2Plugin.getDefault().getPreferenceStore(); final String repositories = ps.getString(Maven2PreferenceConstants.P_M2_REPOSITORIES); final String[] repos = repositories.split(org.maven.ide.eclipse.ext.Maven2Plugin.REPO_SEPARATOR); final StringBuffer sbRepos = new StringBuffer(); for (int k = 0; k < repos.length; k++) { sbRepos.append(repos[k]); if (k != repos.length - 1) { sbRepos.append(","); } } properties.put("remoteRepositories", sbRepos.toString()); } workingCopy.setAttribute(ATTR_GOALS, goalName); workingCopy.setAttribute(ATTR_POM_DIR, archetypePomDirectory.getAbsolutePath()); workingCopy.setAttribute(ATTR_PROPERTIES, convertPropertiesToList(properties)); final long timeout = org.maven.ide.eclipse.ext.Maven2Plugin.getTimeout(); TimeoutLaunchConfiguration.launchWithTimeout(new NullProgressMonitor(), workingCopy, project, timeout); FileUtils.copyDirectoryStructure(new File(archetypePomDirectory, project.getName()), new File(location)); FileUtils.deleteDirectory(new File(location + "/src")); FileUtils.forceDelete(new File(location, "pom.xml")); project.refreshLocal(IResource.DEPTH_INFINITE, null); } finally { FileUtils.deleteDirectory(archetypePomDirectory); Logger.log(Logger.INFO, "Invoked removing of archetype POM directory"); } }
Code Sample 2:
public static boolean copy(File from, File to) { if (from.isDirectory()) { for (String name : Arrays.asList(from.list())) { if (!copy(from, to, name)) { LogUtils.info("Failed to copy " + name + " from " + from + " to " + to, null); return false; } } } else { try { FileInputStream is = new FileInputStream(from); FileChannel ifc = is.getChannel(); FileOutputStream os = makeFile(to); if (USE_NIO) { FileChannel ofc = os.getChannel(); ofc.transferFrom(ifc, 0, from.length()); } else { pipe(is, os, false); } is.close(); os.close(); } catch (IOException ex) { LogUtils.warning("Failed to copy " + from + " to " + to, ex); return false; } } long time = from.lastModified(); setLastModified(to, time); long newtime = to.lastModified(); if (newtime != time) { LogUtils.info("Failed to set timestamp for file " + to + ": tried " + new Date(time) + ", have " + new Date(newtime), null); to.setLastModified(time); long morenewtime = to.lastModified(); return false; } return time == newtime; }
|
11
|
Code Sample 1:
public static void copyfile(String src, String dst) throws IOException { dst = new File(dst).getAbsolutePath(); new File(new File(dst).getParent()).mkdirs(); FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
Code Sample 2:
private void doConvert(HttpServletResponse response, ConversionRequestResolver rr, EGE ege, ConversionsPath cpath) throws FileUploadException, IOException, RequestResolvingException, EGEException, FileNotFoundException, ConverterException, ZipException { InputStream is = null; OutputStream os = null; if (ServletFileUpload.isMultipartContent(rr.getRequest())) { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(rr.getRequest()); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { is = item.openStream(); applyConversionsProperties(rr.getConversionProperties(), cpath); DataBuffer buffer = new DataBuffer(0, EGEConstants.BUFFER_TEMP_PATH); String alloc = buffer.allocate(is); InputStream ins = buffer.getDataAsStream(alloc); is.close(); try { ValidationResult vRes = ege.performValidation(ins, cpath.getInputDataType()); if (vRes.getStatus().equals(ValidationResult.Status.FATAL)) { ValidationServlet valServ = new ValidationServlet(); valServ.printValidationResult(response, vRes); try { ins.close(); } finally { buffer.removeData(alloc, true); } return; } } catch (ValidatorException vex) { LOGGER.warn(vex.getMessage()); } finally { try { ins.close(); } catch (Exception ex) { } } File zipFile = null; FileOutputStream fos = null; String newTemp = UUID.randomUUID().toString(); IOResolver ior = EGEConfigurationManager.getInstance().getStandardIOResolver(); File buffDir = new File(buffer.getDataDir(alloc)); zipFile = new File(EGEConstants.BUFFER_TEMP_PATH + File.separator + newTemp + EZP_EXT); fos = new FileOutputStream(zipFile); ior.compressData(buffDir, fos); ins = new FileInputStream(zipFile); File szipFile = new File(EGEConstants.BUFFER_TEMP_PATH + File.separator + newTemp + ZIP_EXT); fos = new FileOutputStream(szipFile); try { try { ege.performConversion(ins, fos, cpath); } finally { fos.close(); } boolean isComplex = EGEIOUtils.isComplexZip(szipFile); response.setContentType(APPLICATION_OCTET_STREAM); String fN = item.getName().substring(0, item.getName().lastIndexOf(".")); if (isComplex) { String fileExt; if (cpath.getOutputDataType().getMimeType().equals(APPLICATION_MSWORD)) { fileExt = DOCX_EXT; } else { fileExt = ZIP_EXT; } response.setHeader("Content-Disposition", "attachment; filename=\"" + fN + fileExt + "\""); FileInputStream fis = new FileInputStream(szipFile); os = response.getOutputStream(); try { EGEIOUtils.copyStream(fis, os); } finally { fis.close(); } } else { String fileExt = getMimeExtensionProvider().getFileExtension(cpath.getOutputDataType().getMimeType()); response.setHeader("Content-Disposition", "attachment; filename=\"" + fN + fileExt + "\""); os = response.getOutputStream(); EGEIOUtils.unzipSingleFile(new ZipFile(szipFile), os); } } finally { ins.close(); if (os != null) { os.flush(); os.close(); } buffer.clear(true); szipFile.delete(); if (zipFile != null) { zipFile.delete(); } } } } } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } }
|
00
|
Code Sample 1:
public static boolean update(String user, String pass, String channelString, String globalIP) { FTPClient ftp = new FTPClient(); int reply; try { ftp.connect("witna.co.uk", 21); ftp.login(user, pass); reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { updateChannelList(ftp, channelString); if (!ipUpdated) { ipUpdated = updateMasterChannelIP(ftp, globalIP); } ftp.disconnect(); return true; } else { ftp.disconnect(); } } catch (Exception ex) { ex.printStackTrace(); } return false; }
Code Sample 2:
private static String md5(String text) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(text.getBytes("UTF-8")); byte[] messageDigest = digest.digest(); StringBuilder hexString = new StringBuilder(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
|
11
|
Code Sample 1:
public void copy(String pathFileIn, String pathFileOut) { try { File inputFile = new File(pathFileIn); File outputFile = new File(pathFileOut); FileReader in = new FileReader(inputFile); File outDir = new File(DirOut); if (!outDir.exists()) outDir.mkdirs(); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); this.printColumn(inputFile.getName(), outputFile.getPath()); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public String getText() throws IOException { InputStreamReader r = new InputStreamReader(getInputStream(), encoding); StringWriter w = new StringWriter(256 * 128); try { IOUtils.copy(r, w); } finally { IOUtils.closeQuietly(w); IOUtils.closeQuietly(r); } return w.toString(); }
|
00
|
Code Sample 1:
public boolean saveVideoXMLOnWebserver() { String text = ""; boolean erg = false; try { URL url = new URL("http://localhost:8080/virtPresenterVerwalter/videofile.jsp?id=" + this.getId()); HttpURLConnection http = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream())); String zeile = ""; while ((zeile = in.readLine()) != null) { text += zeile + "\n"; } in.close(); http.disconnect(); erg = saveVideoXMLOnWebserver(text); System.err.println("Job " + this.getId() + " erfolgreich bearbeitet!"); } catch (MalformedURLException e) { System.err.println("Job " + this.getId() + ": Konnte video.xml nicht erstellen. Verbindung konnte nicht aufgebaut werden."); return false; } catch (IOException e) { System.err.println("Job " + this.getId() + ": Konnte video.xml nicht erstellen. Konnte Daten nicht lesen/schreiben."); return false; } return erg; }
Code Sample 2:
private static String readJarURL(URL url) throws IOException { JarURLConnection juc = (JarURLConnection) url.openConnection(); InputStream in = juc.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int i = in.read(); while (i != -1) { out.write(i); i = in.read(); } return out.toString(); }
|
00
|
Code Sample 1:
public InputStream unZip(URL url) throws Exception { ZipInputStream zipped = new ZipInputStream(url.openStream()); System.out.println("unzipping: " + url.getFile()); ZipEntry zip = zipped.getNextEntry(); byte[] b = new byte[4096]; ByteArrayOutputStream bOut = new ByteArrayOutputStream(); for (int iRead = zipped.read(b); iRead != -1; iRead = zipped.read(b)) { bOut.write(b, 0, iRead); } zipped.close(); ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); return (InputStream) bIn; }
Code Sample 2:
@Override public DownloadObject download() throws IOException { final HttpGet findLink = new HttpGet(url.toString()); final HttpResponse response = this.client.execute(findLink); final String body = IOUtil.getString(response); LinkTag linkTag = null; try { linkTag = HtmlParserUtil.findLink(MegaUploadDownloader.DOWNLOAD_LINK_PATTERN, body); } catch (ParserException e) { } if (linkTag != null) { String link = linkTag.extractLink(); final String filename = IOUtil.getBaseName(link).trim(); link = link.replaceAll("&#[0-9]*;", "_"); final URL url = new URL(link); final String newLink = link.replaceAll(Pattern.quote(IOUtil.getBaseName(url.getPath())), URLEncoder.encode(IOUtil.getBaseName(url.getPath()), "UTF-8")); final HttpGet download = new HttpGet(newLink); final HttpResponse downloadResponse = this.client.execute(download); final HttpEntity downloadEntity = downloadResponse.getEntity(); final long filesize = downloadEntity.getContentLength(); return createObject(downloadEntity.getContent(), filename, filesize); } else { throw new RuntimeException("No download link."); } }
|
11
|
Code Sample 1:
public static void copyFile(File srcFile, File destFolder) { try { File destFile = new File(destFolder, srcFile.getName()); if (destFile.exists()) { throw new BuildException("Could not copy " + srcFile + " to " + destFolder + " as " + destFile + " already exists"); } FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(srcFile).getChannel(); destChannel = new FileOutputStream(destFile).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) { srcChannel.close(); } if (destChannel != null) { destChannel.close(); } } destFile.setLastModified((srcFile.lastModified())); } catch (IOException e) { throw new BuildException("Could not copy " + srcFile + " to " + destFolder + ": " + e, e); } }
Code Sample 2:
public String merge(int width, int height) throws Exception { htErrors.clear(); sendGetImageRequests(width, height); Vector files = new Vector(); ConcurrentHTTPTransactionHandler c = new ConcurrentHTTPTransactionHandler(); c.setCache(cache); c.checkIfModified(false); for (int i = 0; i < vImageUrls.size(); i++) { if ((String) vImageUrls.get(i) != null) { c.register((String) vImageUrls.get(i)); } else { } } c.doTransactions(); vTransparency = new Vector(); for (int i = 0; i < vImageUrls.size(); i++) { if (vImageUrls.get(i) != null) { String path = c.getResponseFilePath((String) vImageUrls.get(i)); if (path != null) { String contentType = c.getHeaderValue((String) vImageUrls.get(i), "content-type"); if (contentType.startsWith("image")) { files.add(path); vTransparency.add(htTransparency.get(vRank.get(i))); } } } } if (files.size() > 1) { File output = TempFiles.getFile(); String path = output.getPath(); ImageMerger.mergeAndSave(files, vTransparency, path, ImageMerger.GIF); imageName = output.getName(); imagePath = output.getPath(); return (imageName); } else if (files.size() == 1) { File f = new File((String) files.get(0)); File out = TempFiles.getFile(); BufferedInputStream is = new BufferedInputStream(new FileInputStream(f)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(out)); byte buf[] = new byte[1024]; for (int nRead; (nRead = is.read(buf, 0, 1024)) > 0; os.write(buf, 0, nRead)) ; os.flush(); os.close(); is.close(); imageName = out.getName(); return imageName; } else return ""; }
|
11
|
Code Sample 1:
protected void setUp() throws Exception { this.testOutputDirectory = new File(getClass().getResource("/").getPath()); this.pluginFile = new File(this.testOutputDirectory, "/plugin.zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(pluginFile)); zos.putNextEntry(new ZipEntry("WEB-INF/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/lib/")); zos.putNextEntry(new ZipEntry("WEB-INF/lib/plugin.jar")); File jarFile = new File(this.testOutputDirectory.getPath() + "/plugin.jar"); JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile)); jos.putNextEntry(new ZipEntry("vqwiki/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/system.properties")); System.getProperties().store(jos, null); jos.closeEntry(); jos.close(); IOUtils.copy(new FileInputStream(jarFile), zos); zos.closeEntry(); zos.close(); jarFile.delete(); pcl = new PluginClassLoader(new File(testOutputDirectory, "/work")); pcl.addPlugin(pluginFile); }
Code Sample 2:
public static Object fetchCached(String address, int hours) throws MalformedURLException, IOException { String cacheName = md5(address); checkAndCreateDirectoryIfNeeded(); File r = new File(CACHELOCATION + cacheName); Date d = new Date(); long limit = d.getTime() - (1000 * 60 * 60 * hours); if (!r.exists() || (hours != -1 && r.lastModified() < limit)) { InputStream is = (InputStream) fetch(address); FileOutputStream fos = new FileOutputStream(CACHELOCATION + cacheName); int nextChar; while ((nextChar = is.read()) != -1) fos.write((char) nextChar); fos.flush(); } FileInputStream fis = new FileInputStream(CACHELOCATION + cacheName); return fis; }
|
11
|
Code Sample 1:
public static void compressFile(File f) throws IOException { File target = new File(f.toString() + ".gz"); System.out.print("Compressing: " + f.getName() + ".. "); long initialSize = f.length(); FileInputStream fis = new FileInputStream(f); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(target)); byte[] buf = new byte[1024]; int read; while ((read = fis.read(buf)) != -1) { out.write(buf, 0, read); } System.out.println("Done."); fis.close(); out.close(); long endSize = target.length(); System.out.println("Initial size: " + initialSize + "; Compressed size: " + endSize); }
Code Sample 2:
public static void copyFile(File from, File to) throws Exception { if (!from.exists()) return; FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; while (true) { bytes_read = in.read(buffer); if (bytes_read == -1) break; out.write(buffer, 0, bytes_read); } out.flush(); out.close(); in.close(); }
|
00
|
Code Sample 1:
public static final String convertPassword(final String srcPwd) { StringBuilder out; MessageDigest md; byte[] byteValues; byte singleChar = 0; try { md = MessageDigest.getInstance("MD5"); md.update(srcPwd.getBytes()); byteValues = md.digest(); if ((byteValues == null) || (byteValues.length <= 0)) { return null; } out = new StringBuilder(byteValues.length * 2); for (byte element : byteValues) { singleChar = (byte) (element & 0xF0); singleChar = (byte) (singleChar >>> 4); singleChar = (byte) (singleChar & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); singleChar = (byte) (element & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); } return out.toString(); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
Code Sample 2:
private static InputSource getInputSourceFromURI(String uri, String username, String password) throws IOException, ProtocolException, UnsupportedEncodingException { URL wsdlurl = null; try { wsdlurl = new URL(uri); } catch (MalformedURLException e) { return new InputSource(uri); } if (username == null && wsdlurl.getUserInfo() == null) { return new InputSource(uri); } if (!wsdlurl.getProtocol().startsWith("http")) { return new InputSource(uri); } URLConnection connection = wsdlurl.openConnection(); if (!(connection instanceof HttpURLConnection)) { return new InputSource(uri); } HttpURLConnection uconn = (HttpURLConnection) connection; String userinfo = wsdlurl.getUserInfo(); uconn.setRequestMethod("GET"); uconn.setAllowUserInteraction(false); uconn.setDefaultUseCaches(false); uconn.setDoInput(true); uconn.setDoOutput(false); uconn.setInstanceFollowRedirects(true); uconn.setUseCaches(false); String auth = null; if (userinfo != null) { auth = userinfo; } else if (username != null) { auth = (password == null) ? username : username + ":" + password; } if (auth != null) { uconn.setRequestProperty("Authorization", "Basic " + base64encode(auth.getBytes(httpAuthCharEncoding))); } uconn.connect(); return new InputSource(uconn.getInputStream()); }
|
00
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private void createNodes() { try { URL url = this.getClass().getResource("NodesFile.txt"); InputStreamReader inReader = new InputStreamReader(url.openStream()); BufferedReader inNodes = new BufferedReader(inReader); String s; while ((s = inNodes.readLine()) != null) { String label = inNodes.readLine(); String fullText = inNodes.readLine(); String type = inNodes.readLine(); Node n = new Node(s, type); n.label = label; n.fullText = fullText; node.add(n); } inNodes.close(); url = this.getClass().getResource("EdgesFile.txt"); inReader = new InputStreamReader(url.openStream()); BufferedReader inEdges = new BufferedReader(inReader); while ((s = inEdges.readLine()) != null) edge.add(new Edge(s, inEdges.readLine(), inEdges.readLine(), inEdges.readLine())); inEdges.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
Code Sample 2:
public static String SHA1(String text) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } StringBuffer hexString = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }
|
11
|
Code Sample 1:
public byte[] exportCommunityData(String communityId) throws RepositoryException, IOException { Community community; try { community = getCommunityById(communityId); } catch (CommunityNotFoundException e1) { throw new GroupwareRuntimeException("Community to export not found"); } String contentPath = JCRUtil.getNodeById(communityId, community.getWorkspace()).getPath(); try { File zipOutFilename = File.createTempFile("exported-community", ".zip.tmp"); TemporaryFilesHandler.register(null, zipOutFilename); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipOutFilename)); File file = File.createTempFile("exported-community", null); TemporaryFilesHandler.register(null, file); FileOutputStream fos = new FileOutputStream(file); exportCommunitySystemView(community, contentPath, fos); fos.close(); File propertiesFile = File.createTempFile("exported-community-properties", null); TemporaryFilesHandler.register(null, propertiesFile); FileOutputStream fosProperties = new FileOutputStream(propertiesFile); fosProperties.write(("communityId=" + communityId).getBytes()); fosProperties.write(";".getBytes()); fosProperties.write(("externalId=" + community.getExternalId()).getBytes()); fosProperties.write(";".getBytes()); fosProperties.write(("title=" + I18NUtils.localize(community.getTitle())).getBytes()); fosProperties.write(";".getBytes()); fosProperties.write(("communityType=" + community.getType()).getBytes()); fosProperties.write(";".getBytes()); fosProperties.write(("communityName=" + community.getName()).getBytes()); fosProperties.close(); FileInputStream finProperties = new FileInputStream(propertiesFile); byte[] bufferProperties = new byte[4096]; out.putNextEntry(new ZipEntry("properties")); int readProperties = 0; while ((readProperties = finProperties.read(bufferProperties)) > 0) { out.write(bufferProperties, 0, readProperties); } finProperties.close(); FileInputStream fin = new FileInputStream(file); byte[] buffer = new byte[4096]; out.putNextEntry(new ZipEntry("xmlData")); int read = 0; while ((read = fin.read(buffer)) > 0) { out.write(buffer, 0, read); } fin.close(); out.close(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileInputStream fisZipped = new FileInputStream(zipOutFilename); byte[] bufferOut = new byte[4096]; int readOut = 0; while ((readOut = fisZipped.read(bufferOut)) > 0) { baos.write(bufferOut, 0, readOut); } return baos.toByteArray(); } catch (Exception e) { String errorMessage = "Error exporting backup data, for comunnity with id " + communityId; log.error(errorMessage, e); throw new CMSRuntimeException(errorMessage, e); } }
Code Sample 2:
private HashSet<String> href(String urlstr) throws IOException { HashSet<String> hrefs = new HashSet<String>(); URL url = new URL(urlstr); URLConnection con = url.openConnection(); con.setRequestProperty("Cookie", "_session_id=" + _session_id); InputStreamReader r = new InputStreamReader(con.getInputStream()); StringWriter b = new StringWriter(); IOUtils.copyTo(r, b); r.close(); try { Thread.sleep(WAIT_SECONDS * 1000); } catch (Exception err) { } String tokens[] = b.toString().replace("\n", " ").replaceAll("[\\<\\>]", "\n").split("[\n]"); for (String s1 : tokens) { if (!(s1.startsWith("a") && s1.contains("href"))) continue; String tokens2[] = s1.split("[\\\"\\\']"); for (String s2 : tokens2) { if (!(s2.startsWith("mailto:") || s2.matches("/profile/index/[0-9]+"))) continue; hrefs.add(s2); } } return hrefs; }
|
11
|
Code Sample 1:
public void access() { Authenticator.setDefault(new MyAuthenticator()); try { URL url = new URL("http://localhost/ws/test"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
Code Sample 2:
public static String getStringFromAFileAtURL(String anURL) { String htmlCode = "<html><body></body></html>"; try { URL url = new URL(anURL); URLConnection urlConnection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine = ""; htmlCode = ""; while ((inputLine = in.readLine()) != null) htmlCode += inputLine + "\n"; in.close(); } catch (Exception e) { logs.info("URLResolver : lien mort"); JOptionPane.showMessageDialog(null, "lien mort"); return "<html><body></body></html>"; } return checkXMLTagsLowerCase(htmlCode); }
|
11
|
Code Sample 1:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
Code Sample 2:
public static File extract(File source, String filename, File target) { if (source.exists() == false || filename == null || filename.trim().length() < 1 || target == null) return null; boolean isDirectory = (filename.lastIndexOf("/") == filename.length() - 1); try { Map contents = (Map) jarContents.get(source.getPath()); if (contents == null) { contents = new HashMap(); jarContents.put(source.getPath(), contents); ZipInputStream input = new ZipInputStream(new FileInputStream(source)); ZipEntry zipEntry = null; while ((zipEntry = input.getNextEntry()) != null) { if (zipEntry.isDirectory()) continue; contents.put(zipEntry.getName(), zipEntry); } input.close(); } if (isDirectory) { Iterator it = contents.keySet().iterator(); while (it.hasNext()) { String next = (String) it.next(); if (next.startsWith(filename)) { ZipEntry zipEntry = (ZipEntry) contents.get(next); int n = filename.length(); File newTarget = new File(target, zipEntry.getName().substring(n)); extract(source, next, newTarget); } } return target; } ZipEntry entry = (ZipEntry) contents.get(filename); ZipFile input = new ZipFile(source); InputStream in = input.getInputStream(entry); target.getParentFile().mkdirs(); int bytesRead; byte[] buffer = new byte[1024]; FileOutputStream output = new FileOutputStream(target); while ((bytesRead = in.read(buffer)) != -1) output.write(buffer, 0, bytesRead); output.close(); input.close(); return target; } catch (Exception ex) { ex.printStackTrace(); } return null; }
|
00
|
Code Sample 1:
public boolean resolve(String parameters, Reader in, Writer out, DataFieldResolver dataFieldResolver, int[] arrayPositioner) throws IOException { PrintWriter printOut = new PrintWriter(out); URL url = new URL(parameters); Reader urlIn = new InputStreamReader(url.openStream()); int ch = urlIn.read(); while (ch != -1) { out.write(ch); ch = urlIn.read(); } out.flush(); return false; }
Code Sample 2:
private String calculateCredential(Account account) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return null; } try { md5.update(account.getUsername().getBytes("UTF-8")); md5.update(account.getCryptPassword().getBytes("UTF-8")); md5.update(String.valueOf(account.getObjectId()).getBytes("UTF-8")); md5.update(account.getUid().getBytes("UTF-8")); byte[] digest = md5.digest(); return TextUtils.calculateMD5(digest); } catch (UnsupportedEncodingException e) { return null; } }
|
11
|
Code Sample 1:
public void test() throws Exception { StorageString s = new StorageString("UTF-8"); s.addText("Test"); try { s.getOutputStream(); fail("Should throw IOException as method not supported."); } catch (IOException e) { } try { s.getWriter(); fail("Should throw IOException as method not supported."); } catch (IOException e) { } s.addText("ing is important"); s.close(ResponseStateOk.getInstance()); assertEquals("Testing is important", s.getText()); InputStream input = s.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer, "UTF-8"); assertEquals("Testing is important", writer.toString()); }
Code Sample 2:
public void createZip(File zipFileName, Vector<File> selected) { try { byte[] buffer = new byte[4096]; ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName), 8096)); out.setLevel(Deflater.BEST_COMPRESSION); out.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < selected.size(); i++) { FileInputStream in = new FileInputStream(selected.get(i)); String file = selected.get(i).getPath(); if (file.indexOf("\\") != -1) file = file.substring(file.lastIndexOf(fs) + 1, file.length()); ZipEntry ze = new ZipEntry(file); out.putNextEntry(ze); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); selected.get(i).delete(); } out.close(); } catch (IllegalArgumentException iae) { iae.printStackTrace(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } }
|
00
|
Code Sample 1:
private void importDocument(String path, boolean detectParagraphs, Parser parser, ReadingAnnotationFilter filter, String encoding) { try { Reader in = null; int contentlength = 0; if (JGloss.messages.getString("encodings.default").equals(encoding)) encoding = null; String title = ""; try { URL url = new URL(path); URLConnection c = url.openConnection(); contentlength = c.getContentLength(); String enc = c.getContentEncoding(); InputStream is = new BufferedInputStream(c.getInputStream()); if (encoding != null) in = new InputStreamReader(is, encoding); else { in = CharacterEncodingDetector.getReader(is, enc); encoding = ((InputStreamReader) in).getEncoding(); } title = url.getFile(); if (title == null || title.length() == 0) title = path; } catch (MalformedURLException ex) { File f = new File(path); contentlength = (int) f.length(); title = f.getName(); if (title.toLowerCase().endsWith("htm") || title.toLowerCase().endsWith("html")) { } InputStream is = new BufferedInputStream(new FileInputStream(path)); if (encoding != null) in = new InputStreamReader(is, encoding); else { in = CharacterEncodingDetector.getReader(is); encoding = ((InputStreamReader) in).getEncoding(); } } importFromReader(in, detectParagraphs, path, title, filter, parser, CharacterEncodingDetector.guessLength(contentlength, encoding)); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showConfirmDialog(this, JGloss.messages.getString("error.import.exception", new Object[] { path, ex.getClass().getName(), ex.getLocalizedMessage() }), JGloss.messages.getString("error.import.title"), JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE); if (model.getDocumentName() == null) this.dispose(); } }
Code Sample 2:
private static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { if (!destFile.createNewFile()) { throw new IOException("Destination file cannot be created: " + destFile.getPath()); } } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
00
|
Code Sample 1:
public String translate(String before, int translateType) throws CoreException { if (before == null) throw new IllegalArgumentException("before is null."); if ((translateType != ENGLISH_TO_JAPANESE) && (translateType != JAPANESE_TO_ENGLISH)) { throw new IllegalArgumentException("Invalid translateType. value=" + translateType); } try { URL url = new URL(config.getTranslatorSiteUrl()); URLConnection connection = url.openConnection(); sendTranslateRequest(before, translateType, connection); String afterContents = receiveTranslatedResponse(connection); String afterStartKey = config.getTranslationResultStart(); String afterEndKey = config.getTranslationResultEnd(); int startLength = afterStartKey.length(); int startPos = afterContents.indexOf(afterStartKey); if (startPos != -1) { int endPos = afterContents.indexOf(afterEndKey, startPos); if (endPos != -1) { String after = afterContents.substring(startPos + startLength, endPos); after = replaceEntities(after); return after; } else { throwCoreException(ERROR_END_KEYWORD_NOT_FOUND, "End keyword not found.", null); } } else { throwCoreException(ERROR_START_KEYWORD_NOT_FOUND, "Start keyword not found.", null); } } catch (IOException e) { throwCoreException(ERROR_IO, e.getMessage(), e); } throw new IllegalStateException("CoreException not occurd."); }
Code Sample 2:
public ProjectDeploymentConfiguration deleteProjectDeploymentConfig(int id) throws AdaptationException { ProjectDeploymentConfiguration config = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProjectDeploymentConfigurations " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete project deployment " + "configuration failed."; log.error(msg); throw new AdaptationException(msg); } config = getProjectDeploymentConfiguration(resultSet); query = "DELETE FROM ProjectDeploymentConfigurations " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProjectDeploymentConfig"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return config; }
|
11
|
Code Sample 1:
private String mkSid() { String temp = toString(); MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } messagedigest.update(temp.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } return chk.toString(); }
Code Sample 2:
public static String getEncryptedPassword(String password) throws PasswordException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); } catch (Exception e) { throw new PasswordException(e); } return convertToString(md.digest()); }
|
11
|
Code Sample 1:
@Test public void testCopy_readerToOutputStream_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); try { IOUtils.copy((Reader) null, out); fail(); } catch (NullPointerException ex) { } }
Code Sample 2:
private static void execute(String fileName) throws IOException, SQLException { InputStream input = DatabaseConstants.class.getResourceAsStream(fileName); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer); String sql = writer.toString(); Statement statement = connection.createStatement(); statement.execute(sql); }
|
00
|
Code Sample 1:
public static final void copy(String source, String destination) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } catch (FileNotFoundException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } }
Code Sample 2:
public int delete(BusinessObject o) throws DAOException { int delete = 0; Project project = (Project) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_PROJECT")); pst.setInt(1, project.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; }
|
00
|
Code Sample 1:
public void googleImageSearch(String start) { try { String u = "http://images.google.com/images?q=" + custom + start; if (u.contains(" ")) { u = u.replace(" ", "+"); } URL url = new URL(u); HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); httpcon.addRequestProperty("User-Agent", "Mozilla/4.76"); BufferedReader readIn = new BufferedReader(new InputStreamReader(httpcon.getInputStream())); googleImages.clear(); String text = ""; String lin = ""; while ((lin = readIn.readLine()) != null) { text += lin; } readIn.close(); if (text.contains("\n")) { text = text.replace("\n", ""); } String[] array = text.split("\\Qhref=\"/imgres?imgurl=\\E"); for (String s : array) { if (s.startsWith("http://") || s.startsWith("https://") && s.contains("&")) { String s1 = s.substring(0, s.indexOf("&")); googleImages.add(s1); } } } catch (Exception ex4) { MusicBoxView.showErrorDialog(ex4); } jButton4.setEnabled(true); jButton2.setEnabled(true); getContentPane().remove(jLabel1); ImageIcon icon; try { icon = new ImageIcon(new URL(googleImages.elementAt(googleImageLocation))); int h = icon.getIconHeight(); int w = icon.getIconWidth(); jLabel1.setSize(w, h); jLabel1.setIcon(icon); add(jLabel1, BorderLayout.CENTER); } catch (MalformedURLException ex) { MusicBoxView.showErrorDialog(ex); jLabel1.setIcon(MusicBoxView.noImage); } add(jPanel1, BorderLayout.PAGE_END); pack(); }
Code Sample 2:
public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); }
|
11
|
Code Sample 1:
private String unJar(String jarPath, String jarEntry) { String path; if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/")); String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/")); try { new File(path + "/" + relPath).mkdirs(); JarFile jar = new JarFile(jarPath); ZipEntry ze = jar.getEntry(jarEntry); File bin = new File(path + "/" + jarEntry); IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin)); } catch (Exception e) { e.printStackTrace(); } return path + "/" + jarEntry; }
Code Sample 2:
public static void copyFile(String inName, String otName) throws Exception { File inFile = null; File otFile = null; try { inFile = new File(inName); otFile = new File(otName); } catch (Exception e) { e.printStackTrace(); } if (inFile == null || otFile == null) return; FileChannel sourceChannel = new FileInputStream(inFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(otFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
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:
public void Sort(int a[]) { for (int i = a.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } }
|
11
|
Code Sample 1:
private void addPNMLFileToLibrary(File selected) { try { FileChannel srcChannel = new FileInputStream(selected.getAbsolutePath()).getChannel(); FileChannel dstChannel = new FileOutputStream(new File(matchingOrderXML).getParent() + "/" + selected.getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); order.add(new ComponentDescription(false, selected.getName().replaceAll(".pnml", ""), 1.0)); updateComponentList(); } catch (IOException ioe) { JOptionPane.showMessageDialog(dialog, "Could not add the PNML file " + selected.getName() + " to the library!"); } }
Code Sample 2:
public static void extract(final File destDir, final ZipInfo zipInfo, final IProgressMonitor monitor) throws IOException { if (!destDir.exists()) destDir.mkdirs(); for (String key : zipInfo.getEntryKeys()) { ZipEntry entry = zipInfo.getEntry(key); InputStream in = zipInfo.getInputStream(entry); 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(); if (monitor != null) monitor.worked(1); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } if (monitor != null) monitor.done(); }
|
00
|
Code Sample 1:
@Test public void shouldSetAlias() throws Exception { HttpResponse response = executePost("/yum/alias/snapshots/testAlias", new StringEntity(VERSION_1)); assertEquals(VERSION_1, EntityUtils.toString(response.getEntity())); assertEquals(VERSION_1, executeGet("/yum/alias/snapshots/testAlias")); response = executePost("/yum/alias/snapshots/testAlias", new StringEntity(VERSION_2)); assertEquals(VERSION_2, EntityUtils.toString(response.getEntity())); assertEquals(VERSION_2, executeGet("/yum/alias/snapshots/testAlias")); }
Code Sample 2:
public static void upLoadFile(File sourceFile, File targetFile) throws IOException { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(sourceFile).getChannel(); outChannel = new FileOutputStream(targetFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { try { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } catch (IOException e) { e.printStackTrace(); } } }
|
11
|
Code Sample 1:
static List<String> listProperties(final MetadataType type) { List<String> props = new ArrayList<String>(); try { File adapter = File.createTempFile("adapter", null); InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(type.adapter); if (stream == null) { throw new IllegalStateException("Could not load adapter Jar: " + type.adapter); } FileOutputStream out = new FileOutputStream(adapter); IOUtils.copyLarge(stream, out); out.close(); JarFile jar = new JarFile(adapter); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().endsWith("dtd")) { InputStream inputStream = jar.getInputStream(entry); Scanner s = new Scanner(inputStream); while (s.hasNextLine()) { String nextLine = s.nextLine(); if (nextLine.startsWith("<!ELEMENT")) { String prop = nextLine.split(" ")[1]; props.add(prop); } } break; } } } catch (IOException e) { e.printStackTrace(); } return props; }
Code Sample 2:
public Void doInBackground() { setProgress(0); for (int i = 0; i < uploadFiles.size(); i++) { String filePath = uploadFiles.elementAt(i).getFilePath(); String fileName = uploadFiles.elementAt(i).getFileName(); String fileMsg = "Uploading file " + (i + 1) + "/" + uploadFiles.size() + "\n"; this.publish(fileMsg); try { File inFile = new File(filePath); FileInputStream in = new FileInputStream(inFile); byte[] inBytes = new byte[(int) chunkSize]; int count = 1; int maxCount = (int) (inFile.length() / chunkSize); if (inFile.length() % chunkSize > 0) { maxCount++; } int readCount = 0; readCount = in.read(inBytes); while (readCount > 0) { File splitFile = File.createTempFile("upl", null, null); String splitName = splitFile.getPath(); FileOutputStream out = new FileOutputStream(splitFile); out.write(inBytes, 0, readCount); out.close(); boolean chunkFinal = (count == maxCount); fileMsg = " - Sending chunk " + count + "/" + maxCount + ": "; this.publish(fileMsg); boolean uploadSuccess = false; int uploadTries = 0; while (!uploadSuccess && uploadTries <= 5) { uploadTries++; boolean uploadStatus = upload(splitName, fileName, count, chunkFinal); if (uploadStatus) { fileMsg = "OK\n"; this.publish(fileMsg); uploadSuccess = true; } else { fileMsg = "ERROR\n"; this.publish(fileMsg); uploadSuccess = false; } } if (!uploadSuccess) { fileMsg = "There was an error uploading your files. Please let the pipeline administrator know about this problem. Cut and paste the messages in this box, and supply them.\n"; this.publish(fileMsg); errorFlag = true; return null; } float thisProgress = (count * 100) / (maxCount); float completeProgress = (i * (100 / uploadFiles.size())); float totalProgress = completeProgress + (thisProgress / uploadFiles.size()); setProgress((int) totalProgress); splitFile.delete(); readCount = in.read(inBytes); count++; } } catch (Exception e) { this.publish(e.toString()); } } return null; }
|
11
|
Code Sample 1:
@Override public void run() { try { IOUtils.copy(getSource(), processStdIn); System.err.println("Copy done."); close(); } catch (IOException e) { e.printStackTrace(); IOUtils.closeQuietly(ExternalDecoder.this); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
public static String getMD5(final String text) { if (null == text) return null; final MessageDigest algorithm; try { algorithm = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } algorithm.reset(); algorithm.update(text.getBytes()); final byte[] digest = algorithm.digest(); final StringBuffer hexString = new StringBuffer(); for (byte b : digest) { String str = Integer.toHexString(0xFF & b); str = str.length() == 1 ? '0' + str : str; hexString.append(str); } return hexString.toString(); }
Code Sample 2:
public NodeId generateTopicId(String topicName) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.err.println("No SHA support!"); } md.update(topicName.getBytes()); byte[] digest = md.digest(); NodeId newId = new NodeId(digest); return newId; }
|
00
|
Code Sample 1:
private boolean processar(int iCodProd) { String sSQL = null; String sSQLCompra = null; String sSQLInventario = null; String sSQLVenda = null; String sSQLRMA = null; String sSQLOP = null; String sSQLOP_SP = null; String sWhere = null; String sProd = null; String sWhereCompra = null; String sWhereInventario = null; String sWhereVenda = null; String sWhereRMA = null; String sWhereOP = null; String sWhereOP_SP = null; PreparedStatement ps = null; ResultSet rs = null; boolean bOK = false; try { try { sWhere = ""; sProd = ""; if (cbTudo.getVlrString().equals("S")) sProd = "[" + iCodProd + "] "; if (!(txtDataini.getVlrString().equals(""))) { sWhere = " AND DTMOVPROD >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; } sSQL = "DELETE FROM EQMOVPROD WHERE " + "CODEMP=? AND CODPROD=?" + sWhere; state(sProd + "Limpando movimenta��es desatualizadas..."); ps = con.prepareStatement(sSQL); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, iCodProd); ps.executeUpdate(); ps.close(); if ((txtDataini.getVlrString().equals(""))) { sSQL = "UPDATE EQPRODUTO SET SLDPROD=0 WHERE " + "CODEMP=? AND CODPROD=?"; ps = con.prepareStatement(sSQL); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, iCodProd); ps.executeUpdate(); ps.close(); state(sProd + "Limpando saldos..."); sSQL = "UPDATE EQSALDOPROD SET SLDPROD=0 WHERE CODEMP=? AND CODPROD=?"; ps = con.prepareStatement(sSQL); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, iCodProd); ps.executeUpdate(); ps.close(); state(sProd + "Limpando saldos..."); } bOK = true; } catch (SQLException err) { Funcoes.mensagemErro(null, "Erro ao limpar estoques!\n" + err.getMessage(), true, con, err); } if (bOK) { bOK = false; if (!txtDataini.getVlrString().equals("")) { sWhereCompra = " AND C.DTENTCOMPRA >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; sWhereInventario = " AND I.DATAINVP >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; sWhereVenda = " AND V.DTEMITVENDA >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; sWhereRMA = " AND RMA.DTAEXPRMA >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; sWhereOP = " AND O.DTFABROP >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; sWhereOP_SP = " AND O.DTSUBPROD >= '" + Funcoes.dateToStrDB(txtDataini.getVlrDate()) + "'"; } else { sWhereCompra = ""; sWhereInventario = ""; sWhereVenda = ""; sWhereRMA = ""; sWhereOP = ""; sWhereOP_SP = ""; } sSQLInventario = "SELECT 'A' TIPOPROC, I.CODEMPPD, I.CODFILIALPD, I.CODPROD," + "I.CODEMPLE, I.CODFILIALLE, I.CODLOTE," + "I.CODEMPTM, I.CODFILIALTM, I.CODTIPOMOV," + "I.CODEMP, I.CODFILIAL, CAST(NULL AS CHAR(1)) TIPOVENDA, " + "I.CODINVPROD CODMASTER, I.CODINVPROD CODITEM, " + "CAST(NULL AS INTEGER) CODEMPNT, CAST(NULL AS SMALLINT) CODFILIALNT ,CAST(NULL AS CHAR(4)) CODNAT," + "I.DATAINVP DTPROC, I.CODINVPROD DOCPROC,'N' FLAG," + "I.QTDINVP QTDPROC, I.PRECOINVP CUSTOPROC, " + "I.CODEMPAX, I.CODFILIALAX, I.CODALMOX, CAST(NULL AS SMALLINT) as seqent, CAST(NULL AS SMALLINT) as seqsubprod " + "FROM EQINVPROD I " + "WHERE I.CODEMP=? AND I.CODPROD = ?" + sWhereInventario; sSQLCompra = "SELECT 'C' TIPOPROC, IC.CODEMPPD, IC.CODFILIALPD, IC.CODPROD," + "IC.CODEMPLE, IC.CODFILIALLE, IC.CODLOTE," + "C.CODEMPTM, C.CODFILIALTM, C.CODTIPOMOV," + "C.CODEMP, C.CODFILIAL, CAST(NULL AS CHAR(1)) TIPOVENDA, " + "C.CODCOMPRA CODMASTER, IC.CODITCOMPRA CODITEM," + "IC.CODEMPNT, IC.CODFILIALNT, IC.CODNAT, " + "C.DTENTCOMPRA DTPROC, C.DOCCOMPRA DOCPROC, C.FLAG," + "IC.QTDITCOMPRA QTDPROC, IC.CUSTOITCOMPRA CUSTOPROC, " + "IC.CODEMPAX, IC.CODFILIALAX, IC.CODALMOX, CAST(NULL AS SMALLINT) as seqent, CAST(NULL AS SMALLINT) as seqsubprod " + "FROM CPCOMPRA C,CPITCOMPRA IC " + "WHERE IC.CODCOMPRA=C.CODCOMPRA AND " + "IC.CODEMP=C.CODEMP AND IC.CODFILIAL=C.CODFILIAL AND IC.QTDITCOMPRA > 0 AND " + "C.CODEMP=? AND IC.CODPROD = ?" + sWhereCompra; sSQLOP = "SELECT 'O' TIPOPROC, O.CODEMPPD, O.CODFILIALPD, O.CODPROD," + "O.CODEMPLE, O.CODFILIALLE, O.CODLOTE," + "O.CODEMPTM, O.CODFILIALTM, O.CODTIPOMOV," + "O.CODEMP, O.CODFILIAL, CAST(NULL AS CHAR(1)) TIPOVENDA ," + "O.CODOP CODMASTER, CAST(O.SEQOP AS INTEGER) CODITEM," + "CAST(NULL AS INTEGER) CODEMPNT, CAST(NULL AS SMALLINT) CODFILIALNT, " + "CAST(NULL AS CHAR(4)) CODNAT, " + "coalesce(oe.dtent,O.DTFABROP) DTPROC, " + "O.CODOP DOCPROC, 'N' FLAG, " + "coalesce(oe.qtdent,O.QTDFINALPRODOP) QTDPROC, " + "( SELECT SUM(PD.CUSTOMPMPROD) FROM PPITOP IT, EQPRODUTO PD " + "WHERE IT.CODEMP=O.CODEMP AND IT.CODFILIAL=O.CODFILIAL AND " + "IT.CODOP=O.CODOP AND IT.SEQOP=O.SEQOP AND " + "PD.CODEMP=IT.CODEMPPD AND PD.CODFILIAL=IT.CODFILIALPD AND " + "PD.CODPROD=IT.CODPROD) CUSTOPROC, " + "O.CODEMPAX, O.CODFILIALAX, O.CODALMOX, oe.seqent, CAST(NULL AS SMALLINT) as seqsubprod " + "FROM PPOP O " + " left outer join ppopentrada oe on oe.codemp=o.codemp and oe.codfilial=o.codfilial and oe.codop=o.codop and oe.seqop=o.seqop " + "WHERE O.QTDFINALPRODOP > 0 AND " + "O.CODEMP=? AND O.CODPROD = ? " + sWhereOP; sSQLOP_SP = "SELECT 'S' TIPOPROC, O.CODEMPPD, O.CODFILIALPD, O.CODPROD," + "O.CODEMPLE, O.CODFILIALLE, O.CODLOTE," + "O.CODEMPTM, O.CODFILIALTM, O.CODTIPOMOV," + "O.CODEMP, O.CODFILIAL, CAST(NULL AS CHAR(1)) TIPOVENDA ," + "O.CODOP CODMASTER, CAST(O.SEQOP AS INTEGER) CODITEM," + "CAST(NULL AS INTEGER) CODEMPNT, CAST(NULL AS SMALLINT) CODFILIALNT, " + "CAST(NULL AS CHAR(4)) CODNAT, " + "coalesce(o.dtsubprod,Op.DTFABROP) DTPROC, " + "O.CODOP DOCPROC, 'N' FLAG, " + "O.QTDITSP QTDPROC, " + "( SELECT PD.CUSTOMPMPROD FROM EQPRODUTO PD " + "WHERE PD.CODEMP=O.CODEMPPD AND PD.CODFILIAL=O.CODFILIALPD AND " + "PD.CODPROD=O.CODPROD) CUSTOPROC, " + "OP.CODEMPAX, OP.CODFILIALAX, OP.CODALMOX, CAST(NULL AS SMALLINT) as seqent, O.SEQSUBPROD " + "FROM PPOPSUBPROD O, PPOP OP " + "WHERE O.QTDITSP > 0 AND " + "O.CODEMP=OP.CODEMP and O.CODFILIAL=OP.CODFILIAL and O.CODOP=OP.CODOP and O.SEQOP=OP.SEQOP AND " + "O.CODEMP=? AND O.CODPROD = ?" + sWhereOP_SP; sSQLRMA = "SELECT 'R' TIPOPROC, IT.CODEMPPD, IT.CODFILIALPD, IT.CODPROD, " + "IT.CODEMPLE, IT.CODFILIALLE, IT.CODLOTE, " + "RMA.CODEMPTM, RMA.CODFILIALTM, RMA.CODTIPOMOV, " + "RMA.CODEMP, RMA.CODFILIAL, CAST(NULL AS CHAR(1)) TIPOVENDA, " + "IT.CODRMA CODMASTER, CAST(IT.CODITRMA AS INTEGER) CODITEM, " + "CAST(NULL AS INTEGER) CODEMPNT, CAST(NULL AS SMALLINT) CODFILIALNT, " + "CAST(NULL AS CHAR(4)) CODNAT, " + "COALESCE(IT.DTAEXPITRMA,RMA.DTAREQRMA) DTPROC, " + "RMA.CODRMA DOCPROC, 'N' FLAG, " + "IT.QTDEXPITRMA QTDPROC, IT.PRECOITRMA CUSTOPROC," + "IT.CODEMPAX, IT.CODFILIALAX, IT.CODALMOX, CAST(NULL AS SMALLINT) as seqent, CAST(NULL AS SMALLINT) as seqsubprod " + "FROM EQRMA RMA ,EQITRMA IT " + "WHERE IT.CODRMA=RMA.CODRMA AND " + "IT.CODEMP=RMA.CODEMP AND IT.CODFILIAL=RMA.CODFILIAL AND " + "IT.QTDITRMA > 0 AND " + "RMA.CODEMP=? AND IT.CODPROD = ?" + sWhereRMA; sSQLVenda = "SELECT 'V' TIPOPROC, IV.CODEMPPD, IV.CODFILIALPD, IV.CODPROD," + "IV.CODEMPLE, IV.CODFILIALLE, IV.CODLOTE," + "V.CODEMPTM, V.CODFILIALTM, V.CODTIPOMOV," + "V.CODEMP, V.CODFILIAL, V.TIPOVENDA, " + "V.CODVENDA CODMASTER, IV.CODITVENDA CODITEM, " + "IV.CODEMPNT, IV.CODFILIALNT, IV.CODNAT, " + "V.DTEMITVENDA DTPROC, V.DOCVENDA DOCPROC, V.FLAG, " + "IV.QTDITVENDA QTDPROC, IV.VLRLIQITVENDA CUSTOPROC, " + "IV.CODEMPAX, IV.CODFILIALAX, IV.CODALMOX, CAST(NULL AS SMALLINT) as seqent, CAST(NULL AS SMALLINT) as seqsubprod " + "FROM VDVENDA V ,VDITVENDA IV " + "WHERE IV.CODVENDA=V.CODVENDA AND IV.TIPOVENDA = V.TIPOVENDA AND " + "IV.CODEMP=V.CODEMP AND IV.CODFILIAL=V.CODFILIAL AND " + "IV.QTDITVENDA > 0 AND " + "V.CODEMP=? AND IV.CODPROD = ?" + sWhereVenda; try { state(sProd + "Iniciando reconstru��o..."); sSQL = sSQLInventario + " UNION ALL " + sSQLCompra + " UNION ALL " + sSQLOP + " UNION ALL " + sSQLOP_SP + " UNION ALL " + sSQLRMA + " UNION ALL " + sSQLVenda + " ORDER BY 19,1,20"; System.out.println(sSQL); ps = con.prepareStatement(sSQL); ps.setInt(paramCons.CODEMPIV.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODIV.ordinal(), iCodProd); ps.setInt(paramCons.CODEMPCP.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODCP.ordinal(), iCodProd); ps.setInt(paramCons.CODEMPOP.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODOP.ordinal(), iCodProd); ps.setInt(paramCons.CODEMPOPSP.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODOPSP.ordinal(), iCodProd); ps.setInt(paramCons.CODEMPRM.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODRM.ordinal(), iCodProd); ps.setInt(paramCons.CODEMPVD.ordinal(), Aplicativo.iCodEmp); ps.setInt(paramCons.CODPRODVD.ordinal(), iCodProd); rs = ps.executeQuery(); bOK = true; while (rs.next() && bOK) { bOK = insereMov(rs, sProd); } rs.close(); ps.close(); state(sProd + "Aguardando grava��o final..."); } catch (SQLException err) { bOK = false; err.printStackTrace(); Funcoes.mensagemErro(null, "Erro ao reconstruir base!\n" + err.getMessage(), true, con, err); } } try { if (bOK) { con.commit(); state(sProd + "Registros processados com sucesso!"); } else { state(sProd + "Registros antigos restaurados!"); con.rollback(); } } catch (SQLException err) { err.printStackTrace(); Funcoes.mensagemErro(null, "Erro ao relizar procedimento!\n" + err.getMessage(), true, con, err); } } finally { sSQL = null; sSQLCompra = null; sSQLInventario = null; sSQLVenda = null; sSQLRMA = null; sWhere = null; sProd = null; sWhereCompra = null; sWhereInventario = null; sWhereVenda = null; sWhereRMA = null; rs = null; ps = null; bRunProcesso = false; btProcessar.setEnabled(true); } return bOK; }
Code Sample 2:
public static String hash(String plainTextPwd) { MessageDigest hashAlgo; try { hashAlgo = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new QwickException(e); } hashAlgo.update(plainTextPwd.getBytes()); return new String(hashAlgo.digest()); }
|
11
|
Code Sample 1:
public static void gunzip() throws Exception { System.out.println("gunzip()"); GZIPInputStream zipin = new GZIPInputStream(new FileInputStream("/zip/myzip.gz")); byte buffer[] = new byte[BLOCKSIZE]; FileOutputStream out = new FileOutputStream("/zip/covers"); for (int length; (length = zipin.read(buffer, 0, BLOCKSIZE)) != -1; ) out.write(buffer, 0, length); out.close(); zipin.close(); }
Code Sample 2:
private static void zip(File d) throws FileNotFoundException, IOException { String[] entries = d.list(); byte[] buffer = new byte[4096]; int bytesRead; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(new File(d.getParent() + File.separator + "dist.zip"))); for (int i = 0; i < entries.length; i++) { File f = new File(d, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); int skipl = d.getCanonicalPath().length(); ZipEntry entry = new ZipEntry(f.getPath().substring(skipl)); out.putNextEntry(entry); while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); FileUtils.moveFile(new File(d.getParent() + File.separator + "dist.zip"), new File(d + File.separator + "dist.zip")); }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private static byte[] tryLoadFile(String path) throws IOException { InputStream in = new FileInputStream(path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); out.close(); return out.toByteArray(); }
|
11
|
Code Sample 1:
private void copy(File from, File to) { if (from.isDirectory()) { File[] files = from.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { File newTo = new File(to.getPath() + File.separator + files[i].getName()); newTo.mkdirs(); copy(files[i], newTo); } else { copy(files[i], to); } } } else { try { to = new File(to.getPath() + File.separator + from.getName()); to.createNewFile(); FileChannel src = new FileInputStream(from).getChannel(); FileChannel dest = new FileOutputStream(to).getChannel(); dest.transferFrom(src, 0, src.size()); dest.close(); src.close(); } catch (FileNotFoundException e) { errorLog(e.toString()); e.printStackTrace(); } catch (IOException e) { errorLog(e.toString()); e.printStackTrace(); } } }
Code Sample 2:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
|
11
|
Code Sample 1:
public void run() { if (saveAsDialog == null) { saveAsDialog = new FileDialog(window.getShell(), SWT.SAVE); saveAsDialog.setFilterExtensions(saveAsTypes); } String outputFile = saveAsDialog.open(); if (outputFile != null) { Object inputFile = DataSourceSingleton.getInstance().getContainer().getWrapped(); InputStream in; try { if (inputFile instanceof URL) in = ((URL) inputFile).openStream(); else in = new FileInputStream((File) inputFile); OutputStream out = new FileOutputStream(outputFile); if (outputFile.endsWith("xml")) { int c; while ((c = in.read()) != -1) out.write(c); } else { PrintWriter pw = new PrintWriter(out); Element data = DataSourceSingleton.getInstance().getRawData(); writeTextFile(data, pw, -1); pw.close(); } in.close(); out.close(); } catch (MalformedURLException e1) { } catch (IOException e) { } } }
Code Sample 2:
@Override public void render(Output output) throws IOException { output.setStatus(headersFile.getStatusCode(), headersFile.getStatusMessage()); for (Entry<String, Set<String>> header : headersFile.getHeadersMap().entrySet()) { Set<String> values = header.getValue(); for (String value : values) { output.addHeader(header.getKey(), value); } } if (file != null) { InputStream inputStream = new FileInputStream(file); try { output.open(); OutputStream out = output.getOutputStream(); IOUtils.copy(inputStream, out); } finally { inputStream.close(); output.close(); } } }
|
11
|
Code Sample 1:
protected Object openDialogBox(Control cellEditorWindow) { FileDialog dialog = new FileDialog(parent.getShell(), SWT.OPEN); dialog.setFilterExtensions(new String[] { "*.jpg;*.JPG;*.JPEG;*.gif;*.GIF;*.png;*.PNG", "*.jpg;*.JPG;*.JPEG", "*.gif;*.GIF", "*.png;*.PNG" }); dialog.setFilterNames(new String[] { "All", "Joint Photographic Experts Group (JPEG)", "Graphics Interchange Format (GIF)", "Portable Network Graphics (PNG)" }); String imagePath = dialog.open(); if (imagePath == null) return null; IProject project = ProjectManager.getInstance().getCurrentProject(); String projectFolderPath = project.getLocation().toOSString(); File imageFile = new File(imagePath); String fileName = imageFile.getName(); ImageData imageData = null; try { imageData = new ImageData(imagePath); } catch (SWTException e) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } if (imageData == null) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } File copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + fileName); if (copiedImageFile.exists()) { Path path = new Path(copiedImageFile.getPath()); copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString() + "." + path.getFileExtension()); } try { copiedImageFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); copiedImageFile = null; } if (copiedImageFile == null) { copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString()); try { copiedImageFile.createNewFile(); } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } } FileReader in = null; FileWriter out = null; try { in = new FileReader(imageFile); out = new FileWriter(copiedImageFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } return imageFolderPath + File.separator + copiedImageFile.getName(); }
Code Sample 2:
public static void copy_file(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[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) { ; } } }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dst) throws IOException { FileChannel sourceChannel = new FileInputStream(src).getChannel(); FileChannel destinationChannel = new FileOutputStream(dst).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
public void setTableBraille(String tableBraille, boolean sys) { fiConf.setProperty(OptNames.fi_braille_table, tableBraille); fiConf.setProperty(OptNames.fi_is_sys_braille_table, Boolean.toString(sys)); FileChannel in = null; FileChannel out = null; try { String fichTable; if (!(tableBraille.endsWith(".ent"))) { tableBraille = tableBraille + ".ent"; } if (sys) { fichTable = ConfigNat.getInstallFolder() + "xsl/tablesBraille/" + tableBraille; } else { fichTable = ConfigNat.getUserBrailleTableFolder() + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(getUserBrailleTableFolder() + "Brltab.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
@Test public void testDocumentDownloadKnowledgeBase() throws IOException { if (uploadedKbDocumentID == null) { fail("Document Upload Test should run first"); } String downloadLink = GoogleDownloadLinkGenerator.generateTextDownloadLink(uploadedKbDocumentID); URL url = new URL(downloadLink); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); InputStream input = url.openStream(); FileWriter fw = new FileWriter("tmpOutput.kb"); Reader reader = new InputStreamReader(input); BufferedReader bufferedReader = new BufferedReader(reader); String strLine = ""; int count = 0; while (count < 10000) { strLine = bufferedReader.readLine(); if (strLine != null && strLine != "") { fw.write(strLine); } count++; } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public void concatFiles() throws IOException { Writer writer = null; try { final File targetFile = new File(getTargetDirectory(), getTargetFile()); targetFile.getParentFile().mkdirs(); if (null != getEncoding()) { getLog().info("Writing aggregated file with encoding '" + getEncoding() + "'"); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), getEncoding())); } else { getLog().info("WARNING: writing aggregated file with system encoding"); writer = new FileWriter(targetFile); } for (File file : getFiles()) { Reader reader = null; try { if (null != getEncoding()) { getLog().info("Reading file " + file.getCanonicalPath() + " with encoding '" + getEncoding() + "'"); reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), getEncoding())); } else { getLog().info("WARNING: Reading file " + file.getCanonicalPath() + " with system encoding"); reader = new FileReader(file); } IOUtils.copy(reader, writer); final String delimiter = getDelimiter(); if (delimiter != null) { writer.write(delimiter.toCharArray()); } } finally { IOUtils.closeQuietly(reader); } } } finally { IOUtils.closeQuietly(writer); } }
|
00
|
Code Sample 1:
public Download(URL url, int segs) { this.url = url; Mediator.register(this); status = "Starting..."; try { totalSize = url.openConnection().getContentLength(); name = url.getPath().substring(url.getPath().lastIndexOf('/') + 1); if (name.isEmpty()) { name = "UNKNOWN"; } tempFolder = new File(Configuration.PARTS_FOLDER, getName()); tempFolder.mkdir(); } catch (IOException ex) { Logger.post(Logger.Level.WARNING, "URL could not be opened: " + url); } dest = new File(System.getProperty("user.home") + File.separator + name); if (segs > totalSize) { segs = totalSize; } Properties props = new Properties(); props.setProperty("url", getUrl().toString()); props.setProperty("segments", String.valueOf(segs)); try { props.storeToXML(new FileOutputStream(new File(getTempFolder(), "index.xml")), "Warning: Editing this file may compromise the integrity of the download"); } catch (IOException ex) { ex.printStackTrace(); } segments = new Segment[segs]; for (int i = 0; i < segs; i++) { segments[i] = new Segment(this, i); } Thread thread = new Thread(this); thread.setDaemon(true); thread.start(); status = "Downloading..."; Mediator.post(new DownloadStatusChanged(this)); Logger.post(Logger.Level.INFO, "Starting download: " + getName()); }
Code Sample 2:
public int getDBVersion() throws MigrationException { int dbVersion; PreparedStatement ps; try { Connection conn = getConnection(); ps = conn.prepareStatement("SELECT version FROM " + getTablename()); try { ResultSet rs = ps.executeQuery(); try { if (rs.next()) { dbVersion = rs.getInt(1); if (rs.next()) { throw new MigrationException("Too many version in table: " + getTablename()); } } else { ps.close(); ps = conn.prepareStatement("INSERT INTO " + getTablename() + " (version) VALUES (?)"); ps.setInt(1, 1); try { ps.executeUpdate(); } finally { ps.close(); } dbVersion = 1; } } finally { rs.close(); } } finally { ps.close(); } } catch (SQLException e) { logger.log(Level.WARNING, "Could not access " + tablename + ": " + e); dbVersion = 0; Connection conn = getConnection(); try { if (!conn.getAutoCommit()) { conn.rollback(); } conn.setAutoCommit(false); } catch (SQLException e1) { throw new MigrationException("Could not reset transaction state", e1); } } return dbVersion; }
|
11
|
Code Sample 1:
@Override public void execute() throws ProcessorExecutionException { try { if (getSource().getPaths() == null || getSource().getPaths().size() == 0 || getDestination().getPaths() == null || getDestination().getPaths().size() == 0) { throw new ProcessorExecutionException("No input and/or output paths specified."); } String temp_dir_prefix = getDestination().getPath().getParent().toString() + "/bcc_" + getDestination().getPath().getName() + "_"; SequenceTempDirMgr dirMgr = new SequenceTempDirMgr(temp_dir_prefix, context); dirMgr.setSeqNum(0); Path tmpDir; System.out.println("++++++>" + dirMgr.getSeqNum() + ": Transform input to AdjSetVertex"); Transformer transformer = new OutAdjVertex2AdjSetVertexTransformer(); transformer.setConf(context); transformer.setSrcPath(getSource().getPath()); tmpDir = dirMgr.getTempDir(); transformer.setDestPath(tmpDir); transformer.setMapperNum(getMapperNum()); transformer.setReducerNum(getReducerNum()); transformer.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + ": Transform input to LabeledAdjSetVertex"); Vertex2LabeledTransformer l_transformer = new Vertex2LabeledTransformer(); l_transformer.setConf(context); l_transformer.setSrcPath(tmpDir); tmpDir = dirMgr.getTempDir(); l_transformer.setDestPath(tmpDir); l_transformer.setMapperNum(getMapperNum()); l_transformer.setReducerNum(getReducerNum()); l_transformer.setOutputValueClass(LabeledAdjSetVertex.class); l_transformer.execute(); Graph src; Graph dest; Path path_to_remember = tmpDir; System.out.println("++++++>" + dirMgr.getSeqNum() + ": SpanningTreeRootChoose"); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); GraphAlgorithm choose_root = new SpanningTreeRootChoose(); choose_root.setConf(context); choose_root.setSource(src); choose_root.setDestination(dest); choose_root.setMapperNum(getMapperNum()); choose_root.setReducerNum(getReducerNum()); choose_root.execute(); Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); String root_vertex_id = the_line.substring(SpanningTreeRootChoose.SPANNING_TREE_ROOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("++++++> Chosen the root of spanning tree = " + root_vertex_id); while (true) { System.out.println("++++++>" + dirMgr.getSeqNum() + " Generate the spanning tree rooted at : (" + root_vertex_id + ") from " + tmpDir); src = new Graph(Graph.defaultGraph()); src.setPath(path_to_remember); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); path_to_remember = tmpDir; GraphAlgorithm spanning = new SpanningTreeGenerate(); spanning.setConf(context); spanning.setSource(src); spanning.setDestination(dest); spanning.setMapperNum(getMapperNum()); spanning.setReducerNum(getReducerNum()); spanning.setParameter(ConstantLabels.ROOT_ID, root_vertex_id); spanning.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + " Test spanning convergence"); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); GraphAlgorithm conv_tester = new SpanningConvergenceTest(); conv_tester.setConf(context); conv_tester.setSource(src); conv_tester.setDestination(dest); conv_tester.setMapperNum(getMapperNum()); conv_tester.setReducerNum(getReducerNum()); conv_tester.execute(); long vertexes_out_of_tree = MRConsoleReader.getMapOutputRecordNum(conv_tester.getFinalStatus()); System.out.println("++++++> number of vertexes out of the spanning tree = " + vertexes_out_of_tree); if (vertexes_out_of_tree == 0) { break; } } System.out.println("++++++> From spanning tree to sets of edges"); src = new Graph(Graph.defaultGraph()); src.setPath(path_to_remember); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); GraphAlgorithm tree2set = new Tree2EdgeSet(); tree2set.setConf(context); tree2set.setSource(src); tree2set.setDestination(dest); tree2set.setMapperNum(getMapperNum()); tree2set.setReducerNum(getReducerNum()); tree2set.execute(); long map_input_records_num = -1; long map_output_records_num = -2; Stack<Path> expanding_stack = new Stack<Path>(); do { System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetMinorJoin"); GraphAlgorithm minorjoin = new EdgeSetMinorJoin(); minorjoin.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); minorjoin.setSource(src); minorjoin.setDestination(dest); minorjoin.setMapperNum(getMapperNum()); minorjoin.setReducerNum(getReducerNum()); minorjoin.execute(); expanding_stack.push(tmpDir); System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetJoin"); GraphAlgorithm join = new EdgeSetJoin(); join.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); join.setSource(src); join.setDestination(dest); join.setMapperNum(getMapperNum()); join.setReducerNum(getReducerNum()); join.execute(); map_input_records_num = MRConsoleReader.getMapInputRecordNum(join.getFinalStatus()); map_output_records_num = MRConsoleReader.getMapOutputRecordNum(join.getFinalStatus()); System.out.println("++++++> map in/out : " + map_input_records_num + "/" + map_output_records_num); } while (map_input_records_num != map_output_records_num); while (expanding_stack.size() > 0) { System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetExpand"); GraphAlgorithm expand = new EdgeSetExpand(); expand.setConf(context); src = new Graph(Graph.defaultGraph()); src.addPath(expanding_stack.pop()); src.addPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); expand.setSource(src); expand.setDestination(dest); expand.setMapperNum(getMapperNum()); expand.setReducerNum(getReducerNum()); expand.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetMinorExpand"); GraphAlgorithm minorexpand = new EdgeSetMinorExpand(); minorexpand.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); minorexpand.setSource(src); minorexpand.setDestination(dest); minorexpand.setMapperNum(getMapperNum()); minorexpand.setReducerNum(getReducerNum()); minorexpand.execute(); } System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetSummarize"); GraphAlgorithm summarize = new EdgeSetSummarize(); summarize.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); dest.setPath(getDestination().getPath()); summarize.setSource(src); summarize.setDestination(dest); summarize.setMapperNum(getMapperNum()); summarize.setReducerNum(getReducerNum()); summarize.execute(); dirMgr.deleteAll(); } catch (IOException e) { throw new ProcessorExecutionException(e); } catch (IllegalAccessException e) { throw new ProcessorExecutionException(e); } }
Code Sample 2:
public static String backupFile(File source) { File backup = new File(source.getParent() + "/~" + source.getName()); try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(source))); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(backup))); return FileUtil.backupFile(reader, writer, source.getAbsolutePath()); } catch (FileNotFoundException fe) { String msg = "Failed to find file for backup [" + source.getAbsolutePath() + "]."; _log.error(msg, fe); throw new InvalidImplementationException(msg, fe); } }
|
00
|
Code Sample 1:
public int updatewuliao(Addwuliao aw) { int flag = 0; Connection conn = null; PreparedStatement pm = null; try { conn = Pool.getConnection(); conn.setAutoCommit(false); pm = conn.prepareStatement("update addwuliao set inname=?,innum=?,inprice=?,productsdetail=?where pid=?"); pm.setString(1, aw.getInname()); pm.setInt(2, aw.getInnum()); pm.setDouble(3, aw.getInprice()); pm.setString(4, aw.getProductsdetail()); pm.setString(5, aw.getPid()); flag = pm.executeUpdate(); conn.commit(); Pool.close(pm); Pool.close(conn); } catch (Exception e) { e.printStackTrace(); try { conn.rollback(); } catch (Exception ep) { ep.printStackTrace(); } Pool.close(pm); Pool.close(conn); } finally { Pool.close(pm); Pool.close(conn); } return flag; }
Code Sample 2:
public static byte[] loadURLToBuffer(URL url, int maxLength) throws IOException { byte[] buf = new byte[maxLength]; byte[] data = null; int iCount = 0; BufferedInputStream in = new BufferedInputStream(url.openStream(), 20480); iCount = in.read(buf, 0, buf.length); if (iCount != -1) { data = new byte[iCount]; System.arraycopy(buf, 0, data, 0, iCount); } in.close(); return data; }
|
00
|
Code Sample 1:
private static MapEntry<String, Properties> loadFpmConf() throws ConfigurationReadException { MapEntry<String, Properties> ret = null; Scanner sc = new Scanner(CONF_PATHS).useDelimiter(SEP_P); String prev = ""; while (sc.hasNext() && !hasLoaded) { Properties fpmConf = null; boolean relative = false; String path = sc.next(); if (path.startsWith(PREV_P)) { path = path.replace(PREV_P, prev.substring(0, prev.length() - 1)); } else if (path.startsWith(REL_P)) { path = path.replace(REL_P + FS, ""); relative = true; } else if (path.contains(HOME_P)) { path = path.replace(HOME_P, USER_HOME); } prev = path; path = path.concat(MAIN_CONF_FILE); try { InputStream is = null; if (relative) { is = ClassLoader.getSystemResourceAsStream(path); path = getSystemConfDir(); Strings.getOne().createPath(path); path += MAIN_CONF_FILE; FileOutputStream os = new FileOutputStream(path); IOUtils.copy(is, os); os.flush(); os.close(); os = null; } else { is = new FileInputStream(path); } fpmConf = new Properties(); fpmConf.load(is); if (fpmConf.isEmpty()) { throw new ConfigurationReadException(); } ret = new MapEntry<String, Properties>(path, fpmConf); hasLoaded = true; } catch (FileNotFoundException e) { fpmConf = null; singleton = null; hasLoaded = false; } catch (IOException e) { throw new ConfigurationReadException(); } } return ret; }
Code Sample 2:
@Override public void execute(Client client, TaskProperties properties, TaskLog taskLog) throws SearchLibException { String url = properties.getValue(propUrl); URI uri; try { uri = new URI(url); } catch (URISyntaxException e) { throw new SearchLibException(e); } String login = properties.getValue(propLogin); String password = properties.getValue(propPassword); String instanceId = properties.getValue(propInstanceId); HttpParams params = new BasicHttpParams(); HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params); paramsBean.setVersion(HttpVersion.HTTP_1_1); paramsBean.setContentCharset("UTF-8"); HttpClientParams.setRedirecting(params, true); DefaultHttpClient httpClient = new DefaultHttpClient(params); CredentialsProvider credential = httpClient.getCredentialsProvider(); if (login != null && login.length() > 0 && password != null && password.length() > 0) credential.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(login, password)); else credential.clear(); HttpPost httpPost = new HttpPost(uri); MultipartEntity reqEntity = new MultipartEntity(); new Monitor().writeToPost(reqEntity); try { reqEntity.addPart("instanceId", new StringBody(instanceId)); } catch (UnsupportedEncodingException e) { throw new SearchLibException(e); } httpPost.setEntity(reqEntity); try { HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity resEntity = httpResponse.getEntity(); StatusLine statusLine = httpResponse.getStatusLine(); EntityUtils.consume(resEntity); if (statusLine.getStatusCode() != 200) throw new SearchLibException("Wrong code status:" + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase()); taskLog.setInfo("Monitoring data uploaded"); } catch (ClientProtocolException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } finally { ClientConnectionManager connectionManager = httpClient.getConnectionManager(); if (connectionManager != null) connectionManager.shutdown(); } }
|
11
|
Code Sample 1:
public static Shader loadShader(String vspath, String fspath, int textureUnits, boolean separateCam, boolean fog) throws ShaderProgramProcessException { if (vspath == "" || fspath == "") return null; BufferedReader in; String vert = "", frag = ""; try { URL v_url = Graphics.class.getClass().getResource("/eu/cherrytree/paj/graphics/shaders/" + vspath); String v_path = AppDefinition.getDefaultDataPackagePath() + "/shaders/" + vspath; if (v_url != null) in = new BufferedReader(new InputStreamReader(v_url.openStream())); else in = new BufferedReader(new InputStreamReader(new FileReader(v_path).getInputStream())); boolean run = true; String str; while (run) { str = in.readLine(); if (str != null) vert += str + "\n"; else run = false; } in.close(); } catch (Exception e) { System.err.println("Couldn't read in vertex shader \"" + vspath + "\"."); throw new ShaderNotLoadedException(vspath, fspath); } try { URL f_url = Graphics.class.getClass().getResource("/eu/cherrytree/paj/graphics/shaders/" + fspath); String f_path = AppDefinition.getDefaultDataPackagePath() + "/shaders/" + fspath; if (f_url != null) in = new BufferedReader(new InputStreamReader(f_url.openStream())); else in = new BufferedReader(new InputStreamReader(new FileReader(f_path).getInputStream())); boolean run = true; String str; while (run) { str = in.readLine(); if (str != null) frag += str + "\n"; else run = false; } in.close(); } catch (Exception e) { System.err.println("Couldn't read in fragment shader \"" + fspath + "\"."); throw new ShaderNotLoadedException(vspath, fspath); } return loadShaderFromSource(vert, frag, textureUnits, separateCam, fog); }
Code Sample 2:
public static String getPageSource(String url) throws ClientProtocolException, IOException { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); InputStream in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder source = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) source.append(line); in.close(); return source.toString(); }
|
11
|
Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } }
Code Sample 2:
private void copyFile(File sourcefile, File targetfile) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(sourcefile)); out = new BufferedOutputStream(new FileOutputStream(targetfile)); byte[] buffer = new byte[4096]; int bytesread = 0; while ((bytesread = in.read(buffer)) >= 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } }
|
11
|
Code Sample 1:
public void copy(String pathFileIn, String pathFileOut) { try { File inputFile = new File(pathFileIn); File outputFile = new File(pathFileOut); FileReader in = new FileReader(inputFile); File outDir = new File(DirOut); if (!outDir.exists()) outDir.mkdirs(); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); this.printColumn(inputFile.getName(), outputFile.getPath()); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
@Override @RemoteMethod public boolean encrypt(int idAnexo) { try { Anexo anexo = anexoService.selectById(idAnexo); aes.init(Cipher.ENCRYPT_MODE, aeskeySpec); FileInputStream fis = new FileInputStream(config.baseDir + "/arquivos_upload_direto/" + anexo.getAnexoCaminho()); CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(config.baseDir + "/arquivos_upload_direto/encrypt/" + anexo.getAnexoCaminho()), aes); IOUtils.copy(fis, cos); cos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
|
11
|
Code Sample 1:
private void googleImageSearch() { bottomShowing = true; googleSearched = true; googleImageLocation = 0; googleImages = new Vector<String>(); custom = ""; int r = JOptionPane.showConfirmDialog(this, "Customize google search?", "Google Search", JOptionPane.YES_NO_OPTION); if (r == JOptionPane.YES_OPTION) { custom = JOptionPane.showInputDialog("Custom Search", ""); } else { custom = artist; } try { String u = "http://images.google.com/images?q=" + custom; if (u.contains(" ")) { u = u.replace(" ", "+"); } URL url = new URL(u); HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); httpcon.addRequestProperty("User-Agent", "Mozilla/4.76"); BufferedReader readIn = new BufferedReader(new InputStreamReader(httpcon.getInputStream())); googleImages.clear(); String lin = new String(); while ((lin = readIn.readLine()) != null) { while (lin.contains("href=\"/imgres?imgurl=")) { while (!lin.contains(">")) { lin += readIn.readLine(); } String s = lin.substring(lin.indexOf("href=\"/imgres?imgurl="), lin.indexOf(">", lin.indexOf("href=\"/imgres?imgurl="))); lin = lin.substring(lin.indexOf(">", lin.indexOf("href=\"/imgres?imgurl="))); if (s.contains("&") && s.indexOf("http://") < s.indexOf("&")) { s = s.substring(s.indexOf("http://"), s.indexOf("&")); } else { s = s.substring(s.indexOf("http://"), s.length()); } googleImages.add(s); } } readIn.close(); } catch (Exception ex4) { MusicBoxView.showErrorDialog(ex4); } jButton1.setEnabled(false); getContentPane().remove(jLabel1); ImageIcon icon; try { icon = new ImageIcon(new URL(googleImages.elementAt(googleImageLocation))); int h = icon.getIconHeight(); int w = icon.getIconWidth(); jLabel1.setSize(w, h); jLabel1.setIcon(icon); add(jLabel1, BorderLayout.CENTER); } catch (MalformedURLException ex) { MusicBoxView.showErrorDialog(ex); jLabel1.setIcon(MusicBoxView.noImage); } add(jPanel1, BorderLayout.PAGE_END); pack(); }
Code Sample 2:
private static void grab(String urlString) throws MalformedURLException, IOException { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); BufferedReader in = null; StringBuffer sb = new StringBuffer(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; boolean f = false; while ((inputLine = in.readLine()) != null) { inputLine = inputLine.trim(); if (inputLine.startsWith("<tbody>")) { f = true; continue; } if (inputLine.startsWith("</table>")) { f = false; continue; } if (f) { sb.append(inputLine); sb.append("\n"); } } process(sb.toString()); }
|
11
|
Code Sample 1:
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); } } } }
Code Sample 2:
public static Boolean decompress(File source, File destination) { FileOutputStream outputStream; ZipInputStream inputStream; try { outputStream = null; inputStream = new ZipInputStream(new FileInputStream(source)); int read; byte buffer[] = new byte[BUFFER_SIZE]; ZipEntry zipEntry; while ((zipEntry = inputStream.getNextEntry()) != null) { if (zipEntry.isDirectory()) new File(destination, zipEntry.getName()).mkdirs(); else { File fileEntry = new File(destination, zipEntry.getName()); fileEntry.getParentFile().mkdirs(); outputStream = new FileOutputStream(fileEntry); while ((read = inputStream.read(buffer, 0, BUFFER_SIZE)) != -1) { outputStream.write(buffer, 0, read); } outputStream.flush(); outputStream.close(); } } inputStream.close(); } catch (Exception oException) { return false; } return true; }
|
00
|
Code Sample 1:
public InputStream getFileStream(String filePath) { if (this.inJar) { try { URL url = getClassResourceUrl(this.getClass(), filePath); if (url != null) { return url.openStream(); } } catch (IOException ioe) { Debug.signal(Debug.ERROR, this, ioe); } } else { try { return new FileInputStream(filePath); } catch (FileNotFoundException fe) { Debug.signal(Debug.ERROR, this, fe); } } return null; }
Code Sample 2:
public void loadJarFile(String jarFileNameParam) throws KExceptionClass { jarFileName = jarFileNameParam; { String message = "Loading resource file ["; message += jarFileName; message += "]..."; log.log(this, message); } try { URL url = new URL(jarFileName); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); jarConnection.setUseCaches(false); JarFile jarFile = jarConnection.getJarFile(); Enumeration jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { ZipEntry zipEntrie = (ZipEntry) jarEntries.nextElement(); { String message = "Scanning ["; message += jarFileName; message += "] found ["; message += describeEntry(zipEntrie); message += "]"; log.log(this, message); } htSizes.put(zipEntrie.getName(), new Integer((int) zipEntrie.getSize())); } ; jarFile.close(); BufferedInputStream inputBuffer = new BufferedInputStream(jarConnection.getJarFileURL().openStream()); ZipInputStream input = new ZipInputStream(inputBuffer); ZipEntry zipEntrie = null; while ((zipEntrie = input.getNextEntry()) != null) { if (zipEntrie.isDirectory()) continue; { String message = "Scanning ["; message += jarFileName; message += "] loading ["; message += zipEntrie.getName(); message += "] for ["; message += zipEntrie.getSize(); message += "] bytes."; log.log(this, message); } int size = (int) zipEntrie.getSize(); if (size == -1) { size = ((Integer) htSizes.get(zipEntrie.getName())).intValue(); } ; byte[] entrieData = new byte[(int) size]; int offset = 0; int dataRead = 0; while (((int) size - offset) > 0) { dataRead = input.read(entrieData, offset, (int) size - offset); if (dataRead == -1) break; offset += dataRead; } htJarContents.put(zipEntrie.getName(), entrieData); if (debugOn) { System.out.println(zipEntrie.getName() + " offset=" + offset + ",size=" + size + ",csize=" + zipEntrie.getCompressedSize()); } ; } ; } catch (Exception error) { String message = "Error loading data from JAR file ["; message += error.toString(); message += "]"; throw new KExceptionClass(message, new KExceptionClass(error.toString(), null)); } ; }
|
00
|
Code Sample 1:
private static Vector<String> getIgnoreList() { try { URL url = DeclarationTranslation.class.getClassLoader().getResource("ignorelist"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); Vector<String> ret = new Vector<String>(); String line = null; while ((line = bufferedReader.readLine()) != null) { ret.add(line); } return ret; } catch (Exception e) { return null; } }
Code Sample 2:
public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) { h = "0" + h; } hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
|
11
|
Code Sample 1:
@Test public void testCopy_inputStreamToOutputStream_IO84() throws Exception { long size = (long) Integer.MAX_VALUE + (long) 1; InputStream in = new NullInputStreamTest(size); OutputStream out = new OutputStream() { @Override public void write(int b) throws IOException { } @Override public void write(byte[] b) throws IOException { } @Override public void write(byte[] b, int off, int len) throws IOException { } }; assertEquals(-1, IOUtils.copy(in, out)); in.close(); assertEquals("copyLarge()", size, IOUtils.copyLarge(in, out)); }
Code Sample 2:
public static Boolean decompress(File source, File destination) { FileOutputStream outputStream; ZipInputStream inputStream; try { outputStream = null; inputStream = new ZipInputStream(new FileInputStream(source)); int read; byte buffer[] = new byte[BUFFER_SIZE]; ZipEntry zipEntry; while ((zipEntry = inputStream.getNextEntry()) != null) { if (zipEntry.isDirectory()) new File(destination, zipEntry.getName()).mkdirs(); else { File fileEntry = new File(destination, zipEntry.getName()); fileEntry.getParentFile().mkdirs(); outputStream = new FileOutputStream(fileEntry); while ((read = inputStream.read(buffer, 0, BUFFER_SIZE)) != -1) { outputStream.write(buffer, 0, read); } outputStream.flush(); outputStream.close(); } } inputStream.close(); } catch (Exception oException) { return false; } return true; }
|
00
|
Code Sample 1:
public void run() { try { URL url = new URL(UPDATE_URL); URLConnection urlc = url.openConnection(); BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String versionString = br.readLine(); if (versionString != null && !versionString.equals(PinEmUp.VERSION)) { StringBuilder changelogString = new StringBuilder(); changelogString.append("<html>"); changelogString.append("<p>" + I18N.getInstance().getString("info.updateavailable.part1") + "</p>"); changelogString.append("<p>" + I18N.getInstance().getString("info.updateavailable.part2") + " " + PinEmUp.VERSION + "<br />"); changelogString.append(I18N.getInstance().getString("info.updateavailable.part3") + " " + versionString + "</p>"); changelogString.append("<p>" + I18N.getInstance().getString("info.updateavailable.part4") + " <a href=\"http://pinemup.sourceforge.net\">http://pinemup.sourceforge.net</a></p>"); changelogString.append("<p> </p>"); changelogString.append("<p>Changelog:<br />"); changelogString.append("--------------------------------</p><p>"); boolean firstList = true; String nextLine; do { nextLine = br.readLine(); if (nextLine != null) { if (nextLine.startsWith("-")) { changelogString.append("<li>" + nextLine.substring(2) + "</li>"); } else { if (!firstList) { changelogString.append("</ul>"); } else { firstList = false; } changelogString.append(nextLine + "<ul>"); } } } while (nextLine != null); changelogString.append("</p></html>"); new UpdateDialog(changelogString.toString()); } else if (showUpToDateMessage) { JOptionPane.showMessageDialog(null, I18N.getInstance().getString("info.versionuptodate"), I18N.getInstance().getString("info.title"), JOptionPane.INFORMATION_MESSAGE); } br.close(); } catch (IOException e) { } }
Code Sample 2:
private void updateSystem() throws IOException { String stringUrl="http://code.google.com/p/senai-pe-cronos/downloads/list"; try { url = new URL(stringUrl); } catch (MalformedURLException ex) { ex.printStackTrace(); } InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String linha = br.readLine(); while (linha != null) { linha = br.readLine(); if(linha.contains("/files/updateCronos-0-")){ String[] s=linha.split("-"); String[] v=s[4].split(".exe"); versao=v[0]; println("----"+versao); break; } } stringUrl="http://senai-pe-cronos.googlecode.com/files/updateCronos-0-"+versao+".exe"; UpdateCronos update=new UpdateCronos(); try { url = new URL(stringUrl); } catch (MalformedURLException ex) { ex.printStackTrace(); } System.out.println("versão:"+versao); if(Integer.parseInt(versao)>version){ File f = update.gravaArquivoDeURL(url,System.getProperty("user.dir"),String.valueOf(version),versao); if(update.isS()) { Runtime.getRuntime().exec(location+"\\update.exe"); System.exit(0); } } }
|
00
|
Code Sample 1:
protected StringBuffer readURL(java.net.URL url) throws IOException { StringBuffer result = new StringBuffer(4096); InputStreamReader reader = new InputStreamReader(url.openStream()); for (; ; ) { char portion[] = new char[4096]; int numRead = reader.read(portion, 0, portion.length); if (numRead < 0) break; result.append(portion, 0, numRead); } dout("Read " + result.length() + " bytes."); return result; }
Code Sample 2:
public static String generateGuid(boolean secure) { MessageDigest md5 = null; String valueBeforeMD5 = null; String valueAfterMD5 = 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 = 0L; 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 < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); }
|
00
|
Code Sample 1:
public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { BufferedReader reader; if (baseUrl == null) setBaseUrlFromUrl(url); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); } catch (IOException e) { throw new FileNotFoundException(e.getMessage()); } fromUrl = true; return load(reader); }
Code Sample 2:
public static boolean downloadFile(String url, String destination) throws Exception { BufferedInputStream bi = null; BufferedOutputStream bo = null; File destfile; java.net.URL fileurl; fileurl = new java.net.URL(url); bi = new BufferedInputStream(fileurl.openStream()); destfile = new File(destination); if (!destfile.createNewFile()) { destfile.delete(); destfile.createNewFile(); } bo = new BufferedOutputStream(new FileOutputStream(destfile)); int readedbyte; while ((readedbyte = bi.read()) != -1) { bo.write(readedbyte); } bi.close(); bo.close(); return true; }
|
11
|
Code Sample 1:
public static void exportGestureSet(List<GestureSet> sets, File file) { try { FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(exportGestureSetsAsStream(sets), outputStream); outputStream.close(); } catch (FileNotFoundException e) { LOGGER.log(Level.SEVERE, "Could not export Gesture Sets. Export File not found.", e); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Could not export Gesture Sets.", e); } }
Code Sample 2:
public void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
11
|
Code Sample 1:
@Before public void setUp() throws IOException { testSbk = File.createTempFile("songbook", "sbk"); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("test.sbk"), new FileOutputStream(testSbk)); test1Sbk = File.createTempFile("songbook", "sbk"); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("test1.sbk"), new FileOutputStream(test1Sbk)); }
Code Sample 2:
public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_name); System.out.print("Overwrite existing file " + to_name + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("FileCopy: existing file was not overwritten."); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
11
|
Code Sample 1:
public static byte[] readUrl(URL url) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream is = url.openStream(); try { IOUtils.copy(is, os); return os.toByteArray(); } finally { is.close(); } }
Code Sample 2:
private File unzipArchive(File zipArchive, File outDir, String nameInZipArchive) throws IOException { File mainFile = null; ZipEntry entry = null; ZipInputStream zis = new ZipInputStream(new FileInputStream((zipArchive))); FileOutputStream fos = null; byte buffer[] = new byte[4096]; int bytesRead; while ((entry = zis.getNextEntry()) != null) { File outFile = new File(outDir, entry.getName()); if (entry.getName().equals(nameInZipArchive)) mainFile = outFile; fos = new FileOutputStream(outFile); while ((bytesRead = zis.read(buffer)) != -1) fos.write(buffer, 0, bytesRead); fos.close(); } zis.close(); return mainFile; }
|
11
|
Code Sample 1:
public boolean moveFileSafely(final File in, final File out) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; FileChannel inChannel = null; FileChannel outChannel = null; final File tempOut = File.createTempFile("move", ".tmp"); try { fis = new FileInputStream(in); fos = new FileOutputStream(tempOut); inChannel = fis.getChannel(); outChannel = fos.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { try { if (inChannel != null) inChannel.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", inChannel); } try { if (outChannel != null) outChannel.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", outChannel); } try { if (fis != null) fis.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fis); } try { if (fos != null) fos.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fos); } } out.delete(); if (!out.exists()) { tempOut.renameTo(out); return in.delete(); } return false; }
Code Sample 2:
public static void decompressGZIP(File gzip, File to, long skip) throws IOException { GZIPInputStream gis = null; BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(to)); FileInputStream fis = new FileInputStream(gzip); fis.skip(skip); gis = new GZIPInputStream(fis); final byte[] buffer = new byte[IO_BUFFER]; int read = -1; while ((read = gis.read(buffer)) != -1) { bos.write(buffer, 0, read); } } finally { try { gis.close(); } catch (Exception nope) { } try { bos.flush(); } catch (Exception nope) { } try { bos.close(); } catch (Exception nope) { } } }
|
00
|
Code Sample 1:
private static void sentRequest() { try { URLConnection urlConn; URL url = new URL(gatewayURL); urlConn = url.openConnection(); urlConn.setRequestProperty("Content-Type", "text/xml"); urlConn.setDoOutput(true); OutputStream ostream = urlConn.getOutputStream(); PrintWriter out = new PrintWriter(ostream); out.print(request); out.close(); ostream.close(); InputStream inStream = urlConn.getInputStream(); File myFile = new File(styleSheetLocation); if (type.equals("A") && myFile.exists()) { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new StreamSource(styleSheetLocation)); transformer.transform(new StreamSource(inStream), new StreamResult(System.out)); } else { BufferedReader in = new BufferedReader(new InputStreamReader(inStream)); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public static String getURLContent(String href) throws BuildException { URL url = null; String content; try { URL context = new URL("file:" + System.getProperty("user.dir") + "/"); url = new URL(context, href); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); StringBuffer stringBuffer = new StringBuffer(); char[] buffer = new char[1024]; int len; while ((len = isr.read(buffer, 0, 1024)) > 0) stringBuffer.append(buffer, 0, len); content = stringBuffer.toString(); isr.close(); } catch (Exception ex) { throw new BuildException("Cannot get content of URL " + href + ": " + ex); } return content; }
|
00
|
Code Sample 1:
@Override public long insertStatement(String sql) { Statement statement = null; try { statement = getConnection().createStatement(); long result = statement.executeUpdate(sql.toString()); if (result == 0) log.warn(sql + " result row count is 0"); getConnection().commit(); return getInsertId(statement); } catch (SQLException e) { try { getConnection().rollback(); } catch (SQLException e1) { log.error(e1.getMessage(), e1); } log.error(e.getMessage(), e); throw new RuntimeException(); } finally { try { statement.close(); getConnection().close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } }
Code Sample 2:
public static byte[] hashFile(File file) { long size = file.length(); long jump = (long) (size / (float) CHUNK_SIZE); MessageDigest digest; FileInputStream stream; try { stream = new FileInputStream(file); digest = MessageDigest.getInstance("SHA-256"); if (size < CHUNK_SIZE * 4) { readAndUpdate(size, stream, digest); } else { if (stream.skip(jump) != jump) return null; readAndUpdate(CHUNK_SIZE, stream, digest); if (stream.skip(jump - CHUNK_SIZE) != jump - CHUNK_SIZE) return null; readAndUpdate(CHUNK_SIZE, stream, digest); if (stream.skip(jump - CHUNK_SIZE) != jump - CHUNK_SIZE) return null; readAndUpdate(CHUNK_SIZE, stream, digest); digest.update(Long.toString(size).getBytes()); } return digest.digest(); } catch (FileNotFoundException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } catch (IOException e) { return null; } }
|
00
|
Code Sample 1:
private boolean authenticateWithServer(String user, String password) { Object o; String response; byte[] dataKey; try { o = objectIn.readObject(); if (o instanceof String) { response = (String) o; Debug.netMsg("Connected to JFritz Server: " + response); if (!response.equals("JFRITZ SERVER 1.1")) { Debug.netMsg("Unkown Server version, newer JFritz protocoll version?"); Debug.netMsg("Canceling login attempt!"); } objectOut.writeObject(user); objectOut.flush(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); DESKeySpec desKeySpec = new DESKeySpec(md.digest()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); desCipher.init(Cipher.DECRYPT_MODE, secretKey); SealedObject sealedObject = (SealedObject) objectIn.readObject(); o = sealedObject.getObject(desCipher); if (o instanceof byte[]) { dataKey = (byte[]) o; desKeySpec = new DESKeySpec(dataKey); secretKey = keyFactory.generateSecret(desKeySpec); inCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); outCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); inCipher.init(Cipher.DECRYPT_MODE, secretKey); outCipher.init(Cipher.ENCRYPT_MODE, secretKey); SealedObject sealed_ok = new SealedObject("OK", outCipher); objectOut.writeObject(sealed_ok); SealedObject sealed_response = (SealedObject) objectIn.readObject(); o = sealed_response.getObject(inCipher); if (o instanceof String) { if (o.equals("OK")) { return true; } else { Debug.netMsg("Server sent wrong string as response to authentication challenge!"); } } else { Debug.netMsg("Server sent wrong object as response to authentication challenge!"); } } else { Debug.netMsg("Server sent wrong type for data key!"); } } } catch (ClassNotFoundException e) { Debug.error("Server authentication response invalid!"); Debug.error(e.toString()); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { Debug.netMsg("MD5 Algorithm not present in this JVM!"); Debug.error(e.toString()); e.printStackTrace(); } catch (InvalidKeySpecException e) { Debug.netMsg("Error generating cipher, problems with key spec?"); Debug.error(e.toString()); e.printStackTrace(); } catch (InvalidKeyException e) { Debug.netMsg("Error genertating cipher, problems with key?"); Debug.error(e.toString()); e.printStackTrace(); } catch (NoSuchPaddingException e) { Debug.netMsg("Error generating cipher, problems with padding?"); Debug.error(e.toString()); e.printStackTrace(); } catch (EOFException e) { Debug.error("Server closed Stream unexpectedly!"); Debug.error(e.toString()); e.printStackTrace(); } catch (SocketTimeoutException e) { Debug.error("Read timeout while authenticating with server!"); Debug.error(e.toString()); e.printStackTrace(); } catch (IOException e) { Debug.error("Error reading response during authentication!"); Debug.error(e.toString()); e.printStackTrace(); } catch (IllegalBlockSizeException e) { Debug.error("Illegal block size exception!"); Debug.error(e.toString()); e.printStackTrace(); } catch (BadPaddingException e) { Debug.error("Bad padding exception!"); Debug.error(e.toString()); e.printStackTrace(); } return false; }
Code Sample 2:
public void bubbleSort(int[] arr) { boolean swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < arr.length - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } }
|
11
|
Code Sample 1:
public void generate(String rootDir, RootModel root) throws Exception { IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("stylesheet.css"), new FileOutputStream(new File(rootDir, "stylesheet.css"))); Velocity.init(); VelocityContext context = new VelocityContext(); context.put("model", root); context.put("util", new VelocityUtils()); context.put("msg", messages); processTemplate("index.html", new File(rootDir, "index.html"), context); processTemplate("list.html", new File(rootDir, "list.html"), context); processTemplate("summary.html", new File(rootDir, "summary.html"), context); File imageDir = new File(rootDir, "images"); imageDir.mkdir(); IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("primarykey.gif"), new FileOutputStream(new File(imageDir, "primarykey.gif"))); File tableDir = new File(rootDir, "tables"); tableDir.mkdir(); for (TableModel table : root.getTables()) { context.put("table", table); processTemplate("table.html", new File(tableDir, table.getTableName() + ".html"), context); } }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
|
11
|
Code Sample 1:
private String unJar(String jarPath, String jarEntry) { String path; if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/")); String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/")); try { new File(path + "/" + relPath).mkdirs(); JarFile jar = new JarFile(jarPath); ZipEntry ze = jar.getEntry(jarEntry); File bin = new File(path + "/" + jarEntry); IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin)); } catch (Exception e) { e.printStackTrace(); } return path + "/" + jarEntry; }
Code Sample 2:
private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(inputStream, outputStream); } finally { outputStream.close(); inputStream.close(); } }
|
11
|
Code Sample 1:
public static void copy(final File src, final File dest) throws IOException { OutputStream stream = new FileOutputStream(dest); FileInputStream fis = new FileInputStream(src); byte[] buffer = new byte[16384]; while (fis.available() != 0) { int read = fis.read(buffer); stream.write(buffer, 0, read); } stream.flush(); }
Code Sample 2:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
11
|
Code Sample 1:
public static void copy(File src, File dst) throws IOException { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { try { srcChannel.close(); } finally { dstChannel.close(); } } }
Code Sample 2:
public static boolean copyFile(File sourceFile, File destinationFile) { boolean copySuccessfull = false; FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinationFile).getChannel(); long transferedBytes = destination.transferFrom(source, 0, source.size()); copySuccessfull = transferedBytes == source.size() ? true : false; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (source != null) { try { source.close(); } catch (IOException e) { e.printStackTrace(); } } if (destination != null) { try { destination.close(); } catch (IOException e) { e.printStackTrace(); } } } return copySuccessfull; }
|
00
|
Code Sample 1:
@SuppressWarnings("unchecked") @Override public synchronized void drop(DropTargetDropEvent arg0) { Helper.log().debug("Dropped"); Transferable t = arg0.getTransferable(); try { arg0.acceptDrop(arg0.getDropAction()); List<File> filelist = (List<File>) t.getTransferData(t.getTransferDataFlavors()[0]); for (File file : filelist) { Helper.log().debug(file.getAbsolutePath()); if (file.getName().toLowerCase().contains(".lnk")) { Helper.log().debug(file.getName() + " is a link"); File target = new File(rp.getRoot().getFullPath() + "/" + file.getName()); Helper.log().debug("I have opened the mayor at " + target.getAbsolutePath()); FileOutputStream fo = new FileOutputStream(target); FileInputStream fi = new FileInputStream(file); int i = 0; while (fi.available() > 0) { fo.write(fi.read()); System.out.print("."); i++; } Helper.log().debug(i + " bytes have been written to " + target.getAbsolutePath()); fo.close(); fi.close(); } } rp.redraw(); } catch (Throwable tr) { tr.printStackTrace(); } Helper.log().debug(arg0.getSource().toString()); }
Code Sample 2:
public APIResponse update(Transaction transaction) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/transaction/update").openConnection(); connection.setDoOutput(true); connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setUseCaches(false); connection.setConnectTimeout(TIMEOUT); connection.connect(); marshaller.marshal(transaction, new MappedXMLStreamWriter(new MappedNamespaceConvention(new Configuration()), new OutputStreamWriter(connection.getOutputStream(), "utf-8"))); connection.getOutputStream().flush(); connection.getOutputStream().close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { JSONObject obj = new JSONObject(new String(new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")).readLine())); response.setDone(true); response.setMessage(unmarshaller.unmarshal(new MappedXMLStreamReader(obj, new MappedNamespaceConvention(new Configuration())))); connection.getInputStream().close(); } else { response.setDone(false); response.setMessage("Update Transaction Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; }
|
11
|
Code Sample 1:
@Test public void testCopy_readerToOutputStream() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, false, true); IOUtils.copy(reader, out); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); }
Code Sample 2:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
00
|
Code Sample 1:
@Override protected IProject createProject(String projectName, IProgressMonitor monitor) throws CoreException { monitor.beginTask(CheatSheetsPlugin.INSTANCE.getString("_UI_CreateJavaProject_message", new String[] { projectName }), 5); IProject project = super.createProject(projectName, new SubProgressMonitor(monitor, 1)); if (project != null) { IProjectDescription description = project.getDescription(); if (!description.hasNature(JavaCore.NATURE_ID)) { IJavaProject javaProject = JavaCore.create(project); if (javaProject != null) { String[] natures = description.getNatureIds(); String[] javaNatures = new String[natures.length + 1]; System.arraycopy(natures, 0, javaNatures, 0, natures.length); javaNatures[natures.length] = JavaCore.NATURE_ID; description.setNatureIds(javaNatures); project.setDescription(description, new SubProgressMonitor(monitor, 1)); IFolder sourceFolder = project.getFolder(SOURCE_FOLDER); if (!sourceFolder.exists()) { sourceFolder.create(true, true, new SubProgressMonitor(monitor, 1)); } javaProject.setOutputLocation(project.getFolder(OUTPUT_FOLDER).getFullPath(), new SubProgressMonitor(monitor, 1)); IClasspathEntry[] entries = new IClasspathEntry[] { JavaCore.newSourceEntry(sourceFolder.getFullPath()), JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")) }; javaProject.setRawClasspath(entries, new SubProgressMonitor(monitor, 1)); } } } monitor.done(); return project; }
Code Sample 2:
public static void forEachLine(final URL url, final LineListener lit, final String encoding) { try { ReaderUtils.forEachLine(url.openStream(), lit); } catch (final IOException ioe) { lit.exception(ioe); } }
|
00
|
Code Sample 1:
protected void extractArchive(File archive) { ZipInputStream zis = null; FileOutputStream fos; ZipEntry entry; File curEntry; int n; try { zis = new ZipInputStream(new FileInputStream(archive)); while ((entry = zis.getNextEntry()) != null) { curEntry = new File(workingDir, entry.getName()); if (entry.isDirectory()) { System.out.println("skip directory: " + entry.getName()); continue; } System.out.print("zip-entry (file): " + entry.getName()); System.out.println(" ==> real path: " + curEntry.getAbsolutePath()); if (!curEntry.getParentFile().exists()) curEntry.getParentFile().mkdirs(); fos = new FileOutputStream(curEntry); while ((n = zis.read(buf, 0, buf.length)) > -1) fos.write(buf, 0, n); fos.close(); zis.closeEntry(); } } catch (Throwable t) { t.printStackTrace(); } finally { try { if (zis != null) zis.close(); } catch (Throwable t) { } } }
Code Sample 2:
public static void reset() throws Exception { Session session = DataStaticService.getHibernateSessionFactory().openSession(); try { Connection connection = session.connection(); try { Statement statement = connection.createStatement(); try { statement.executeUpdate("delete from Tag"); connection.commit(); } finally { statement.close(); } } catch (HibernateException e) { connection.rollback(); throw new Exception(e); } catch (SQLException e) { connection.rollback(); throw new Exception(e); } } catch (SQLException e) { throw new Exception(e); } finally { session.close(); } }
|
00
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
protected static String readUrl(URL url) throws IOException { BufferedReader in = null; StringBuffer buf = new StringBuffer(); try { in = new BufferedReader(new InputStreamReader(url.openStream())); final char[] charBuf = new char[1024]; int len = 0; while ((len = in.read(charBuf)) != -1) buf.append(charBuf, 0, len); } finally { if (in != null) in.close(); } return buf.toString(); }
|
00
|
Code Sample 1:
public boolean setRecipeToTimetable(int recipeId, Timestamp time, int meal) { System.out.println("setRecipeToTimetable"); PreparedStatement statement = null; StringBuffer query = new StringBuffer("insert into timetable (recipe_id, time, meal) values (?,?,?)"); try { conn = getConnection(); statement = conn.prepareStatement(query.toString()); statement.setInt(1, recipeId); statement.setTimestamp(2, time); statement.setInt(3, meal); statement.executeUpdate(); conn.commit(); } catch (Exception e) { try { conn.rollback(); } catch (Exception ex) { } MainFrame.appendStatusText("Error when trying to execute sql: " + e.getMessage()); } finally { try { if (statement != null) statement.close(); statement = null; } catch (Exception ex) { MainFrame.appendStatusText("Can't close database connection."); } } return true; }
Code Sample 2:
public void actionPerformed(ActionEvent e) { String line, days; String oldType, newType; String dept = ""; buttonPressed = true; char first; int caretIndex; int tempIndex; int oldDisplayNum = displayNum; for (int i = 0; i < 10; i++) { if (e.getSource() == imageButtons[i]) { if (rePrintAnswer) printAnswer(); print.setVisible(true); selectTerm.setVisible(true); displayNum = i; textArea2.setCaretPosition(textArea2.getText().length() - 1); caretIndex = textArea2.getText().indexOf("#" + (i + 1)); if (caretIndex != -1) textArea2.setCaretPosition(caretIndex); repaint(); } } if (e.getSource() == print) { if (textArea2.getText().charAt(0) != '#') printAnswer(); String data = textArea2.getText(); int start = data.indexOf("#" + (displayNum + 1)); start = data.indexOf("\n", start); start++; int end = data.indexOf("\n---------", start); data = data.substring(start, end); String tr = ""; if (term.getSelectedItem() == "Spring") tr = "SP"; else if (term.getSelectedItem() == "Summer") tr = "SU"; else tr = "FL"; String s = getCodeBase().toString() + "schedule.cgi?term=" + tr + "&data=" + URLEncoder.encode(data); try { AppletContext a = getAppletContext(); URL u = new URL(s); a.showDocument(u, "_blank"); } catch (MalformedURLException rea) { } } if (e.getSource() == webSite) { String tr; if (term.getSelectedItem() == "Spring") tr = "SP"; else if (term.getSelectedItem() == "Summer") tr = "SU"; else tr = "FL"; String num = courseNum.getText().toUpperCase(); String s = "http://sis450.berkeley.edu:4200/OSOC/osoc?p_term=" + tr + "&p_deptname=" + URLEncoder.encode(lst.getSelectedItem().toString()) + "&p_course=" + num; try { AppletContext a = getAppletContext(); URL u = new URL(s); a.showDocument(u, "_blank"); } catch (MalformedURLException rea) { } } if (e.getSource() == loadButton) { printSign("Loading..."); String fileName = idField.getText(); fileName = fileName.replace(' ', '_'); String text = readURL(fileName); if (!publicSign.equals("Error loading.")) { textArea1.setText(text); fileName += ".2"; text = readURL(fileName); absorb(text); printAnswer(); for (int i = 0; i < 10; i++) { if (answer[i].gap != -1 && answer[i].gap != 9999 && answer[i].gap != 10000) { imageButtons[i].setVisible(true); } else imageButtons[i].setVisible(false); } if (!imageButtons[0].isVisible()) { print.setVisible(false); selectTerm.setVisible(false); } else { print.setVisible(true); selectTerm.setVisible(true); } printSign("Load complete."); } displayNum = 0; repaint(); } if (e.getSource() == saveButton) { String fileName = idField.getText(); fileName = fileName.replace(' ', '_'); printSign("Saving..."); writeURL(fileName, 1); printSign("Saving......"); fileName += ".2"; writeURL(fileName, 2); printSign("Save complete."); } if (e.getSource() == instructions) { showInstructions(); } if (e.getSource() == net) { drawWarning = false; String inputLine = ""; String text = ""; String out; String urlIn = ""; textArea2.setText("Retrieving Data..."); try { String tr; if (term.getSelectedItem() == "Spring") tr = "SP"; else if (term.getSelectedItem() == "Summer") tr = "SU"; else tr = "FL"; String num = courseNum.getText().toUpperCase(); dept = lst.getSelectedItem().toString(); { urlIn = "http://sis450.berkeley.edu:4200/OSOC/osoc?p_term=" + tr + "&p_deptname=" + URLEncoder.encode(dept) + "&p_course=" + num; try { URL url = new URL(getCodeBase().toString() + "getURL.cgi"); URLConnection con = url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); DataOutputStream out2 = new DataOutputStream(con.getOutputStream()); String content = "url=" + URLEncoder.encode(urlIn); out2.writeBytes(content); out2.flush(); DataInputStream in = new DataInputStream(con.getInputStream()); String s; while ((s = in.readLine()) != null) { } in.close(); } catch (IOException err) { } } URL yahoo = new URL(this.getCodeBase(), "classData.txt"); URLConnection yc = yahoo.openConnection(); StringBuffer buf = new StringBuffer(""); DataInputStream in = new DataInputStream(new BufferedInputStream(yc.getInputStream())); while ((inputLine = in.readLine()) != null) { buf.append(inputLine); } text = buf.toString(); in.close(); } catch (IOException errr) { } String inText = (parseData(text, false)); if (inText.equals("-1")) inText = parseData(text, true); if (inText.equals("\n")) { textArea2.append("\nNO DATA FOUND \n(" + urlIn + ")"); } else textArea1.append(inText); repaint(); } badInput = false; if (e.getSource() == button1) { if (t != null && t.isAlive()) { t.stop(); epilogue(); return; } displayNum = 0; textArea2.setCaretPosition(0); for (int i = 0; i < 30; i++) for (int j = 0; j < 20; j++) { matrix[i][j] = new entry(); matrix[i][j].time = new Time[4]; for (int k = 0; k < 4; k++) { matrix[i][j].time[k] = new Time(); matrix[i][j].time[k].from = 0; } } val = new entry[30]; for (int i = 0; i < 30; i++) { val[i] = new entry(); val[i].time = new Time[4]; for (int j = 0; j < 4; j++) { val[i].time[j] = new Time(); val[i].time[j].from = 0; } } oldPercentDone = -5; oldAmountDone = -1 * PRINTINTERVAL; percentDone = 0; amountDone = 0; drawWarning = false; errorMessage = ""; String text1 = textArea1.getText(); if (text1.toUpperCase().indexOf("OR:") == -1) containsOR = false; else containsOR = true; text1 = removeOR(text1.toUpperCase()); StringTokenizer st = new StringTokenizer(text1, "\n"); clss = -1; timeEntry = -1; boolean noTimesListed = false; while (st.hasMoreTokens()) { line = st.nextToken().toString(); if (line.equals("")) break; else first = line.charAt(0); if (first == '0') { badInput = true; repaint(); break; } if (first >= '1' && first <= '9') { noTimesListed = false; timeEntry++; if (timeEntry == 30) { rePrintAnswer = true; textArea2.setText("Error: Exceeded 30 time entries per class."); badInput = true; repaint(); return; } nextTime = -1; StringTokenizer andST = new StringTokenizer(line, ","); while (andST.hasMoreTokens()) { String temp; String entry; int index, fromTime, toTime; nextTime++; if (nextTime == 4) { rePrintAnswer = true; textArea2.setText("Error: Exceeded 4 time intervals per entry!"); badInput = true; repaint(); return; } StringTokenizer timeST = new StringTokenizer(andST.nextToken()); temp = timeST.nextToken().toString(); entry = ""; index = 0; if (temp.equals("")) break; while (temp.charAt(index) != '-') { entry += temp.charAt(index); index++; if (index >= temp.length()) { rePrintAnswer = true; textArea2.setText("Error: There should be no space before hyphens."); badInput = true; repaint(); return; } } try { fromTime = Integer.parseInt(entry); } catch (NumberFormatException re) { rePrintAnswer = true; textArea2.setText("Error: There should be no a/p sign after FROM_TIME."); badInput = true; repaint(); return; } index++; entry = ""; if (index >= temp.length()) { badInput = true; repaint(); rePrintAnswer = true; textArea2.setText("Error: am/pm sign missing??"); return; } while (temp.charAt(index) >= '0' && temp.charAt(index) <= '9') { entry += temp.charAt(index); index++; if (index >= temp.length()) { badInput = true; repaint(); rePrintAnswer = true; textArea2.setText("Error: am/pm sign missing??"); return; } } toTime = Integer.parseInt(entry); if (temp.charAt(index) == 'a' || temp.charAt(index) == 'A') { } else { if (isLesse(fromTime, toTime) && !timeEq(toTime, 1200)) { if (String.valueOf(fromTime).length() == 4 || String.valueOf(fromTime).length() == 3) { fromTime += 1200; } else fromTime += 12; } if (!timeEq(toTime, 1200)) { if (String.valueOf(toTime).length() == 4 || String.valueOf(toTime).length() == 3) { toTime += 1200; } else toTime += 12; } } if (String.valueOf(fromTime).length() == 2 || String.valueOf(fromTime).length() == 1) fromTime *= 100; if (String.valueOf(toTime).length() == 2 || String.valueOf(toTime).length() == 1) toTime *= 100; matrix[timeEntry][clss].time[nextTime].from = fromTime; matrix[timeEntry][clss].time[nextTime].to = toTime; if (timeST.hasMoreTokens()) days = timeST.nextToken().toString(); else { rePrintAnswer = true; textArea2.setText("Error: days not specified?"); badInput = true; repaint(); return; } if (days.equals("")) return; if (days.indexOf("M") != -1 || days.indexOf("m") != -1) matrix[timeEntry][clss].time[nextTime].m = 1; if (days.indexOf("TU") != -1 || days.indexOf("Tu") != -1 || days.indexOf("tu") != -1) matrix[timeEntry][clss].time[nextTime].tu = 1; if (days.indexOf("W") != -1 || days.indexOf("w") != -1) matrix[timeEntry][clss].time[nextTime].w = 1; if (days.indexOf("TH") != -1 || days.indexOf("Th") != -1 || days.indexOf("th") != -1) matrix[timeEntry][clss].time[nextTime].th = 1; if (days.indexOf("F") != -1 || days.indexOf("f") != -1) matrix[timeEntry][clss].time[nextTime].f = 1; } } else { if (noTimesListed) clss--; clss++; if (clss == 20) { rePrintAnswer = true; textArea2.setText("Error: No more than 20 class entries!"); badInput = true; repaint(); return; } timeEntry = -1; line = line.trim(); for (int i = 0; i < 30; i++) matrix[i][clss].name = line; noTimesListed = true; } } for (int i = 0; i < 30; i++) { for (int j = 0; j < 4; j++) { val[i].time[j].from = 0; } } for (int i = 0; i < 10; i++) { beat10[i] = 10000; answer[i].gap = 10000; for (int j = 0; j < 30; j++) answer[i].classes[j].name = ""; } time = 0; calcTotal = 0; int k = 0; calculateTotalPercent(0, "\n"); amountToReach = calcTotal; button1.setLabel("...HALT GENERATION..."); printWarn(); if (t != null && t.isAlive()) t.stop(); t = new Thread(this, "Generator"); t.start(); } }
|
00
|
Code Sample 1:
public static String md(String passwd) { MessageDigest md5 = null; String digest = passwd; try { md5 = MessageDigest.getInstance("MD5"); md5.update(passwd.getBytes()); byte[] digestData = md5.digest(); digest = byteArrayToHex(digestData); } catch (NoSuchAlgorithmException e) { LOG.warn("MD5 not supported. Using plain string as password!"); } catch (Exception e) { LOG.warn("Digest creation failed. Using plain string as password!"); } return digest; }
Code Sample 2:
public static Image getPluginImage(Object plugin, String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; }
|
00
|
Code Sample 1:
private void copyValidFile(File file, int cviceni) { try { String filename = String.format("%s%s%02d%s%s", validovane, File.separator, cviceni, File.separator, file.getName()); boolean copy = false; File newFile = new File(filename); if (newFile.exists()) { if (file.lastModified() > newFile.lastModified()) copy = true; else copy = false; } else { newFile.createNewFile(); copy = true; } if (copy) { String EOL = "" + (char) 0x0D + (char) 0x0A; FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(newFile); String line; while ((line = br.readLine()) != null) fw.write(line + EOL); br.close(); fw.close(); newFile.setLastModified(file.lastModified()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public synchronized String encrypt(String plaintext) { if (plaintext == null) plaintext = ""; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } byte raw[] = md.digest(); String hash = ""; try { hash = Base64Encoder.encode(raw); } catch (IOException e1) { System.err.println("Error encoding password using Jboss Base64Encoder"); e1.printStackTrace(); } return hash; }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.