label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public static void main(String[] args) { int[] mas = { 5, 10, 20, -30, 55, -60, 9, -40, -20 }; int next; for (int a = 0; a < mas.length; a++) { for (int i = 0; i < mas.length - 1; i++) { if (mas[i] > mas[i + 1]) { next = mas[i]; mas[i] = mas[i + 1]; mas[i + 1] = next; } } } for (int i = 0; i < mas.length; i++) System.out.print(" " + mas[i]); } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
11
Code Sample 1: protected N save(String sql, Object[] args) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); this.setParameters(pstmt, args); pstmt.executeUpdate(); conn.commit(); conn.setAutoCommit(true); rs = pstmt.getGeneratedKeys(); return (N) rs.getObject(1); } catch (SQLException e) { try { if (conn != null) { conn.rollback(); conn.setAutoCommit(true); } } catch (SQLException ex) { ex.printStackTrace(); } throw new JdbcDaoException(e.getMessage(), e); } finally { JdbcUtils.free(rs, pstmt, conn); } } Code Sample 2: public int create(BusinessObject o) throws DAOException { int insert = 0; int id = 0; Bill bill = (Bill) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_BILL")); pst.setDate(1, new java.sql.Date(bill.getDate().getTime())); pst.setInt(2, bill.getIdAccount()); insert = pst.executeUpdate(); if (insert <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (insert > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select max(id) from bill"); rs.next(); id = rs.getInt(1); connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return id; }
00
Code Sample 1: private static final void cloneFile(File origin, File target) throws IOException { FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(origin).getChannel(); destChannel = new FileOutputStream(target).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) srcChannel.close(); if (destChannel != null) destChannel.close(); } } Code Sample 2: protected long loadFromSource(long afterThisTime) { long startTime = System.currentTimeMillis(); QuoteDataSourceDescriptor quoteDataSourceDescriptor = (QuoteDataSourceDescriptor) dataSourceDescriptor; List<Quote> dataPool = dataPools.get(quoteDataSourceDescriptor.sourceSymbol); Calendar calendar = Calendar.getInstance(); calendar.clear(); SimpleDateFormat sdf = new SimpleDateFormat(quoteDataSourceDescriptor.dateFormat, Locale.US); Date fromDate = new Date(); Date toDate = new Date(); if (afterThisTime == FIRST_TIME_LOAD) { fromDate = quoteDataSourceDescriptor.fromDate; toDate = quoteDataSourceDescriptor.toDate; } else { calendar.setTimeInMillis(afterThisTime); fromDate = calendar.getTime(); } calendar.setTime(fromDate); int a = calendar.get(Calendar.MONTH); int b = calendar.get(Calendar.DAY_OF_MONTH); int c = calendar.get(Calendar.YEAR); calendar.setTime(toDate); int d = calendar.get(Calendar.MONTH); int e = calendar.get(Calendar.DAY_OF_MONTH); int f = calendar.get(Calendar.YEAR); BufferedReader dis; StringBuffer urlStr = new StringBuffer(); urlStr.append("http://table.finance.yahoo.com/table.csv").append("?s="); urlStr.append(quoteDataSourceDescriptor.sourceSymbol); urlStr.append("&a=" + a + "&b=" + b + "&c=" + c + "&d=" + d + "&e=" + e + "&f=" + f); urlStr.append("&g=d&ignore=.csv"); try { URL url = new URL(urlStr.toString()); System.out.println(url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setAllowUserInteraction(true); conn.setRequestMethod("GET"); conn.setInstanceFollowRedirects(true); InputStreamReader isr = new InputStreamReader(conn.getInputStream()); dis = new BufferedReader(isr); String s = dis.readLine(); int iDateTime = 0; int iOpen = 1; int iHigh = 2; int iLow = 3; int iClose = 4; int iVolume = 5; int iAdjClose = 6; count = 0; calendar.clear(); while ((s = dis.readLine()) != null) { String[] items; items = s.split(","); if (items.length < 6) { break; } Date date = null; try { date = sdf.parse(items[iDateTime].trim()); } catch (ParseException ex) { ex.printStackTrace(); continue; } calendar.clear(); calendar.setTime(date); long time = calendar.getTimeInMillis(); if (time <= afterThisTime) { continue; } Quote quote = new Quote(); quote.time = time; quote.open = Float.parseFloat(items[iOpen].trim()); quote.high = Float.parseFloat(items[iHigh].trim()); quote.low = Float.parseFloat(items[iLow].trim()); quote.close = Float.parseFloat(items[iClose].trim()); quote.volume = Float.parseFloat(items[iVolume].trim()) / 100f; quote.amount = -1; quote.close_adj = Float.parseFloat(items[iAdjClose].trim()); if (quote.high * quote.low * quote.close == 0) { quote = null; continue; } dataPool.add(quote); if (count == 0) { firstTime = time; } lastTime = time; setAscending((lastTime >= firstTime) ? true : false); count++; } } catch (Exception ex) { System.out.println("Error in Reading File: " + ex.getMessage()); } long newestTime = (lastTime >= firstTime) ? lastTime : firstTime; return newestTime; }
00
Code Sample 1: private RatingServiceSelectionResponseType contactService(String xmlInputString) throws Exception { OutputStream outputStream = null; RatingServiceSelectionResponseType rType = null; try { URL url = new URL(ENDPOINT_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); outputStream = connection.getOutputStream(); outputStream.write(xmlInputString.getBytes()); outputStream.flush(); outputStream.close(); rType = readURLConnection(connection); connection.disconnect(); } catch (Exception e) { throw e; } finally { if (outputStream != null) { outputStream.close(); outputStream = null; } } return rType; } Code Sample 2: @Override public String resolveItem(String oldJpgFsPath) throws DatabaseException { if (oldJpgFsPath == null || "".equals(oldJpgFsPath)) throw new NullPointerException("oldJpgFsPath"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } PreparedStatement statement = null; String ret = null; try { statement = getConnection().prepareStatement(SELECT_ITEM_STATEMENT); statement.setString(1, oldJpgFsPath); ResultSet rs = statement.executeQuery(); int i = 0; int id = -1; int rowsAffected = 0; while (rs.next()) { id = rs.getInt("id"); ret = rs.getString("imageFile"); i++; } if (id != -1 && new File(ret).exists()) { statement = getConnection().prepareStatement(UPDATE_ITEM_STATEMENT); statement.setInt(1, id); rowsAffected = statement.executeUpdate(); } else { return null; } if (rowsAffected == 1) { getConnection().commit(); LOGGER.debug("DB has been updated."); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback!"); } } catch (SQLException e) { LOGGER.error(e); } finally { closeConnection(); } return ret; }
00
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { if (TDebug.TraceAudioFileReader) { TDebug.out("MpegAudioFileReader.getAudioInputStream(URL): begin"); } long lFileLengthInBytes = AudioSystem.NOT_SPECIFIED; URLConnection conn = url.openConnection(); boolean isShout = false; int toRead = 4; byte[] head = new byte[toRead]; conn.setRequestProperty("Icy-Metadata", "1"); BufferedInputStream bInputStream = new BufferedInputStream(conn.getInputStream()); bInputStream.mark(toRead); int read = bInputStream.read(head, 0, toRead); if ((read > 2) && (((head[0] == 'I') | (head[0] == 'i')) && ((head[1] == 'C') | (head[1] == 'c')) && ((head[2] == 'Y') | (head[2] == 'y')))) isShout = true; bInputStream.reset(); InputStream inputStream = null; if (isShout == true) { IcyInputStream icyStream = new IcyInputStream(bInputStream); icyStream.addTagParseListener(IcyListener.getInstance()); inputStream = icyStream; } else { String metaint = conn.getHeaderField("icy-metaint"); if (metaint != null) { IcyInputStream icyStream = new IcyInputStream(bInputStream, metaint); icyStream.addTagParseListener(IcyListener.getInstance()); inputStream = icyStream; } else { inputStream = bInputStream; } } AudioInputStream audioInputStream = null; try { audioInputStream = getAudioInputStream(inputStream, lFileLengthInBytes); } catch (UnsupportedAudioFileException e) { inputStream.close(); throw e; } catch (IOException e) { inputStream.close(); throw e; } if (TDebug.TraceAudioFileReader) { TDebug.out("MpegAudioFileReader.getAudioInputStream(URL): end"); } return audioInputStream; }
11
Code Sample 1: private File getTempFile(DigitalObject object, String pid) throws Exception { File directory = new File(tmpDir, object.getId()); File target = new File(directory, pid); if (!target.exists()) { target.getParentFile().mkdirs(); target.createNewFile(); } Payload payload = object.getPayload(pid); InputStream in = payload.open(); FileOutputStream out = null; try { out = new FileOutputStream(target); IOUtils.copyLarge(in, out); } catch (Exception ex) { close(out); target.delete(); payload.close(); throw ex; } close(out); payload.close(); return target; } Code Sample 2: @Override protected String getRawPage(String url) throws IOException { HttpClient httpClient = new HttpClient(); String proxyHost = config.getString("proxy.host"), proxyPortString = config.getString("proxy.port"); if (proxyHost != null && proxyPortString != null) { int proxyPort = -1; try { proxyPort = Integer.parseInt(proxyPortString); } catch (NumberFormatException e) { } if (proxyPort != -1) { httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort); } } GetMethod urlGet = new GetMethod(url); urlGet.setRequestHeader("Accept-Encoding", ""); urlGet.setRequestHeader("User-Agent", "Mozilla/5.0"); int retCode; if ((retCode = httpClient.executeMethod(urlGet)) != HttpStatus.SC_OK) { throw new RuntimeException("Unexpected HTTP code: " + retCode); } String encoding = null; Header contentType = urlGet.getResponseHeader("Content-Type"); if (contentType != null) { String contentTypeString = contentType.toString(); int i = contentTypeString.indexOf("charset="); if (i != -1) { encoding = contentTypeString.substring(i + "charset=".length()).trim(); } } boolean gzipped = false; Header contentEncoding = urlGet.getResponseHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { gzipped = true; } byte[] htmlData; try { InputStream in = gzipped ? new GZIPInputStream(urlGet.getResponseBodyAsStream()) : urlGet.getResponseBodyAsStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); htmlData = out.toByteArray(); in.close(); } finally { urlGet.releaseConnection(); } if (encoding == null) { Matcher m = Pattern.compile("(?i)<meta[^>]*charset=(([^\"]+\")|(\"[^\"]+\"))").matcher(new String(htmlData)); if (m.find()) { encoding = m.group(1).trim().replace("\"", ""); } } if (encoding == null) { encoding = "UTF-8"; } return new String(htmlData, encoding); }
00
Code Sample 1: private String encryptPassword(String password) throws NoSuchAlgorithmException { MessageDigest encript = MessageDigest.getInstance("MD5"); encript.update(password.getBytes()); byte[] b = encript.digest(); int size = b.length; StringBuffer h = new StringBuffer(size); for (int i = 0; i < size; i++) { h.append(b[i]); } return h.toString(); } Code Sample 2: public String getResource(String resourceName) throws IOException { InputStream resourceStream = resourceClass.getResourceAsStream(resourceName); ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); IOUtils.copyAndClose(resourceStream, baos); String expected = new String(baos.toByteArray()); return expected; }
11
Code Sample 1: @Override public void createCopy(File sourceFile, File destinnationFile) throws IOException { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinnationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\testTDESENC.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESDEC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.decrypt(reader, writer, key, mode); }
11
Code Sample 1: private static void extract(ZipFile zipFile) throws Exception { FileUtils.deleteQuietly(WEBKIT_DIR); WEBKIT_DIR.mkdirs(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { new File(WEBKIT_DIR, entry.getName()).mkdirs(); continue; } InputStream inputStream = zipFile.getInputStream(entry); File outputFile = new File(WEBKIT_DIR, entry.getName()); FileOutputStream outputStream = new FileOutputStream(outputFile); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } Code Sample 2: public boolean clonarFichero(String rutaFicheroOrigen, String rutaFicheroDestino) { System.out.println(""); System.out.println("*********** DENTRO DE 'clonarFichero' ***********"); boolean estado = false; try { FileInputStream entrada = new FileInputStream(rutaFicheroOrigen); FileOutputStream salida = new FileOutputStream(rutaFicheroDestino); FileChannel canalOrigen = entrada.getChannel(); FileChannel canalDestino = salida.getChannel(); canalOrigen.transferTo(0, canalOrigen.size(), canalDestino); entrada.close(); salida.close(); estado = true; } catch (IOException e) { System.out.println("No se encontro el archivo"); e.printStackTrace(); estado = false; } return estado; }
11
Code Sample 1: @Test public void testCopyOverSize() throws IOException { final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(TEST_DATA.length); final int cpySize = ExtraIOUtils.copy(in, out, TEST_DATA.length + Long.SIZE); assertEquals("Mismatched copy size", TEST_DATA.length, cpySize); final byte[] outArray = out.toByteArray(); assertArrayEquals("Mismatched data", TEST_DATA, outArray); } Code Sample 2: public void save() { final JFileChooser fc = new JFileChooser(); fc.setFileFilter(new FileFilter() { public String getDescription() { return "PDF File"; } public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".pdf"); } }); if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) { return; } File targetFile = fc.getSelectedFile(); if (!targetFile.getName().toLowerCase().endsWith(".pdf")) { targetFile = new File(targetFile.getParentFile(), targetFile.getName() + ".pdf"); } if (targetFile.exists()) { if (JOptionPane.showConfirmDialog(this, "Do you want to overwrite the file?") != JOptionPane.YES_OPTION) { return; } } try { final InputStream is = new FileInputStream(filename); try { final OutputStream os = new FileOutputStream(targetFile); try { final byte[] buffer = new byte[32768]; for (int read; (read = is.read(buffer)) != -1; ) { os.write(buffer, 0, read); } } finally { os.close(); } } finally { is.close(); } } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: private long getLastModification() { try { if (connection == null) connection = url.openConnection(); return connection.getLastModified(); } catch (IOException e) { LOG.warn("URL could not be opened: " + e.getMessage(), e); return 0; } } Code Sample 2: public Epg unmarshallFromUrl(URL url) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String tmp = null; StringBuilder buffer = new StringBuilder(); while ((tmp = reader.readLine()) != null) { buffer.append(tmp); } return unmarshall(buffer.toString().getBytes()); }
11
Code Sample 1: private static void copy(File source, File target, byte[] buffer) throws FileNotFoundException, IOException { InputStream in = new FileInputStream(source); File parent = target.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } if (target.isDirectory()) { target = new File(target, source.getName()); } OutputStream out = new FileOutputStream(target); int read; try { while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } catch (IOException e) { throw e; } finally { in.close(); out.close(); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public Node external_open_url(Node startAt) throws Exception { if (inUse) { throw new InterpreterException(StdErrors.extend(StdErrors.Already_used, "File already open")); } inUse = true; startAt.isGoodArgsLength(false, 2); ExtURL url = new ExtURL(startAt.getSubNode(1, Node.TYPE_STRING).getString()); String protocol = url.getProtocol(); String mode = null; Node props = null; Node datas = null; byte[] buffer = null; String old_c = null; String old_r = null; int max_i = startAt.size() - 1; if (startAt.elementAt(max_i).getSymbolicValue_undestructive().isVList()) { props = startAt.getSubNode(max_i--, Node.TYPE_LIST); } int i_ = 2; if (i_ <= max_i) { mode = startAt.getSubNode(i_++, Node.TYPE_STRING).getString().toUpperCase().trim(); if (protocol.equalsIgnoreCase("http") || protocol.equalsIgnoreCase("https")) { if (!(mode.equals("GET") || mode.equals("POST") || mode.equals("PUT"))) { throw new InterpreterException(128010, "Unsupported request methode"); } } else if (protocol.equalsIgnoreCase("ftp") || protocol.equalsIgnoreCase("file")) { if (!(mode.equalsIgnoreCase("r") || mode.equalsIgnoreCase("w"))) { throw new InterpreterException(128015, "Unsupported access methode"); } } else if (protocol.equalsIgnoreCase("jar") || protocol.equalsIgnoreCase("stdin")) { if (!(mode.equalsIgnoreCase("r"))) { throw new InterpreterException(128015, "Unsupported access methode"); } } else if (protocol.equalsIgnoreCase("tcp") || protocol.equalsIgnoreCase("ssl+tcp")) { if (!(mode.equalsIgnoreCase("rw"))) { throw new InterpreterException(128015, "Unsupported access methode"); } } else if (protocol.equalsIgnoreCase("stdout") || protocol.equalsIgnoreCase("stderr")) { if (!(mode.equalsIgnoreCase("w"))) { throw new InterpreterException(128015, "Unsupported access methode"); } } else { throw new InterpreterException(128011, "Unsupported protocol"); } } if (i_ <= max_i) { if (!protocol.equalsIgnoreCase("http") && !protocol.equalsIgnoreCase("https")) { throw new InterpreterException(128016, "Unsupported request datas"); } datas = startAt.getSubNode(i_++, Node.TYPE_STRING | Node.TYPE_OBJECT); if (datas.isVObject()) { Object obj = datas.getVObjectExternalInstance(); if (External_Buffer.class.isInstance(obj)) { Buffer bbuffer = ((External_Buffer) obj).getBuffer(); buffer = bbuffer.read_bytes(); } else { throw new InterpreterException(StdErrors.extend(StdErrors.Invalid_parameter, "Object (" + obj.getClass().getName() + ") required " + External_Buffer.class.getName())); } } else { buffer = datas.getString().getBytes(); } } if (datas != null && mode != null && mode.equals("GET")) { throw new InterpreterException(128012, "GET request with data body"); } if (props != null && (!protocol.equalsIgnoreCase("http") && !protocol.equalsIgnoreCase("https"))) { throw new InterpreterException(128013, "Cannot handle header properties in request"); } try { if (protocol.equalsIgnoreCase("file") && mode != null && mode.equalsIgnoreCase("w")) { File f = new File(url.toURI()); outputStream = new FileOutputStream(f); outputBuffer = new BufferedOutputStream(outputStream); output = new DataOutputStream(outputBuffer); } else if (protocol.equalsIgnoreCase("tcp")) { tcpHost = url.getHost(); tcpPort = url.getPort(); if (tcpPort < 0 || tcpPort > 65535) { throw new InterpreterException(StdErrors.extend(StdErrors.Out_of_range, "" + tcpPort)); } socket = new Socket(tcpHost, tcpPort); if (readTimeOut > 0) { socket.setSoTimeout(readTimeOut); } inputStream = socket.getInputStream(); inputBuffer = new BufferedInputStream(inputStream); input = new DataInputStream(inputBuffer); outputStream = socket.getOutputStream(); outputBuffer = new BufferedOutputStream(outputStream); output = new DataOutputStream(outputBuffer); } else if (protocol.equalsIgnoreCase("ssl+tcp")) { tcpHost = url.getHost(); tcpPort = url.getPort(); if (tcpPort < 0 || tcpPort > 65535) { throw new InterpreterException(StdErrors.extend(StdErrors.Out_of_range, "" + tcpPort)); } SocketFactory socketFactory = SSLSocketFactory.getDefault(); socket = socketFactory.createSocket(tcpHost, tcpPort); if (readTimeOut > 0) { socket.setSoTimeout(readTimeOut); } inputStream = socket.getInputStream(); inputBuffer = new BufferedInputStream(inputStream); input = new DataInputStream(inputBuffer); outputStream = socket.getOutputStream(); outputBuffer = new BufferedOutputStream(outputStream); output = new DataOutputStream(outputBuffer); } else if (protocol.equalsIgnoreCase("stdout")) { setBufOut(System.out); } else if (protocol.equalsIgnoreCase("stderr")) { setBufOut(System.err); } else if (protocol.equalsIgnoreCase("stdin")) { setBufIn(System.in); } else { urlConnection = url.openConnection(); if (connectTimeOut > 0) { urlConnection.setConnectTimeout(connectTimeOut); } if (readTimeOut > 0) { urlConnection.setReadTimeout(readTimeOut); } urlConnection.setUseCaches(false); urlConnection.setDoInput(true); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpCon = (HttpURLConnection) urlConnection; if (props != null) { for (int i = 0; i < props.size(); i++) { Node pnode = props.getSubNode(i, Node.TYPE_DICO); String header_s = Node.getPairKey(pnode); String value_s = Node.node2VString(Node.getPairValue(pnode)).getString(); Interpreter.Log(" HTTP-Header: " + header_s + " : " + value_s); httpCon.setRequestProperty(header_s, value_s); } } if (mode != null && (mode.equals("POST") || mode.equals("PUT"))) { if (mode.equals("PUT")) { Interpreter.Log(" HTTP PUT: " + url.toString()); } else { Interpreter.Log(" HTTP POST: " + url.toString()); } urlConnection.setDoOutput(true); httpCon.setRequestMethod(mode); outputStream = urlConnection.getOutputStream(); outputBuffer = new BufferedOutputStream(outputStream); output = new DataOutputStream(outputBuffer); output.write(buffer); output.flush(); } inputStream = urlConnection.getInputStream(); inputBuffer = new BufferedInputStream(inputStream); input = new DataInputStream(inputBuffer); } else { if (mode == null || (mode != null && mode.equalsIgnoreCase("r"))) { Interpreter.Log(" " + protocol + " read : " + url.toString()); inputStream = urlConnection.getInputStream(); inputBuffer = new BufferedInputStream(inputStream); input = new DataInputStream(inputBuffer); } else { Interpreter.Log(" " + protocol + " write : " + url.toString()); outputStream = urlConnection.getOutputStream(); outputBuffer = new BufferedOutputStream(outputStream); output = new DataOutputStream(outputBuffer); } } } } catch (Exception e) { throw e; } bytePos = 0; putHook(); return null; } Code Sample 2: void IconmenuItem6_actionPerformed(ActionEvent e) { JFileChooser jFileChooser1 = new JFileChooser(); String separator = ""; if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) { setDefaultPath(jFileChooser1.getSelectedFile().getPath()); separator = jFileChooser1.getSelectedFile().separator; File dirImg = new File("." + separator + "images"); if (!dirImg.exists()) { dirImg.mkdir(); } int index = getDefaultPath().lastIndexOf(separator); String imgName = getDefaultPath().substring(index); String newPath = dirImg + imgName; try { File inputFile = new File(getDefaultPath()); File outputFile = new File(newPath); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), getFatherPanel().MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "", JOptionPane.ERROR_MESSAGE); } setDefaultPath(newPath); createDefaultImage(); } }
11
Code Sample 1: public static void s_copy(FileInputStream fis, FileOutputStream fos) throws Exception { FileChannel in = fis.getChannel(); FileChannel out = fos.getChannel(); in.transferTo(0, in.size(), out); if (in != null) in.close(); if (out != null) out.close(); } Code Sample 2: public static boolean copyFile(String source, String destination, boolean replace) { File sourceFile = new File(source); File destinationFile = new File(destination); if (sourceFile.isDirectory() || destinationFile.isDirectory()) return false; if (destinationFile.isFile() && !replace) return false; if (!sourceFile.isFile()) return false; if (replace) destinationFile.delete(); try { File dir = destinationFile.getParentFile(); while (dir != null && !dir.exists()) { dir.mkdir(); } DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationFile), 10240)); DataInputStream inStream = new DataInputStream(new BufferedInputStream(new FileInputStream(sourceFile), 10240)); try { while (inStream.available() > 0) { outStream.write(inStream.readUnsignedByte()); } } catch (EOFException eof) { } inStream.close(); outStream.close(); } catch (IOException ex) { throw new FailedException("Failed to copy file " + sourceFile.getAbsolutePath() + " to " + destinationFile.getAbsolutePath(), ex).setFile(destinationFile.getAbsolutePath()); } return true; }
11
Code Sample 1: public static void unzipFile(File zipFile, File destFile, boolean removeSrcFile) throws Exception { ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry zipentry = zipinputstream.getNextEntry(); int BUFFER_SIZE = 4096; while (zipentry != null) { String entryName = zipentry.getName(); log.info("<<<<<< ZipUtility.unzipFile - Extracting: " + zipentry.getName()); File newFile = null; if (destFile.isDirectory()) newFile = new File(destFile, entryName); else newFile = destFile; if (zipentry.isDirectory() || entryName.endsWith(File.separator + ".")) { newFile.mkdirs(); } else { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); byte[] bufferArray = buffer.array(); FileUtilities.createDirectory(newFile.getParentFile()); FileChannel destinationChannel = new FileOutputStream(newFile).getChannel(); while (true) { buffer.clear(); int lim = zipinputstream.read(bufferArray); if (lim == -1) break; buffer.flip(); buffer.limit(lim); destinationChannel.write(buffer); } destinationChannel.close(); zipinputstream.closeEntry(); } zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); if (removeSrcFile) { if (zipFile.exists()) zipFile.delete(); } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public static InputStream getRemoteIS(URL url, String post) throws ArcImsException { InputStream lector = null; try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-length", "" + post.length()); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(post); wr.flush(); logger.info("downloading '" + url.toString()); lector = conn.getInputStream(); } catch (ConnectException e) { logger.error("Timed out error", e); throw new ArcImsException("arcims_server_timeout"); } catch (ProtocolException e) { logger.error(e.getMessage(), e); throw new ArcImsException("arcims_server_error"); } catch (IOException e) { logger.error(e.getMessage(), e); throw new ArcImsException("arcims_server_error"); } return lector; } Code Sample 2: public static String getKeyWithRightLength(final String key, int keyLength) { if (keyLength > 0) { if (key.length() == keyLength) { return key; } else { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { return ""; } md.update(key.getBytes()); byte[] hash = md.digest(); if (keyLength > 20) { byte nhash[] = new byte[keyLength]; for (int i = 0; i < keyLength; i++) { nhash[i] = hash[i % 20]; } hash = nhash; } return new String(hash).substring(0, keyLength); } } else { return key; } }
11
Code Sample 1: public void writeTo(File f) throws IOException { if (state != STATE_OK) throw new IllegalStateException("Upload failed"); if (tempLocation == null) throw new IllegalStateException("File already saved"); if (f.isDirectory()) f = new File(f, filename); FileInputStream fis = new FileInputStream(tempLocation); FileOutputStream fos = new FileOutputStream(f); byte[] buf = new byte[BUFFER_SIZE]; try { int i = 0; while ((i = fis.read(buf)) != -1) fos.write(buf, 0, i); } finally { deleteTemporaryFile(); fis.close(); fos.close(); } } Code Sample 2: public static String CreateZip(String[] filesToZip, String zipFileName) { byte[] buffer = new byte[18024]; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); out.setLevel(Deflater.BEST_COMPRESSION); for (int i = 0; i < filesToZip.length; i++) { FileInputStream in = new FileInputStream(filesToZip[i]); String fileName = null; for (int X = filesToZip[i].length() - 1; X >= 0; X--) { if (filesToZip[i].charAt(X) == '\\' || filesToZip[i].charAt(X) == '/') { fileName = filesToZip[i].substring(X + 1); break; } else if (X == 0) fileName = filesToZip[i]; } out.putNextEntry(new ZipEntry(fileName)); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); } out.close(); } catch (IllegalArgumentException e) { return "Failed to create zip: " + e.toString(); } catch (FileNotFoundException e) { return "Failed to create zip: " + e.toString(); } catch (IOException e) { return "Failed to create zip: " + e.toString(); } return "Success"; }
00
Code Sample 1: public static String getBiopaxId(Reaction reaction) { String id = null; if (reaction.getId() > Reaction.NO_ID_ASSIGNED) { id = reaction.getId().toString(); } else { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(reaction.getTextualRepresentation().getBytes()); byte[] digestBytes = md.digest(); StringBuilder digesterSb = new StringBuilder(32); for (int i = 0; i < digestBytes.length; i++) { int intValue = digestBytes[i] & 0xFF; if (intValue < 0x10) digesterSb.append('0'); digesterSb.append(Integer.toHexString(intValue)); } id = digesterSb.toString(); } catch (NoSuchAlgorithmException e) { } } return id; } Code Sample 2: public Object read(InputStream inputStream, Map metadata) throws IOException, ClassNotFoundException { if (log.isTraceEnabled()) log.trace("Read input stream with metadata=" + metadata); Integer resCode = (Integer) metadata.get(HTTPMetadataConstants.RESPONSE_CODE); String resMessage = (String) metadata.get(HTTPMetadataConstants.RESPONSE_CODE_MESSAGE); if (resCode != null && validResponseCodes.contains(resCode) == false) throw new RuntimeException("Invalid HTTP server response [" + resCode + "] - " + resMessage); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); String soapMessage = new String(baos.toByteArray(), charsetEncoding); if (isTraceEnabled) { String prettySoapMessage = DOMWriter.printNode(DOMUtils.parse(soapMessage), true); log.trace("Incoming Response SOAPMessage\n" + prettySoapMessage); } return soapMessage; }
11
Code Sample 1: public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("LOAD")) { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new JPEGFilter()); chooser.setMultiSelectionEnabled(false); if (chooser.showOpenDialog(getTopLevelAncestor()) == JFileChooser.APPROVE_OPTION) { try { File file = chooser.getSelectedFile(); BufferedInputStream is = new BufferedInputStream(new FileInputStream(file)); ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length()); int read = is.read(); while (read != -1) { bos.write(read); read = is.read(); } is.close(); _changed = true; setImage(bos.toByteArray()); } catch (Exception e1) { _log.error("actionPerformed(ActionEvent)", e1); } } } else if (e.getActionCommand().equals("SAVE")) { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new JPEGFilter()); chooser.setMultiSelectionEnabled(false); if (_data != null && chooser.showSaveDialog(getTopLevelAncestor()) == JFileChooser.APPROVE_OPTION) { try { File file = chooser.getSelectedFile(); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file)); os.write(_data); os.flush(); os.close(); } catch (Exception e1) { _log.error("actionPerformed(ActionEvent)", e1); } } } else if (e.getActionCommand().equals("DELETE")) { if (_data != null) { int result = JOptionPane.showConfirmDialog(getTopLevelAncestor(), GuiStrings.getString("message.removeimg"), GuiStrings.getString("title.confirm"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { removeImage(); _changed = true; } } } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static byte[] md5raw(String data) { try { MessageDigest md = MessageDigest.getInstance(MD); md.update(data.getBytes(UTF8)); return md.digest(); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: public void print(PrintWriter out) { out.println("<?xml version=\"1.0\"?>\n" + "<?xml-stylesheet type=\"text/xsl\" href=\"http://www.urbigene.com/foaf/foaf2html.xsl\" ?>\n" + "<rdf:RDF \n" + "xml:lang=\"en\" \n" + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" \n" + "xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\" \n" + "xmlns=\"http://xmlns.com/foaf/0.1/\" \n" + "xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" \n" + "xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"); out.println("<!-- generated with SciFoaf http://www.urbigene.com/foaf -->"); if (this.mainAuthor == null && this.authors.getAuthorCount() > 0) { this.mainAuthor = this.authors.getAuthorAt(0); } if (this.mainAuthor != null) { out.println("<foaf:PersonalProfileDocument rdf:about=\"\">\n" + "\t<foaf:primaryTopic rdf:nodeID=\"" + this.mainAuthor.getID() + "\"/>\n" + "\t<foaf:maker rdf:resource=\"mailto:plindenbaum@yahoo.fr\"/>\n" + "\t<dc:title>FOAF for " + XMLUtilities.escape(this.mainAuthor.getName()) + "</dc:title>\n" + "\t<dc:description>\n" + "\tFriend-of-a-Friend description for " + XMLUtilities.escape(this.mainAuthor.getName()) + "\n" + "\t</dc:description>\n" + "</foaf:PersonalProfileDocument>\n\n"); } for (int i = 0; i < this.laboratories.size(); ++i) { Laboratory lab = this.laboratories.getLabAt(i); out.println("<foaf:Group rdf:ID=\"laboratory_ID" + i + "\" >"); out.println("\t<foaf:name>" + XMLUtilities.escape(lab.toString()) + "</foaf:name>"); for (int j = 0; j < lab.getAuthorCount(); ++j) { out.println("\t<foaf:member rdf:resource=\"#" + lab.getAuthorAt(j).getID() + "\" />"); } out.println("</foaf:Group>\n\n"); } for (int i = 0; i < this.authors.size(); ++i) { Author author = authors.getAuthorAt(i); out.println("<foaf:Person rdf:ID=\"" + xmlName(author.getID()) + "\" >"); out.println("\t<foaf:name>" + xmlName(author.getName()) + "</foaf:name>"); out.println("\t<foaf:title>Dr</foaf:title>"); out.println("\t<foaf:family_name>" + xmlName(author.getLastName()) + "</foaf:family_name>"); if (author.getForeName() != null && author.getForeName().length() > 2) { out.println("\t<foaf:firstName>" + xmlName(author.getForeName()) + "</foaf:firstName>"); } String prop = author.getProperty("foaf:mbox"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (tokens[j].trim().length() == 0) continue; if (tokens[j].equals("mailto:")) continue; if (!tokens[j].startsWith("mailto:")) tokens[j] = "mailto:" + tokens[j]; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(tokens[j].getBytes()); byte[] digest = md.digest(); out.print("\t<foaf:mbox_sha1sum>"); for (int k = 0; k < digest.length; k++) { String hex = Integer.toHexString(digest[k]); if (hex.length() == 1) hex = "0" + hex; hex = hex.substring(hex.length() - 2); out.print(hex); } out.println("</foaf:mbox_sha1sum>"); } catch (Exception err) { out.println("\t<foaf:mbox rdf:resource=\"" + tokens[j] + "\" />"); } } } prop = author.getProperty("foaf:nick"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (tokens[j].trim().length() == 0) continue; out.println("\t<foaf:surname>" + XMLUtilities.escape(tokens[j]) + "</foaf:surname>"); } } prop = author.getProperty("foaf:homepage"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (!tokens[j].trim().startsWith("http://")) continue; if (tokens[j].trim().equals("http://")) continue; out.println("\t<foaf:homepage rdf:resource=\"" + XMLUtilities.escape(tokens[j].trim()) + "\"/>"); } } out.println("\t<foaf:publications rdf:resource=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=pubmed&amp;cmd=Search&amp;itool=pubmed_Abstract&amp;term=" + author.getTerm() + "\"/>"); prop = author.getProperty("foaf:img"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (!tokens[j].trim().startsWith("http://")) continue; if (tokens[j].trim().equals("http://")) continue; out.println("\t<foaf:depiction rdf:resource=\"" + XMLUtilities.escape(tokens[j].trim()) + "\"/>"); } } AuthorList knows = this.whoknowwho.getKnown(author); for (int j = 0; j < knows.size(); ++j) { out.println("\t<foaf:knows rdf:resource=\"#" + xmlName(knows.getAuthorAt(j).getID()) + "\" />"); } Paper publications[] = this.papers.getAuthorPublications(author).toArray(); if (!(publications.length == 0)) { HashSet meshes = new HashSet(); for (int j = 0; j < publications.length; ++j) { meshes.addAll(publications[j].meshTerms); } for (Iterator itermesh = meshes.iterator(); itermesh.hasNext(); ) { MeshTerm meshterm = (MeshTerm) itermesh.next(); out.println("\t<foaf:interest>\n" + "\t\t<rdf:Description rdf:about=\"" + meshterm.getURL() + "\">\n" + "\t\t\t<dc:title>" + XMLUtilities.escape(meshterm.toString()) + "</dc:title>\n" + "\t\t</rdf:Description>\n" + "\t</foaf:interest>"); } } out.println("</foaf:Person>\n\n"); } Paper paperarray[] = this.papers.toArray(); for (int i = 0; i < paperarray.length; ++i) { out.println("<foaf:Document rdf:about=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&amp;db=pubmed&amp;dopt=Abstract&amp;list_uids=" + paperarray[i].getPMID() + "\">"); out.println("<dc:title>" + XMLUtilities.escape(paperarray[i].getTitle()) + "</dc:title>"); for (Iterator iter = paperarray[i].authors.iterator(); iter.hasNext(); ) { Author author = (Author) iter.next(); out.println("<dc:author rdf:resource=\"#" + XMLUtilities.escape(author.getID()) + "\"/>"); } out.println("</foaf:Document>"); } out.println("</rdf:RDF>"); }
00
Code Sample 1: public static String getAnalysisServletOutput(String inputXml) { java.io.BufferedWriter bWriter = null; URLConnection connection = null; String resultString = ""; bWriter = null; connection = null; String target = ServletConstant.ANALYSIS_SERVLET; String message = "\nTHIS MESSAGE IS SENT FROM THE CLIENT APPLET \n\r"; try { URL url = new URL(target); connection = (HttpURLConnection) url.openConnection(); ((HttpURLConnection) connection).setRequestMethod("POST"); connection.setDoOutput(true); bWriter = new java.io.BufferedWriter(new java.io.OutputStreamWriter(connection.getOutputStream())); bWriter.write(message); bWriter.flush(); bWriter.close(); java.io.BufferedReader bReader = null; bReader = new java.io.BufferedReader(new java.io.InputStreamReader(connection.getInputStream())); String line; StringBuffer sb = new StringBuffer(); while ((line = bReader.readLine()) != null) { sb.append(line); } resultString = sb.toString(); bReader.close(); ((HttpURLConnection) connection).disconnect(); } catch (java.io.IOException ex) { resultString += ex.toString(); } finally { if (bWriter != null) { try { bWriter.close(); } catch (Exception ex) { resultString += ex.toString(); } } if (connection != null) { try { ((HttpURLConnection) connection).disconnect(); } catch (Exception ex) { resultString += ex.toString(); } } } return resultString; } Code Sample 2: public static boolean copyFileToDir(File inputFile, File outputDir) { try { String outputFileName = inputFile.getName(); int index = 1; while (existFileInDir(outputFileName, outputDir)) { outputFileName = index + inputFile.getName(); index++; } String directory = getDirectoryWithSlash(outputDir.getAbsolutePath()); File outputFile = new File(directory + outputFileName); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { return false; } return true; }
11
Code Sample 1: public void transaction() { String delPets = "delete from PETS where PERSON_ID = 1"; String delPersons = "delete from PERSONS where PERSON_ID = 1"; if (true) { System.out.println(delPets); System.out.println(delPersons); } Connection conn = null; Statement stmt = null; try { conn = ConnHelper.getConnectionByDriverManager(); conn.setAutoCommit(false); stmt = conn.createStatement(); int affectedRows = stmt.executeUpdate(delPets); System.out.println("affectedRows = " + affectedRows); if (true) { throw new SQLException("fasfdsaf"); } affectedRows = stmt.executeUpdate(delPersons); System.out.println("affectedRows = " + affectedRows); conn.commit(); conn.setAutoCommit(true); } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { e.printStackTrace(System.out); } e.printStackTrace(System.out); } finally { ConnHelper.close(conn, stmt, null); } } Code Sample 2: protected long incrementInDatabase(Object type) { long current_value; long new_value; String entry; if (global_entry != null) entry = global_entry; else throw new UnsupportedOperationException("Named key generators are not yet supported."); String lkw = (String) properties.get("net.ontopia.topicmaps.impl.rdbms.HighLowKeyGenerator.SelectSuffix"); String sql_select; if (lkw == null && (database.equals("sqlserver"))) { sql_select = "select " + valcol + " from " + table + " with (XLOCK) where " + keycol + " = ?"; } else { if (lkw == null) { if (database.equals("sapdb")) lkw = "with lock"; else lkw = "for update"; } sql_select = "select " + valcol + " from " + table + " where " + keycol + " = ? " + lkw; } if (log.isDebugEnabled()) log.debug("KeyGenerator: retrieving: " + sql_select); Connection conn = null; try { conn = connfactory.requestConnection(); PreparedStatement stm1 = conn.prepareStatement(sql_select); try { stm1.setString(1, entry); ResultSet rs = stm1.executeQuery(); if (!rs.next()) throw new OntopiaRuntimeException("HIGH/LOW key generator table '" + table + "' not initialized (no rows)."); current_value = rs.getLong(1); rs.close(); } finally { stm1.close(); } new_value = current_value + grabsize; String sql_update = "update " + table + " set " + valcol + " = ? where " + keycol + " = ?"; if (log.isDebugEnabled()) log.debug("KeyGenerator: incrementing: " + sql_update); PreparedStatement stm2 = conn.prepareStatement(sql_update); try { stm2.setLong(1, new_value); stm2.setString(2, entry); stm2.executeUpdate(); } finally { stm2.close(); } conn.commit(); } catch (SQLException e) { try { if (conn != null) conn.rollback(); } catch (SQLException e2) { } throw new OntopiaRuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { throw new OntopiaRuntimeException(e); } } } value = current_value + 1; max_value = new_value; return value; }
00
Code Sample 1: protected String md5sum(String toCompute) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toCompute.getBytes()); java.math.BigInteger hash = new java.math.BigInteger(1, md.digest()); return hash.toString(16); } Code Sample 2: public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files, int label, String charset) throws FilesException { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { if ((files == null) || (files.size() <= 0)) { return; } if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } Users user = getUser(hsession, repositoryName); Identity identity = getDefaultIdentity(hsession, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); for (int i = 0; i < files.size(); i++) { MultiPartEmail email = email = new MultiPartEmail(); email.setCharset(charset); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if (_to != null) { email.addTo(_to.getAddress(), _to.getPersonal()); } MailPartObj obj = (MailPartObj) files.get(i); email.setSubject("Files-System " + obj.getName()); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); email.attach(attachment); String mid = getId(); email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader("X-DBox", "FILES"); email.addHeader("X-DRecent", "false"); email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeMessage(mid, mime, user); } } catch (FilesException e) { throw e; } catch (Exception e) { throw new FilesException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new FilesException(ex); } catch (Throwable e) { throw new FilesException(e); } finally { GeneralOperations.closeHibernateSession(hsession); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } }
00
Code Sample 1: private File sendQuery(String query) throws MusicBrainzException { File xmlServerResponse = null; try { xmlServerResponse = new File(SERVER_RESPONSE_FILE); long start = Calendar.getInstance().getTimeInMillis(); System.out.println("\n\n++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println(" consulta de busqueda -> " + query); URL url = new URL(query); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String response = ""; String line = ""; System.out.println(" Respuesta del servidor: \n"); while ((line = in.readLine()) != null) { response += line; } xmlServerResponse = new File(SERVER_RESPONSE_FILE); System.out.println(" Ruta del archivo XML -> " + xmlServerResponse.getAbsolutePath()); BufferedWriter out = new BufferedWriter(new FileWriter(xmlServerResponse)); out.write(response); out.close(); System.out.println("Tamanho del xmlFile -> " + xmlServerResponse.length()); long ahora = (Calendar.getInstance().getTimeInMillis() - start); System.out.println(" Tiempo transcurrido en la consulta (en milesimas) -> " + ahora); System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n"); } catch (IOException e) { e.printStackTrace(); String msg = e.getMessage(); if (e instanceof FileNotFoundException) { msg = "ERROR: MusicBrainz URL used is not found:\n" + msg; } else { } throw new MusicBrainzException(msg); } return xmlServerResponse; } Code Sample 2: public void close() { try { if (writer != null) { BufferedReader reader; writer.close(); writer = new BufferedWriter(new FileWriter(fileName)); for (int i = 0; i < headers.size(); i++) writer.write(headers.get(i) + ","); writer.write("\n"); reader = new BufferedReader(new FileReader(file)); while (reader.ready()) writer.write(reader.readLine() + "\n"); reader.close(); writer.close(); file.delete(); } } catch (java.io.IOException e) { throw new RuntimeException(e); } }
11
Code Sample 1: public void readPage(String search) { InputStream is = null; try { URL url = new URL("http://www.english-german-dictionary.com/index.php?search=" + search.trim()); is = url.openStream(); InputStreamReader isr = new InputStreamReader(is, "ISO-8859-15"); Scanner scan = new Scanner(isr); String str = new String(); String translate = new String(); String temp; while (scan.hasNextLine()) { temp = (scan.nextLine()); if (temp.contains("<td style='padding-top:4px;' class='ergebnisse_res'>")) { int anfang = temp.indexOf("-->") + 3; temp = temp.substring(anfang); temp = temp.substring(0, temp.indexOf("<!--")); translate = temp.trim(); } else if (temp.contains("<td style='' class='ergebnisse_art'>") || temp.contains("<td style='' class='ergebnisse_art_dif'>") || temp.contains("<td style='padding-top:4px;' class='ergebnisse_art'>")) { if (searchEnglish == false && searchGerman == false) { searchEnglish = temp.contains("<td style='' class='ergebnisse_art'>"); searchGerman = temp.contains("<td style='' class='ergebnisse_art_dif'>"); } int anfang1 = temp.lastIndexOf("'>") + 2; temp = temp.substring(anfang1, temp.lastIndexOf("</td>")); String to = temp.trim() + " "; temp = scan.nextLine(); int anfang2 = temp.lastIndexOf("\">") + 2; temp = (to != null ? to : "") + temp.substring(anfang2, temp.lastIndexOf("</a>")); str += translate + " - " + temp + "\n"; germanList.add(translate); englishList.add(temp.trim()); } } if (searchEnglish) { List<String> temp2 = englishList; englishList = germanList; germanList = temp2; } } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) try { is.close(); } catch (IOException e) { } } } Code Sample 2: public String GetMemberName(String id) { String name = null; try { String line; URL url = new URL(intvasmemberDeatails + "?CID=" + id); URLConnection connection = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { name = line; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String[] parts = name.split(" "); rating = parts[2]; return parts[0] + " " + parts[1]; }
00
Code Sample 1: private PrecomputedAnimatedModel loadPrecomputedModel_(URL url) { if (precompCache.containsKey(url.toExternalForm())) { return (precompCache.get(url.toExternalForm()).copy()); } TextureLoader.getInstance().getTexture(""); List<SharedGroup> frames = new ArrayList<SharedGroup>(); Map<String, Animation> animations = new Hashtable<String, Animation>(); if (url.toExternalForm().endsWith(".amo")) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String objFileName = reader.readLine(); objFileName = url.toExternalForm().substring(0, url.toExternalForm().lastIndexOf("/")) + "/" + objFileName; frames = loadOBJFrames(objFileName); String line; while ((line = reader.readLine()) != null) { StringTokenizer tokenizer = new StringTokenizer(line); String animName = tokenizer.nextToken(); int from = Integer.valueOf(tokenizer.nextToken()); int to = Integer.valueOf(tokenizer.nextToken()); tokenizer.nextToken(); animations.put(animName, new Animation(animName, from, to)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { frames = loadOBJFrames(url.toExternalForm()); } PrecomputedAnimatedModel precompModel = new PrecomputedAnimatedModel(frames, animations); precompCache.put(url.toExternalForm(), precompModel); return (precompModel); } Code Sample 2: public static void main(String[] args) { Usage u = new ccngetmeta(); for (int i = 0; i < args.length - 3; 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 + 3) { u.usage(); System.exit(1); } try { int readsize = 1024; CCNHandle handle = CCNHandle.open(); String metaArg = args[CommonParameters.startArg + 1]; if (!metaArg.startsWith("/")) metaArg = "/" + metaArg; ContentName fileName = MetadataProfile.getLatestVersion(ContentName.fromURI(args[CommonParameters.startArg]), ContentName.fromNative(metaArg), CommonParameters.timeout, handle); if (fileName == null) { System.out.println("File " + args[CommonParameters.startArg] + " does not exist"); System.exit(1); } if (VersioningProfile.hasTerminalVersion(fileName)) { } else { System.out.println("File " + fileName + " does not exist... exiting"); System.exit(1); } File theFile = new File(args[CommonParameters.startArg + 2]); 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(fileName, handle); else input = new CCNFileInputStream(fileName, 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 String hash(String message) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(12345); md.update(saltString.getBytes()); md.update(message.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString().trim(); return digestStr; } Code Sample 2: public T02OTSUnitTestCase(String name) throws java.io.IOException { super(name); java.net.URL url = ClassLoader.getSystemResource("host0.cosnaming.jndi.properties"); jndiProps = new java.util.Properties(); jndiProps.load(url.openStream()); }
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 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: protected void createDb() { File rootFolder = new File(dbFolderPath); if (!rootFolder.exists()) { rootFolder.mkdirs(); } openConnection(); try { Statement stat = connection.createStatement(); ResourceBundle bundle = ResourceBundle.getBundle("uTaggerDb"); for (String key : bundle.keySet()) { stat.executeUpdate(bundle.getString(key)); } commit(); } catch (SQLException e) { LOG.warn(e); rollback(); } } Code Sample 2: public static String getMd5Digest(String pInput) { try { MessageDigest lDigest = MessageDigest.getInstance("MD5"); lDigest.update(pInput.getBytes()); BigInteger lHashInt = new BigInteger(1, lDigest.digest()); return String.format("%1$032x", lHashInt).toLowerCase(); } catch (NoSuchAlgorithmException lException) { throw new RuntimeException(lException); } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static boolean start(RootDoc root) { Logger log = Logger.getLogger("DocletGenerator"); if (destination == null) { try { ruleListenerDef = IOUtils.toString(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/RuleListenersFragment.xsd"), "UTF-8"); String fn = System.getenv("annocultor.xconverter.destination.file.name"); fn = (fn == null) ? "./../../../src/site/resources/schema/XConverterInclude.xsd" : fn; destination = new File(fn); if (destination.exists()) { destination.delete(); } FileOutputStream os; os = new FileOutputStream(new File(destination.getParentFile(), "XConverter.xsd")); IOUtils.copy(new AutoCloseInputStream(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/XConverterTemplate.xsd")), os); os.close(); os = new FileOutputStream(destination); IOUtils.copy(new AutoCloseInputStream(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/XConverterInclude.xsd")), os); os.close(); } catch (Exception e) { try { throw new RuntimeException("On destination " + destination.getCanonicalPath(), e); } catch (IOException e1) { throw new RuntimeException(e1); } } } try { String s = Utils.loadFileToString(destination.getCanonicalPath(), "\n"); int breakPoint = s.indexOf(XSD_TEXT_TO_REPLACED_WITH_GENERATED_XML_SIGNATURES); if (breakPoint < 0) { throw new Exception("Signature not found in XSD: " + XSD_TEXT_TO_REPLACED_WITH_GENERATED_XML_SIGNATURES); } String preambula = s.substring(0, breakPoint); String appendix = s.substring(breakPoint); destination.delete(); PrintWriter schemaWriter = new PrintWriter(destination); schemaWriter.print(preambula); ClassDoc[] classes = root.classes(); for (int i = 0; i < classes.length; ++i) { ClassDoc cd = classes[i]; PrintWriter documentationWriter = null; if (getSuperClasses(cd).contains(Rule.class.getName())) { for (ConstructorDoc constructorDoc : cd.constructors()) { if (constructorDoc.isPublic()) { if (isMeantForXMLAccess(constructorDoc)) { if (documentationWriter == null) { File file = new File("./../../../src/site/xdoc/rules." + cd.name() + ".xml"); documentationWriter = new PrintWriter(file); log.info("Generating doc for rule " + file.getCanonicalPath()); printRuleDocStart(cd, documentationWriter); } boolean initFound = false; for (MethodDoc methodDoc : cd.methods()) { if ("init".equals(methodDoc.name())) { if (methodDoc.parameters().length == 0) { initFound = true; break; } } } if (!initFound) { } printConstructorSchema(constructorDoc, schemaWriter); if (documentationWriter != null) { printConstructorDoc(constructorDoc, documentationWriter); } } } } } if (documentationWriter != null) { printRuleDocEnd(documentationWriter); } } schemaWriter.print(appendix); schemaWriter.close(); log.info("Saved to " + destination.getCanonicalPath()); } catch (Exception e) { throw new RuntimeException(e); } return true; }
00
Code Sample 1: public void add(String user, String pass, boolean admin, boolean developer) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); String sql; if (contains(stmt, user) == true) { sql = "update Principals set Password = '" + pass + "' " + " where PrincipalId = '" + user + "'"; } else { sql = "insert into Principals (PrincipalId, Password) " + " values ('" + user + "', '" + pass + "')"; } stmt.executeUpdate(sql); updateRoles(stmt, user, admin, developer); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: public void execute(PaymentInfoMagcard payinfo) { if (payinfo.getTotal().compareTo(BigDecimal.ZERO) > 0) { try { StringBuffer sb = new StringBuffer(); sb.append("x_login="); sb.append(URLEncoder.encode(m_sCommerceID, "UTF-8")); sb.append("&x_password="); sb.append(URLEncoder.encode(m_sCommercePassword, "UTF-8")); sb.append("&x_version=3.1"); sb.append("&x_test_request="); sb.append(m_bTestMode); sb.append("&x_method=CC"); sb.append("&x_type="); sb.append(OPERATIONVALIDATE); sb.append("&x_amount="); NumberFormat formatter = new DecimalFormat("000.00"); String amount = formatter.format(payinfo.getTotal()); sb.append(URLEncoder.encode((String) amount, "UTF-8")); sb.append("&x_delim_data=TRUE"); sb.append("&x_delim_char=|"); sb.append("&x_relay_response=FALSE"); sb.append("&x_exp_date="); String tmp = payinfo.getExpirationDate(); sb.append(tmp.charAt(2)); sb.append(tmp.charAt(3)); sb.append(tmp.charAt(0)); sb.append(tmp.charAt(1)); sb.append("&x_card_num="); sb.append(URLEncoder.encode(payinfo.getCardNumber(), "UTF-8")); sb.append("&x_description=Shop+Transaction"); String[] cc_name = payinfo.getHolderName().split(" "); sb.append("&x_first_name="); if (cc_name.length > 0) { sb.append(URLEncoder.encode(cc_name[0], "UTF-8")); } sb.append("&x_last_name="); if (cc_name.length > 1) { sb.append(URLEncoder.encode(cc_name[1], "UTF-8")); } URL url = new URL(ENDPOINTADDRESS); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(sb.toString().getBytes()); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; line = in.readLine(); in.close(); String[] ccRep = line.split("\\|"); if ("1".equals(ccRep[0])) { payinfo.paymentOK((String) ccRep[4]); } else { payinfo.paymentError(AppLocal.getIntString("message.paymenterror") + "\n" + ccRep[0] + " -- " + ccRep[3]); } } catch (UnsupportedEncodingException eUE) { payinfo.paymentError(AppLocal.getIntString("message.paymentexceptionservice") + "\n" + eUE.getMessage()); } catch (MalformedURLException eMURL) { payinfo.paymentError(AppLocal.getIntString("message.paymentexceptionservice") + "\n" + eMURL.getMessage()); } catch (IOException e) { payinfo.paymentError(AppLocal.getIntString("message.paymenterror") + "\n" + e.getMessage()); } } else { payinfo.paymentError(AppLocal.getIntString("message.paymentrefundsnotsupported")); } }
11
Code Sample 1: public static void copy(String a, String b) throws IOException { File inputFile = new File(a); File outputFile = new File(b); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public void testCodingCompletedFromFile() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 5); encoder.write(wrap("stuff")); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("more stuff"); wrtout.flush(); wrtout.close(); try { FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 10); fail("IllegalStateException should have been thrown"); } catch (IllegalStateException ex) { } finally { tmpFile.delete(); } }
00
Code Sample 1: protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (name.startsWith("java.")) { return super.loadClass(name, resolve); } Class<?> c = super.findLoadedClass(name); if (c != null) { return c; } String resource = name.replace('.', '/') + ".class"; try { URL url = super.getResource(resource); if (url == null) { throw new ClassNotFoundException(name); } File f = new File("build/bin/" + resource); System.out.println("FileLen:" + f.length() + " " + f.getName()); InputStream is = url.openStream(); try { ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] b = new byte[2048]; int count; while ((count = is.read(b, 0, 2048)) != -1) { os.write(b, 0, count); } byte[] bytes = os.toByteArray(); System.err.println("bytes: " + bytes.length + " " + resource); return defineClass(name, bytes, 0, bytes.length); } finally { if (is != null) { is.close(); } } } catch (SecurityException e) { return super.loadClass(name, resolve); } catch (IOException e) { throw new ClassNotFoundException(name, e); } } Code Sample 2: public static String generateDigest(String password, String saltHex, String alg) { try { MessageDigest sha = MessageDigest.getInstance(alg); byte[] salt = new byte[0]; if (saltHex != null) { salt = fromHex(saltHex); } String label = null; if (alg.startsWith("SHA")) { label = (salt.length <= 0) ? "{SHA}" : "{SSHA}"; } else if (alg.startsWith("MD5")) { label = (salt.length <= 0) ? "{MD5}" : "{SMD5}"; } sha.reset(); sha.update(password.getBytes()); sha.update(salt); byte[] pwhash = sha.digest(); StringBuffer digest = new StringBuffer(label); digest.append(Base64.encode(concatenate(pwhash, salt)).toCharArray()); return digest.toString(); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException("failed to find " + "algorithm for password hashing.", nsae); } }
00
Code Sample 1: private boolean createFTPConnection() { client = new FTPClient(); System.out.println("Client created"); try { client.connect(this.hostname, this.port); System.out.println("Connected: " + this.hostname + ", " + this.port); client.login(username, password); System.out.println("Logged in: " + this.username + ", " + this.password); this.setupActiveFolder(); return true; } catch (IllegalStateException ex) { Logger.getLogger(FTPProject.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(FTPProject.class.getName()).log(Level.SEVERE, null, ex); } catch (FTPIllegalReplyException ex) { Logger.getLogger(FTPProject.class.getName()).log(Level.SEVERE, null, ex); } catch (FTPException ex) { Logger.getLogger(FTPProject.class.getName()).log(Level.SEVERE, null, ex); } return false; } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
11
Code Sample 1: public int NthLowestSkill(int n) { int[] skillIds = new int[] { 0, 1, 2, 3 }; for (int j = 0; j < 3; j++) { for (int i = 0; i < 3 - j; i++) { if (Skills()[skillIds[i]] > Skills()[skillIds[i + 1]]) { int temp = skillIds[i]; skillIds[i] = skillIds[i + 1]; skillIds[i + 1] = temp; } } } return skillIds[n - 1]; } Code Sample 2: public void process(String dir) { String[] list = new File(dir).list(); if (list == null) return; int n = list.length; long[] bubblesort = new long[list.length + 1]; if (!statustext) { IJ.log("Current Directory is: " + dir); IJ.log(" "); IJ.log("DICOM File Name / " + prefix1 + " / " + prefix2 + " / " + prefix3 + " / " + pick); IJ.log(" "); } for (int i = 0; i < n; i++) { IJ.showStatus(i + "/" + n); File f = new File(dir + list[i]); if (!f.isDirectory()) { ImagePlus img = new Opener().openImage(dir, list[i]); if (img != null && img.getStackSize() == 1) { if (!scoutengine(img)) return; if (!statustext) { IJ.log(list[i] + "/" + whichprefix1 + "/" + whichprefix2 + "/" + whichprefix3 + "/" + whichcase); } int lastDigit = whichcase.length() - 1; while (lastDigit > 0) { if (!Character.isDigit(whichcase.charAt(lastDigit))) lastDigit -= 1; else break; } if (lastDigit < whichcase.length() - 1) whichcase = whichcase.substring(0, lastDigit + 1); bubblesort[i] = Long.parseLong(whichcase); } } } if (statussorta || statussortd || statustext) { boolean sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < n - 1; i++) { if (statussorta) { if (bubblesort[i] > bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } else { if (bubblesort[i] < bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } } } IJ.log(" "); for (int i = 0; i < n; i++) { if (!statustext) { IJ.log(list[i] + " / " + bubblesort[i]); } else { IJ.log(dir + list[i]); } } } if (open_as_stack || only_images) { boolean sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < n - 1; i++) { if (bubblesort[i] > bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } } if (only_images) { Opener o = new Opener(); int counter = 0; IJ.log(" "); for (int i = 0; i < n; i++) { String path = (dir + list[i]); if (path == null) break; else { ImagePlus imp = o.openImage(path); counter++; if (imp != null) { IJ.log(counter + " + " + path); imp.show(); } else IJ.log(counter + " - " + path); } } return; } int width = 0, height = 0, type = 0; ImageStack stack = null; double min = Double.MAX_VALUE; double max = -Double.MAX_VALUE; int k = 0; try { for (int i = 0; i < n; i++) { String path = (dir + list[i]); if (path == null) break; if (list[i].endsWith(".txt")) continue; ImagePlus imp = new Opener().openImage(path); if (imp != null && stack == null) { width = imp.getWidth(); height = imp.getHeight(); type = imp.getType(); ColorModel cm = imp.getProcessor().getColorModel(); if (halfSize) stack = new ImageStack(width / 2, height / 2, cm); else stack = new ImageStack(width, height, cm); } if (stack != null) k = stack.getSize() + 1; IJ.showStatus(k + "/" + n); IJ.showProgress((double) k / n); if (imp == null) IJ.log(list[i] + ": unable to open"); else if (imp.getWidth() != width || imp.getHeight() != height) IJ.log(list[i] + ": wrong dimensions"); else if (imp.getType() != type) IJ.log(list[i] + ": wrong type"); else { ImageProcessor ip = imp.getProcessor(); if (grayscale) ip = ip.convertToByte(true); if (halfSize) ip = ip.resize(width / 2, height / 2); if (ip.getMin() < min) min = ip.getMin(); if (ip.getMax() > max) max = ip.getMax(); String label = imp.getTitle(); String info = (String) imp.getProperty("Info"); if (info != null) label += "\n" + info; stack.addSlice(label, ip); } System.gc(); } } catch (OutOfMemoryError e) { IJ.outOfMemory("FolderOpener"); stack.trim(); } if (stack != null && stack.getSize() > 0) { ImagePlus imp2 = new ImagePlus("Stack", stack); if (imp2.getType() == ImagePlus.GRAY16 || imp2.getType() == ImagePlus.GRAY32) imp2.getProcessor().setMinAndMax(min, max); imp2.show(); } IJ.showProgress(1.0); } }
00
Code Sample 1: public static IProject createEMFProject(IPath javaSource, URI projectLocationURI, List<IProject> referencedProjects, Monitor monitor, int style, List<?> pluginVariables) { IProgressMonitor progressMonitor = BasicMonitor.toIProgressMonitor(monitor); String projectName = javaSource.segment(0); IProject project = null; try { List<IClasspathEntry> classpathEntries = new UniqueEList<IClasspathEntry>(); progressMonitor.beginTask("", 10); progressMonitor.subTask(CodeGenEcorePlugin.INSTANCE.getString("_UI_CreatingEMFProject_message", new Object[] { projectName, projectLocationURI != null ? projectLocationURI.toString() : projectName })); IWorkspace workspace = ResourcesPlugin.getWorkspace(); project = workspace.getRoot().getProject(projectName); if (!project.exists()) { URI location = projectLocationURI; if (location == null) { location = URI.createFileURI(workspace.getRoot().getLocation().append(projectName).toOSString()); } location = location.appendSegment(".project"); File projectFile = new File(location.toString()); if (projectFile.exists()) { projectFile.renameTo(new File(location.toString() + ".old")); } } IJavaProject javaProject = JavaCore.create(project); IProjectDescription projectDescription = null; if (!project.exists()) { projectDescription = ResourcesPlugin.getWorkspace().newProjectDescription(projectName); if (projectLocationURI != null) { projectDescription.setLocationURI(new java.net.URI(projectLocationURI.toString())); } project.create(projectDescription, new SubProgressMonitor(progressMonitor, 1)); project.open(new SubProgressMonitor(progressMonitor, 1)); } else { projectDescription = project.getDescription(); project.open(new SubProgressMonitor(progressMonitor, 1)); if (project.hasNature(JavaCore.NATURE_ID)) { classpathEntries.addAll(Arrays.asList(javaProject.getRawClasspath())); } } boolean isInitiallyEmpty = classpathEntries.isEmpty(); { if (referencedProjects.size() != 0 && (style & (EMF_PLUGIN_PROJECT_STYLE | EMF_EMPTY_PROJECT_STYLE)) == 0) { projectDescription.setReferencedProjects(referencedProjects.toArray(new IProject[referencedProjects.size()])); for (IProject referencedProject : referencedProjects) { IClasspathEntry referencedProjectClasspathEntry = JavaCore.newProjectEntry(referencedProject.getFullPath()); classpathEntries.add(referencedProjectClasspathEntry); } } String[] natureIds = projectDescription.getNatureIds(); if (natureIds == null) { natureIds = new String[] { JavaCore.NATURE_ID, "org.eclipse.pde.PluginNature" }; } else { if (!project.hasNature(JavaCore.NATURE_ID)) { String[] oldNatureIds = natureIds; natureIds = new String[oldNatureIds.length + 1]; System.arraycopy(oldNatureIds, 0, natureIds, 0, oldNatureIds.length); natureIds[oldNatureIds.length] = JavaCore.NATURE_ID; } if (!project.hasNature("org.eclipse.pde.PluginNature")) { String[] oldNatureIds = natureIds; natureIds = new String[oldNatureIds.length + 1]; System.arraycopy(oldNatureIds, 0, natureIds, 0, oldNatureIds.length); natureIds[oldNatureIds.length] = "org.eclipse.pde.PluginNature"; } } projectDescription.setNatureIds(natureIds); ICommand[] builders = projectDescription.getBuildSpec(); if (builders == null) { builders = new ICommand[0]; } boolean hasManifestBuilder = false; boolean hasSchemaBuilder = false; for (int i = 0; i < builders.length; ++i) { if ("org.eclipse.pde.ManifestBuilder".equals(builders[i].getBuilderName())) { hasManifestBuilder = true; } if ("org.eclipse.pde.SchemaBuilder".equals(builders[i].getBuilderName())) { hasSchemaBuilder = true; } } if (!hasManifestBuilder) { ICommand[] oldBuilders = builders; builders = new ICommand[oldBuilders.length + 1]; System.arraycopy(oldBuilders, 0, builders, 0, oldBuilders.length); builders[oldBuilders.length] = projectDescription.newCommand(); builders[oldBuilders.length].setBuilderName("org.eclipse.pde.ManifestBuilder"); } if (!hasSchemaBuilder) { ICommand[] oldBuilders = builders; builders = new ICommand[oldBuilders.length + 1]; System.arraycopy(oldBuilders, 0, builders, 0, oldBuilders.length); builders[oldBuilders.length] = projectDescription.newCommand(); builders[oldBuilders.length].setBuilderName("org.eclipse.pde.SchemaBuilder"); } projectDescription.setBuildSpec(builders); project.setDescription(projectDescription, new SubProgressMonitor(progressMonitor, 1)); IContainer sourceContainer = project; if (javaSource.segmentCount() > 1) { IPath sourceContainerPath = javaSource.removeFirstSegments(1).makeAbsolute(); sourceContainer = project.getFolder(sourceContainerPath); if (!sourceContainer.exists()) { for (int i = sourceContainerPath.segmentCount() - 1; i >= 0; i--) { sourceContainer = project.getFolder(sourceContainerPath.removeLastSegments(i)); if (!sourceContainer.exists()) { ((IFolder) sourceContainer).create(false, true, new SubProgressMonitor(progressMonitor, 1)); } } } IClasspathEntry sourceClasspathEntry = JavaCore.newSourceEntry(javaSource); for (Iterator<IClasspathEntry> i = classpathEntries.iterator(); i.hasNext(); ) { IClasspathEntry classpathEntry = i.next(); if (classpathEntry.getPath().isPrefixOf(javaSource)) { i.remove(); } } classpathEntries.add(0, sourceClasspathEntry); } if (isInitiallyEmpty) { IClasspathEntry jreClasspathEntry = JavaCore.newVariableEntry(new Path(JavaRuntime.JRELIB_VARIABLE), new Path(JavaRuntime.JRESRC_VARIABLE), new Path(JavaRuntime.JRESRCROOT_VARIABLE)); for (Iterator<IClasspathEntry> i = classpathEntries.iterator(); i.hasNext(); ) { IClasspathEntry classpathEntry = i.next(); if (classpathEntry.getPath().isPrefixOf(jreClasspathEntry.getPath())) { i.remove(); } } String jreContainer = JavaRuntime.JRE_CONTAINER; String complianceLevel = CodeGenUtil.EclipseUtil.getJavaComplianceLevel(project); if ("1.5".equals(complianceLevel)) { jreContainer += "/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"; } else if ("1.6".equals(complianceLevel)) { jreContainer += "/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"; } classpathEntries.add(JavaCore.newContainerEntry(new Path(jreContainer))); } if ((style & EMF_EMPTY_PROJECT_STYLE) == 0) { if ((style & EMF_PLUGIN_PROJECT_STYLE) != 0) { classpathEntries.add(JavaCore.newContainerEntry(new Path("org.eclipse.pde.core.requiredPlugins"))); for (Iterator<IClasspathEntry> i = classpathEntries.iterator(); i.hasNext(); ) { IClasspathEntry classpathEntry = i.next(); if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE && !JavaRuntime.JRELIB_VARIABLE.equals(classpathEntry.getPath().toString()) || classpathEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { i.remove(); } } } else { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_CORE_RUNTIME", "org.eclipse.core.runtime"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_CORE_RESOURCES", "org.eclipse.core.resources"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_COMMON", "org.eclipse.emf.common"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_ECORE", "org.eclipse.emf.ecore"); if ((style & EMF_XML_PROJECT_STYLE) != 0) { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_ECORE_XMI", "org.eclipse.emf.ecore.xmi"); } if ((style & EMF_MODEL_PROJECT_STYLE) == 0) { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_EDIT", "org.eclipse.emf.edit"); if ((style & EMF_EDIT_PROJECT_STYLE) == 0) { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_SWT", "org.eclipse.swt"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_JFACE", "org.eclipse.jface"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_UI_VIEWS", "org.eclipse.ui.views"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_UI_EDITORS", "org.eclipse.ui.editors"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_UI_IDE", "org.eclipse.ui.ide"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_UI_WORKBENCH", "org.eclipse.ui.workbench"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_COMMON_UI", "org.eclipse.emf.common.ui"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_EDIT_UI", "org.eclipse.emf.edit.ui"); if ((style & EMF_XML_PROJECT_STYLE) == 0) { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_ECORE_XMI", "org.eclipse.emf.ecore.xmi"); } } } if ((style & EMF_TESTS_PROJECT_STYLE) != 0) { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "JUNIT", "org.junit"); } if (pluginVariables != null) { for (Iterator<?> i = pluginVariables.iterator(); i.hasNext(); ) { Object variable = i.next(); if (variable instanceof IClasspathEntry) { classpathEntries.add((IClasspathEntry) variable); } else if (variable instanceof String) { String pluginVariable = (String) variable; String name; String id; int index = pluginVariable.indexOf("="); if (index == -1) { name = pluginVariable.replace('.', '_').toUpperCase(); id = pluginVariable; } else { name = pluginVariable.substring(0, index); id = pluginVariable.substring(index + 1); } CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, name, id); } } } } } javaProject.setRawClasspath(classpathEntries.toArray(new IClasspathEntry[classpathEntries.size()]), new SubProgressMonitor(progressMonitor, 1)); } if (isInitiallyEmpty) { javaProject.setOutputLocation(new Path("/" + javaSource.segment(0) + "/bin"), new SubProgressMonitor(progressMonitor, 1)); } } catch (Exception exception) { exception.printStackTrace(); CodeGenEcorePlugin.INSTANCE.log(exception); } finally { progressMonitor.done(); } return project; } Code Sample 2: public synchronized String encrypt(String password) { try { MessageDigest md = null; md = MessageDigest.getInstance("SHA-1"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); byte[] hash = (new Base64()).encode(raw); return new String(hash); } catch (NoSuchAlgorithmException e) { System.out.println("Algorithm SHA-1 is not supported"); return null; } catch (UnsupportedEncodingException e) { System.out.println("UTF-8 encoding is not supported"); return null; } }
00
Code Sample 1: private void _resetLanguages(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception { List list = (List) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST); for (int i = 0; i < list.size(); i++) { long langId = ((Language) list.get(i)).getId(); try { String filePath = getGlobalVariablesPath() + "cms_language_" + langId + ".properties"; File from = new java.io.File(filePath); from.createNewFile(); String tmpFilePath = getTemporyDirPath() + "cms_language_" + langId + "_properties.tmp"; File to = new java.io.File(tmpFilePath); to.createNewFile(); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { Logger.debug(this, "Property File copy Failed " + e, e); } } } Code Sample 2: public static void messageDigestTest() { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update("computer".getBytes()); md.update("networks".getBytes()); System.out.println(new String(md.digest())); System.out.println(new String(md.digest("computernetworks".getBytes()))); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: private void copyFileToPhotoFolder(File photo, String personId) { try { FileChannel in = new FileInputStream(photo).getChannel(); File dirServer = new File(Constants.PHOTO_DIR); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.PHOTO_DIR + personId + ".jpg"); if (!fileServer.exists()) { fileServer.createNewFile(); } in.transferTo(0, in.size(), new FileOutputStream(fileServer).getChannel()); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
11
Code Sample 1: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); getLog().info("Process request " + pathInfo); if (null != pathInfo) { String pathId = getPathId(pathInfo); JobResources res = ContextUtil.getJobResource(pathId); if (null != res) { RequestType requType = getRequestType(request); ResultAccess access = new ResultAccess(res); Collection<Long> uIdColl = res.getUniqIds(); boolean isFiltered = false; { List<String> postSeqIds = getSeqList(request); if (!postSeqIds.isEmpty()) { isFiltered = true; uIdColl = access.loadIds(postSeqIds); } } try { if ((requType.equals(RequestType.FASTA)) || (requType.equals(RequestType.SWISSPROT))) { OutputStreamWriter out = null; out = new OutputStreamWriter(response.getOutputStream()); for (Long uid : uIdColl) { if (requType.equals(RequestType.FASTA)) { SwissProt sw = access.getSwissprotEntry(uid); if (null != sw) { PrintFactory.instance().print(ConvertFactory.instance().SwissProt2fasta(sw), out); } else { System.err.println("Not able to read Swissprot entry " + uid + " in project " + res.getBaseDir()); } } else if (requType.equals(RequestType.SWISSPROT)) { File swissFile = res.getSwissprotFile(uid); if (swissFile.exists()) { InputStream in = null; try { in = new FileInputStream(swissFile); IOUtils.copy(in, out); } catch (IOException e) { e.printStackTrace(); System.err.println("Problems with reading file to output stream " + swissFile); } finally { IOUtils.closeQuietly(in); } } else { System.err.println("Swissprot file does not exist: " + swissFile); } } } out.flush(); } else { if (uIdColl.size() <= 2) { isFiltered = false; uIdColl = res.getUniqIds(); } Tree tree = access.getTreeByUniquId(uIdColl); if (requType.equals(RequestType.TREE)) { response.getWriter().write(tree.toNewHampshireX()); } else if (requType.equals(RequestType.PNG)) { List<SwissProt> sp = access.getSwissprotEntriesByUniquId(uIdColl); ImageMap map = ImageFactory.instance().createProteinCard(sp, tree, true, res); response.setContentType("image/png"); response.addHeader("Content-Disposition", "filename=ProteinCards.png"); ImageFactory.instance().printPNG(map.getImage(), response.getOutputStream()); response.getOutputStream().flush(); } else if (requType.equals(RequestType.HTML)) { List<SwissProt> sp = access.getSwissprotEntriesByUniquId(uIdColl); createHtml(res, access, tree, request, response, sp, isFiltered); } } } catch (Exception e) { e.printStackTrace(); getLog().error("Problem with Request: " + pathInfo + "; type " + requType, e); } } else { getLog().error("Resource is null: " + pathId + "; path " + pathInfo); } } else { getLog().error("PathInfo is null!!!"); } } Code Sample 2: public MemoryBinaryBody(InputStream is) throws IOException { TempPath tempPath = TempStorage.getInstance().getRootTempPath(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); out.close(); tempFile = out.toByteArray(); }
11
Code Sample 1: private void writeFile(FileInputStream inFile, FileOutputStream outFile) throws IOException { byte[] buf = new byte[2048]; int read; while ((read = inFile.read(buf)) > 0) outFile.write(buf, 0, read); inFile.close(); } Code Sample 2: private void createWar() throws IOException, XMLStreamException { String appName = this.fileout.getName(); int i = appName.indexOf("."); if (i != -1) appName = appName.substring(0, i); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(this.fileout)); { ZipEntry entry = new ZipEntry("WEB-INF/web.xml"); zout.putNextEntry(entry); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter w = factory.createXMLStreamWriter(zout, "ASCII"); w.writeStartDocument("ASCII", "1.0"); w.writeStartElement("web-app"); w.writeAttribute("xsi", XSI, "schemaLocation", "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml /ns/javaee/web-app_2_5.xsd"); w.writeAttribute("version", "2.5"); w.writeAttribute("xmlns", J2EE); w.writeAttribute("xmlns:xsi", XSI); w.writeStartElement("description"); w.writeCharacters("Site maintenance for " + appName); w.writeEndElement(); w.writeStartElement("display-name"); w.writeCharacters(appName); w.writeEndElement(); w.writeStartElement("servlet"); w.writeStartElement("servlet-name"); w.writeCharacters("down"); w.writeEndElement(); w.writeStartElement("jsp-file"); w.writeCharacters("/WEB-INF/jsp/down.jsp"); w.writeEndElement(); w.writeEndElement(); w.writeStartElement("servlet-mapping"); w.writeStartElement("servlet-name"); w.writeCharacters("down"); w.writeEndElement(); w.writeStartElement("url-pattern"); w.writeCharacters("/*"); w.writeEndElement(); w.writeEndElement(); w.writeEndElement(); w.writeEndDocument(); w.flush(); zout.closeEntry(); } { ZipEntry entry = new ZipEntry("WEB-INF/jsp/down.jsp"); zout.putNextEntry(entry); PrintWriter w = new PrintWriter(zout); if (this.messageFile != null) { IOUtils.copyTo(new FileReader(this.messageFile), w); } else if (this.messageString != null) { w.print("<html><body>" + this.messageString + "</body></html>"); } else { w.print("<html><body><div style='text-align:center;font-size:500%;'>Oh No !<br/><b>" + appName + "</b><br/>is down for maintenance!</div></body></html>"); } w.flush(); zout.closeEntry(); } zout.finish(); zout.flush(); zout.close(); }
00
Code Sample 1: public static String encrypt(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw new WebDocRuntimeException(ex); } md.update(text.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); return hash.toString(HEX); } Code Sample 2: public static String post(String strUrl, String strPostString) { try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(true); conn.setAllowUserInteraction(true); conn.setFollowRedirects(true); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(strPostString); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String s = ""; String sRet = ""; while ((s = in.readLine()) != null) { sRet += s; } in.close(); return sRet; } catch (MalformedURLException e) { System.out.println("Internal Error. Malformed URL."); e.printStackTrace(); } catch (IOException e) { System.out.println("Internal I/O Error."); e.printStackTrace(); } return ""; }
11
Code Sample 1: public void create_list() { try { String data = URLEncoder.encode("PHPSESSID", "UTF-8") + "=" + URLEncoder.encode(this.get_session(), "UTF-8"); URL url = new URL(URL_LOLA + FILE_CREATE_LIST); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; line = rd.readLine(); wr.close(); rd.close(); System.out.println("Gene list saved in LOLA"); } catch (Exception e) { System.out.println("error in createList()"); e.printStackTrace(); } } Code Sample 2: private void calculateCoverageAndSpecificity(String mainCat) throws IOException, JSONException { for (String cat : Rules.categoryTree.get(mainCat)) { for (String queryString : Rules.queries.get(cat)) { String urlEncodedQueryString = URLEncoder.encode(queryString, "UTF-8"); URL url = new URL("http://boss.yahooapis.com/ysearch/web/v1/" + urlEncodedQueryString + "?appid=" + yahoo_ap_id + "&count=4&format=json&sites=" + site); URLConnection con = url.openConnection(); String line; StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } String response = builder.toString(); JSONObject json = new JSONObject(response); JSONObject jsonObject = json.getJSONObject("ysearchresponse"); String totalhits = jsonObject.getString("totalhits"); long totalhitsLong = Long.parseLong(totalhits); QueryInfo qinfo = new QueryInfo(queryString, totalhitsLong); queryInfoMap.put(queryString, qinfo); cov.put(cat, cov.get(cat) + totalhitsLong); if (totalhitsLong == 0) { continue; } ja = jsonObject.getJSONArray("resultset_web"); for (int j = 0; j < ja.length(); j++) { JSONObject k = ja.getJSONObject(j); String dispurl = filterBold(k.getString("url")); qinfo.addUrl(dispurl); } } } calculateSpecificity(mainCat); }
00
Code Sample 1: ServiceDescription getServiceDescription() throws ConfigurationException { final XPath pathsXPath = this.xPathFactory.newXPath(); try { final Node serviceDescriptionNode = (Node) pathsXPath.evaluate(ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration, XPathConstants.NODE); final String title = getMandatoryElementText(serviceDescriptionNode, ConfigurationFileTagsV1.TITLE_ELEMENT); ServiceDescription.Builder builder = new ServiceDescription.Builder(title, Migrate.class.getCanonicalName()); Property[] serviceProperties = getServiceProperties(serviceDescriptionNode); builder.author(getMandatoryElementText(serviceDescriptionNode, ConfigurationFileTagsV1.CREATOR_ELEMENT)); builder.classname(this.canonicalServiceName); builder.description(getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.DESCRIPTION_ELEMENT)); final String serviceVersion = getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.VERSION_ELEMENT); final Tool toolDescription = getToolDescriptionElement(serviceDescriptionNode); String identifier = getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.IDENTIFIER_ELEMENT); if (identifier == null || "".equals(identifier)) { try { final MessageDigest identDigest = MessageDigest.getInstance("MD5"); identDigest.update(this.canonicalServiceName.getBytes()); final String versionInfo = (serviceVersion != null) ? serviceVersion : ""; identDigest.update(versionInfo.getBytes()); final URI toolIDURI = toolDescription.getIdentifier(); final String toolIdentifier = toolIDURI == null ? "" : toolIDURI.toString(); identDigest.update(toolIdentifier.getBytes()); final BigInteger md5hash = new BigInteger(identDigest.digest()); identifier = md5hash.toString(16); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException(nsae); } } builder.identifier(identifier); builder.version(serviceVersion); builder.tool(toolDescription); builder.instructions(getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.INSTRUCTIONS_ELEMENT)); builder.furtherInfo(getOptionalURIElement(serviceDescriptionNode, ConfigurationFileTagsV1.FURTHER_INFO_ELEMENT)); builder.logo(getOptionalURIElement(serviceDescriptionNode, ConfigurationFileTagsV1.LOGO_ELEMENT)); builder.serviceProvider(this.serviceProvider); final DBMigrationPathFactory migrationPathFactory = new DBMigrationPathFactory(this.configuration); final MigrationPaths migrationPaths = migrationPathFactory.getAllMigrationPaths(); builder.paths(MigrationPathConverter.toPlanetsPaths(migrationPaths)); builder.inputFormats(migrationPaths.getInputFormatURIs().toArray(new URI[0])); builder.parameters(getUniqueParameters(migrationPaths)); builder.properties(serviceProperties); return builder.build(); } catch (XPathExpressionException xPathExpressionException) { throw new ConfigurationException(String.format("Failed parsing the '%s' element in the '%s' element.", ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration.getNodeName()), xPathExpressionException); } catch (NullPointerException nullPointerException) { throw new ConfigurationException(String.format("Failed parsing the '%s' element in the '%s' element.", ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration.getNodeName()), nullPointerException); } } Code Sample 2: protected void writeGZippedBytes(byte array[], TupleOutput out) { if (array == null || array.length == 0) { out.writeBoolean(false); writeBytes(array, out); return; } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(array.length); GZIPOutputStream gzout = new GZIPOutputStream(baos); ByteArrayInputStream bais = new ByteArrayInputStream(array); IOUtils.copyTo(bais, gzout); gzout.finish(); gzout.close(); bais.close(); byte compressed[] = baos.toByteArray(); if (compressed.length < array.length) { out.writeBoolean(true); writeBytes(compressed, out); } else { out.writeBoolean(false); writeBytes(array, out); } } catch (IOException err) { throw new RuntimeException(err); } }
00
Code Sample 1: public static String getMD5(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] digest = md.digest(); String out = ""; for (int i = 0; i < digest.length; i++) { out += digest[i]; } return out; } catch (NoSuchAlgorithmException e) { System.err.println("Manca l'MD5 (piuttosto strano)"); } return ""; } Code Sample 2: private void fileCopy(final File src, final File dest) throws IOException { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
11
Code Sample 1: public static void copyFile5(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copyLarge(in, out); in.close(); out.close(); } Code Sample 2: public String copyImages(Document doc, String sXML, String newPath, String tagName, String itemName) { NodeList nl = null; Node n = null; NamedNodeMap nnp = null; Node nsrc = null; URL url = null; String sFilename = ""; String sNewPath = ""; int index; String sOldPath = ""; try { nl = doc.getElementsByTagName(tagName); for (int i = 0; i < nl.getLength(); i++) { n = nl.item(i); nnp = n.getAttributes(); nsrc = nnp.getNamedItem(itemName); String sTemp = nsrc.getTextContent(); url = new URL("file", "localhost", sTemp); sOldPath = url.getPath(); sOldPath = sOldPath.replace('/', File.separatorChar); int indexFirstSlash = sOldPath.indexOf(File.separatorChar); String sSourcePath; if (itemName.equals("data")) sSourcePath = sOldPath; else sSourcePath = sOldPath.substring(indexFirstSlash + 1); index = sOldPath.lastIndexOf(File.separatorChar); sFilename = sOldPath.substring(index + 1); sNewPath = newPath + sFilename; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sSourcePath).getChannel(); out = new FileOutputStream(sNewPath).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(); } sXML = sXML.replace(nsrc.getTextContent(), sFilename); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sXML; }
00
Code Sample 1: public Set<Plugin<?>> loadPluginImplementationMetaData() throws PluginRegistryException { try { final Enumeration<URL> urls = JavaSystemHelper.getResources(pluginImplementationMetaInfPath); pluginImplsSet.clear(); if (urls != null) { while (urls.hasMoreElements()) { final URL url = urls.nextElement(); echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.found", "classes", url.getPath())); InputStream resourceInput = null; Reader reader = null; BufferedReader buffReader = null; String line; try { resourceInput = url.openStream(); reader = new InputStreamReader(resourceInput); buffReader = new BufferedReader(reader); line = buffReader.readLine(); while (line != null) { try { pluginImplsSet.add(inspectPluginImpl(Class.forName(line.trim()))); echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.processing", "class", line)); line = buffReader.readLine(); } catch (final ClassNotFoundException cnfe) { throw new PluginRegistryException("plugin.error.load.classnotfound", cnfe, pluginImplementationMetaInfPath, line); } catch (final LinkageError ncfe) { if (LOGGER.isDebugEnabled()) { echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.linkageError", "class", line, ncfe.getMessage())); } line = buffReader.readLine(); } } } catch (final IOException ioe) { throw new PluginRegistryException("plugin.error.load.ioe", ioe, url.getFile(), ioe.getMessage()); } finally { if (buffReader != null) { buffReader.close(); } if (reader != null) { reader.close(); } if (resourceInput != null) { resourceInput.close(); } } } } return Collections.unmodifiableSet(pluginImplsSet); } catch (final IOException ioe) { throw new PluginRegistryException("plugin.error.load.ioe", ioe, pluginImplementationMetaInfPath, ioe.getMessage()); } } Code Sample 2: public static byte[] getHashedID(String ID) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(ID.getBytes()); byte[] digest = md5.digest(); byte[] bytes = new byte[WLDB_ID_SIZE]; for (int i = 0; i < bytes.length; i++) { bytes[i] = digest[i]; } return bytes; } catch (NoSuchAlgorithmException exception) { System.err.println("Java VM is not compatible"); return null; } }
00
Code Sample 1: public static int unzipFile(File file_input, File dir_output) { ZipInputStream zip_in_stream; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in); zip_in_stream = new ZipInputStream(source); } catch (IOException e) { return STATUS_IN_FAIL; } byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; do { try { ZipEntry zip_entry = zip_in_stream.getNextEntry(); if (zip_entry == null) break; File output_file = new File(dir_output, zip_entry.getName()); FileOutputStream out = new FileOutputStream(output_file); BufferedOutputStream destination = new BufferedOutputStream(out, BUF_SIZE); while ((len = zip_in_stream.read(input_buffer, 0, BUF_SIZE)) != -1) destination.write(input_buffer, 0, len); destination.flush(); out.close(); } catch (IOException e) { return STATUS_GUNZIP_FAIL; } } while (true); try { zip_in_stream.close(); } catch (IOException e) { } return STATUS_OK; } Code Sample 2: public static String getKeyWithRightLength(final String key, int keyLength) { if (keyLength > 0) { if (key.length() == keyLength) { return key; } else { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { return ""; } md.update(key.getBytes()); byte[] hash = md.digest(); if (keyLength > 20) { byte nhash[] = new byte[keyLength]; for (int i = 0; i < keyLength; i++) { nhash[i] = hash[i % 20]; } hash = nhash; } return new String(hash).substring(0, keyLength); } } else { return key; } }
11
Code Sample 1: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); } Code Sample 2: public static void fileCopy(final File src, final File dest, final boolean overwrite) throws IOException { if (!dest.exists() || (dest.exists() && overwrite)) { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } }
11
Code Sample 1: private void copy(File fromFile, File toFile) throws IOException { String fromFileName = fromFile.getName(); File tmpFile = new File(fromFileName); String toFileName = toFile.getName(); if (!tmpFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!tmpFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!tmpFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(tmpFile); File toF = new File(toFile.getCanonicalPath()); if (!toF.exists()) ; toF.createNewFile(); if (!SBCMain.DEBUG_MODE) to = new FileOutputStream(toFile); else to = new FileOutputStream(toF); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
11
Code Sample 1: 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"); } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { try { FileReader inf = new FileReader(in); OutputStreamWriter outf = new OutputStreamWriter(new FileOutputStream(out), "UTF-8"); int c; while ((c = inf.read()) != -1) outf.write(c); inf.close(); outf.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: @Override public Object execute(ExecutionEvent event) throws ExecutionException { URL url; try { url = new URL("platform:/plugin/de.vogella.rcp.plugin.filereader/files/test.txt"); InputStream inputStream = url.openConnection().getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } catch (IOException e) { e.printStackTrace(); } return null; } Code Sample 2: private String hashMD5(String strToHash) throws Exception { try { byte[] bHash = new byte[strToHash.length() * 2]; MessageDigest md = MessageDigest.getInstance("MD5"); md.update(strToHash.getBytes("UTF-16LE")); bHash = md.digest(); StringBuffer hexString = new StringBuffer(); for (byte element : bHash) { String strTemp = Integer.toHexString(element); hexString.append(strTemp.replaceAll("f", "")); } return hexString.toString(); } catch (NoSuchAlgorithmException duu) { throw new Exception("NoSuchAlgorithmException: " + duu.getMessage()); } }
00
Code Sample 1: private BufferedReader getReader(final String fileUrl) throws IOException { InputStreamReader reader; try { reader = new FileReader(fileUrl); } catch (FileNotFoundException e) { URL url = new URL(fileUrl); reader = new InputStreamReader(url.openStream()); } return new BufferedReader(reader); } Code Sample 2: public static String encrypt32(String plainText) { String str = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } str = buf.toString(); System.out.println("result: " + buf.toString()); System.out.println("result: " + buf.toString().substring(8, 24)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return str; } return str; }
11
Code Sample 1: public void sendFile(File file, String filename, String contentType) throws SearchLibException { response.setContentType(contentType); response.addHeader("Content-Disposition", "attachment; filename=" + filename); FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); ServletOutputStream outputStream = getOutputStream(); IOUtils.copy(inputStream, outputStream); outputStream.close(); } catch (FileNotFoundException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } finally { if (inputStream != null) IOUtils.closeQuietly(inputStream); } } Code Sample 2: @Override public void run() { try { FileChannel out = new FileOutputStream(outputfile).getChannel(); long pos = 0; status.setText("Slučovač: Proces Slučování spuštěn.. Prosím čekejte.."); for (int i = 1; i <= noofparts; i++) { FileChannel in = new FileInputStream(originalfilename.getAbsolutePath() + "." + "v" + i).getChannel(); status.setText("Slučovač: Slučuji část " + i + ".."); this.splitsize = in.size(); out.transferFrom(in, pos, splitsize); pos += splitsize; in.close(); if (deleteOnFinish) new File(originalfilename + ".v" + i).delete(); pb.setValue(100 * i / noofparts); } out.close(); status.setText("Slučovač: Hotovo.."); JOptionPane.showMessageDialog(null, "Sloučeno!", "Slučovač", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e) { } }
11
Code Sample 1: public String getMd5CodeOf16(String str) { StringBuffer buf = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte b[] = md.digest(); int i; buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { return buf.toString().substring(8, 24); } } Code Sample 2: public String getMD5(String data) { try { MessageDigest md5Algorithm = MessageDigest.getInstance("MD5"); md5Algorithm.update(data.getBytes(), 0, data.length()); byte[] digest = md5Algorithm.digest(); StringBuffer hexString = new StringBuffer(); String hexDigit = null; for (int i = 0; i < digest.length; i++) { hexDigit = Integer.toHexString(0xFF & digest[i]); if (hexDigit.length() < 2) { hexDigit = "0" + hexDigit; } hexString.append(hexDigit); } return hexString.toString(); } catch (NoSuchAlgorithmException ne) { return data; } }
11
Code Sample 1: @SuppressWarnings("unchecked") public static void zip(String input, OutputStream out) { File file = new File(input); ZipOutputStream zip = null; FileInputStream in = null; try { if (file.exists()) { Collection<File> items = new ArrayList(); if (file.isDirectory()) { items = FileUtils.listFiles(file, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); zip = new ZipOutputStream(out); zip.putNextEntry(new ZipEntry(file.getName() + "/")); Iterator iter = items.iterator(); while (iter.hasNext()) { File item = (File) iter.next(); in = new FileInputStream(item); zip.putNextEntry(new ZipEntry(file.getName() + "/" + item.getName())); IOUtils.copy(in, zip); IOUtils.closeQuietly(in); zip.closeEntry(); } IOUtils.closeQuietly(zip); } } else { log.info("-->>���ļ���û���ļ�"); } } catch (Exception e) { log.error("����ѹ��" + input + "�������", e); throw new RuntimeException("����ѹ��" + input + "�������", e); } finally { try { if (null != zip) { zip.close(); zip = null; } if (null != in) { in.close(); in = null; } } catch (Exception e) { log.error("�ر��ļ�������"); } } } Code Sample 2: public Vector split() { File nextFile = new File(filename); long fileSize = nextFile.length(); long parts = fileSize / splitSize; Vector vec = new Vector(new Long(parts).intValue()); if (debug) { System.out.println("File: " + nextFile.getName() + "\nfileSize: " + fileSize + "\nsplitSize: " + splitSize + "\nparts: " + parts); } if (fileSize % splitSize > 0) { parts++; } try { FileInputStream fis = new FileInputStream(nextFile); DataInputStream dis = new DataInputStream(fis); long bytesRead = 0; File destinationDirectory = new File(nextFile.getParent()); if (!destinationDirectory.exists()) { destinationDirectory.mkdir(); } for (long k = 0; k < parts; k++) { if (debug) { System.out.println("Splitting parts: " + nextFile.getName() + " into part " + k); } String filePartName = nextFile.getName(); filePartName = filePartName + "." + String.valueOf(k); File outputFile = new File(destinationDirectory, filePartName); FileOutputStream fos = new FileOutputStream(outputFile); DataOutputStream dos = new DataOutputStream(fos); long bytesWritten = 0; while ((bytesWritten < splitSize) && (bytesRead < fileSize)) { dos.writeByte(dis.readByte()); bytesRead++; bytesWritten++; } dos.close(); vec.addElement(outputFile.getAbsolutePath()); if (debug) { System.out.println("Wrote " + bytesWritten + " bytes." + outputFile.getName() + " created."); } } } catch (FileNotFoundException fnfe) { System.err.println("FileNotFoundException: " + fnfe.getMessage()); vec = null; } catch (IOException ioe) { System.err.println("IOException: " + ioe.getMessage()); vec = null; } return vec; }
00
Code Sample 1: public static String machineInfo() { StringBuilder machineInfo = new StringBuilder(); try { Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement(); if ("eth0".equals(networkInterface.getDisplayName())) { for (byte b : networkInterface.getHardwareAddress()) { StringTools.appendWithDelimiter(machineInfo, String.format("%02x", b).toUpperCase(), ":"); } machineInfo.append("\n"); break; } } } catch (IOException x) { System.out.println("LicenseTools.machineInfo: " + x.getMessage()); x.printStackTrace(); } if (machineInfo.length() == 0) { return null; } String info = machineInfo.toString(); try { MessageDigest messageDigest = MessageDigest.getInstance("MD5", "SUN"); messageDigest.update(info.getBytes()); byte[] md5 = messageDigest.digest(info.getBytes()); return new String(Base64.encodeBase64(md5)); } catch (Exception x) { System.out.println("LicenseTools.machineInfo: " + x.getMessage()); x.printStackTrace(); } return null; } Code Sample 2: public static Chunk updateLastSend(Chunk c) throws Exception { DBConnectionManager dbm = null; Connection conn = null; PreparedStatement stmt = null; Chunk ret = null; String SQL = "UPDATE CHUNK SET SENT=? WHERE FILEHASH=? AND STARTOFF=? AND LENGTH=?"; log.debug("update chunk last sent for chunk " + c.getHash() + " startoff " + c.getStartOffset()); try { dbm = DBConnectionManager.getInstance(); conn = dbm.getConnection("satmule"); stmt = conn.prepareStatement(SQL); stmt.setDate(1, new java.sql.Date(c.getLastSend().getTime())); stmt.setString(2, c.getHash()); stmt.setLong(3, c.getStartOffset()); stmt.setLong(4, c.getSize()); stmt.executeUpdate(); conn.commit(); stmt.close(); dbm.freeConnection("satmule", conn); } catch (Exception e) { log.error("Error while updating chunk " + c.getHash() + "offset:" + c.getStartOffset() + "SQL error: " + SQL, e); Exception excep; if (dbm == null) excep = new Exception("Could not obtain pool object DbConnectionManager"); else if (conn == null) excep = new Exception("The Db connection pool could not obtain a database connection"); else { conn.rollback(); excep = new Exception("SQL Error : " + SQL + " error: " + e); dbm.freeConnection("satmule", conn); } throw excep; } return ret; }
00
Code Sample 1: private void populateAPI(API api) { try { if (api.isPopulated()) { log.traceln("Skipping API " + api.getName() + " (already populated)"); return; } api.setPopulated(true); String sql = "update API set populated=1 where name=?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, api.getName()); pstmt.executeUpdate(); pstmt.close(); storePackagesAndClasses(api); conn.commit(); } catch (SQLException ex) { log.error("Store (api: " + api.getName() + ") failed!"); DBUtils.logSQLException(ex); log.error("Rolling back.."); try { conn.rollback(); } catch (SQLException inner_ex) { log.error("rollback failed!"); } } } Code Sample 2: private StringBuffer hashPassword(StringBuffer password, String mode) { MessageDigest m = null; StringBuffer hash = new StringBuffer(); try { m = MessageDigest.getInstance(mode); m.update(password.toString().getBytes("UTF8")); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] digest = m.digest(); for (int i = 0; i < digest.length; i++) { String hex = Integer.toHexString(digest[i]); if (hex.length() == 1) hex = "0" + hex; hex = hex.substring(hex.length() - 2); hash.append(hex); } return hash; }
00
Code Sample 1: @Override protected byte[] fetch0() throws IOException { if (sourceFile.getProtocol().equalsIgnoreCase("jar")) { throw new IOException("Jar protocol unsupported!"); } else { URL url; if (sourceFile.getFile().endsWith(CLASS_FILE_EXTENSION)) { url = sourceFile; } else { url = new URL(sourceFile, className.replace(PACKAGE_SEPARATOR, URL_DIRECTORY_SEPARATOR) + CLASS_FILE_EXTENSION); } InputStream stream = url.openStream(); try { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[PACKET_SIZE]; int bytesRead; while ((bytesRead = stream.read(buffer, 0, buffer.length)) != -1) { output.write(buffer, 0, bytesRead); } return output.toByteArray(); } finally { stream.close(); } } } Code Sample 2: private String addEqError(EquivalencyException e, int namespaceId) throws SQLException { List l = Arrays.asList(e.getListOfEqErrors()); int size = l.size(); String sql = getClassifyDAO().getStatement(TABLE_KEY, "ADD_CLASSIFY_EQ_ERROR"); PreparedStatement ps = null; conn.setAutoCommit(false); try { deleteCycleError(namespaceId); deleteEqError(namespaceId); long conceptGID1 = -1; long conceptGID2 = -1; ps = conn.prepareStatement(sql); for (int i = 0; i < l.size(); i++) { EqError error = (EqError) l.get(i); ConceptRef ref1 = error.getConcept1(); ConceptRef ref2 = error.getConcept2(); conceptGID1 = getConceptGID(ref1, namespaceId); conceptGID2 = getConceptGID(ref2, namespaceId); ps.setLong(1, conceptGID1); ps.setLong(2, conceptGID2); ps.setInt(3, namespaceId); int result = ps.executeUpdate(); if (result == 0) { throw new SQLException("unable to add eq error: " + sql); } } conn.commit(); return "EquivalencyException: Concept: " + conceptGID1 + " namespaceId: " + namespaceId + " conceptGID2: " + conceptGID2 + ((size > 1) ? "...... more" : ""); } catch (SQLException sqle) { conn.rollback(); throw sqle; } catch (Exception ex) { conn.rollback(); throw toSQLException(ex, "cannot add eq errors"); } finally { conn.setAutoCommit(true); if (ps != null) { ps.close(); } } }
11
Code Sample 1: private void writeAndCheckFile(DataFileReader reader, String base, String path, String hash, Reference ref, boolean hashall) throws Exception { Data data = ref.data; File file = new File(base + path); file.getParentFile().mkdirs(); if (Debug.level > 1) System.err.println("read file " + data.file + " at index " + data.index); OutputStream output = new FileOutputStream(file); if (hashall) output = new DigestOutputStream(output, MessageDigest.getInstance("MD5")); reader.read(output, data.index, data.file); output.close(); if (hashall) { String filehash = StringUtils.toHex(((DigestOutputStream) output).getMessageDigest().digest()); if (!hash.equals(filehash)) throw new RuntimeException("hash wasn't equal for " + file); } file.setLastModified(ref.lastmod); if (file.length() != data.size) throw new RuntimeException("corrupted file " + file); } 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: List HttpPost(URL url, List requestList) throws IOException { List responseList = new ArrayList(); URLConnection con; BufferedReader in; OutputStreamWriter out; StringBuffer req; String line; logInfo("HTTP POST: " + url); con = url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); out = new OutputStreamWriter(con.getOutputStream()); req = new StringBuffer(); for (int i = 0, n = requestList.size(); i < n; i++) { if (i != 0) req.append("&"); req.append(((HttpHeader) requestList.get(i)).key); req.append("="); if (((HttpHeader) requestList.get(i)).unicode) { StringBuffer tmp = new StringBuffer(200); byte[] uniBytes = ((HttpHeader) requestList.get(i)).value.getBytes("UnicodeBigUnmarked"); for (int j = 0; j < uniBytes.length; j++) tmp.append(Integer.toHexString(uniBytes[j]).length() == 1 ? "0" + Integer.toHexString(uniBytes[j]) : Integer.toHexString(uniBytes[j])); req.append(tmp.toString().replaceAll("ff", "")); } else req.append(((HttpHeader) requestList.get(i)).value); } out.write(req.toString()); out.flush(); out.close(); in = new BufferedReader(new InputStreamReader((con.getInputStream()))); while ((line = in.readLine()) != null) responseList.add(line); in.close(); return responseList; } 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: @Override protected boolean sendBytes(byte[] data, int offset, int length) { try { String hex = toHex(data, offset, length); URL url = new URL(this.endpoint, "?raw=" + hex); System.out.println("Connecting to " + url); URLConnection conn = url.openConnection(); conn.connect(); Object content = conn.getContent(); return true; } catch (IOException ex) { LOGGER.warning(ex.getMessage()); return false; } } Code Sample 2: public static void ExtraeArchivoJAR(String Archivo, String DirJAR, String DirDestino) { FileInputStream entrada = null; FileOutputStream salida = null; try { File f = new File(DirDestino + separador + Archivo); try { f.createNewFile(); } catch (Exception sad) { sad.printStackTrace(); } InputStream source = OP_Proced.class.getResourceAsStream(DirJAR + "/" + Archivo); BufferedInputStream in = new BufferedInputStream(source); FileOutputStream out = new FileOutputStream(f); int ch; while ((ch = in.read()) != -1) out.write(ch); in.close(); out.close(); } catch (IOException ex) { System.out.println(ex); } finally { if (entrada != null) { try { entrada.close(); } catch (IOException ex) { ex.printStackTrace(); } } if (salida != null) { try { salida.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
11
Code Sample 1: private void renameTo(File from, File to) { if (!from.exists()) return; if (to.exists()) to.delete(); boolean worked = false; try { worked = from.renameTo(to); } catch (Exception e) { database.logError(this, "" + e, null); } if (!worked) { database.logWarning(this, "Could not rename GEDCOM to " + to.getAbsolutePath(), null); try { to.delete(); final FileReader in = new FileReader(from); final FileWriter out = new FileWriter(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); from.delete(); } catch (Exception e) { database.logError(this, "" + e, null); } } } Code Sample 2: private static void copy(File source, File target) throws IOException { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(source)); os = new BufferedOutputStream(new FileOutputStream(target)); int b; while ((b = is.read()) > -1) os.write(b); } finally { try { if (is != null) is.close(); } catch (IOException ignore) { } try { if (os != null) os.close(); } catch (IOException ignore) { } } }
00
Code Sample 1: public static String md5Crypt(final byte[] key, final byte[] salt) throws NoSuchAlgorithmException { if (key == null || key.length == 0) { throw new IllegalArgumentException("Argument 'key' cannot be null or an empty array."); } if (salt == null || salt.length == 0) { throw new IllegalArgumentException("Argument 'salt' cannot be null or an empty array."); } final MessageDigest _md = MessageDigest.getInstance("MD5"); _md.update(key); _md.update(MAGIC.getBytes()); _md.update(salt); final MessageDigest md2 = MessageDigest.getInstance("MD5"); md2.update(key); md2.update(salt); md2.update(key); byte[] abyFinal = md2.digest(); for (int n = key.length; n > 0; n -= 16) { _md.update(abyFinal, 0, n > 16 ? 16 : n); } abyFinal = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; for (int j = 0, i = key.length; i != 0; i >>>= 1) { if ((i & 1) == 1) _md.update(abyFinal, j, 1); else _md.update(key, j, 1); } final StringBuilder sbPasswd = new StringBuilder(); sbPasswd.append(MAGIC); sbPasswd.append(new String(salt)); sbPasswd.append('$'); abyFinal = _md.digest(); for (int n = 0; n < 1000; n++) { final MessageDigest md3 = MessageDigest.getInstance("MD5"); if ((n & 1) != 0) { md3.update(key); } else { md3.update(abyFinal); } if ((n % 3) != 0) { md3.update(salt); } if ((n % 7) != 0) { md3.update(key); } if ((n & 1) != 0) { md3.update(abyFinal); } else { md3.update(key); } abyFinal = md3.digest(); } int[] anFinal = new int[] { (abyFinal[0] & 0x7f) | (abyFinal[0] & 0x80), (abyFinal[1] & 0x7f) | (abyFinal[1] & 0x80), (abyFinal[2] & 0x7f) | (abyFinal[2] & 0x80), (abyFinal[3] & 0x7f) | (abyFinal[3] & 0x80), (abyFinal[4] & 0x7f) | (abyFinal[4] & 0x80), (abyFinal[5] & 0x7f) | (abyFinal[5] & 0x80), (abyFinal[6] & 0x7f) | (abyFinal[6] & 0x80), (abyFinal[7] & 0x7f) | (abyFinal[7] & 0x80), (abyFinal[8] & 0x7f) | (abyFinal[8] & 0x80), (abyFinal[9] & 0x7f) | (abyFinal[9] & 0x80), (abyFinal[10] & 0x7f) | (abyFinal[10] & 0x80), (abyFinal[11] & 0x7f) | (abyFinal[11] & 0x80), (abyFinal[12] & 0x7f) | (abyFinal[12] & 0x80), (abyFinal[13] & 0x7f) | (abyFinal[13] & 0x80), (abyFinal[14] & 0x7f) | (abyFinal[14] & 0x80), (abyFinal[15] & 0x7f) | (abyFinal[15] & 0x80) }; to64(sbPasswd, anFinal[0] << 16 | anFinal[6] << 8 | anFinal[12], 4); to64(sbPasswd, anFinal[1] << 16 | anFinal[7] << 8 | anFinal[13], 4); to64(sbPasswd, anFinal[2] << 16 | anFinal[8] << 8 | anFinal[14], 4); to64(sbPasswd, anFinal[3] << 16 | anFinal[9] << 8 | anFinal[15], 4); to64(sbPasswd, anFinal[4] << 16 | anFinal[10] << 8 | anFinal[5], 4); to64(sbPasswd, anFinal[11], 2); return sbPasswd.toString(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: private static byte[] finalizeStringHash(String loginHash) throws NoSuchAlgorithmException { MessageDigest md5Hasher; md5Hasher = MessageDigest.getInstance("MD5"); md5Hasher.update(loginHash.getBytes()); md5Hasher.update(LOGIN_FINAL_SALT); return md5Hasher.digest(); } Code Sample 2: private void unzipResource(final String resourceName, final File targetDirectory) throws IOException { assertTrue(resourceName.startsWith("/")); final URL resource = this.getClass().getResource(resourceName); assertNotNull("Expected '" + resourceName + "' not found.", resource); assertTrue(targetDirectory.isAbsolute()); FileUtils.deleteDirectory(targetDirectory); assertTrue(targetDirectory.mkdirs()); ZipInputStream in = null; boolean suppressExceptionOnClose = true; try { in = new ZipInputStream(resource.openStream()); ZipEntry e; while ((e = in.getNextEntry()) != null) { if (e.isDirectory()) { continue; } final File dest = new File(targetDirectory, e.getName()); assertTrue(dest.isAbsolute()); OutputStream out = null; try { out = FileUtils.openOutputStream(dest); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } suppressExceptionOnClose = true; } catch (final IOException ex) { if (!suppressExceptionOnClose) { throw ex; } } } in.closeEntry(); } suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } }
00
Code Sample 1: public final void testT4CClientWriter() throws Exception { InputStream is = ClassLoader.getSystemResourceAsStream(this.testFileName); T4CClientReader reader = new T4CClientReader(is, rc); File tmpFile = File.createTempFile("barde", ".log", this.tmpDir); System.out.println("tmp=" + tmpFile.getAbsolutePath()); T4CClientWriter writer = new T4CClientWriter(new FileOutputStream(tmpFile), rc); for (Message m = reader.read(); m != null; m = reader.read()) writer.write(m); writer.close(); InputStream fa = ClassLoader.getSystemResourceAsStream(this.testFileName); FileInputStream fb = new FileInputStream(tmpFile); for (int ba = fa.read(); ba != -1; ba = fa.read()) assertEquals(ba, fb.read()); } Code Sample 2: protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletConfig config = getServletConfig(); ServletContext context = config.getServletContext(); try { String driver = context.getInitParameter("driver"); Class.forName(driver); String dbURL = context.getInitParameter("db"); String username = context.getInitParameter("username"); String password = ""; connection = DriverManager.getConnection(dbURL, username, password); } catch (ClassNotFoundException e) { System.out.println("Database driver not found."); } catch (SQLException e) { System.out.println("Error opening the db connection: " + e.getMessage()); } String action = ""; HttpSession session = request.getSession(); session.setMaxInactiveInterval(300); if (request.getParameter("action") != null) { action = request.getParameter("action"); } else { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/login.jsp"); dispatcher.forward(request, response); return; } if (action.equals("login")) { String username = request.getParameter("username"); String password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { error = "There was an error encrypting password."; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } try { md.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { error = "There was an error encrypting password."; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } String encrypted_password = (new BASE64Encoder()).encode(md.digest()); try { String sql = "SELECT * FROM person WHERE email LIKE '" + username + "' AND password='" + encrypted_password + "'"; dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); if (dbResultSet.next()) { Person person = new Person(dbResultSet.getString("fname"), dbResultSet.getString("lname"), dbResultSet.getString("address1"), dbResultSet.getString("address2"), dbResultSet.getString("city"), dbResultSet.getString("state"), dbResultSet.getString("zip"), dbResultSet.getString("email"), dbResultSet.getString("password"), dbResultSet.getInt("is_admin")); String member_type = dbResultSet.getString("member_type"); String person_id = Integer.toString(dbResultSet.getInt("id")); session.setAttribute("person", person); session.setAttribute("member_type", member_type); session.setAttribute("person_id", person_id); } else { notice = "Your username and/or password is incorrect."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } catch (SQLException e) { error = "There was an error trying to login. (SQL Statement)"; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Unable to log you in. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/login.jsp"); dispatcher.forward(request, response); return; } }
00
Code Sample 1: public void loadLicenceText() { try { URL url = this.getClass().getResource("/licences/" + this.files[this.licence_text_id]); InputStreamReader ins = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(ins); String line; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } this.licence_text = sb.toString(); } catch (Exception ex) { System.out.println("LicenceInfo::error reading. Ex: " + ex); ex.printStackTrace(); } } Code Sample 2: public URLConnection makeURLcon() { URI uri; URL url; try { uri = new URI(this.URLString); url = uri.toURL(); this.urlcon = (HttpURLConnection) url.openConnection(); } catch (final URISyntaxException e) { e.printStackTrace(); } catch (final MalformedURLException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } return this.urlcon; }
00
Code Sample 1: public static void copyFile(File in, File out) throws Exception { Permissions before = getFilePermissons(in); FileChannel inFile = new FileInputStream(in).getChannel(); FileChannel outFile = new FileOutputStream(out).getChannel(); inFile.transferTo(0, inFile.size(), outFile); inFile.close(); outFile.close(); setFilePermissions(out, before); } Code Sample 2: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final EditText eText = (EditText) findViewById(R.id.address); final Button button = (Button) findViewById(R.id.ButtonGo); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("m", "login")); nameValuePairs.add(new BasicNameValuePair("c", "User")); nameValuePairs.add(new BasicNameValuePair("password", "cloudisgreat")); nameValuePairs.add(new BasicNameValuePair("alias", "cs588")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); String result = ""; try { HttpResponse response = httpclient.execute(httppost); result = EntityUtils.toString(response.getEntity()); } catch (Exception e) { result = e.getMessage(); } LayoutInflater inflater = (LayoutInflater) WebTest.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View layout = inflater.inflate(R.layout.window1, null); final PopupWindow popup = new PopupWindowTest(layout, 100, 100); Button b = (Button) layout.findViewById(R.id.test_button); b.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.d("Debug", "Button activate"); popup.dismiss(); return false; } }); popup.showAtLocation(layout, Gravity.CENTER, 0, 0); View layout2 = inflater.inflate(R.layout.window1, null); final PopupWindow popup2 = new PopupWindowTest(layout2, 100, 100); TextView tview = (TextView) layout2.findViewById(R.id.pagetext); tview.setText(result); popup2.showAtLocation(layout, Gravity.CENTER, 50, -90); } catch (Exception e) { Log.d("Debug", e.toString()); } } }); }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static long copy(File src, long amount, File dst) { final int BUFFER_SIZE = 1024; long amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, (int) Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { close(in); flush(out); close(out); } return amount - amountToRead; }
11
Code Sample 1: public void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { message = ("���Ƶ����ļ���������"); } } Code Sample 2: public String storeUploadedZip(byte[] zip, String name) { List filesToStore = new ArrayList(); int i = 0; ZipInputStream zipIs = new ZipInputStream(new ByteArrayInputStream(zip)); ZipEntry zipEntry = zipIs.getNextEntry(); while (zipEntry != null) { if (zipEntry.isDirectory() == false) { i++; ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(zipIs, baos); baos.close(); } zipIs.closeEntry(); zipEntry = zipIs.getNextEntry(); } }
00
Code Sample 1: public static void executePost(String targetURL, File file, int msec) { URL url; HttpURLConnection connection = null; try { long wrCount = 0; long fileLen = file.length(); log("File length is " + fileLen); log("Sleep " + msec + " between each send"); FileInputStream fis = new FileInputStream(file); url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml"); connection.setRequestProperty("Content-Length", Long.toString(fileLen)); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); OutputStream wr = connection.getOutputStream(); int count = 0; byte[] buffer = new byte[1024 * 10]; while ((count = fis.read(buffer)) != -1) { wr.write(buffer, 0, count); wr.flush(); wrCount += (long) count; log("Progress is " + (wrCount * 100) / fileLen + "%"); Thread.sleep(msec); } wr.close(); fis.close(); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } rd.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return; } Code Sample 2: public static void unzip(final File file, final ZipFile zipFile, final File targetDirectory) throws PtException { LOG.info("Unzipping zip file '" + file.getAbsolutePath() + "' to directory " + "'" + targetDirectory.getAbsolutePath() + "'."); assert (file.exists() && file.isFile()); if (targetDirectory.exists() == false) { LOG.debug("Creating target directory."); if (targetDirectory.mkdirs() == false) { throw new PtException("Could not create target directory at " + "'" + targetDirectory.getAbsolutePath() + "'!"); } } ZipInputStream zipin = null; try { zipin = new ZipInputStream(new FileInputStream(file)); ZipEntry nextZipEntry = zipin.getNextEntry(); while (nextZipEntry != null) { LOG.debug("Unzipping entry '" + nextZipEntry.getName() + "'."); if (nextZipEntry.isDirectory()) { LOG.debug("Skipping directory."); continue; } final File targetFile = new File(targetDirectory, nextZipEntry.getName()); final File parentTargetFile = targetFile.getParentFile(); if (parentTargetFile.exists() == false) { LOG.debug("Creating directory '" + parentTargetFile.getAbsolutePath() + "'."); if (parentTargetFile.mkdirs() == false) { throw new PtException("Could not create target directory at " + "'" + parentTargetFile.getAbsolutePath() + "'!"); } } InputStream input = null; FileOutputStream output = null; try { input = zipFile.getInputStream(nextZipEntry); if (targetFile.createNewFile() == false) { throw new PtException("Could not create target file " + "'" + targetFile.getAbsolutePath() + "'!"); } output = new FileOutputStream(targetFile); byte[] buffer = new byte[BUFFER_SIZE]; int readBytes = input.read(buffer, 0, buffer.length); while (readBytes > 0) { output.write(buffer, 0, readBytes); readBytes = input.read(buffer, 0, buffer.length); } } finally { PtCloseUtil.close(input, output); } nextZipEntry = zipin.getNextEntry(); } } catch (IOException e) { throw new PtException("Could not unzip file '" + file.getAbsolutePath() + "'!", e); } finally { PtCloseUtil.close(zipin); } }
11
Code Sample 1: private void getRandomGUID(boolean secure, Object o) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(o.getClass().getName()); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public final String encrypt(String input) throws Exception { try { MessageDigest messageDigest = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); messageDigest.reset(); messageDigest.update(input.getBytes()); String output = convert(messageDigest.digest()); return output; } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Fatal Error while digesting input string", ex); } } return input; }
00
Code Sample 1: public synchronized long nextValue(final Session session) { if (sequence < seqLimit) { return ++sequence; } else { final MetaDatabase db = MetaTable.DATABASE.of(table); Connection connection = null; ResultSet res = null; String sql = null; PreparedStatement statement = null; StringBuilder out = new StringBuilder(64); try { connection = session.getSeqConnection(db); String tableName = db.getDialect().printFullTableName(getTable(), true, out).toString(); out.setLength(0); out.setLength(0); sql = db.getDialect().printSequenceNextValue(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); int i = statement.executeUpdate(); if (i == 0) { out.setLength(0); sql = db.getDialect().printSequenceInit(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); statement.executeUpdate(); } out.setLength(0); sql = db.getDialect().printSequenceCurrentValue(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); res = statement.executeQuery(); res.next(); seqLimit = res.getLong(1); int step = res.getInt(2); maxValue = res.getLong(3); sequence = (seqLimit - step) + 1; if (maxValue != 0L) { if (seqLimit > maxValue) { seqLimit = maxValue; if (sequence > maxValue) { String msg = "The sequence '" + tableName + "' needs to raise the maximum value: " + maxValue; throw new IllegalStateException(msg); } statement.close(); sql = db.getDialect().printSetMaxSequence(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); statement.execute(); } if (maxValue > Long.MAX_VALUE - step) { String msg = "The sequence attribute '" + tableName + ".maxValue' is too hight," + " the recommended maximal value is: " + (Long.MAX_VALUE - step) + " (Long.MAX_VALUE-step)"; LOGGER.log(Level.WARNING, msg); } } connection.commit(); } catch (Throwable e) { if (connection != null) try { connection.rollback(); } catch (SQLException ex) { LOGGER.log(Level.WARNING, "Rollback fails"); } IllegalStateException exception = e instanceof IllegalStateException ? (IllegalStateException) e : new IllegalStateException("ILLEGAL SQL: " + sql, e); throw exception; } finally { MetaDatabase.close(null, statement, res, true); } return sequence; } } Code Sample 2: @Override public void init() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Throwable e) { } try { PopupFactory.setSharedInstance(new PopupFactory()); } catch (Throwable e) { } Container c = getContentPane(); c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS)); String[] labels = getAppletInfo().split("\n"); for (int i = 0; i < labels.length; i++) { c.add(new JLabel((labels[i].length() == 0) ? " " : labels[i])); } new Worker<Drawing>() { @Override protected Drawing construct() throws IOException { Drawing result; System.out.println("getParameter.datafile:" + getParameter("datafile")); if (getParameter("data") != null) { NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), new StringReader(getParameter("data"))); result = (Drawing) domi.readObject(0); } else if (getParameter("datafile") != null) { URL url = new URL(getDocumentBase(), getParameter("datafile")); InputStream in = url.openConnection().getInputStream(); try { NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), in); result = (Drawing) domi.readObject(0); } finally { in.close(); } } else { result = null; } return result; } @Override protected void done(Drawing result) { Container c = getContentPane(); c.setLayout(new BorderLayout()); c.removeAll(); c.add(drawingPanel = new NetPanel()); if (result != null) { Drawing drawing = (Drawing) result; setDrawing(drawing); } } @Override protected void failed(Throwable value) { Container c = getContentPane(); c.setLayout(new BorderLayout()); c.removeAll(); c.add(drawingPanel = new NetPanel()); value.printStackTrace(); getDrawing().add(new TextFigure(value.toString())); value.printStackTrace(); } @Override protected void finished() { Container c = getContentPane(); initDrawing(getDrawing()); c.validate(); } }.start(); }
11
Code Sample 1: public static void main(String[] args) throws IOException { long readfilelen = 0; BufferedRandomAccessFile brafReadFile, brafWriteFile; brafReadFile = new BufferedRandomAccessFile("C:\\WINNT\\Fonts\\STKAITI.TTF"); readfilelen = brafReadFile.initfilelen; brafWriteFile = new BufferedRandomAccessFile(".\\STKAITI.001", "rw", 10); byte buf[] = new byte[1024]; int readcount; long start = System.currentTimeMillis(); while ((readcount = brafReadFile.read(buf)) != -1) { brafWriteFile.write(buf, 0, readcount); } brafWriteFile.close(); brafReadFile.close(); System.out.println("BufferedRandomAccessFile Copy & Write File: " + brafReadFile.filename + " FileSize: " + java.lang.Integer.toString((int) readfilelen >> 1024) + " (KB) " + "Spend: " + (double) (System.currentTimeMillis() - start) / 1000 + "(s)"); java.io.FileInputStream fdin = new java.io.FileInputStream("C:\\WINNT\\Fonts\\STKAITI.TTF"); java.io.BufferedInputStream bis = new java.io.BufferedInputStream(fdin, 1024); java.io.DataInputStream dis = new java.io.DataInputStream(bis); java.io.FileOutputStream fdout = new java.io.FileOutputStream(".\\STKAITI.002"); java.io.BufferedOutputStream bos = new java.io.BufferedOutputStream(fdout, 1024); java.io.DataOutputStream dos = new java.io.DataOutputStream(bos); start = System.currentTimeMillis(); for (int i = 0; i < readfilelen; i++) { dos.write(dis.readByte()); } dos.close(); dis.close(); System.out.println("DataBufferedios Copy & Write File: " + brafReadFile.filename + " FileSize: " + java.lang.Integer.toString((int) readfilelen >> 1024) + " (KB) " + "Spend: " + (double) (System.currentTimeMillis() - start) / 1000 + "(s)"); } Code Sample 2: private static void prepare() { System.err.println("PREPARING-----------------------------------------"); deleteHome(); InputStream configStream = null; FileOutputStream tempStream = null; try { configStream = AllTests.class.getClassLoader().getResourceAsStream("net/sf/archimede/test/resources/repository.xml"); new File("temp").mkdir(); tempStream = new FileOutputStream(new File("temp/repository.xml")); IOUtils.copy(configStream, tempStream); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (configStream != null) { configStream.close(); } } catch (IOException e) { e.printStackTrace(); } finally { if (tempStream != null) { try { tempStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } String repositoryName = "jackrabbit.repository"; Properties jndiProperties = new Properties(); jndiProperties.put("java.naming.provider.url", "http://sf.net/projects/archimede#1"); jndiProperties.put("java.naming.factory.initial", "org.apache.jackrabbit.core.jndi.provider.DummyInitialContextFactory"); startupUtil = new StartupJcrUtil(REPOSITORY_HOME, "temp/repository.xml", repositoryName, jndiProperties); startupUtil.init(); }
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: public static void main(String args[]) { try { URL url = new URL("http://www.hungry.com/"); InputStream stream = url.openStream(); int size = 0; while (-1 != stream.read()) { size++; } stream.close(); System.out.println("PASSED: new URL() size=" + size); } catch (Exception e) { System.out.println("FAILED: " + e); } }
00
Code Sample 1: private void getRandomGuid(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = secureRandom.nextLong(); } else { rand = random.nextLong(); } sbValueBeforeMD5.append(id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); String valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } guid = sb.toString(); } Code Sample 2: public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { InputStream urlStream = url.openStream(); AudioFileFormat fileFormat = null; try { fileFormat = getFMT(urlStream, false); } finally { if (fileFormat == null) { urlStream.close(); } } return new AudioInputStream(urlStream, fileFormat.getFormat(), fileFormat.getFrameLength()); }
11
Code Sample 1: public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { Git git = Git.getCurrent(req.getSession()); GitComponentReader gitReader = git.getComponentReader("warpinjector"); String id = req.getParameter("id"); GitElement element = gitReader.getElement(id); String path = (String) element.getAttribute("targetdir"); File folder = new File(path); PrintWriter out = helper.getPrintWriter(resp); MessageBundle messageBundle = new MessageBundle("net.sf.warpcore.cms/servlets/InjectorServletMessages"); Locale locale = req.getLocale(); helper.header(out, messageBundle, locale); if (git.getUser() == null) { helper.notLoggedIn(out, messageBundle, locale); } else { try { MultiPartRequest request = new MultiPartRequest(req); FileInfo info = request.getFileInfo("userfile"); File file = info.getFile(); out.println("tempfile found: " + file.getPath() + "<br>"); String fileName = info.getFileName(); File target = new File(folder, fileName); out.println("copying tempfile to: " + target.getPath() + "<br>"); FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(target); byte buf[] = new byte[1024]; int n; while ((n = fis.read(buf)) > 0) fos.write(buf, 0, n); fis.close(); fos.close(); out.println("copy successful - deleting old tempfile<br>"); out.println("deletion result. " + file.delete() + "<p>"); out.println(messageBundle.getMessage("Done. The file {0} has been uploaded", new String[] { "'" + fileName + "'" }, locale)); out.println("<p><a href=\"" + req.getRequestURI() + "?id=" + req.getParameter("id") + "\">" + messageBundle.getMessage("Click here to import another file.", locale) + "</a>"); } catch (Exception ex) { out.println(messageBundle.getMessage("An error occured: {0}", new String[] { ex.getMessage() }, locale)); } } helper.footer(out); } Code Sample 2: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String arg = req.getParameter("file"); if (arg == null) { resp.sendError(404, "Missing 'file' Arg"); return; } int mfid = NumberUtils.toInt(arg); Object sageFile = MediaFileAPI.GetMediaFileForID(mfid); if (sageFile == null) { resp.sendError(404, "Sage File not found " + mfid); return; } int seconds = NumberUtils.toInt(req.getParameter("ss"), -1); long offset = NumberUtils.toLong(req.getParameter("sb"), -1); if (seconds < 0 && offset < 0) { resp.sendError(501, "Missing 'ss' or 'sb' args"); return; } int width = NumberUtils.toInt(req.getParameter("w"), 320); int height = NumberUtils.toInt(req.getParameter("h"), 320); File dir = new File(Phoenix.getInstance().getUserCacheDir(), "videothumb/" + mfid); if (!dir.exists()) { dir.mkdirs(); } String prefix = ""; if (offset > 0) { prefix = "O" + offset; } else { prefix = "S" + seconds; } File f = new File(dir, prefix + "_" + width + "_" + height + ".jpg").getCanonicalFile(); if (!f.exists()) { try { generateThumbnailNew(sageFile, f, seconds, offset, width, height); } catch (Exception e) { e.printStackTrace(); resp.sendError(503, "Failed to generate thumbnail\n " + e.getMessage()); return; } } if (!f.exists()) { resp.sendError(404, "Missing File: " + f); return; } resp.setContentType("image/jpeg"); resp.setContentLength((int) f.length()); FileInputStream fis = null; try { fis = new FileInputStream(f); OutputStream os = resp.getOutputStream(); IOUtils.copyLarge(fis, os); os.flush(); fis.close(); } catch (Throwable e) { log.error("Failed to send file: " + f); resp.sendError(500, "Failed to get file " + f); } finally { IOUtils.closeQuietly(fis); } }
11
Code Sample 1: private void backupOriginalFile(String myFile) { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_S"); String datePortion = format.format(date); try { FileInputStream fis = new FileInputStream(myFile); FileOutputStream fos = new FileOutputStream(myFile + "-" + datePortion + "_UserID" + ".html"); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); fis.close(); fos.close(); System.out.println("**** Backup of file made."); } catch (Exception e) { System.out.println(e); } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public void run() { try { URL url = new URL(myListURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; Pattern folderPattern = Pattern.compile(".*DIR.*<a href=.(.*)/.>(.*)</a>.*"); Pattern folderPatternCloudmake = Pattern.compile(".*<li><a href=./(.*)#breadcrumbs. class=.folder.>(.*)</a></li>.*"); Pattern filePatternCloudmake = Pattern.compile(".*<a href=.(.*).bz2. class=.default.>(.*).osm(.*).bz2</a>&nbsp;<span class=\"file-size\">(.*)</span>.*"); while ((line = reader.readLine()) != null) { Matcher matcher = folderPattern.matcher(line); if (matcher.matches()) { String dirUrl = myListURL + matcher.group(1) + "/"; String name = matcher.group(2); if (name.equalsIgnoreCase("Parent Directory")) { continue; } DownloadMenu.this.add(new DownloadMenu(DownloadMenu.this.myMainFrame, dirUrl, name, myLoadChildren)); continue; } matcher = folderPatternCloudmake.matcher(line); if (matcher.matches()) { String dirUrl = myListURL.substring(0, myListURL.indexOf(".com/") + ".com/".length()) + matcher.group(1); String name = matcher.group(2); DownloadMenu.this.add(new DownloadMenu(DownloadMenu.this.myMainFrame, dirUrl, name, myLoadChildren)); continue; } matcher = filePatternCloudmake.matcher(line); if (matcher.matches()) { String fileUrl = myListURL.substring(0, myListURL.indexOf(".com") + ".com".length()) + matcher.group(1) + ".bz2"; final int typeAt = 3; final int nameAt = 2; String type = matcher.group(typeAt); String name = matcher.group(nameAt); if (type.length() > 0) { if (type.startsWith(".")) { type = type.substring(1); } name += "-" + type; } JMenuItem subMenu = new JMenuItem(name); subMenu.addActionListener(new DownloadActionListener(fileUrl, name)); subMenu.putClientProperty("URL", fileUrl); add(subMenu); continue; } int index = line.indexOf("<a href=\""); if (index < 0) { continue; } index += "<a href=\"".length(); int index2 = line.indexOf("</a"); if (index2 < 0) { continue; } int index1 = line.indexOf(".osm.bz2\">"); if (index1 < 0) { continue; } index1 += ".osm.bz2".length(); String fileUrl = line.substring(index, index1); if (!fileUrl.contains(".osm")) continue; if (!fileUrl.startsWith("http")) fileUrl = myListURL + fileUrl; index1 += "\">".length(); String fileName = line.substring(index1, index2); JMenuItem subMenu = new JMenuItem(fileName); subMenu.addActionListener(new DownloadActionListener(fileUrl, fileName)); subMenu.putClientProperty("URL", fileUrl); add(subMenu); } } catch (Exception e) { LOG.log(Level.SEVERE, "[Exception] Problem in " + getClass().getName(), e); } LOG.info("Done with async download of list of downloadable maps for " + getText() + "..."); remove(isLoadingMenuItem); if (myTreeNode != null) { myTreeNode.doneLoading(); } } Code Sample 2: public static void concatFiles(List<File> sourceFiles, File destFile) throws IOException { FileOutputStream outFile = new FileOutputStream(destFile); FileChannel outChannel = outFile.getChannel(); for (File f : sourceFiles) { FileInputStream fis = new FileInputStream(f); FileChannel channel = fis.getChannel(); channel.transferTo(0, channel.size(), outChannel); channel.close(); fis.close(); } outChannel.close(); }
11
Code Sample 1: public static void unzip(String destDir, String zipPath) { PrintWriter stdout = new PrintWriter(System.out, true); int read = 0; byte[] data = new byte[1024]; ZipEntry entry; try { ZipInputStream in = new ZipInputStream(new FileInputStream(zipPath)); stdout.println(zipPath); while ((entry = in.getNextEntry()) != null) { if (entry.getMethod() == ZipEntry.DEFLATED) { stdout.println(" Inflating: " + entry.getName()); } else { stdout.println(" Extracting: " + entry.getName()); } FileOutputStream out = new FileOutputStream(destDir + File.separator + entry.getName()); while ((read = in.read(data, 0, 1024)) != -1) { out.write(data, 0, read); } out.close(); } in.close(); stdout.println(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public byte[] loadResource(String name) throws IOException { ClassPathResource cpr = new ClassPathResource(name); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(cpr.getInputStream(), baos); return baos.toByteArray(); }
11
Code Sample 1: public void run() { String s; s = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + word); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while (((str = in.readLine()) != null) && (!stopped)) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("Main Entry:.+?<br>(.+?)</td>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); java.io.StringWriter wr = new java.io.StringWriter(); HTMLDocument doc = null; HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit(); try { doc = (HTMLDocument) editor.getDocument(); } catch (Exception e) { } System.out.println(wr); editor.setContentType("text/html"); if (matcher.find()) try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR>" + matcher.group(1) + "<HR>", 0, 0, null); } catch (Exception e) { System.out.println(e.getMessage()); } else try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR><FONT COLOR='RED'>NOT FOUND!!</FONT><HR>", 0, 0, null); } catch (Exception e) { System.out.println(e.getMessage()); } button.setEnabled(true); } Code Sample 2: public int getUrl() { try { final URL url = new URL(this.url); conn = url.openConnection(); if (cookies != null) { conn.setRequestProperty("Cookie", cookies); } InputStreamReader inputstream = new InputStreamReader(conn.getInputStream(), charset); charset = inputstream.getEncoding(); BufferedReader input = new BufferedReader(inputstream); String line; while ((line = input.readLine()) != null) { content += line + "\n"; } return 0; } catch (MalformedURLException e) { return 1; } catch (IOException e2) { return 2; } }
00
Code Sample 1: public static void main(String[] args) throws Exception { URL url = new URL("http://www.sohu.com"); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is, Charset.forName("GB18030")); FileOutputStream fos = new FileOutputStream("gen/sohu2.html"); OutputStreamWriter osw = new OutputStreamWriter(fos); char[] b = new char[2048]; int temp; while (-1 != (temp = isr.read(b, 0, b.length))) { osw.write(b); } osw.close(); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; } Code Sample 2: private FTPClient getClient() throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.setDefaultPort(getPort()); ftp.connect(getIp()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { log.warn("FTP server refused connection: {}", getIp()); ftp.disconnect(); return null; } if (!ftp.login(getUsername(), getPassword())) { log.warn("FTP server refused login: {}, user: {}", getIp(), getUsername()); ftp.logout(); ftp.disconnect(); return null; } ftp.setControlEncoding(getEncoding()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; }
00
Code Sample 1: private IMolecule readMolecule() throws Exception { String xpath = ""; if (index.equals("ichi")) { xpath = URLEncoder.encode("//molecule[./identifier/basic='" + query + "']", UTF8); } else if (index.equals("kegg")) { xpath = URLEncoder.encode("//molecule[./@name='" + query + "' and ./@dictRef='KEGG']", UTF8); } else if (index.equals("nist")) { xpath = URLEncoder.encode("//molecule[../@id='" + query + "']", UTF8); } else { logger.error("Did not recognize index type: " + index); return null; } String colname = URLEncoder.encode("/" + this.collection, UTF8); logger.info("Doing query: " + xpath + " in collection " + colname); URL url = new URL("http://" + server + "/Bob/QueryXindice"); logger.info("Connection to server: " + url.toString()); URLConnection connection = url.openConnection(); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print("detailed=on"); out.print("&"); out.print("xmlOnly=on"); out.print("&"); out.print("colName=" + colname); out.print("&"); out.print("xpathString=" + xpath); out.print("&"); out.println("query=Query"); out.close(); InputStream stream = connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(stream)); in.mark(1000000); in.readLine(); String comment = in.readLine(); logger.debug("The comment is: " + comment); Pattern p = Pattern.compile("<!-- There are (\\d{1,6}) results! -->"); Matcher match = p.matcher(comment); if (match.find()) { resultNum = match.group(1); } else { resultNum = "0"; } logger.debug("The number of result is " + resultNum); in.reset(); CMLReader reader = new CMLReader(stream); ChemFile cf = (ChemFile) reader.read((ChemObject) new ChemFile()); logger.debug("#sequences: " + cf.getChemSequenceCount()); IMolecule m = null; if (cf.getChemSequenceCount() > 0) { org.openscience.cdk.interfaces.IChemSequence chemSequence = cf.getChemSequence(0); logger.debug("#models in sequence: " + chemSequence.getChemModelCount()); if (chemSequence.getChemModelCount() > 0) { org.openscience.cdk.interfaces.IChemModel chemModel = chemSequence.getChemModel(0); org.openscience.cdk.interfaces.IMoleculeSet setOfMolecules = chemModel.getMoleculeSet(); logger.debug("#mols in model: " + setOfMolecules.getMoleculeCount()); if (setOfMolecules.getMoleculeCount() > 0) { m = setOfMolecules.getMolecule(0); } else { logger.warn("No molecules in the model"); } } else { logger.warn("No models in the sequence"); } } else { logger.warn("No sequences in the file"); } in.close(); return m; } Code Sample 2: public static void copy(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: protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } } Code Sample 2: private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir, BackUpInfoFileGroup fileGroup, LinkedList<String> restoreList) { LinkedList<BackUpInfoFile> fileList = fileGroup.getFileList(); if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } for (int i = 0; i < fileList.size(); i++) { if (fileList.get(i).getId().equals(entry.getName())) { for (int j = 0; j < restoreList.size(); j++) { if ((fileList.get(i).getName() + "." + fileList.get(i).getType()).equals(restoreList.get(j))) { counter += 1; File outputFile = new File(outputDir, fileList.get(i).getName() + "." + fileList.get(i).getType()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream; BufferedOutputStream outputStream; try { inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (IOException ex) { throw new BackupException(ex.getMessage()); } } } } } }
11
Code Sample 1: private static boolean copyFile(File src, File dest) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); for (int c = fis.read(); c != -1; c = fis.read()) fos.write(c); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (fis != null) try { fis.close(); } catch (IOException e) { e.printStackTrace(); } if (fos != null) try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } Code Sample 2: private static void downloadFile(String downloadFileName) throws Exception { URL getFileUrl = new URL("http://www.tegsoft.com/Tobe/getFile" + "?tegsoftFileName=" + downloadFileName); URLConnection getFileUrlConnection = getFileUrl.openConnection(); InputStream is = getFileUrlConnection.getInputStream(); String tobeHome = UiUtil.getParameter("RealPath.Context"); OutputStream out = new FileOutputStream(tobeHome + "/setup/" + downloadFileName); IOUtils.copy(is, out); is.close(); out.close(); }
11
Code Sample 1: @SuppressWarnings("static-access") @RequestMapping(value = "/upload/upload.html", method = RequestMethod.POST) protected void save(HttpServletRequest request, HttpServletResponse response) throws ServletException { UPLOAD_DIRECTORY = uploadDiretory(); File diretorioUsuario = new File(UPLOAD_DIRECTORY); boolean diretorioCriado = false; if (!diretorioUsuario.exists()) { diretorioCriado = diretorioUsuario.mkdir(); if (!diretorioCriado) throw new RuntimeException("Não foi possível criar o diretório do usuário"); } PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(UPLOAD_DIRECTORY + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); } Code Sample 2: 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) { } } }
00
Code Sample 1: private byte[] cacheInputStream(URL url) throws IOException { InputStream ins = url.openStream(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buf = new byte[256]; while (true) { int n = ins.read(buf); if (n == -1) break; bout.write(buf, 0, n); } return bout.toByteArray(); } Code Sample 2: private boolean performModuleInstallation(Model m) { String seldir = directoryHandler.getSelectedDirectory(); if (seldir == null) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A target directory must be selected."); box.open(); return false; } String sjar = pathText.getText(); File fjar = new File(sjar); if (!fjar.exists()) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A non-existing jar file has been selected."); box.open(); return false; } int count = 0; try { URLClassLoader loader = new URLClassLoader(new URL[] { fjar.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(fjar)); JarEntry entry = jis.getNextJarEntry(); while (entry != null) { String name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); Class<?> cls = loader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && (cls.getModifiers() & Modifier.ABSTRACT) == 0) { if (!testAlgorithm(cls, m)) return false; count++; } } entry = jis.getNextJarEntry(); } } catch (Exception e1) { Application.logexcept("Could not load classes from jar file.", e1); return false; } if (count == 0) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("There don't seem to be any algorithms in the specified module."); box.open(); return false; } try { FileChannel ic = new FileInputStream(sjar).getChannel(); FileChannel oc = new FileOutputStream(seldir + File.separator + fjar.getName()).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (Exception e) { Application.logexcept("Could not install module", e); return false; } result = new Object(); return true; }
11
Code Sample 1: public static void copyFile(File file, String destDir) throws IOException { if (!isCanReadFile(file)) throw new RuntimeException("The File can't read:" + file.getPath()); if (!isCanWriteDirectory(destDir)) throw new RuntimeException("The Directory can't write:" + destDir); FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(file).getChannel(); dstChannel = new FileOutputStream(destDir + "/" + file.getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (IOException e) { throw e; } finally { if (srcChannel != null) try { srcChannel.close(); } catch (IOException e) { } if (dstChannel != null) try { dstChannel.close(); } catch (IOException e) { } } } Code Sample 2: public static void copyFile(final String inFile, final String outFile) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(inFile).getChannel(); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } catch (final Exception e) { } finally { if (in != null) { try { in.close(); } catch (final Exception e) { } } if (out != null) { try { out.close(); } catch (final Exception e) { } } } }
11
Code Sample 1: public static void copyFile(String input, String output) { try { FileChannel srcChannel = new FileInputStream("srcFilename").getChannel(); FileChannel dstChannel = new FileOutputStream("dstFilename").getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } Code Sample 2: private static String fetchImageViaHttp(URL imgUrl) throws IOException { String sURL = imgUrl.toString(); String imgFile = imgUrl.getPath(); HttpURLConnection cnx = (HttpURLConnection) imgUrl.openConnection(); String uri = null; try { cnx.setAllowUserInteraction(false); cnx.setDoOutput(true); cnx.addRequestProperty("Cache-Control", "no-cache"); RequestContext ctx = RequestContext.get(); if (ctx != null) cnx.addRequestProperty("User-Agent", ctx.header("user-agent")); else cnx.addRequestProperty("User-Agent", user_agent); cnx.addRequestProperty("Referer", sURL.substring(0, sURL.indexOf('/', sURL.indexOf('.')) + 1)); cnx.connect(); if (cnx.getResponseCode() != HttpURLConnection.HTTP_OK) return null; InputStream imgData = cnx.getInputStream(); String ext = FilenameUtils.getExtension(imgFile).toLowerCase(); if (!Multimedia.isImageFile("aa." + ext)) ext = "jpg"; uri = FMT_FN.format(new Date()) + RandomStringUtils.randomAlphanumeric(4) + '.' + ext; File fileDest = new File(img_path + uri); if (!fileDest.getParentFile().exists()) fileDest.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(fileDest); try { IOUtils.copy(imgData, fos); } finally { IOUtils.closeQuietly(imgData); IOUtils.closeQuietly(fos); } } finally { cnx.disconnect(); } return RequestContext.get().contextPath() + "/uploads/img/" + uri; }
11
Code Sample 1: public static LicenseKey parseKey(String key) throws InvalidLicenseKeyException { final String f_key = key.trim(); StringTokenizer st = new StringTokenizer(f_key, FIELD_SEPERATOR); int tc = st.countTokens(); int tc_name = tc - 9; try { final String product = st.nextToken(); final String type = st.nextToken(); final String loadStr = st.nextToken(); final int load = Integer.parseInt(loadStr); final String lowMajorVersionStr = st.nextToken(); final int lowMajorVersion = Integer.parseInt(lowMajorVersionStr); final String lowMinorVersionStr = st.nextToken(); final double lowMinorVersion = Double.parseDouble("0." + lowMinorVersionStr); final String highMajorVersionStr = st.nextToken(); final int highMajorVersion = Integer.parseInt(highMajorVersionStr); final String highMinorVersionStr = st.nextToken(); final double highMinorVersion = Double.parseDouble("0." + highMinorVersionStr); String regName = ""; for (int i = 0; i < tc_name; i++) regName += (i == 0 ? st.nextToken() : FIELD_SEPERATOR + st.nextToken()); final String randomHexStr = st.nextToken(); final String md5Str = st.nextToken(); String subKey = f_key.substring(0, f_key.indexOf(md5Str) - 1); byte[] md5; MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(subKey.getBytes()); md.update(FIELD_SEPERATOR.getBytes()); md.update(zuonicsPassword.getBytes()); md5 = md.digest(); String testKey = subKey + FIELD_SEPERATOR; for (int i = 0; i < md5.length; i++) testKey += Integer.toHexString(md5[i]).toUpperCase(); if (!testKey.equals(f_key)) throw new InvalidLicenseKeyException("doesn't hash"); final String f_regName = regName; return new LicenseKey() { public String getProduct() { return product; } public String getType() { return type; } public int getLoad() { return load; } public String getRegName() { return f_regName; } public double getlowVersion() { return lowMajorVersion + lowMinorVersion; } public double getHighVersion() { return highMajorVersion + highMinorVersion; } public String getRandomHexStr() { return randomHexStr; } public String getMD5HexStr() { return md5Str; } public String toString() { return f_key; } public boolean equals(Object obj) { if (obj.toString().equals(toString())) return true; return false; } }; } catch (Exception e) { throw new InvalidLicenseKeyException(e.getMessage()); } } Code Sample 2: private String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
00
Code Sample 1: private String readJsonString() { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(SERVER_URL); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(TAG, "Failed to download file"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } Code Sample 2: @Override protected void write(InputStream in, OutputStream out, javax.sound.sampled.AudioFormat javaSoundFormat) throws IOException { if (USE_JAVASOUND) { super.write(in, out, javaSoundFormat); } else { try { byte[] header = JavaSoundCodec.createWavHeader(javaSoundFormat); if (header == null) throw new IOException("Unable to create wav header"); out.write(header); IOUtils.copyStream(in, out); } catch (InterruptedIOException e) { logger.log(Level.FINE, "" + e, e); throw e; } catch (IOException e) { logger.log(Level.WARNING, "" + e, e); throw e; } } }
11
Code Sample 1: public static void copy(File in, File out) throws IOException { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } Code Sample 2: protected void saveResponse(final WebResponse response, final WebRequest request) throws IOException { counter_++; final String extension = chooseExtension(response.getContentType()); final File f = createFile(request.getUrl(), extension); final InputStream input = response.getContentAsStream(); final OutputStream output = new FileOutputStream(f); try { IOUtils.copy(response.getContentAsStream(), output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } final URL url = response.getWebRequest().getUrl(); LOG.info("Created file " + f.getAbsolutePath() + " for response " + counter_ + ": " + url); final StringBuilder buffer = new StringBuilder(); buffer.append("tab[tab.length] = {code: " + response.getStatusCode() + ", "); buffer.append("fileName: '" + f.getName() + "', "); buffer.append("contentType: '" + response.getContentType() + "', "); buffer.append("method: '" + request.getHttpMethod().name() + "', "); if (request.getHttpMethod() == HttpMethod.POST && request.getEncodingType() == FormEncodingType.URL_ENCODED) { buffer.append("postParameters: " + nameValueListToJsMap(request.getRequestParameters()) + ", "); } buffer.append("url: '" + escapeJSString(url.toString()) + "', "); buffer.append("loadTime: " + response.getLoadTime() + ", "); final byte[] bytes = IOUtils.toByteArray(response.getContentAsStream()); buffer.append("responseSize: " + ((bytes == null) ? 0 : bytes.length) + ", "); buffer.append("responseHeaders: " + nameValueListToJsMap(response.getResponseHeaders())); buffer.append("};\n"); appendToJSFile(buffer.toString()); }
11
Code Sample 1: public static void copy(File source, File destination) throws IOException { InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(destination); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); in.close(); out.close(); } Code Sample 2: public static void copyFile(File src, File dest, boolean notifyUserOnError) { if (src.exists()) { try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); } catch (IOException e) { String message = "Error while copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " : " + e.getMessage(); if (notifyUserOnError) { Log.getInstance(SystemUtils.class).warnWithUserNotification(message); } else { Log.getInstance(SystemUtils.class).warn(message); } } } else { String message = "Unable to copy file: source does not exists: " + src.getAbsolutePath(); if (notifyUserOnError) { Log.getInstance(SystemUtils.class).warnWithUserNotification(message); } else { Log.getInstance(SystemUtils.class).warn(message); } } }
00
Code Sample 1: public String getHtmlCode(String urlString) { StringBuffer result = new StringBuffer(); BufferedReader in = null; try { URL url = new URL((urlString)); URLConnection con = url.openConnection(); in = new BufferedReader(new InputStreamReader(con.getInputStream(), "ISO-8859-1")); String line = null; while ((line = in.readLine()) != null) { result.append(line + "\r\n"); } in.close(); } catch (MalformedURLException e) { System.out.println("Unable to connect to URL: " + urlString); } catch (IOException e) { System.out.println("IOException when connecting to URL: " + urlString); } finally { if (in != null) { try { in.close(); } catch (Exception ex) { System.out.println("Exception throws at finally close reader when connecting to URL: " + urlString); } } } return result.toString(); } Code Sample 2: private String postData(String requestUrl, String atom) throws AuthenticationException, IOException { URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); String header; try { header = oauthAuthenticator.getHttpAuthorizationHeader(url.toString(), "POST", profile.getOAuthToken(), profile.getOAuthTokenSecret()); } catch (OAuthException e) { throw new AuthenticationException(e); } conn.setRequestProperty("Authorization", header); conn.setRequestProperty("Content-Type", "application/atom+xml"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); writer.write(atom); writer.close(); if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new AuthenticationException(); } InputStreamReader reader = new InputStreamReader(conn.getInputStream()); char[] buffer = new char[1024]; int bytesRead = 0; StringBuilder data = new StringBuilder(); while ((bytesRead = reader.read(buffer)) != -1) { data.append(buffer, 0, bytesRead); } reader.close(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new IOException(conn.getResponseCode() + " " + conn.getResponseMessage() + "\n" + data); } return data.toString(); }
00
Code Sample 1: public static void copyFile(File src, File dest, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file: " + dest); } } byte[] buffer = new byte[1]; 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(); } } } } } Code Sample 2: public static String getURLData(String stringUrl, boolean secure) throws Exception { URL url = new URL(stringUrl); HttpURLConnection httpURLConnection; if (secure) { httpURLConnection = (HttpsURLConnection) url.openConnection(); } else { httpURLConnection = (HttpURLConnection) url.openConnection(); } return getDataFromURL(httpURLConnection); }
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 static boolean copyFile(File src, File des) { try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(des)); int b; while ((b = in.read()) != -1) out.write(b); out.flush(); out.close(); in.close(); return true; } catch (IOException ie) { m_logCat.error("Copy file + " + src + " to " + des + " failed!", ie); return false; } }
11
Code Sample 1: public String getPloidy(String source) { StringBuilder ploidyHtml = new StringBuilder(); String hyperdiploidyUrl = customParameters.getHyperdiploidyUrl(); String urlString = hyperdiploidyUrl + "?source=" + source; URL url = null; try { url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; while ((line = in.readLine()) != null) { ploidyHtml.append(line); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ploidyHtml.toString(); } Code Sample 2: public static String loadURLToString(String url, String EOL) throws FileNotFoundException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); String result = ""; String str; while ((str = in.readLine()) != null) { result += str + EOL; } in.close(); return result; }
00
Code Sample 1: public String getIpAddress() { try { URL url = new URL("http://checkip.dyndns.org"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String linha; String rtn = ""; while ((linha = in.readLine()) != null) rtn += linha; ; in.close(); return filtraRetorno(rtn); } catch (IOException ex) { Logger.getLogger(ExternalIp.class.getName()).log(Level.SEVERE, null, ex); return "ERRO."; } } Code Sample 2: private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public static void readDefault() { ClassLoader l = Skeleton.class.getClassLoader(); URL url; if (l != null) { url = l.getResource(DEFAULT_LOC); } else { url = ClassLoader.getSystemResource(DEFAULT_LOC); } if (url == null) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } try { InputStreamReader reader = new InputStreamReader(url.openStream()); readSkel(new BufferedReader(reader)); } catch (IOException e) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } }
11
Code Sample 1: public static String SHA(String s) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(s.getBytes(), 0, s.getBytes().length); byte[] hash = md.digest(); StringBuilder sb = new StringBuilder(); int msb; int lsb = 0; int i; for (i = 0; i < hash.length; i++) { msb = ((int) hash[i] & 0x000000FF) / 16; lsb = ((int) hash[i] & 0x000000FF) % 16; sb.append(hexChars[msb]); sb.append(hexChars[lsb]); } return sb.toString(); } catch (NoSuchAlgorithmException e) { return null; } } Code Sample 2: public String obfuscateString(String string) { String obfuscatedString = null; try { MessageDigest md = MessageDigest.getInstance(ENCRYPTION_ALGORITHM); md.update(string.getBytes()); byte[] digest = md.digest(); obfuscatedString = new String(Base64.encode(digest)).replace(DELIM_PATH, '='); } catch (NoSuchAlgorithmException e) { StatusHandler.log("SHA not available", null); obfuscatedString = LABEL_FAILED_TO_OBFUSCATE; } return obfuscatedString; }
00
Code Sample 1: private String doSearch(String query) { StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("http://boss.yahooapis.com/ysearch/web/v1/").append(query).append("?appid=wGsFV_DV34EwXnC.2Bt_Ql8Kcir_HmrxMzWUF2fv64CA8ha7e4zgudqXFA8K_J4-&format=xml&filter=-porn"); try { URL url = new URL(queryBuilder.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); return safeParseXml(buffer.toString()); } catch (MalformedURLException e) { log.error("The used url is not right : " + queryBuilder.toString(), e); return "The used url is not right."; } catch (IOException e) { log.error("Problem obtaining search results, connection maybe?", e); return "Problem obtaining search results, connection maybe?"; } } Code Sample 2: @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object msg = e.getMessage(); if (!(msg instanceof HttpMessage) && !(msg instanceof HttpChunk)) { ctx.sendUpstream(e); return; } HttpMessage currentMessage = this.currentMessage; File localFile = this.file; if (currentMessage == null) { HttpMessage m = (HttpMessage) msg; if (m.isChunked()) { final String localName = UUID.randomUUID().toString(); List<String> encodings = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING); encodings.remove(HttpHeaders.Values.CHUNKED); if (encodings.isEmpty()) { m.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING); } this.currentMessage = m; this.file = new File(Play.tmpDir, localName); this.out = new FileOutputStream(file, true); } else { ctx.sendUpstream(e); } } else { final HttpChunk chunk = (HttpChunk) msg; if (maxContentLength != -1 && (localFile.length() > (maxContentLength - chunk.getContent().readableBytes()))) { currentMessage.setHeader(HttpHeaders.Names.WARNING, "play.netty.content.length.exceeded"); } else { IOUtils.copyLarge(new ChannelBufferInputStream(chunk.getContent()), this.out); if (chunk.isLast()) { this.out.flush(); this.out.close(); currentMessage.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(localFile.length())); currentMessage.setContent(new FileChannelBuffer(localFile)); this.out = null; this.currentMessage = null; this.file = null; Channels.fireMessageReceived(ctx, currentMessage, e.getRemoteAddress()); } } } }