label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
11
| Code Sample 1:
public String sendXml(URL url, String xmlMessage, boolean isResponseExpected) throws IOException { if (url == null) { throw new IllegalArgumentException("url == null"); } if (xmlMessage == null) { throw new IllegalArgumentException("xmlMessage == null"); } LOGGER.finer("url = " + url); LOGGER.finer("xmlMessage = :" + xmlMessage + ":"); LOGGER.finer("isResponseExpected = " + isResponseExpected); String answer = null; try { URLConnection urlConnection = url.openConnection(); urlConnection.setRequestProperty("Content-type", "text/xml"); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); Writer writer = null; try { writer = new OutputStreamWriter(urlConnection.getOutputStream()); writer.write(xmlMessage); writer.flush(); } finally { if (writer != null) { writer.close(); } } LOGGER.finer("message written"); StringBuilder sb = new StringBuilder(); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); if (isResponseExpected) { String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine).append("\n"); } answer = sb.toString(); LOGGER.finer("response read"); } } catch (FileNotFoundException e) { LOGGER.log(Level.SEVERE, "No response", e); } finally { if (in != null) { in.close(); } } } catch (ConnectException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } LOGGER.finer("answer = :" + answer + ":"); return answer; }
Code Sample 2:
private String clientLogin(AuthInfo authInfo) throws AuthoricationRequiredException { logger.fine("clientLogin."); try { String url = "https://www.google.com/accounts/ClientLogin"; HttpPost httpPost = new HttpPost(url); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("accountType", "HOSTED_OR_GOOGLE")); params.add(new BasicNameValuePair("Email", authInfo.getEmail())); params.add(new BasicNameValuePair("Passwd", new String(authInfo.getPassword()))); params.add(new BasicNameValuePair("service", "ah")); params.add(new BasicNameValuePair("source", "client.kotan-server.appspot.com")); httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse response = clientManager.httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { entity.consumeContent(); throw new AuthoricationRequiredException(EntityUtils.toString(entity)); } BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); while (true) { String line = reader.readLine(); if (line == null) break; if (line.startsWith("Auth=")) { return line.substring("Auth=".length()); } } reader.close(); throw new AuthoricationRequiredException("Login failure."); } catch (IOException e) { throw new AuthoricationRequiredException(e); } } |
00
| Code Sample 1:
public static String getMD5Hash(String hashthis) throws NoSuchAlgorithmException { byte[] key = "PATIENTISAUTHENTICATION".getBytes(); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(hashthis.getBytes()); return new String(HashUtility.base64Encode(md5.digest(key))); }
Code Sample 2:
public void writeBack(File destinationFile, boolean makeCopy) throws IOException { if (makeCopy) { FileChannel sourceChannel = new java.io.FileInputStream(getFile()).getChannel(); FileChannel destinationChannel = new java.io.FileOutputStream(destinationFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } else { getFile().renameTo(destinationFile); } if (getExifTime() != null && getOriginalTime() != null && !getExifTime().equals(getOriginalTime())) { String adjustArgument = "-ts" + m_dfJhead.format(getExifTime()); ProcessBuilder pb = new ProcessBuilder(m_tm.getJheadCommand(), adjustArgument, destinationFile.getAbsolutePath()); pb.directory(destinationFile.getParentFile()); System.out.println(pb.command().get(0) + " " + pb.command().get(1) + " " + pb.command().get(2)); final Process p = pb.start(); try { p.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } } } |
00
| Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
private static <T> Collection<T> loadFromServices(Class<T> interf) throws Exception { ClassLoader classLoader = DSServiceLoader.class.getClassLoader(); Enumeration<URL> e = classLoader.getResources("META-INF/services/" + interf.getName()); Collection<T> services = new ArrayList<T>(); while (e.hasMoreElements()) { URL url = e.nextElement(); InputStream is = url.openStream(); try { BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) { break; } int comment = line.indexOf('#'); if (comment >= 0) { line = line.substring(0, comment); } String name = line.trim(); if (name.length() == 0) { continue; } Class<?> clz = Class.forName(name, true, classLoader); Class<? extends T> impl = clz.asSubclass(interf); Constructor<? extends T> ctor = impl.getConstructor(); T svc = ctor.newInstance(); services.add(svc); } } finally { is.close(); } } return services; } |
00
| Code Sample 1:
public static void copyFile(File sourceFile, File targetFile) throws FileCopyingException { try { FileInputStream inputStream = new FileInputStream(sourceFile); FileOutputStream outputStream = new FileOutputStream(targetFile); FileChannel readableChannel = inputStream.getChannel(); FileChannel writableChannel = outputStream.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); inputStream.close(); outputStream.close(); } catch (IOException ioException) { String exceptionMessage = "An error occurred when copying from the file \"" + sourceFile.getAbsolutePath() + "\" to the file \"" + targetFile.getAbsolutePath() + "\"."; throw new FileCopyingException(exceptionMessage, ioException); } }
Code Sample 2:
public String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } |
11
| Code Sample 1:
public void copyTo(String newname) throws IOException { FileChannel srcChannel = new FileInputStream(dosname).getChannel(); FileChannel dstChannel = new FileOutputStream(newname).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
Code Sample 2:
public static void copyFile(File src, File dst) throws IOException { if (T.t) T.info("Copying " + src + " -> " + dst + "..."); FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dst); byte buf[] = new byte[40 * KB]; int read; while ((read = in.read(buf)) != -1) { out.write(buf, 0, read); } out.flush(); out.close(); in.close(); if (T.t) T.info("File copied."); } |
11
| Code Sample 1:
public static void copyFile(final File in, final File out) throws IOException { final FileChannel sourceChannel = new FileInputStream(in).getChannel(); final FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
private static void zipFolder(File folder, ZipOutputStream zipOutputStream, String relativePath) throws IOException { File[] children = folder.listFiles(); for (int i = 0; i < children.length; i++) { File child = children[i]; if (child.isFile()) { String zipEntryName = children[i].getCanonicalPath().replace(relativePath + File.separator, ""); ZipEntry entry = new ZipEntry(zipEntryName); zipOutputStream.putNextEntry(entry); InputStream inputStream = new FileInputStream(child); IOUtils.copy(inputStream, zipOutputStream); inputStream.close(); } else { ZipUtil.zipFolder(child, zipOutputStream, relativePath); } } } |
00
| Code Sample 1:
private String MD5(String s) { Log.d("MD5", "Hashing '" + s + "'"); String hash = ""; try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(s.getBytes(), 0, s.length()); hash = new BigInteger(1, m.digest()).toString(16); Log.d("MD5", "Hash: " + hash); } catch (Exception e) { Log.e("MD5", e.getMessage()); } return hash; }
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 String generateSHA1Digest(String text) { try { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("UTF-8"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
Code Sample 2:
public String readLines() { StringBuffer lines = new StringBuffer(); try { int HttpResult; URL url = new URL(address); URLConnection urlconn = url.openConnection(); urlconn.connect(); HttpURLConnection httpconn = (HttpURLConnection) urlconn; HttpResult = httpconn.getResponseCode(); if (HttpResult != HttpURLConnection.HTTP_OK) { System.out.println("�����ӵ�" + address); } else { BufferedReader reader = new BufferedReader(new InputStreamReader(urlconn.getInputStream())); while (true) { String line = reader.readLine(); if (line == null) break; lines.append(line + "\r\n"); } reader.close(); } } catch (Exception e) { e.printStackTrace(); } return lines.toString(); } |
00
| Code Sample 1:
public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
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; } |
11
| Code Sample 1:
public String insertBuilding() { homeMap = homeMapDao.getHomeMapById(homeMap.getId()); homeBuilding.setHomeMap(homeMap); Integer id = homeBuildingDao.saveHomeBuilding(homeBuilding); String dir = "E:\\ganymede_workspace\\training01\\web\\user_buildings\\"; FileOutputStream fos; try { fos = new FileOutputStream(dir + id); IOUtils.copy(new FileInputStream(imageFile), fos); IOUtils.closeQuietly(fos); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return execute(); }
Code Sample 2:
public static void copyFileStreams(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) { return; } FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); int read = 0; byte[] buf = new byte[1024]; while (-1 != read) { read = fis.read(buf); if (read >= 0) { fos.write(buf, 0, read); } } fos.close(); fis.close(); } |
11
| Code Sample 1:
public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
Code Sample 2:
public static void copy(String sourceName, String destName) throws IOException { File src = new File(sourceName); File dest = new File(destName); BufferedInputStream source = null; BufferedOutputStream destination = null; byte[] buffer; int bytes_read; long byteCount = 0; if (!src.exists()) throw new IOException("Source not found: " + src); if (!src.canRead()) throw new IOException("Source is unreadable: " + src); if (src.isFile()) { if (!dest.exists()) { File parentdir = parent(dest); if (!parentdir.exists()) parentdir.mkdir(); } else if (dest.isDirectory()) { if (src.isDirectory()) dest = new File(dest + File.separator + src); else dest = new File(dest + File.separator + src.getName()); } } else if (src.isDirectory()) { if (dest.isFile()) throw new IOException("Cannot copy directory " + src + " to file " + dest); if (!dest.exists()) dest.mkdir(); } if ((!dest.canWrite()) && (dest.exists())) throw new IOException("Destination is unwriteable: " + dest); if (src.isFile()) { try { source = new BufferedInputStream(new FileInputStream(src)); destination = new BufferedOutputStream(new FileOutputStream(dest)); buffer = new byte[4096]; byteCount = 0; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } else if (src.isDirectory()) { String targetfile, target, targetdest; String[] files = src.list(); for (int i = 0; i < files.length; i++) { targetfile = files[i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File(target)).isDirectory()) { copy(new File(target).getCanonicalPath(), new File(targetdest).getCanonicalPath()); } else { try { byteCount = 0; source = new BufferedInputStream(new FileInputStream(target)); destination = new BufferedOutputStream(new FileOutputStream(targetdest)); buffer = new byte[4096]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } } } } |
00
| Code Sample 1:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { jButton1.setEnabled(false); for (int i = 0; i < max; i++) { Card crd = WLP.getSelectedCard(WLP.jTable1.getSelectedRows()[i]); String s, s2; s = ""; s2 = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + crd.getWord()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("popWin\\('/cgi-bin/(.+?)'", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); if (matcher.find()) { String newurl = "http://m-w.com/cgi-bin/" + matcher.group(1); try { URL url2 = new URL(newurl); BufferedReader in2 = new BufferedReader(new InputStreamReader(url2.openStream())); String str; while ((str = in2.readLine()) != null) { s2 = s2 + str; } in2.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern2 = Pattern.compile("<A HREF=\"http://(.+?)\">Click here to listen with your default audio player", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher2 = pattern2.matcher(s2); if (matcher2.find()) { getWave("http://" + matcher2.group(1), crd.getWord()); } int val = jProgressBar1.getValue(); val++; jProgressBar1.setValue(val); this.paintAll(this.getGraphics()); } } jButton1.setEnabled(true); }
Code Sample 2:
public static void main(String[] args) throws IOException { httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); loginLocalhostr(); initialize(); HttpOptions httpoptions = new HttpOptions(localhostrurl); HttpResponse myresponse = httpclient.execute(httpoptions); HttpEntity myresEntity = myresponse.getEntity(); System.out.println(EntityUtils.toString(myresEntity)); fileUpload(); } |
00
| Code Sample 1:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
Code Sample 2:
private RssEvent getLastEvent() throws DocumentException, IOException { Document document = new SAXReader().read(url.openStream()); Element item = document.getRootElement().element("channel").element("item"); Date date = new Date(); String dateStr = item.element("pubDate").getStringValue(); try { date = dateFormat.parse(dateStr); } catch (ParseException e) { String message = MessageFormat.format("Unable to parse string \"{0}\" with pattern \"{1}\".", dateStr, FORMAT); logger.warn(message, e); } RssEvent event = new RssEvent(this, item.element("title").getStringValue(), item.element("link").getStringValue(), item.element("description").getStringValue(), item.element("author").getStringValue(), date); return event; } |
00
| Code Sample 1:
public boolean saveTemplate(Template t) { try { conn.setAutoCommit(false); Statement stmt = conn.createStatement(); String query; ResultSet rset; if (Integer.parseInt(executeMySQLGet("SELECT COUNT(*) FROM templates WHERE name='" + escapeCharacters(t.getName()) + "'")) != 0) return false; query = "select * from templates where templateid = " + t.getID(); rset = stmt.executeQuery(query); if (rset.next()) { System.err.println("Updating already saved template is not supported!!!!!!"); return false; } else { query = "INSERT INTO templates (name, parentid) VALUES ('" + escapeCharacters(t.getName()) + "', " + t.getParentID() + ")"; try { stmt.executeUpdate(query); } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } int templateid = Integer.parseInt(executeMySQLGet("SELECT LAST_INSERT_ID()")); t.setID(templateid); LinkedList<Field> fields = t.getFields(); ListIterator<Field> iter = fields.listIterator(); Field f = null; PreparedStatement pstmt = conn.prepareStatement("INSERT INTO templatefields(fieldtype, name, templateid, defaultvalue)" + "VALUES (?,?,?,?)"); try { while (iter.hasNext()) { f = iter.next(); if (f.getType() == Field.IMAGE) { System.out.println("field is an image."); byte data[] = ((FieldDataImage) f.getDefault()).getDataBytes(); pstmt.setBytes(4, data); } else { System.out.println("field is not an image"); String deflt = (f.getDefault()).getData(); pstmt.setString(4, deflt); } pstmt.setInt(1, f.getType()); pstmt.setString(2, f.getName()); pstmt.setInt(3, t.getID()); pstmt.execute(); f.setID(Integer.parseInt(executeMySQLGet("SELECT LAST_INSERT_ID()"))); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } conn.commit(); conn.setAutoCommit(true); } catch (SQLException ex) { System.err.println("Error saving the Template"); return false; } return true; }
Code Sample 2:
private static String downloadMedia(String mediadir, URL remoteFile) throws Exception, InterruptedException { File tmpDir = new File(System.getProperty("java.io.tmpdir") + "org.ogre4j.examples/" + mediadir); if (!tmpDir.exists()) { tmpDir.mkdirs(); } URLConnection urlConnection = remoteFile.openConnection(); if (urlConnection.getConnectTimeout() != 0) { urlConnection.setConnectTimeout(0); } InputStream content = remoteFile.openStream(); BufferedInputStream bin = new BufferedInputStream(content); String downloaded = tmpDir.getCanonicalPath() + File.separatorChar + new File(remoteFile.getFile()).getName(); File file = new File(downloaded); BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(file)); System.out.println("downloading file " + remoteFile + " ..."); for (long i = 0; i < urlConnection.getContentLength(); i++) { bout.write(bin.read()); } bout.close(); bout = null; bin.close(); return downloaded; } |
00
| Code Sample 1:
static ConversionMap create(String file) { ConversionMap out = new ConversionMap(); URL url = ConversionMap.class.getResource(file); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); while (line != null) { if (line.length() > 0) { String[] arr = line.split("\t"); try { double value = Double.parseDouble(arr[1]); out.put(translate(lowercase(arr[0].getBytes())), value); out.defaultValue += value; out.length = arr[0].length(); } catch (NumberFormatException e) { throw new RuntimeException("Something is wrong with in conversion file: " + e); } } line = in.readLine(); } in.close(); out.defaultValue /= Math.pow(4, out.length); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Their was an error while reading the conversion map: " + e); } return out; }
Code Sample 2:
@Override public IMedium createMedium(String urlString, IMetadata optionalMetadata) throws MM4UCannotCreateMediumElementsException { Debug.println("createMedium(): URL: " + urlString); IAudio tempAudio = null; try { String cachedFileUri = null; try { URL url = new URL(urlString); InputStream is = url.openStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf)) > 0) out.write(buf, 0, len); MediaCache cache = new MediaCache(); cachedFileUri = cache.addAudio(urlString, out).getURI().substring(5); } catch (MalformedURLException e) { cachedFileUri = urlString; } TAudioFileFormat fFormat = null; try { fFormat = (TAudioFileFormat) new MpegAudioFileReader().getAudioFileFormat(new File(cachedFileUri)); } catch (Exception e) { System.err.println("getAudioFileFormat() failed: " + e); } int length = Constants.UNDEFINED_INTEGER; if (fFormat != null) { length = Math.round(Integer.valueOf(fFormat.properties().get("duration").toString()).intValue() / 1000); } String mimeType = Utilities.getMimetype(Utilities.getURISuffix(urlString)); optionalMetadata.addIfNotNull(IMedium.MEDIUM_METADATA_MIMETYPE, mimeType); if (length != Constants.UNDEFINED_INTEGER) { tempAudio = new Audio(this, length, urlString, optionalMetadata); } } catch (Exception exc) { exc.printStackTrace(); return null; } return tempAudio; } |
00
| Code Sample 1:
private static void loadProperties(Properties props, String res, boolean warnIfNotFound) throws IOException { log.debug("Reading properties from resource " + res); URL url = ResourceFileStorageFactory.class.getResource(res); if (null == url) { if (warnIfNotFound) { log.warn("Resource " + res + " was not found"); } else { log.debug("Resource " + res + " was not found"); } } else { InputStream in = url.openStream(); try { props.load(in); } finally { in.close(); } } }
Code Sample 2:
public he3Decode(String in_file) { try { File out = new File(in_file + extension); File in = new File(in_file); int file_size = (int) in.length(); FileInputStream in_stream = new FileInputStream(in_file); out.createNewFile(); FileOutputStream out_stream = new FileOutputStream(out.getName()); ByteArrayOutputStream os = new ByteArrayOutputStream(file_size); byte byte_arr[] = new byte[8]; int buff_size = byte_arr.length; int _fetched = 0; int _chars_read = 0; System.out.println(appname + ".\n" + "decoding: " + in_file + "\n" + "decoding to: " + in_file + extension + "\n" + "\nreading: "); while (_fetched < file_size) { _chars_read = in_stream.read(byte_arr, 0, buff_size); if (_chars_read == -1) break; os.write(byte_arr, 0, _chars_read); _fetched += _chars_read; System.out.print("*"); } System.out.print("\ndecoding: "); out_stream.write(_decode((ByteArrayOutputStream) os)); System.out.print("complete\n\n"); } catch (java.io.FileNotFoundException fnfEx) { System.err.println("Exception: " + fnfEx.getMessage()); } catch (java.io.IOException ioEx) { System.err.println("Exception: " + ioEx.getMessage()); } } |
00
| Code Sample 1:
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
Code Sample 2:
protected void doGetPost(HttpServletRequest req, HttpServletResponse resp, boolean post) throws ServletException, IOException { if (responseBufferSize > 0) resp.setBufferSize(responseBufferSize); String pathinfo = req.getPathInfo(); if (pathinfo == null) { String urlstring = req.getParameter(REMOTE_URL); if (urlstring == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ResourceBundle.getBundle(MESSAGES, req.getLocale(), new UTF8ResourceBundleControl()).getString("error.nourl")); return; } boolean allowCookieForwarding = "true".equals(req.getParameter(ALLOW_COOKIE_FORWARDING)); boolean allowFormDataForwarding = "true".equals(req.getParameter(ALLOW_FORM_DATA_FORWARDING)); String target = new JGlossURLRewriter(req.getContextPath() + req.getServletPath(), new URL(HttpUtils.getRequestURL(req).toString()), null, allowCookieForwarding, allowFormDataForwarding).rewrite(urlstring, true); resp.sendRedirect(target); return; } Set connectionAllowedProtocols; if (req.isSecure()) connectionAllowedProtocols = secureAllowedProtocols; else connectionAllowedProtocols = allowedProtocols; Object[] oa = JGlossURLRewriter.parseEncodedPath(pathinfo); if (oa == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale(), new UTF8ResourceBundleControl()).getString("error.malformedrequest"), new Object[] { pathinfo })); return; } boolean allowCookieForwarding = ((Boolean) oa[0]).booleanValue(); boolean allowFormDataForwarding = ((Boolean) oa[1]).booleanValue(); String urlstring = (String) oa[2]; getServletContext().log("received request for " + urlstring); if (urlstring.toLowerCase().indexOf(req.getServletPath().toLowerCase()) != -1) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.addressnotallowed"), new Object[] { urlstring })); return; } if (urlstring.indexOf(':') == -1) { if (req.isSecure()) { if (secureAllowedProtocols.contains("https")) urlstring = "https://" + urlstring; } else { if (allowedProtocols.contains("http")) urlstring = "http://" + urlstring; } } URL url; try { url = new URL(urlstring); } catch (MalformedURLException ex) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.malformedurl"), new Object[] { urlstring })); return; } String protocol = url.getProtocol(); if (!connectionAllowedProtocols.contains(protocol)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.protocolnotallowed"), new Object[] { protocol })); getServletContext().log("protocol not allowed accessing " + url.toString()); return; } boolean remoteIsHttp = protocol.equals("http") || protocol.equals("https"); boolean forwardCookies = remoteIsHttp && enableCookieForwarding && allowCookieForwarding; boolean forwardFormData = remoteIsHttp && enableFormDataForwarding && allowFormDataForwarding && (enableFormDataSecureInsecureForwarding || !req.isSecure() || url.getProtocol().equals("https")); if (forwardFormData) { String query = req.getQueryString(); if (query != null && query.length() > 0) { if (url.getQuery() == null || url.getQuery().length() == 0) url = new URL(url.toExternalForm() + "?" + query); else url = new URL(url.toExternalForm() + "&" + query); } } JGlossURLRewriter rewriter = new JGlossURLRewriter(new URL(req.getScheme(), req.getServerName(), req.getServerPort(), req.getContextPath() + req.getServletPath()).toExternalForm(), url, connectionAllowedProtocols, allowCookieForwarding, allowFormDataForwarding); URLConnection connection = url.openConnection(); if (forwardFormData && post && remoteIsHttp) { getServletContext().log("using POST"); try { ((HttpURLConnection) connection).setRequestMethod("POST"); } catch (ClassCastException ex) { getServletContext().log("failed to set method POST: " + ex.getMessage()); } connection.setDoInput(true); connection.setDoOutput(true); } String acceptEncoding = buildAcceptEncoding(req.getHeader("accept-encoding")); getServletContext().log("accept-encoding: " + acceptEncoding); if (acceptEncoding != null) connection.setRequestProperty("Accept-Encoding", acceptEncoding); forwardRequestHeaders(connection, req); if (forwardCookies && (enableCookieSecureInsecureForwarding || !req.isSecure() || url.getProtocol().equals("https"))) CookieTools.addRequestCookies(connection, req.getCookies(), getServletContext()); try { connection.connect(); } catch (UnknownHostException ex) { resp.sendError(HttpServletResponse.SC_BAD_GATEWAY, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.unknownhost"), new Object[] { url.toExternalForm(), url.getHost() })); return; } catch (IOException ex) { resp.sendError(HttpServletResponse.SC_BAD_GATEWAY, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.connect"), new Object[] { url.toExternalForm(), ex.getClass().getName(), ex.getMessage() })); return; } if (forwardFormData && post && remoteIsHttp) { InputStream is = req.getInputStream(); OutputStream os = connection.getOutputStream(); byte[] buf = new byte[512]; int len; while ((len = is.read(buf)) != -1) os.write(buf, 0, len); is.close(); os.close(); } forwardResponseHeaders(connection, req, resp, rewriter); if (forwardCookies && (enableCookieSecureInsecureForwarding || req.isSecure() || !url.getProtocol().equals("https"))) CookieTools.addResponseCookies(connection, resp, req.getServerName(), req.getContextPath() + req.getServletPath(), req.isSecure(), getServletContext()); if (remoteIsHttp) { try { int response = ((HttpURLConnection) connection).getResponseCode(); getServletContext().log("response code " + response); resp.setStatus(response); if (response == 304) return; } catch (ClassCastException ex) { getServletContext().log("failed to read response code: " + ex.getMessage()); } } String type = connection.getContentType(); getServletContext().log("content type " + type + " url " + connection.getURL().toString()); boolean supported = false; if (type != null) { for (int i = 0; i < rewrittenContentTypes.length; i++) if (type.startsWith(rewrittenContentTypes[i])) { supported = true; break; } } if (supported) { String encoding = connection.getContentEncoding(); supported = encoding == null || encoding.endsWith("gzip") || encoding.endsWith("deflate") || encoding.equals("identity"); } if (supported) rewrite(connection, req, resp, rewriter); else tunnel(connection, req, resp); } |
11
| Code Sample 1:
public void run() { FileInputStream src; try { src = new FileInputStream(srcName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileOutputStream dest; FileChannel srcC = src.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(BUFFER_SIZE); try { int i = 1; int fileNo = 0; long maxByte = this.maxSize << 10; long nbByte = srcC.size(); long nbFile = (nbByte / maxByte) + 1; for (fileNo = 0; fileNo < nbFile; fileNo++) { long fileByte = 0; String destName = srcName + "_" + fileNo; dest = new FileOutputStream(destName); FileChannel destC = dest.getChannel(); while ((i > 0) && fileByte < maxByte) { i = srcC.read(buf); buf.flip(); fileByte += i; destC.write(buf); buf.compact(); } destC.close(); dest.close(); } } catch (IOException e1) { e1.printStackTrace(); return; } }
Code Sample 2:
protected void zipFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(to)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); } |
00
| Code Sample 1:
private void unpackBundle() throws IOException { File useJarPath = null; if (DownloadManager.isWindowsVista()) { useJarPath = lowJarPath; File jarDir = useJarPath.getParentFile(); if (jarDir != null) { jarDir.mkdirs(); } } else { useJarPath = jarPath; } DownloadManager.log("Unpacking " + this + " to " + useJarPath); InputStream rawStream = new FileInputStream(localPath); JarInputStream in = new JarInputStream(rawStream) { public void close() throws IOException { } }; try { File jarTmp = null; JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { String entryName = entry.getName(); if (entryName.equals("classes.pack")) { File packTmp = new File(useJarPath + ".pack"); packTmp.getParentFile().mkdirs(); DownloadManager.log("Writing temporary .pack file " + packTmp); OutputStream tmpOut = new FileOutputStream(packTmp); try { DownloadManager.send(in, tmpOut); } finally { tmpOut.close(); } jarTmp = new File(useJarPath + ".tmp"); DownloadManager.log("Writing temporary .jar file " + jarTmp); unpack(packTmp, jarTmp); packTmp.delete(); } else if (!entryName.startsWith("META-INF")) { File dest; if (DownloadManager.isWindowsVista()) { dest = new File(lowJavaPath, entryName.replace('/', File.separatorChar)); } else { dest = new File(DownloadManager.JAVA_HOME, entryName.replace('/', File.separatorChar)); } if (entryName.equals(BUNDLE_JAR_ENTRY_NAME)) dest = useJarPath; File destTmp = new File(dest + ".tmp"); boolean exists = dest.exists(); if (!exists) { DownloadManager.log(dest + ".mkdirs()"); dest.getParentFile().mkdirs(); } try { DownloadManager.log("Using temporary file " + destTmp); FileOutputStream out = new FileOutputStream(destTmp); try { byte[] buffer = new byte[2048]; int c; while ((c = in.read(buffer)) > 0) out.write(buffer, 0, c); } finally { out.close(); } if (exists) dest.delete(); DownloadManager.log("Renaming from " + destTmp + " to " + dest); if (!destTmp.renameTo(dest)) { throw new IOException("unable to rename " + destTmp + " to " + dest); } } catch (IOException e) { if (!exists) throw e; } } } if (jarTmp != null) { if (useJarPath.exists()) jarTmp.delete(); else if (!jarTmp.renameTo(useJarPath)) { throw new IOException("unable to rename " + jarTmp + " to " + useJarPath); } } if (DownloadManager.isWindowsVista()) { DownloadManager.log("Using broker to move " + name); if (!DownloadManager.moveDirWithBroker(DownloadManager.getKernelJREDir() + name)) { throw new IOException("unable to create " + name); } DownloadManager.log("Broker finished " + name); } DownloadManager.log("Finished unpacking " + this); } finally { rawStream.close(); } if (deleteOnInstall) { localPath.delete(); } }
Code Sample 2:
public void sendMessageToServer(String msg, Map<String, String> args, StringCallback cb, URLConstructor ctor) { try { int tmpPort = port; for (; tmpPort < port + 10; tmpPort++) { Socket tmpSock; try { tmpSock = socketsManager.connect(new InetSocketAddress(host, port), 5000); tmpSock.close(); break; } catch (IOException e) { } } Map<String, String> newArgs = new HashMap<String, String>(args); newArgs.put("_f", String.valueOf(System.currentTimeMillis())); String request = ctor.constructURL(msg, newArgs); HttpClient client = new SimpleLimeHttpClient(); HttpGet get = new HttpGet("http://" + host + ":" + port + "/" + request); HttpProtocolParams.setVersion(client.getParams(), HttpVersion.HTTP_1_1); HttpResponse response = client.execute(get); String res = ""; if (response.getEntity() != null) { String result; if (response.getEntity() != null) { result = EntityUtils.toString(response.getEntity()); } else { result = null; } res = result; } cb.process(res); } catch (IOException e) { fail(e); } catch (HttpException e) { fail(e); } catch (URISyntaxException e) { fail(e); } catch (InterruptedException e) { fail(e); } } |
00
| Code Sample 1:
public void saveUserUpFile(UserInfo userInfo, String distFileName, InputStream instream) throws IOException { String fullPicFile = BBSCSUtil.getUserWebFilePath(userInfo.getId()) + distFileName; String fullPicFileSmall = BBSCSUtil.getUserWebFilePath(userInfo.getId()) + distFileName + Constant.IMG_SMALL_FILEPREFIX; OutputStream bos = new FileOutputStream(fullPicFile); IOUtils.copy(instream, bos); ImgUtil.reduceImg(fullPicFile, fullPicFileSmall, this.getSysConfig().getFaceWidth(), this.getSysConfig().getFaceHigh(), 0); }
Code Sample 2:
public static void openFile(PublicHubList hublist, String url) { BufferedReader fichAl; String linha; try { if (url.startsWith("http://")) fichAl = new BufferedReader(new InputStreamReader((new java.net.URL(url)).openStream())); else fichAl = new BufferedReader(new FileReader(url)); while ((linha = fichAl.readLine()) != null) { try { hublist.addDCHub(new DCHub(linha, DCHub.hublistFormater)); } catch (Exception e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } |
00
| Code Sample 1:
public int addPermissionsForUserAndAgenda(Integer userId, Integer agendaId, String permissions) throws TechnicalException { if (permissions == null) { throw new TechnicalException(new Exception(new Exception("Column 'permissions' cannot be null"))); } Session session = null; Transaction transaction = null; try { session = HibernateUtil.getCurrentSession(); transaction = session.beginTransaction(); String query = "INSERT INTO j_user_agenda (userId, agendaId, permissions) VALUES(" + userId + "," + agendaId + ",\"" + permissions + "\")"; Statement statement = session.connection().createStatement(); int rowsUpdated = statement.executeUpdate(query); transaction.commit(); return rowsUpdated; } catch (HibernateException ex) { if (transaction != null) transaction.rollback(); throw new TechnicalException(ex); } catch (SQLException e) { if (transaction != null) transaction.rollback(); throw new TechnicalException(e); } }
Code Sample 2:
public UserAgentContext getUserAgentContext() { return new UserAgentContext() { public HttpRequest createHttpRequest() { return new HttpRequest() { private byte[] bytes; private Vector<ReadyStateChangeListener> readyStateChangeListeners = new Vector<ReadyStateChangeListener>(); public void abort() { } public void addReadyStateChangeListener(ReadyStateChangeListener readyStateChangeListener) { readyStateChangeListeners.add(readyStateChangeListener); } public String getAllResponseHeaders() { return null; } public int getReadyState() { return bytes != null ? STATE_COMPLETE : STATE_UNINITIALIZED; } public byte[] getResponseBytes() { return bytes; } public String getResponseHeader(String arg0) { return null; } public Image getResponseImage() { return bytes != null ? Toolkit.getDefaultToolkit().createImage(bytes) : null; } public String getResponseText() { return new String(bytes); } public Document getResponseXML() { return null; } public int getStatus() { return 200; } public String getStatusText() { return "OK"; } public void open(String method, String url) { open(method, url, false); } public void open(String method, URL url) { open(method, url, false); } public void open(String mehod, URL url, boolean async) { try { URLConnection connection = url.openConnection(); bytes = new byte[connection.getContentLength()]; InputStream inputStream = connection.getInputStream(); inputStream.read(bytes); inputStream.close(); for (ReadyStateChangeListener readyStateChangeListener : readyStateChangeListeners) { readyStateChangeListener.readyStateChanged(); } } catch (IOException e) { } } public void open(String method, String url, boolean async) { open(method, URLHelper.createURL(url), async); } public void open(String method, String url, boolean async, String arg3) { open(method, URLHelper.createURL(url), async); } public void open(String method, String url, boolean async, String arg3, String arg4) { open(method, URLHelper.createURL(url), async); } }; } public String getAppCodeName() { return null; } public String getAppMinorVersion() { return null; } public String getAppName() { return null; } public String getAppVersion() { return null; } public String getBrowserLanguage() { return null; } public String getCookie(URL arg0) { return null; } public String getPlatform() { return null; } public int getScriptingOptimizationLevel() { return 0; } public Policy getSecurityPolicy() { return null; } public String getUserAgent() { return null; } public boolean isCookieEnabled() { return false; } public boolean isMedia(String arg0) { return false; } public boolean isScriptingEnabled() { return false; } public void setCookie(URL arg0, String arg1) { } }; } |
11
| Code Sample 1:
protected void copyAndDelete(final URL _src, final long _temp) throws IOException { final File storage = getStorageFile(_src, _temp); final File dest = new File(_src.getFile()); FileChannel in = null; FileChannel out = null; if (storage.equals(dest)) { return; } try { readWriteLock_.lockWrite(); if (dest.exists()) { dest.delete(); } if (storage.exists() && !storage.renameTo(dest)) { in = new FileInputStream(storage).getChannel(); out = new FileOutputStream(dest).getChannel(); final long len = in.size(); final long copied = out.transferFrom(in, 0, in.size()); if (len != copied) { throw new IOException("unable to complete write"); } } } finally { readWriteLock_.unlockWrite(); try { if (in != null) { in.close(); } } catch (final IOException _evt) { FuLog.error(_evt); } try { if (out != null) { out.close(); } } catch (final IOException _evt) { FuLog.error(_evt); } storage.delete(); } }
Code Sample 2:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String requestURI = req.getRequestURI(); logger.info("The requested URI: {}", requestURI); String parameter = requestURI.substring(requestURI.lastIndexOf(ARXIVID_ENTRY) + ARXIVID_ENTRY_LENGTH); int signIndex = parameter.indexOf(StringUtil.ARXIVID_SEGMENTID_DELIMITER); String arxivId = signIndex != -1 ? parameter.substring(0, signIndex) : parameter; String segmentId = signIndex != -1 ? parameter.substring(signIndex + 1) : null; if (arxivId == null) { logger.error("The request with an empty arxiv id parameter"); return; } String filePath = segmentId == null ? format("/opt/mocassin/aux-pdf/%s" + StringUtil.arxivid2filename(arxivId, "pdf")) : "/opt/mocassin/pdf/" + StringUtil.segmentid2filename(arxivId, Integer.parseInt(segmentId), "pdf"); if (!new File(filePath).exists()) { filePath = format("/opt/mocassin/aux-pdf/%s", StringUtil.arxivid2filename(arxivId, "pdf")); } try { FileInputStream fileInputStream = new FileInputStream(filePath); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(fileInputStream, byteArrayOutputStream); resp.setContentType("application/pdf"); resp.setHeader("Content-disposition", String.format("attachment; filename=%s", StringUtil.arxivid2filename(arxivId, "pdf"))); ServletOutputStream outputStream = resp.getOutputStream(); outputStream.write(byteArrayOutputStream.toByteArray()); outputStream.close(); } catch (FileNotFoundException e) { logger.error("Error while downloading: PDF file= '{}' not found", filePath); } catch (IOException e) { logger.error("Error while downloading the PDF file", e); } } |
11
| Code Sample 1:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
Code Sample 2:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) throw new IOException("Destination '" + destFile + "' exists but is a directory"); FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); if (preserveFileDate) destFile.setLastModified(srcFile.lastModified()); } |
11
| Code Sample 1:
public static File createGzip(File inputFile) { File targetFile = new File(inputFile.getParentFile(), inputFile.getName() + ".gz"); if (targetFile.exists()) { log.warn("The target file '" + targetFile + "' already exists. Will overwrite"); } FileInputStream in = null; GZIPOutputStream out = null; try { int read = 0; byte[] data = new byte[BUFFER_SIZE]; in = new FileInputStream(inputFile); out = new GZIPOutputStream(new FileOutputStream(targetFile)); while ((read = in.read(data, 0, BUFFER_SIZE)) != -1) { out.write(data, 0, read); } in.close(); out.close(); boolean deleteSuccess = inputFile.delete(); if (!deleteSuccess) { log.warn("Could not delete file '" + inputFile + "'"); } log.info("Successfully created gzip file '" + targetFile + "'."); } catch (Exception e) { log.error("Exception while creating GZIP.", e); } finally { StreamUtil.tryCloseStream(in); StreamUtil.tryCloseStream(out); } return targetFile; }
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 RespID(PublicKey key) throws OCSPException { try { MessageDigest digest = MessageDigest.getInstance("SHA1"); ASN1InputStream aIn = new ASN1InputStream(key.getEncoded()); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); digest.update(info.getPublicKeyData().getBytes()); ASN1OctetString keyHash = new DEROctetString(digest.digest()); this.id = new ResponderID(keyHash); } catch (Exception e) { throw new OCSPException("problem creating ID: " + e, e); } }
Code Sample 2:
protected Context getResource3ServerInitialContext() throws Exception { if (resource3ServerJndiProps == null) { URL url = ClassLoader.getSystemResource("jndi.properties"); resource3ServerJndiProps = new java.util.Properties(); resource3ServerJndiProps.load(url.openStream()); String jndiHost = System.getProperty("jbosstest.resource3.server.host", "localhost"); String jndiUrl = "jnp://" + jndiHost + ":1099"; resource3ServerJndiProps.setProperty("java.naming.provider.url", jndiUrl); } return new InitialContext(resource3ServerJndiProps); } |
00
| Code Sample 1:
@SuppressWarnings("finally") @Override public String read(EnumSensorType sensorType, Map<String, String> stateMap) { BufferedReader in = null; StringBuffer result = new StringBuffer(); try { URL url = new URL(getUrl()); in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { result.append(str); } } catch (ConnectException ce) { logger.error("MockupStatusCommand excute fail: " + ce.getMessage()); } catch (Exception e) { logger.error("MockupStatusCommand excute fail: " + e.getMessage()); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("BufferedReader could not be closed", e); } } return result.toString(); } }
Code Sample 2:
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()); } } } |
11
| Code Sample 1:
public void testCopyFolderContents() throws IOException { log.info("Running: testCopyFolderContents()"); IOUtils.copyFolderContents(srcFolderName, destFolderName); Assert.assertTrue(destFile1.exists() && destFile1.isFile()); Assert.assertTrue(destFile2.exists() && destFile2.isFile()); Assert.assertTrue(destFile3.exists() && destFile3.isFile()); }
Code Sample 2:
public void copyToZip(ZipOutputStream zout, String entryName) throws IOException { close(); ZipEntry entry = new ZipEntry(entryName); zout.putNextEntry(entry); if (!isEmpty() && this.tmpFile.exists()) { InputStream in = new FileInputStream(this.tmpFile); IOUtils.copyTo(in, zout); in.close(); } zout.flush(); zout.closeEntry(); delete(); } |
00
| Code Sample 1:
public static void addProviders(URL url) { Reader reader = null; Properties prop = new Properties(); try { reader = new InputStreamReader(url.openStream()); prop.load(reader); } catch (Throwable t) { } finally { if (reader != null) { try { reader.close(); } catch (Throwable t) { } } } for (Map.Entry<Object, Object> entry : prop.entrySet()) { try { Class<?> cla = Class.forName((String) entry.getValue(), true, Thread.currentThread().getContextClassLoader()); providers.put(((String) entry.getKey()).toUpperCase(), (CharsetProvider) cla.newInstance()); } catch (Throwable t) { } } }
Code Sample 2:
public static synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } |
00
| Code Sample 1:
public static OMElement createOMRequest(String file, int count, String[] documentIds) throws Exception { ObjectFactory factory = new ObjectFactory(); SubmitDocumentRequest sdr = factory.createSubmitDocumentRequest(); IdType pid = factory.createIdType(); pid.setRoot("1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478"); sdr.setPatientId(pid); ClassLoader classLoader = JUnitHelper.class.getClassLoader(); DocumentsType documents = factory.createDocumentsType(); for (int i = 0; i < count; ++i) { DocumentType document = factory.createDocumentType(); if ((documentIds != null) && (documentIds.length > i)) { document.setId(documentIds[i]); } CodeType type = factory.createCodeType(); type.setCode("51855-5"); type.setCodeSystem("2.16.840.1.113883.6.1"); document.setType(type); ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream is = classLoader.getResourceAsStream(file); assertNotNull(is); IOUtils.copy(is, bos); document.setContent(bos.toByteArray()); documents.getDocument().add(document); } sdr.setDocuments(documents); QName qname = new QName(URIConstants.XDSBRIDGE_URI, "SubmitDocumentRequest"); JAXBContext jc = JAXBContext.newInstance(SubmitDocumentRequest.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); JAXBElement element = new JAXBElement(qname, sdr.getClass(), sdr); StringWriter sw = new StringWriter(); marshaller.marshal(element, sw); String xml = sw.toString(); logger.debug(xml); OMElement result = AXIOMUtil.stringToOM(OMAbstractFactory.getOMFactory(), xml); List<OMElement> list = XPathHelper.selectNodes(result, "./ns:Documents/ns:Document/ns:Content", URIConstants.XDSBRIDGE_URI); for (OMElement contentNode : list) { OMText binaryNode = (OMText) contentNode.getFirstOMChild(); if (binaryNode != null) { binaryNode.setOptimize(true); } } return result; }
Code Sample 2:
private static String encode(String str, String method) { MessageDigest md = null; String dstr = null; try { md = MessageDigest.getInstance(method); md.update(str.getBytes()); dstr = new BigInteger(1, md.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return dstr; } |
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:
public static String encrypt(String text) throws NoSuchAlgorithmException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; try { md.update(text.getBytes("iso-8859-1"), 0, text.length()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } md5hash = md.digest(); return convertToHex(md5hash); } |
11
| Code Sample 1:
public void write(URL exportUrl, OutputStream output) throws Exception { if (exportUrl == null || output == null) { throw new RuntimeException("null passed in for required parameters"); } MediaContent mc = new MediaContent(); mc.setUri(exportUrl.toString()); MediaSource ms = service.getMedia(mc); InputStream input = ms.getInputStream(); IOUtils.copy(input, output); }
Code Sample 2:
@Override public File fetchHSMFile(String fsID, String filePath) throws HSMException { log.debug("fetchHSMFile called with fsID=" + fsID + ", filePath=" + filePath); if (absIncomingDir.mkdirs()) { log.info("M-WRITE " + absIncomingDir); } File tarFile; try { tarFile = File.createTempFile("hsm_", ".tar", absIncomingDir); } catch (IOException x) { throw new HSMException("Failed to create temp file in " + absIncomingDir, x); } log.info("Fetching " + filePath + " from cloud storage"); FileOutputStream fos = null; try { if (s3 == null) createClient(); S3Object object = s3.getObject(new GetObjectRequest(bucketName, filePath)); fos = new FileOutputStream(tarFile); IOUtils.copy(object.getObjectContent(), fos); } catch (AmazonClientException ace) { s3 = null; throw new HSMException("Could not list objects for: " + filePath, ace); } catch (Exception x) { throw new HSMException("Failed to retrieve " + filePath, x); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { log.error("Couldn't close output stream for: " + tarFile); } } } return tarFile; } |
00
| Code Sample 1:
private String mkSid() { String temp = toString(); MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } messagedigest.update(temp.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } return chk.toString(); }
Code Sample 2:
public Resource get(URL serviceUrl, String resourceId) throws Exception { Resource resource = new Resource(); String openurl = serviceUrl.toString() + "?url_ver=Z39.88-2004" + "&rft_id=" + URLEncoder.encode(resourceId, "UTF-8") + "&svc_id=" + SVCID_ADORE4; log.debug("OpenURL Request: " + openurl); URL url; try { url = new URL(openurl); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); int code = huc.getResponseCode(); if (code == 200) { InputStream is = huc.getInputStream(); resource.setBytes(StreamUtil.getByteArray(is)); resource.setContentType(huc.getContentType()); } else { log.error("An error of type " + code + " occurred for " + url.toString()); throw new Exception("Cannot get " + url.toString()); } } catch (MalformedURLException e) { throw new Exception("A MalformedURLException occurred for " + openurl); } catch (IOException e) { throw new Exception("An IOException occurred attempting to connect to " + openurl); } return resource; } |
11
| Code Sample 1:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String act = request.getParameter("act"); if (null == act) { } else if ("down".equalsIgnoreCase(act)) { String vest = request.getParameter("vest"); String id = request.getParameter("id"); if (null == vest) { t_attach_Form attach = null; t_attach_QueryMap query = new t_attach_QueryMap(); attach = query.getByID(id); if (null != attach) { String filename = attach.getAttach_name(); String fullname = attach.getAttach_fullname(); response.addHeader("Content-Disposition", "attachment;filename=" + filename + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); } } } else if ("review".equalsIgnoreCase(vest)) { t_infor_review_QueryMap reviewQuery = new t_infor_review_QueryMap(); t_infor_review_Form review = reviewQuery.getByID(id); String seq = request.getParameter("seq"); String name = null, fullname = null; if ("1".equals(seq)) { name = review.getAttachname1(); fullname = review.getAttachfullname1(); } else if ("2".equals(seq)) { name = review.getAttachname2(); fullname = review.getAttachfullname2(); } else if ("3".equals(seq)) { name = review.getAttachname3(); fullname = review.getAttachfullname3(); } String downTypeStr = DownType.getInst().getDownTypeByFileName(name); logger.debug("filename=" + name + " downtype=" + downTypeStr); response.setContentType(downTypeStr); response.addHeader("Content-Disposition", "attachment;filename=" + name + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); in.close(); } } } else if ("upload".equalsIgnoreCase(act)) { String infoId = request.getParameter("inforId"); logger.debug("infoId=" + infoId); } } catch (Exception e) { } }
Code Sample 2:
public TempFileTextBody(InputStream is, String mimeCharset) throws IOException { this.mimeCharset = mimeCharset; TempPath tempPath = TempStorage.getInstance().getRootTempPath(); tempFile = tempPath.createTempFile("attachment", ".txt"); OutputStream out = tempFile.getOutputStream(); IOUtils.copy(is, out); out.close(); } |
00
| Code Sample 1:
public static String getRandomUserAgent() { if (USER_AGENT_CACHE == null) { Collection<String> userAgentsCache = new ArrayList<String>(); try { URL url = Tools.getResource(UserAgent.class.getClassLoader(), "user-agents-browser.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { userAgentsCache.add(str); } in.close(); USER_AGENT_CACHE = userAgentsCache.toArray(new String[userAgentsCache.size()]); } catch (Exception e) { System.err.println("Can not read file; using default user-agent; error message: " + e.getMessage()); return DEFAULT_USER_AGENT; } } return USER_AGENT_CACHE[new Random().nextInt(USER_AGENT_CACHE.length)]; }
Code Sample 2:
public static void appendFile(String namePrefix, File baseDir, File file, ZipOutputStream zipOut) throws IOException { Assert.Arg.notNull(baseDir, "baseDir"); Assert.Arg.notNull(file, "file"); Assert.Arg.notNull(zipOut, "zipOut"); if (namePrefix == null) namePrefix = ""; String path = FileSystemUtils.getRelativePath(baseDir, file); ZipEntry zipEntry = new ZipEntry(namePrefix + path); zipOut.putNextEntry(zipEntry); InputStream fileInput = FileUtils.openInputStream(file); try { org.apache.commons.io.IOUtils.copyLarge(fileInput, zipOut); } finally { fileInput.close(); } } |
00
| Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
static final void executeUpdate(Collection<String> queries, DBConnector connector) throws IOException { Connection con = null; Statement st = null; try { con = connector.getDB(); con.setAutoCommit(false); st = con.createStatement(); for (String s : queries) st.executeUpdate(s); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } throw new IOException(e.getMessage()); } finally { if (st != null) { try { st.close(); } catch (SQLException ignore) { } } if (con != null) { try { con.close(); } catch (SQLException ignore) { } } } } |
00
| Code Sample 1:
public void run() { date = DateUtil.addMonth(-1); List list = bo.getDao().getHibernateTemplate().find("from MailAffixPojo where upload_time <'" + date + "' and to_number(sized) >" + size); if (null != list && list.size() > 0) { try { FTPClient ftp = new FTPClient(); ftp.connect(config.getHostUrl(), config.getFtpPort()); ftp.login(config.getUname(), config.getUpass()); int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { ftp.disconnect(); return; } for (int i = 0; i < list.size(); i++) { MailAffixPojo pojo = (MailAffixPojo) list.get(i); ftp.changeWorkingDirectory(pojo.getUploadTime().substring(0, 7)); ftp.deleteFile(pojo.getAffixSaveName()); ftp.changeToParentDirectory(); bo.delete(MailAffixPojo.class, new Long(pojo.getId())); } } catch (Exception e) { e.printStackTrace(); } } }
Code Sample 2:
public boolean crear() { int result = 0; String sql = "insert into divisionxTorneo" + "(torneo_idTorneo, tipoTorneo_idTipoTorneo, nombreDivision, descripcion, numJugadores, numFechas, terminado, tipoDesempate, rondaActual, ptosxbye)" + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement(); result = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (result > 0); } |
11
| Code Sample 1:
@Override public void write(OutputStream output) throws IOException, WebApplicationException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final GZIPOutputStream gzipOs = new GZIPOutputStream(baos); IOUtils.copy(is, gzipOs); baos.close(); gzipOs.close(); output.write(baos.toByteArray()); }
Code Sample 2:
public static long writeInputStreamToOutputStream(final InputStream in, final OutputStream out) { long size = 0; try { size = IOUtils.copyLarge(in, out); } catch (IOException e1) { e1.printStackTrace(); } return size; } |
00
| Code Sample 1:
public boolean createUser(String username, String password, String name) throws Exception { boolean user_created = false; try { statement = connect.prepareStatement("SELECT COUNT(*) from toepen.users WHERE username = ? LIMIT 1"); statement.setString(1, username); resultSet = statement.executeQuery(); resultSet.next(); if (resultSet.getInt(1) == 0) { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); String password_hash = hash.toString(16); long ctime = System.currentTimeMillis() / 1000; statement = connect.prepareStatement("INSERT INTO toepen.users " + "(username, password, name, ctime) " + "VALUES (?, ?, ?, ?)"); statement.setString(1, username); statement.setString(2, password_hash); statement.setString(3, name); statement.setLong(4, ctime); if (statement.executeUpdate() > 0) { user_created = true; } } } catch (Exception ex) { System.out.println(ex); } finally { close(); return user_created; } }
Code Sample 2:
private static MimeType getMimeType(URL url) { String mimeTypeString = null; String charsetFromWebServer = null; String contentType = null; InputStream is = null; MimeType mimeTypeFromWebServer = null; MimeType mimeTypeFromFileSuffix = null; MimeType mimeTypeFromMagicNumbers = null; String fileSufix = null; if (url == null) return null; try { try { is = url.openConnection().getInputStream(); contentType = url.openConnection().getContentType(); } catch (IOException e) { } if (contentType != null) { StringTokenizer st = new StringTokenizer(contentType, ";"); if (st.hasMoreTokens()) mimeTypeString = st.nextToken().toLowerCase(); if (st.hasMoreTokens()) charsetFromWebServer = st.nextToken().toLowerCase(); if (charsetFromWebServer != null) { st = new StringTokenizer(charsetFromWebServer, "="); charsetFromWebServer = null; if (st.hasMoreTokens()) st.nextToken(); if (st.hasMoreTokens()) charsetFromWebServer = st.nextToken().toUpperCase(); } } mimeTypeFromWebServer = mimeString2mimeTypeMap.get(mimeTypeString); fileSufix = getFileSufix(url); mimeTypeFromFileSuffix = getMimeType(fileSufix); mimeTypeFromMagicNumbers = guessTypeUsingMagicNumbers(is, charsetFromWebServer); } finally { IOUtils.closeQuietly(is); } return decideBetweenThreeMimeTypes(mimeTypeFromWebServer, mimeTypeFromFileSuffix, mimeTypeFromMagicNumbers); } |
00
| Code Sample 1:
public boolean copy(String file, String path) { try { File file_in = new File(file); String tmp1, tmp2; tmp1 = file; tmp2 = path; while (tmp2.contains("\\")) { tmp2 = tmp2.substring(tmp2.indexOf("\\") + 1); tmp1 = tmp1.substring(tmp1.indexOf("\\") + 1); } tmp1 = file.substring(0, file.length() - tmp1.length()) + tmp2 + tmp1.substring(tmp1.indexOf("\\")); File file_out = new File(tmp1); File parent = file_out.getParentFile(); parent.mkdirs(); FileInputStream in1 = new FileInputStream(file_in); FileOutputStream out1 = new FileOutputStream(file_out); byte[] bytes = new byte[1024]; int c; while ((c = in1.read(bytes)) != -1) out1.write(bytes, 0, c); in1.close(); out1.close(); return true; } catch (Exception e) { e.printStackTrace(); System.out.println("Error!"); return false; } }
Code Sample 2:
public static boolean copyDataToNewTable(EboContext p_eboctx, String srcTableName, String destTableName, String where, boolean log, int mode) throws boRuntimeException { srcTableName = srcTableName.toUpperCase(); destTableName = destTableName.toUpperCase(); Connection cn = null; Connection cndef = null; boolean ret = false; try { boolean srcexists = false; boolean destexists = false; final InitialContext ic = new InitialContext(); cn = p_eboctx.getConnectionData(); cndef = p_eboctx.getConnectionDef(); PreparedStatement pstm = cn.prepareStatement("SELECT TABLE_NAME FROM USER_TABLES WHERE TABLE_NAME=?"); pstm.setString(1, srcTableName); ResultSet rslt = pstm.executeQuery(); if (rslt.next()) { srcexists = true; } rslt.close(); pstm.setString(1, destTableName); rslt = pstm.executeQuery(); if (rslt.next()) { destexists = true; } if (!destexists) { rslt.close(); pstm.close(); pstm = cn.prepareStatement("SELECT VIEW_NAME FROM USER_VIEWS WHERE VIEW_NAME=?"); pstm.setString(1, destTableName); rslt = pstm.executeQuery(); if (rslt.next()) { CallableStatement cstm = cn.prepareCall("DROP VIEW " + destTableName); cstm.execute(); cstm.close(); } } rslt.close(); pstm.close(); if (srcexists && !destexists) { if (log) { logger.finest(LoggerMessageLocalizer.getMessage("CREATING_AND_COPY_DATA_FROM") + " [" + srcTableName + "] " + LoggerMessageLocalizer.getMessage("TO") + " [" + destTableName + "]"); } CallableStatement cstm = cn.prepareCall("CREATE TABLE " + destTableName + " AS SELECT * FROM " + srcTableName + " " + (((where != null) && (where.length() > 0)) ? (" WHERE " + where) : "")); cstm.execute(); cstm.close(); if (log) { logger.finest(LoggerMessageLocalizer.getMessage("UPDATING_NGTDIC")); } cn.commit(); ret = true; } else if (srcexists && destexists) { if (log) { logger.finest(LoggerMessageLocalizer.getMessage("COPY_DATA_FROM") + " [" + srcTableName + "] " + LoggerMessageLocalizer.getMessage("TO") + " [" + destTableName + "]"); } PreparedStatement pstm2 = cn.prepareStatement("SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = ? "); pstm2.setString(1, destTableName); ResultSet rslt2 = pstm2.executeQuery(); StringBuffer fields = new StringBuffer(); PreparedStatement pstm3 = cn.prepareStatement("SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = ? and COLUMN_NAME=?"); while (rslt2.next()) { pstm3.setString(1, srcTableName); pstm3.setString(2, rslt2.getString(1)); ResultSet rslt3 = pstm3.executeQuery(); if (rslt3.next()) { if (fields.length() > 0) { fields.append(','); } fields.append('"').append(rslt2.getString(1)).append('"'); } rslt3.close(); } pstm3.close(); rslt2.close(); pstm2.close(); CallableStatement cstm; int recs = 0; if ((mode == 0) || (mode == 1)) { cstm = cn.prepareCall("INSERT INTO " + destTableName + "( " + fields.toString() + " ) ( SELECT " + fields.toString() + " FROM " + srcTableName + " " + (((where != null) && (where.length() > 0)) ? (" WHERE " + where) : "") + ")"); recs = cstm.executeUpdate(); cstm.close(); if (log) { logger.finest(LoggerMessageLocalizer.getMessage("DONE") + " [" + recs + "] " + LoggerMessageLocalizer.getMessage("RECORDS_COPIED")); } } cn.commit(); ret = true; } } catch (Exception e) { try { cn.rollback(); } catch (Exception z) { throw new boRuntimeException("boBuildDB.moveTable", "BO-1304", z); } throw new boRuntimeException("boBuildDB.moveTable", "BO-1304", e); } finally { try { cn.close(); } catch (Exception e) { } try { cndef.close(); } catch (Exception e) { } } return ret; } |
11
| Code Sample 1:
public static void copyFile(String inputFile, String outputFile) throws IOException { FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); for (int b = fis.read(); b != -1; b = fis.read()) fos.write(b); fos.close(); fis.close(); }
Code Sample 2:
@Test public void testCopy_readerToOutputStream_Encoding_nullEncoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, false, true); IOUtils.copy(reader, out, null); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } |
00
| Code Sample 1:
private String getLatestVersion(URL url) throws IOException { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(new BufferedInputStream(con.getInputStream()))); String lines = ""; String line = null; while ((line = br.readLine()) != null) { lines += line; } con.disconnect(); return lines; }
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 void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
private void initialize() { StringBuffer license = new StringBuffer(); URL url; InputStreamReader in; BufferedReader reader; String str; JTextArea textArea; JButton button; GridBagConstraints c; setTitle("mibible License"); setSize(600, 600); setDefaultCloseOperation(DISPOSE_ON_CLOSE); getContentPane().setLayout(new GridBagLayout()); url = getClass().getClassLoader().getResource("LICENSE.txt"); if (url == null) { license.append("Couldn't locate license file (LICENSE.txt)."); } else { try { in = new InputStreamReader(url.openStream()); reader = new BufferedReader(in); while ((str = reader.readLine()) != null) { if (!str.equals(" ")) { license.append(str); } license.append("\n"); } reader.close(); } catch (IOException e) { license.append("Error reading license file "); license.append("(LICENSE.txt):\n\n"); license.append(e.getMessage()); } } textArea = new JTextArea(license.toString()); textArea.setEditable(false); c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0d; c.weighty = 1.0d; c.insets = new Insets(4, 5, 4, 5); getContentPane().add(new JScrollPane(textArea), c); button = new JButton("Close"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); c = new GridBagConstraints(); c.gridy = 1; c.anchor = GridBagConstraints.CENTER; c.insets = new Insets(10, 10, 10, 10); getContentPane().add(button, c); } |
11
| Code Sample 1:
public static void main(String[] arg) throws IOException { XmlPullParserFactory PULL_PARSER_FACTORY; try { PULL_PARSER_FACTORY = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); PULL_PARSER_FACTORY.setNamespaceAware(true); DasParser dp = new DasParser(PULL_PARSER_FACTORY); URL url = new URL("http://www.ebi.ac.uk/das-srv/uniprot/das/uniprot/features?segment=P05067"); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String aLine, xml = ""; while ((aLine = br.readLine()) != null) { xml += aLine; } WritebackDocument wbd = dp.parse(xml); System.out.println("FIN" + wbd); } catch (XmlPullParserException xppe) { throw new IllegalStateException("Fatal Exception thrown at initialisation. Cannot initialise the PullParserFactory required to allow generation of the DAS XML.", xppe); } }
Code Sample 2:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { if ((this.jTree2.getSelectionPath() == null) || !(this.jTree2.getSelectionPath().getLastPathComponent() instanceof StyleTreeNode)) { Msg.showMsg("Devi selezionare lo stile sotto il quale caricare la ricetta!", this); return; } if ((this.txtUser.getText() == null) || (this.txtUser.getText().length() == 0)) { Msg.showMsg("Il nome utente è obbligatorio!", this); return; } if ((this.txtPwd.getPassword() == null) || (this.txtPwd.getPassword().length == 0)) { Msg.showMsg("La password è obbligatoria!", this); return; } this.nomeRicetta = this.txtNome.getText(); if ((this.nomeRicetta == null) || (this.nomeRicetta.length() == 0)) { Msg.showMsg("Il nome della ricetta è obbligatorio!", this); return; } StyleTreeNode node = null; if (this.jTree2.getSelectionPath().getLastPathComponent() instanceof StyleTreeNode) { node = (StyleTreeNode) this.jTree2.getSelectionPath().getLastPathComponent(); } try { String data = URLEncoder.encode("nick", "UTF-8") + "=" + URLEncoder.encode(this.txtUser.getText(), "UTF-8"); data += "&" + URLEncoder.encode("pwd", "UTF-8") + "=" + URLEncoder.encode(new String(this.txtPwd.getPassword()), "UTF-8"); data += "&" + URLEncoder.encode("id_stile", "UTF-8") + "=" + URLEncoder.encode(node.getIdStile(), "UTF-8"); data += "&" + URLEncoder.encode("nome_ricetta", "UTF-8") + "=" + URLEncoder.encode(this.nomeRicetta, "UTF-8"); data += "&" + URLEncoder.encode("xml_ricetta", "UTF-8") + "=" + URLEncoder.encode(this.xml, "UTF-8"); URL url = new URL("http://" + Main.config.getRemoteServer() + "/upload_ricetta.asp?" + data); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; String str = ""; while ((line = rd.readLine()) != null) { str += line; } rd.close(); Msg.showMsg(str, this); doDefaultCloseAction(); } catch (Exception e) { Utils.showException(e, "Errore in upload", this); } reloadTree(); } |
11
| Code Sample 1:
public static void copyFiles(String strPath, String trgPath) { File src = new File(strPath); File trg = new File(trgPath); if (src.isDirectory()) { if (trg.exists() != true) trg.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { String strPath_1 = src.getAbsolutePath() + SEPARATOR + list[i]; String trgPath_1 = trg.getAbsolutePath() + SEPARATOR + list[i]; copyFiles(strPath_1, trgPath_1); } } else { try { FileChannel srcChannel = new FileInputStream(strPath).getChannel(); FileChannel dstChannel = new FileOutputStream(trgPath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (FileNotFoundException e) { System.out.println("[Error] File not found: " + e.getMessage()); } catch (IOException e) { System.out.println("[Error] " + e.getMessage()); } } }
Code Sample 2:
public void fileCopy(File inFile, File outFile) { try { FileInputStream in = new FileInputStream(inFile); FileOutputStream out = new FileOutputStream(outFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { System.err.println("Hubo un error de entrada/salida!!!"); } } |
11
| Code Sample 1:
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); } }
Code Sample 2:
public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getCanonicalPath()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getCanonicalPath()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getCanonicalPath()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getCanonicalPath()); throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[1024 * 1024]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); if (fromFile.isHidden()) { } toFile.setLastModified(fromFile.lastModified()); toFile.setExecutable(fromFile.canExecute()); toFile.setReadable(fromFile.canRead()); toFile.setWritable(toFile.canWrite()); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } |
11
| 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:
public Object send(URL url, Object params) throws Exception { params = processRequest(params); String response = ""; BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); response += in.readLine(); while (response != null) response += in.readLine(); in.close(); return processResponse(response); } |
11
| Code Sample 1:
public static boolean copyMerge(FileSystem srcFS, Path srcDir, FileSystem dstFS, Path dstFile, boolean deleteSource, Configuration conf, String addString) throws IOException { dstFile = checkDest(srcDir.getName(), dstFS, dstFile, false); if (!srcFS.getFileStatus(srcDir).isDir()) return false; OutputStream out = dstFS.create(dstFile); try { FileStatus contents[] = srcFS.listStatus(srcDir); for (int i = 0; i < contents.length; i++) { if (!contents[i].isDir()) { InputStream in = srcFS.open(contents[i].getPath()); try { IOUtils.copyBytes(in, out, conf, false); if (addString != null) out.write(addString.getBytes("UTF-8")); } finally { in.close(); } } } } finally { out.close(); } if (deleteSource) { return srcFS.delete(srcDir, true); } else { return true; } }
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 boolean synch(boolean verbose) { try { this.verbose = verbose; if (verbose) System.out.println(" -- Synchronizing: " + destDir + " to " + urlStr); URLConnection urc = new URL(urlStr + "/" + MANIFEST).openConnection(); InputStream is = urc.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); while (true) { String str = r.readLine(); if (str == null) { break; } dealWith(str); } is.close(); } catch (Exception ex) { System.out.println("Synchronization of " + destDir + " failed."); ex.printStackTrace(); return false; } return true; }
Code Sample 2:
public void saveAs(File f) throws CoverException { FileOutputStream fw = null; BufferedInputStream in = null; try { HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setDoInput(true); in = new BufferedInputStream(httpConn.getInputStream()); f.delete(); fw = new FileOutputStream(f); int b; while ((b = in.read()) != -1) fw.write(b); fw.close(); in.close(); } catch (IOException e) { throw new CoverException(e.getMessage()); } finally { try { if (fw != null) fw.close(); if (in != null) in.close(); } catch (IOException ex) { System.err.println("Glurps this is severe: " + ex.getMessage()); } } } |
11
| Code Sample 1:
public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text ".getBytes())); fc.close(); fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("Some more".getBytes())); fc.close(); fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) System.out.print((char) buff.get()); }
Code Sample 2:
public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } |
11
| Code Sample 1:
public int procesar() { int mas = 0; String uriOntologia = "", source = "", uri = ""; String fichOrigenHTML = "", fichOrigenLN = ""; String ficheroOutOWL = ""; md5 firma = null; StringTokenV2 entra = null, entra2 = null, entra3 = null; FileInputStream lengNat = null; BufferedInputStream lengNat2 = null; DataInputStream entradaLenguajeNatural = null; FileWriter salOWL = null; BufferedWriter salOWL2 = null; PrintWriter salidaOWL = null; String sujeto = "", verbo = "", CD = "", CI = "", fraseOrigen = ""; StringTokenV2 token2; boolean bandera = false; OntClass c = null; OntClass cBak = null; String claseTrabajo = ""; String nombreClase = "", nombrePropiedad = "", variasPalabras = ""; int incre = 0, emergencia = 0; String lineaSalida = ""; String[] ontologia = new String[5]; ontologia[0] = "http://www.criado.info/owl/vertebrados_es.owl#"; ontologia[1] = "http://www.w3.org/2001/sw/WebOnt/guide-src/wine#"; ontologia[2] = "http://www.co-ode.org/ontologies/pizza/2005/10/18/pizza.owl#"; ontologia[3] = "http://www.w3.org/2001/sw/WebOnt/guide-src/food#"; ontologia[4] = "http://www.daml.org/2001/01/gedcom/gedcom#"; String[] ontologiaSource = new String[5]; ontologiaSource[0] = this.directorioMapeo + "\\" + "mapeo_vertebrados_es.xml"; ontologiaSource[1] = this.directorioMapeo + "\\" + "mapeo_wine_es.xml"; ontologiaSource[2] = this.directorioMapeo + "\\" + "mapeo_pizza_es.xml"; ontologiaSource[3] = this.directorioMapeo + "\\" + "mapeo_food_es.xml"; ontologiaSource[4] = this.directorioMapeo + "\\" + "mapeo_parentesco_es.xml"; mapeoIdiomas clasesOntologias; try { if ((entrada = entradaFichero.readLine()) != null) { if (entrada.trim().length() > 10) { entrada2 = new StringTokenV2(entrada.trim(), "\""); if (entrada2.isIncluidaSubcadena("<fichero ontologia=")) { ontologiaOrigen = entrada2.getToken(2); fichOrigenHTML = entrada2.getToken(4); fichOrigenLN = entrada2.getToken(6); if (ontologiaOrigen.equals("VERTEBRADOS")) { source = ontologiaSource[0]; uriOntologia = ontologia[0]; } if (ontologiaOrigen.equals("WINE")) { source = ontologiaSource[1]; uriOntologia = ontologia[1]; } if (ontologiaOrigen.equals("PIZZA")) { source = ontologiaSource[2]; uriOntologia = ontologia[2]; } if (ontologiaOrigen.equals("FOOD")) { source = ontologiaSource[3]; uriOntologia = ontologia[3]; } if (ontologiaOrigen.equals("PARENTESCOS")) { source = ontologiaSource[4]; uriOntologia = ontologia[4]; } firma = new md5(uriOntologia, false); clasesOntologias = new mapeoIdiomas(source); uri = ""; ficheroOutOWL = ""; entra2 = new StringTokenV2(fichOrigenHTML, "\\"); int numToken = entra2.getNumeroTokenTotales(); entra = new StringTokenV2(fichOrigenHTML, " "); if (entra.isIncluidaSubcadena(directorioLocal)) { entra = new StringTokenV2(entra.getQuitar(directorioLocal) + "", " "); uri = entra.getCambiar("\\", "/"); uri = entra.getQuitar(entra2.getToken(numToken)) + ""; entra3 = new StringTokenV2(entra2.getToken(numToken), "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; uri = urlPatron + uri + ficheroOutOWL; } entra3 = new StringTokenV2(fichOrigenHTML, "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; lineaSalida = "<vistasemantica origen=\"" + fichOrigenLN + "\" destino=\"" + uri + "\" />"; lengNat = new FileInputStream(fichOrigenLN); lengNat2 = new BufferedInputStream(lengNat); entradaLenguajeNatural = new DataInputStream(lengNat2); salOWL = new FileWriter(ficheroOutOWL); salOWL2 = new BufferedWriter(salOWL); salidaOWL = new PrintWriter(salOWL2); while ((entradaInstancias = entradaLenguajeNatural.readLine()) != null) { sujeto = ""; verbo = ""; CD = ""; CI = ""; fraseOrigen = ""; if (entradaInstancias.trim().length() > 10) { entrada2 = new StringTokenV2(entradaInstancias.trim(), "\""); if (entrada2.isIncluidaSubcadena("<oracion sujeto=")) { sujeto = entrada2.getToken(2).trim(); verbo = entrada2.getToken(4).trim(); CD = entrada2.getToken(6).trim(); CI = entrada2.getToken(8).trim(); fraseOrigen = entrada2.getToken(10).trim(); if (sujeto.length() > 0 & verbo.length() > 0 & CD.length() > 0) { bandera = false; c = null; cBak = null; nombreClase = clasesOntologias.getClaseInstancia(CD); if (nombreClase.length() > 0) { bandera = true; } if (bandera) { if (incre == 0) { salidaOWL.write(" <rdf:RDF " + "\n"); salidaOWL.write(" xmlns:j.0=\"" + uriOntologia + "\"" + "\n"); salidaOWL.write(" xmlns:protege=\"http://protege.stanford.edu/plugins/owl/protege#\"" + "\n"); salidaOWL.write(" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"" + "\n"); salidaOWL.write(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"" + "\n"); salidaOWL.write(" xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"" + "\n"); salidaOWL.write(" xmlns:owl=\"http://www.w3.org/2002/07/owl#\" " + "\n"); salidaOWL.write(" xmlns=\"" + uri + "#\"" + "\n"); salidaOWL.write(" xml:base=\"" + uri + "\">" + "\n"); salidaOWL.write(" <owl:Ontology rdf:about=\"\">" + "\n"); salidaOWL.write(" <owl:imports rdf:resource=\"" + uriOntologia + "\"/>" + "\n"); salidaOWL.write(" </owl:Ontology>" + "\n"); salidaOWL.flush(); salida.write(lineaSalida + "\n"); salida.flush(); incre = 1; } salidaOWL.write(" <j.0:" + nombreClase + " rdf:ID=\"" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" <owl:AllDifferent>" + "\n"); salidaOWL.write(" <owl:distinctMembers rdf:parseType=\"Collection\">" + "\n"); salidaOWL.write(" <" + nombreClase + " rdf:about=\"#" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" </owl:distinctMembers>" + "\n"); salidaOWL.write(" </owl:AllDifferent>" + "\n"); salidaOWL.flush(); bandera = false; } } } } } salidaOWL.write(" </rdf:RDF>" + "\n" + "\n"); salidaOWL.write("<!-- Creado por [html2ws] http://www.luis.criado.org -->" + "\n"); salidaOWL.flush(); } } mas = 1; } else { salida.write("</listaVistasSemanticas>\n"); salida.flush(); salida.close(); bw2.close(); fw2.close(); salidaOWL.close(); entradaFichero.close(); ent2.close(); ent1.close(); mas = -1; } } catch (Exception e) { mas = -2; salida.write("No se encuentra: " + fichOrigen + "\n"); salida.flush(); } return mas; }
Code Sample 2:
protected void zipFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(to)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); } |
00
| Code Sample 1:
public UserAgentContext getUserAgentContext() { return new UserAgentContext() { public HttpRequest createHttpRequest() { return new HttpRequest() { private byte[] bytes; private Vector<ReadyStateChangeListener> readyStateChangeListeners = new Vector<ReadyStateChangeListener>(); public void abort() { } public void addReadyStateChangeListener(ReadyStateChangeListener readyStateChangeListener) { readyStateChangeListeners.add(readyStateChangeListener); } public String getAllResponseHeaders() { return null; } public int getReadyState() { return bytes != null ? STATE_COMPLETE : STATE_UNINITIALIZED; } public byte[] getResponseBytes() { return bytes; } public String getResponseHeader(String arg0) { return null; } public Image getResponseImage() { return bytes != null ? Toolkit.getDefaultToolkit().createImage(bytes) : null; } public String getResponseText() { return new String(bytes); } public Document getResponseXML() { return null; } public int getStatus() { return 200; } public String getStatusText() { return "OK"; } public void open(String method, String url) { open(method, url, false); } public void open(String method, URL url) { open(method, url, false); } public void open(String mehod, URL url, boolean async) { try { URLConnection connection = url.openConnection(); bytes = new byte[connection.getContentLength()]; InputStream inputStream = connection.getInputStream(); inputStream.read(bytes); inputStream.close(); for (ReadyStateChangeListener readyStateChangeListener : readyStateChangeListeners) { readyStateChangeListener.readyStateChanged(); } } catch (IOException e) { } } public void open(String method, String url, boolean async) { open(method, URLHelper.createURL(url), async); } public void open(String method, String url, boolean async, String arg3) { open(method, URLHelper.createURL(url), async); } public void open(String method, String url, boolean async, String arg3, String arg4) { open(method, URLHelper.createURL(url), async); } }; } public String getAppCodeName() { return null; } public String getAppMinorVersion() { return null; } public String getAppName() { return null; } public String getAppVersion() { return null; } public String getBrowserLanguage() { return null; } public String getCookie(URL arg0) { return null; } public String getPlatform() { return null; } public int getScriptingOptimizationLevel() { return 0; } public Policy getSecurityPolicy() { return null; } public String getUserAgent() { return null; } public boolean isCookieEnabled() { return false; } public boolean isMedia(String arg0) { return false; } public boolean isScriptingEnabled() { return false; } public void setCookie(URL arg0, String arg1) { } }; }
Code Sample 2:
public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } |
00
| Code Sample 1:
@Test public void test_lookupResourceType_FullSearch_MatchingWordInMiddle() throws Exception { URL url = new URL(baseUrl + "/lookupResourceType/carbo"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("[{\"itemTypeID\":16659,\"itemCategoryID\":4,\"name\":\"Carbon Polymers\",\"icon\":\"50_04\"},{\"itemTypeID\":30310,\"itemCategoryID\":4,\"name\":\"Carbon-86 Epoxy Resin\",\"icon\":\"83_10\"},{\"itemTypeID\":16670,\"itemCategoryID\":4,\"name\":\"Crystalline Carbonide\",\"icon\":\"49_09\"}]")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/json; charset=utf-8")); }
Code Sample 2:
public static void main(String[] args) throws Exception { String codecClassname = args[0]; Class<?> codecClass = Class.forName(codecClassname); Configuration conf = new Configuration(); CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf); Compressor compressor = null; try { compressor = CodecPool.getCompressor(codec); CompressionOutputStream out = codec.createOutputStream(System.out, compressor); IOUtils.copyBytes(System.in, out, 4096, false); out.finish(); } finally { CodecPool.returnCompressor(compressor); } } |
11
| Code Sample 1:
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
Code Sample 2:
public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } } |
11
| Code Sample 1:
@Test public void testWriteAndReadBigger() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); String body = ""; int size = 50 * 1024; for (int i = 0; i < size; i++) { body = body + "a"; } out.write(body.getBytes("utf-8")); out.close(); File expected = new File(dir, "testreadwrite.txt"); assertTrue(expected.isFile()); assertEquals(body.length(), expected.length()); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[body.length()]; int readCount = in.read(buffer); in.close(); assertEquals(body.length(), readCount); String resultRead = new String(buffer, "utf-8"); assertEquals(body, resultRead); } finally { server.stop(); } }
Code Sample 2:
private static void _checkConfigFile() throws Exception { try { String filePath = getUserManagerConfigPath() + "user_manager_config.properties"; boolean copy = false; File from = new java.io.File(filePath); if (!from.exists()) { Properties properties = new Properties(); properties.put(Config.getStringProperty("ADDITIONAL_INFO_MIDDLE_NAME_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_MIDDLE_NAME_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_DATE_OF_BIRTH_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_DATE_OF_BIRTH_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_CELL_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_CELL_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_CATEGORIES_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_CATEGORIES_VISIBILITY")); Company comp = PublicCompanyFactory.getDefaultCompany(); int numberGenericVariables = Config.getIntProperty("MAX_NUMBER_VARIABLES_TO_SHOW"); for (int i = 1; i <= numberGenericVariables; i++) { properties.put(LanguageUtil.get(comp.getCompanyId(), comp.getLocale(), "user.profile.var" + i).replace(" ", "_"), Config.getStringProperty("ADDITIONAL_INFO_DEFAULT_VISIBILITY")); } try { properties.store(new java.io.FileOutputStream(filePath), null); } catch (Exception e) { Logger.error(UserManagerPropertiesFactory.class, e.getMessage(), e); } from = new java.io.File(filePath); copy = true; } String tmpFilePath = UtilMethods.getTemporaryDirPath() + "user_manager_config_properties.tmp"; File to = new java.io.File(tmpFilePath); if (!to.exists()) { to.createNewFile(); copy = true; } if (copy) { 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.error(UserManagerPropertiesFactory.class, "_checkLanguagesFiles:Property File Copy Failed " + e, e); } } |
11
| Code Sample 1:
public void createBankSignature() { byte b; try { _bankMessageDigest = MessageDigest.getInstance("MD5"); _bankSig = Signature.getInstance("MD5/RSA/PKCS#1"); _bankSig.initSign((PrivateKey) _bankPrivateKey); _bankMessageDigest.update(getBankString().getBytes()); _bankMessageDigestBytes = _bankMessageDigest.digest(); _bankSig.update(_bankMessageDigestBytes); _bankSignatureBytes = _bankSig.sign(); } catch (Exception e) { } ; }
Code Sample 2:
private String generateFilename() { byte[] hash = null; try { MessageDigest digest = MessageDigest.getInstance("MD5"); try { digest.update(InetAddress.getLocalHost().toString().getBytes()); } catch (UnknownHostException e) { } digest.update(String.valueOf(System.currentTimeMillis()).getBytes()); digest.update(String.valueOf(Runtime.getRuntime().freeMemory()).getBytes()); byte[] foo = new byte[128]; new SecureRandom().nextBytes(foo); digest.update(foo); hash = digest.digest(); } catch (NoSuchAlgorithmException e) { Debug.assrt(false); } return hexEncode(hash); } |
11
| Code Sample 1:
private void copy(String imgPath, String path) { try { File input = new File(imgPath); File output = new File(path, input.getName()); if (output.exists()) { if (!MessageDialog.openQuestion(getShell(), "Overwrite", "There is already an image file " + input.getName() + " under the package.\n Do you really want to overwrite it?")) return; } byte[] data = new byte[1024]; FileInputStream fis = new FileInputStream(imgPath); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output)); int length; while ((length = bis.read(data)) > 0) { bos.write(data, 0, length); bos.flush(); } bos.close(); fis.close(); IJavaProject ijp = VisualSwingPlugin.getCurrentProject(); if (ijp != null) { ijp.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); view.refresh(); view.expandAll(); } } catch (Exception e) { VisualSwingPlugin.getLogger().error(e); } }
Code Sample 2:
public final void deliver(final String from, final String recipient, final InputStream data) throws TooMuchDataException, IOException { System.out.println("FROM: " + from); System.out.println("TO: " + recipient); final File tmpDir = new File(System.getProperty("java.io.tmpdir")); final File file = new File(tmpDir, recipient); final FileWriter fw = new FileWriter(file); try { IOUtils.copy(data, fw); } finally { fw.close(); } } |
00
| Code Sample 1:
public InputStream getFileStream(String filePath) { if (this.inJar) { try { URL url = getClassResourceUrl(this.getClass(), filePath); if (url != null) { return url.openStream(); } } catch (IOException ioe) { Debug.signal(Debug.ERROR, this, ioe); } } else { try { return new FileInputStream(filePath); } catch (FileNotFoundException fe) { Debug.signal(Debug.ERROR, this, fe); } } return null; }
Code Sample 2:
public synchronized String encrypt(String p_plainText) throws ServiceUnavailableException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new ServiceUnavailableException(e.getMessage()); } try { md.update(p_plainText.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new ServiceUnavailableException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } |
00
| Code Sample 1:
public static boolean copyFileToContentFolder(String source, LearningDesign learningDesign) { File inputFile = new File(source); File outputFile = new File(getRootFilePath(learningDesign) + inputFile.getName()); FileReader in; try { 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) { e.printStackTrace(); return false; } return true; }
Code Sample 2:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; final StringBuilder sbValueBeforeMD5 = new StringBuilder(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.fatal("", e); return; } try { final long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(sId); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); final byte[] array = md5.digest(); final StringBuilder sb = new StringBuilder(); for (int j = 0; j < array.length; ++j) { final int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { logger.fatal("", e); } } |
00
| Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public static String loadUrlContentAsString(URL url) throws IOException { char[] buf = new char[2048]; StringBuffer ret = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); for (int chars = reader.read(buf); chars != -1; chars = reader.read(buf)) { ret.append(buf, 0, chars); } reader.close(); return ret.toString(); } |
11
| Code Sample 1:
public void service(Request req, Response resp) { PrintStream out = null; try { out = resp.getPrintStream(8192); String env = req.getParameter("env"); String regex = req.getParameter("regex"); String deep = req.getParameter("deep"); String term = req.getParameter("term"); String index = req.getParameter("index"); String refresh = req.getParameter("refresh"); String searcher = req.getParameter("searcher"); String grep = req.getParameter("grep"); String fiServerDetails = req.getParameter("fi_server_details"); String serverDetails = req.getParameter("server_details"); String hostDetails = req.getParameter("host_details"); String name = req.getParameter("name"); String show = req.getParameter("show"); String path = req.getPath().getPath(); int page = req.getForm().getInteger("page"); if (path.startsWith("/fs")) { String fsPath = path.replaceAll("^/fs", ""); File realPath = new File("C:\\", fsPath.replace('/', File.separatorChar)); if (realPath.isDirectory()) { out.write(FileSystemDirectory.getContents(new File("c:\\"), fsPath, "/fs")); } else { resp.set("Cache", "no-cache"); FileInputStream fin = new FileInputStream(realPath); FileChannel channel = fin.getChannel(); WritableByteChannel channelOut = resp.getByteChannel(); channel.transferTo(0, realPath.length(), channelOut); channel.close(); fin.close(); System.err.println("Serving " + path + " as " + realPath.getCanonicalPath()); } } else if (path.startsWith("/files/")) { String[] segments = req.getPath().getSegments(); boolean done = false; if (segments.length > 1) { String realPath = req.getPath().getPath(1); File file = context.getFile(realPath); if (file.isFile()) { resp.set("Content-Type", context.getContentType(realPath)); FileInputStream fin = new FileInputStream(file); FileChannel channel = fin.getChannel(); WritableByteChannel channelOut = resp.getByteChannel(); long start = System.currentTimeMillis(); channel.transferTo(0, realPath.length(), channelOut); channel.close(); fin.close(); System.err.println("Time take to write [" + realPath + "] was [" + (System.currentTimeMillis() - start) + "] of size [" + file.length() + "]"); done = true; } } if (!done) { resp.set("Content-Type", "text/plain"); out.println("Can not serve directory: path"); } } else if (path.startsWith("/upload")) { FileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); RequestAdapter adapter = new RequestAdapter(req); List<FileItem> list = upload.parseRequest(adapter); Map<String, FileItem> map = new HashMap<String, FileItem>(); for (FileItem entry : list) { String fileName = entry.getFieldName(); map.put(fileName, entry); } resp.set("Content-Type", "text/html"); out.println("<html>"); out.println("<body>"); for (int i = 0; i < 10; i++) { Part file = req.getPart("datafile" + (i + 1)); if (file != null && file.isFile()) { String partName = file.getName(); String partFileName = file.getFileName(); File partFile = new File(partFileName); FileItem item = map.get(partName); InputStream in = file.getInputStream(); String fileName = file.getFileName().replaceAll("\\\\", "_").replaceAll(":", "_"); File filePath = new File(fileName); OutputStream fileOut = new FileOutputStream(filePath); byte[] chunk = new byte[8192]; int count = 0; while ((count = in.read(chunk)) != -1) { fileOut.write(chunk, 0, count); } fileOut.close(); in.close(); out.println("<table border='1'>"); out.println("<tr><td><b>File</b></td><td>"); out.println(filePath.getCanonicalPath()); out.println("</tr></td>"); out.println("<tr><td><b>Size</b></td><td>"); out.println(filePath.length()); out.println("</tr></td>"); out.println("<tr><td><b>MD5</b></td><td>"); out.println(Digest.getSignature(Digest.Algorithm.MD5, file.getInputStream())); out.println("<br>"); out.println(Digest.getSignature(Digest.Algorithm.MD5, item.getInputStream())); if (partFile.exists()) { out.println("<br>"); out.println(Digest.getSignature(Digest.Algorithm.MD5, new FileInputStream(partFile))); } out.println("</tr></td>"); out.println("<tr><td><b>SHA1</b></td><td>"); out.println(Digest.getSignature(Digest.Algorithm.SHA1, file.getInputStream())); out.println("<br>"); out.println(Digest.getSignature(Digest.Algorithm.SHA1, item.getInputStream())); if (partFile.exists()) { out.println("<br>"); out.println(Digest.getSignature(Digest.Algorithm.SHA1, new FileInputStream(partFile))); } out.println("</tr></td>"); out.println("<tr><td><b>Header</b></td><td><pre>"); out.println(file.toString().trim()); out.println("</pre></tr></td>"); if (partFileName.toLowerCase().endsWith(".xml")) { String xml = file.getContent(); String formatted = format(xml); String fileFormatName = fileName + ".formatted"; File fileFormatOut = new File(fileFormatName); FileOutputStream formatOut = new FileOutputStream(fileFormatOut); formatOut.write(formatted.getBytes("UTF-8")); out.println("<tr><td><b>Formatted XML</b></td><td><pre>"); out.println("<a href='/" + (fileFormatName) + "'>" + partFileName + "</a>"); out.println("</pre></tr></td>"); formatOut.close(); } out.println("<table>"); } } out.println("</body>"); out.println("</html>"); } else if (path.startsWith("/sql/") && index != null && searcher != null) { String file = req.getPath().getPath(1); File root = searchEngine.index(searcher).getRoot(); SearchEngine engine = searchEngine.index(searcher); File indexFile = getStoredProcIndexFile(engine.getRoot(), index); File search = new File(root, "cpsql"); File source = new File(root, file.replace('/', File.separatorChar)); FindStoredProcs.StoredProcProject storedProcProj = FindStoredProcs.getStoredProcProject(search, indexFile); FindStoredProcs.StoredProc proc = storedProcProj.getStoredProc(source.getName()); resp.set("Content-Type", "text/html"); out.println("<html>"); out.println("<body><pre>"); for (String procName : proc.getReferences()) { FindStoredProcs.StoredProc theProc = storedProcProj.getStoredProc(procName); if (theProc != null) { String url = getRelativeURL(root, theProc.getFile()); out.println("<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'><b>" + theProc.getName() + "</b>"); } } out.println("</pre></body>"); out.println("</html>"); } else if (show != null && index != null && searcher != null) { String authentication = req.getValue("Authorization"); if (authentication == null) { resp.setCode(401); resp.setText("Authorization Required"); resp.set("Content-Type", "text/html"); resp.set("WWW-Authenticate", "Basic realm=\"DTS Subversion Repository\""); out.println("<html>"); out.println("<head>"); out.println("401 Authorization Required"); out.println("</head>"); out.println("<body>"); out.println("<h1>401 Authorization Required</h1>"); out.println("</body>"); out.println("</html>"); } else { resp.set("Content-Type", "text/html"); Principal principal = new PrincipalParser(authentication); String file = show; SearchEngine engine = searchEngine.index(searcher); File root = engine.getRoot(); File javaIndexFile = getJavaIndexFile(root, index); File storedProcIndexFile = getStoredProcIndexFile(root, index); File sql = new File(root, "cpsql"); File source = new File(root, file.replace('/', File.separatorChar)); File javaSource = new File(root, file.replace('/', File.separatorChar)); File canonical = source.getCanonicalFile(); Repository repository = Subversion.login(Scheme.HTTP, principal.getName(), principal.getPassword()); Info info = null; try { info = repository.info(canonical); } catch (Exception e) { e.printStackTrace(); } List<Change> logMessages = new ArrayList<Change>(); try { logMessages = repository.log(canonical); } catch (Exception e) { e.printStackTrace(); } FileInputStream in = new FileInputStream(canonical); List<String> lines = LineStripper.stripLines(in); out.println("<html>"); out.println("<head>"); out.println("<!-- username='" + principal.getName() + "' password='" + principal.getPassword() + "' -->"); out.println("<link rel='stylesheet' type='text/css' href='style.css'>"); out.println("<script src='highlight.js'></script>"); out.println("</head>"); out.println("<body onload=\"sh_highlightDocument('lang/', '.js')\">"); if (info != null) { out.println("<table border='1'>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>Author</tt></td><td><tt>" + info.author + "</tt></td></tr>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>Version</tt></td><td><tt>" + info.version + "</tt></td></tr>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>URL</tt></td><td><tt>" + info.location + "</tt></td></tr>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>Path</tt></td><td><tt>" + canonical + "</tt></td></tr>"); out.println("</table>"); } out.println("<table border='1''>"); out.println("<tr>"); out.println("<td valign='top' bgcolor=\"#C4C4C4\"><pre>"); FindStoredProcs.StoredProcProject storedProcProj = FindStoredProcs.getStoredProcProject(sql, storedProcIndexFile); FindStoredProcs.StoredProc storedProc = null; FindJavaSources.JavaProject project = null; FindJavaSources.JavaClass javaClass = null; List<FindJavaSources.JavaClass> importList = null; if (file.endsWith(".sql")) { storedProc = storedProcProj.getStoredProc(canonical.getName()); } else if (file.endsWith(".java")) { project = FindJavaSources.getProject(root, javaIndexFile); javaClass = project.getClass(source); importList = project.getImports(javaSource); } for (int i = 0; i < lines.size(); i++) { out.println(i); } out.println("</pre></td>"); out.print("<td valign='top'><pre"); out.print(getJavaScript(file)); out.println(">"); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); String escaped = escapeHtml(line); if (project != null) { for (FindJavaSources.JavaClass entry : importList) { String className = entry.getClassName(); String fullyQualifiedName = entry.getFullyQualifiedName(); if (line.startsWith("import") && line.indexOf(fullyQualifiedName) > -1) { File classFile = entry.getSourceFile(); String url = getRelativeURL(root, classFile); escaped = escaped.replaceAll(fullyQualifiedName + ";", "<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + fullyQualifiedName + "</a>;"); } else if (line.indexOf(className) > -1) { File classFile = entry.getSourceFile(); String url = getRelativeURL(root, classFile); escaped = escaped.replaceAll("\\s" + className + ",", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>,"); escaped = escaped.replaceAll("\\s" + className + "\\{", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>{"); escaped = escaped.replaceAll("," + className + ",", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>,"); escaped = escaped.replaceAll("," + className + "\\{", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>{"); escaped = escaped.replaceAll("\\s" + className + "\\s", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a> "); escaped = escaped.replaceAll("\\(" + className + "\\s", "(<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a> "); escaped = escaped.replaceAll("\\s" + className + "\\.", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>."); escaped = escaped.replaceAll("\\(" + className + "\\.", "(<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>."); escaped = escaped.replaceAll("\\s" + className + "\\(", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>("); escaped = escaped.replaceAll("\\(" + className + "\\(", "(<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>("); escaped = escaped.replaceAll(">" + className + ",", "><a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>,"); escaped = escaped.replaceAll(">" + className + "\\s", "><a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a> "); escaped = escaped.replaceAll(">" + className + "<", "><a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a><"); escaped = escaped.replaceAll("\\(" + className + "\\);", "(<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>)"); } } } else if (storedProc != null) { Set<String> procSet = storedProc.getTopReferences(); List<String> sortedProcs = new ArrayList(procSet); Collections.sort(sortedProcs, LONGEST_FIRST); for (String procFound : sortedProcs) { if (escaped.indexOf(procFound) != -1) { File nameFile = storedProcProj.getLocation(procFound); if (nameFile != null) { String url = getRelativeURL(root, nameFile); escaped = escaped.replaceAll("\\s" + procFound + "\\s", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a> "); escaped = escaped.replaceAll("\\s" + procFound + ",", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>,"); escaped = escaped.replaceAll("\\s" + procFound + ";", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>;"); escaped = escaped.replaceAll("," + procFound + "\\s", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a> "); escaped = escaped.replaceAll("," + procFound + ",", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>,"); escaped = escaped.replaceAll("," + procFound + ";", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>;"); escaped = escaped.replaceAll("=" + procFound + "\\s", "=<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a> "); escaped = escaped.replaceAll("=" + procFound + ",", "=<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>,"); escaped = escaped.replaceAll("=" + procFound + ";", "=<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>;"); escaped = escaped.replaceAll("." + procFound + "\\s", ".<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a> "); escaped = escaped.replaceAll("." + procFound + ",", ".<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>,"); escaped = escaped.replaceAll("." + procFound + ";", ".<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>;"); } else { System.err.println("NOT FOUND: " + procFound); } } } } out.println(escaped); } out.println("</pre></td>"); out.println("</tr>"); out.println("</table>"); out.println("<table border='1'>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>Revision</tt></td><td bgcolor=\"#C4C4C4\"><tt>Date</tt></td><td bgcolor=\"#C4C4C4\"><tt>Author</tt></td><td bgcolor=\"#C4C4C4\"><tt>Comment</tt></td></tr>"); DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); for (Change message : logMessages) { out.printf("<tr><td><tt>%s</tt></td><td><tt>%s</tt></td><td><tt>%s</tt></td><td><tt>%s</tt></td></tr>%n", message.version, format.format(message.date).replaceAll("\\s", " "), message.author, message.message); } out.println("</table>"); if (project != null) { out.println("<pre>"); for (FindJavaSources.JavaClass entry : importList) { String url = getRelativeURL(root, entry.getSourceFile()); out.println("import <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + entry.getFullyQualifiedName() + "</a> as " + entry.getClassName()); } out.println("</pre>"); } if (storedProc != null) { out.println("<pre>"); for (String procName : storedProc.getReferences()) { FindStoredProcs.StoredProc proc = storedProcProj.getStoredProc(procName); if (proc != null) { String url = getRelativeURL(root, proc.getFile()); out.println("using <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + proc.getName() + "</a>"); } } out.println("</pre>"); } out.println("</form>"); out.println("</body>"); out.println("</html>"); } } else if (path.endsWith(".js") || path.endsWith(".css") || path.endsWith(".formatted")) { path = path.replace('/', File.separatorChar); if (path.endsWith(".formatted")) { resp.set("Content-Type", "text/plain"); } else if (path.endsWith(".js")) { resp.set("Content-Type", "application/javascript"); } else { resp.set("Content-Type", "text/css"); } resp.set("Cache", "no-cache"); WritableByteChannel channelOut = resp.getByteChannel(); File file = new File(".", path).getCanonicalFile(); System.err.println("Serving " + path + " as " + file.getCanonicalPath()); FileChannel sourceChannel = new FileInputStream(file).getChannel(); sourceChannel.transferTo(0, file.length(), channelOut); sourceChannel.close(); channelOut.close(); } else if (env != null && regex != null) { ServerDetails details = config.getEnvironment(env).load(persister, serverDetails != null, fiServerDetails != null, hostDetails != null); List<String> tokens = new ArrayList<String>(); List<Searchable> list = details.search(regex, deep != null, tokens); Collections.sort(tokens, LONGEST_FIRST); for (String token : tokens) { System.out.println("TOKEN: " + token); } resp.set("Content-Type", "text/html"); out.println("<html>"); out.println("<head>"); out.println("<link rel='stylesheet' type='text/css' href='style.css'>"); out.println("<script src='highlight.js'></script>"); out.println("</head>"); out.println("<body onload=\"sh_highlightDocument('lang/', '.js')\">"); writeSearchBox(out, searcher, null, null, regex); out.println("<br>Found " + list.size() + " hits for <b>" + regex + "</b>"); out.println("<table border='1''>"); int countIndex = 1; for (Searchable value : list) { out.println(" <tr><td>" + countIndex++ + " <a href='" + value.getSource() + "'><b>" + value.getSource() + "</b></a></td></tr>"); out.println(" <tr><td><pre class='sh_xml'>"); StringWriter buffer = new StringWriter(); persister.write(value, buffer); String text = buffer.toString(); text = escapeHtml(text); for (String token : tokens) { text = text.replaceAll(token, "<font style='BACKGROUND-COLOR: yellow'>" + token + "</font>"); } out.println(text); out.println(" </pre></td></tr>"); } out.println("</table>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } else if (index != null && term != null && term.length() > 0) { out.println("<html>"); out.println("<head>"); out.println("<link rel='stylesheet' type='text/css' href='style.css'>"); out.println("<script src='highlight.js'></script>"); out.println("</head>"); out.println("<body onload=\"sh_highlightDocument('lang/', '.js')\">"); writeSearchBox(out, searcher, term, index, null); if (searcher == null) { searcher = searchEngine.getDefaultSearcher(); } if (refresh != null) { SearchEngine engine = searchEngine.index(searcher); File root = engine.getRoot(); File searchIndex = getJavaIndexFile(root, index); FindJavaSources.deleteProject(root, searchIndex); } boolean isRefresh = refresh != null; boolean isGrep = grep != null; boolean isSearchNames = name != null; SearchQuery query = new SearchQuery(index, term, page, isRefresh, isGrep, isSearchNames); List<SearchResult> results = searchEngine.index(searcher).search(query); writeSearchResults(query, searcher, results, out); out.println("</body>"); out.println("</html>"); } else { out.println("<html>"); out.println("<body>"); writeSearchBox(out, searcher, null, null, null); out.println("</body>"); out.println("</html>"); } out.close(); } catch (Exception e) { try { e.printStackTrace(); resp.reset(); resp.setCode(500); resp.setText("Internal Server Error"); resp.set("Content-Type", "text/html"); out.println("<html>"); out.println("<body><h1>Internal Server Error</h1><pre>"); e.printStackTrace(out); out.println("</pre></body>"); out.println("</html>"); out.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
Code Sample 2:
public static void compressFile(File orig) throws IOException { File file = new File(INPUT + orig.toString()); File target = new File(OUTPUT + orig.toString().replaceAll(".xml", ".xml.gz")); System.out.println(" Compressing \"" + file.getName() + "\" into \"" + target + "\""); long l = file.length(); FileInputStream fileinputstream = new FileInputStream(file); GZIPOutputStream gzipoutputstream = new GZIPOutputStream(new FileOutputStream(target)); byte abyte0[] = new byte[1024]; int i; while ((i = fileinputstream.read(abyte0)) != -1) gzipoutputstream.write(abyte0, 0, i); fileinputstream.close(); gzipoutputstream.close(); long l1 = target.length(); System.out.println(" Initial size: " + l + "; Compressed size: " + l1 + "."); System.out.println(" Done."); System.out.println(); } |
00
| Code Sample 1:
private List<Feature> getFeatures(String source, EntryPoint e) throws MalformedURLException, SAXException, IOException, ParserConfigurationException, URISyntaxException { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); FeatureParser featp = new FeatureParser(); parser.parse(URIFactory.url(serverPrefix + "/das/" + source + "/features?segment=" + e.id + ":" + e.start + "," + e.stop).openStream(), featp); return featp.list; }
Code Sample 2:
private FTPClient getFTPConnection(String strUser, String strPassword, String strServer, boolean binaryTransfer, String connectionNote) { FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(strServer); ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Connected to " + strServer + ", " + connectionNote); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP server refused connection."); return null; } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { return null; } } ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP Could not connect to server."); ResourcePool.LogException(e, this); return null; } try { if (!ftp.login(strUser, strPassword)) { ftp.logout(); ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP login failed."); return null; } ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Remote system is " + ftp.getSystemName() + ", " + connectionNote); if (binaryTransfer) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } else { ftp.setFileType(FTP.ASCII_FILE_TYPE); } ftp.enterLocalPassiveMode(); } catch (FTPConnectionClosedException e) { ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "Server closed connection."); ResourcePool.LogException(e, this); return null; } catch (IOException e) { ResourcePool.LogException(e, this); return null; } return ftp; } |
11
| Code Sample 1:
public static File writeInternalFile(Context cx, URL url, String dir, String filename) { FileOutputStream fos = null; File fi = null; try { fi = newInternalFile(cx, dir, filename); fos = FileUtils.openOutputStream(fi); int length = IOUtils.copy(url.openStream(), fos); log(length + " bytes copyed."); } catch (IOException e) { AIOUtils.log("", e); } finally { try { fos.close(); } catch (IOException e) { AIOUtils.log("", e); } } return fi; }
Code Sample 2:
protected void copyFile(String inputFilePath, String outputFilePath) throws GenerationException { String from = getTemplateDir() + inputFilePath; try { logger.debug("Copying from " + from + " to " + outputFilePath); InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(from); if (inputStream == null) { throw new GenerationException("Source file not found: " + from); } FileOutputStream outputStream = new FileOutputStream(new File(outputFilePath)); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } catch (Exception e) { throw new GenerationException("Error while copying file: " + from, e); } } |
00
| Code Sample 1:
public ZIPSignatureService(InputStream documentInputStream, SignatureFacet signatureFacet, OutputStream documentOutputStream, RevocationDataService revocationDataService, TimeStampService timeStampService, String role, IdentityDTO identity, byte[] photo, DigestAlgo signatureDigestAlgo) throws IOException { super(signatureDigestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".zip"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new ZIPSignatureFacet(this.tmpFile, signatureDigestAlgo)); XAdESSignatureFacet xadesSignatureFacet = new XAdESSignatureFacet(getSignatureDigestAlgorithm()); xadesSignatureFacet.setRole(role); addSignatureFacet(xadesSignatureFacet); addSignatureFacet(new KeyInfoSignatureFacet(true, false, false)); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(signatureFacet); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } }
Code Sample 2:
public static String readURL(String urlStr, boolean debug) { if (debug) System.out.print(" trying: " + urlStr + "\n"); URL url = null; try { url = new URL(urlStr); } catch (java.net.MalformedURLException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } HttpURLConnection huc = null; try { huc = (HttpURLConnection) url.openConnection(); } catch (IOException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentType = huc.getContentType(); if (contentType == null || contentType.indexOf("text/xml") < 0) { System.out.print("*** Warning *** Content-Type not set to text/xml"); System.out.print('\n'); System.out.print(" Content-type: "); System.out.print(contentType); System.out.print('\n'); } InputStream urlStream = null; try { urlStream = huc.getInputStream(); } catch (java.io.IOException e) { System.out.print("test failed: opening URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(urlStream)); boolean xml = true; String href = null, inputLine = null; StringBuffer content = new StringBuffer(), stylesheet = null; Transformer transformer = null; try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading first line of response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } if (inputLine == null) { System.out.print("test failed: No input read from URL"); System.out.print('\n'); return null; } if (!inputLine.startsWith("<?xml ")) { xml = false; content.append(inputLine); } if (xml) { int offset = inputLine.indexOf('>'); if (offset + 2 < inputLine.length()) { inputLine = inputLine.substring(offset + 1); offset = inputLine.indexOf('<'); if (offset > 0) inputLine = inputLine.substring(offset); } else try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } content.append(inputLine); } try { while ((inputLine = in.readLine()) != null) content.append(inputLine); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentStr = content.toString(); if (transformer != null) { StreamSource streamXMLRecord = new StreamSource(new StringReader(contentStr)); StringWriter xmlRecordWriter = new StringWriter(); try { transformer.transform(streamXMLRecord, new StreamResult(xmlRecordWriter)); System.out.print(" successfully applied stylesheet '"); System.out.print(href); System.out.print("'"); System.out.print('\n'); } catch (javax.xml.transform.TransformerException e) { System.out.print("unable to apply stylesheet '"); System.out.print(href); System.out.print("'to response: "); System.out.print(e.getMessage()); System.out.print('\n'); e.printStackTrace(); } } return contentStr; } |
11
| Code Sample 1:
public int addRecipe(Recipe recipe) throws Exception { PreparedStatement pst1 = null; PreparedStatement pst2 = null; ResultSet rs = null; int retVal = -1; try { conn = getConnection(); pst1 = conn.prepareStatement("INSERT INTO recipes (name, instructions, category_id) VALUES (?, ?, ?)"); pst1.setString(1, recipe.getName()); pst1.setString(2, recipe.getInstructions()); pst1.setInt(3, recipe.getCategoryId()); if (pst1.executeUpdate() > 0) { pst2 = conn.prepareStatement("SELECT recipe_id FROM recipes WHERE name = ? AND instructions = ? AND category_id = ?"); pst2.setString(1, recipe.getName()); pst2.setString(2, recipe.getInstructions()); pst2.setInt(3, recipe.getCategoryId()); rs = pst2.executeQuery(); conn.commit(); if (rs.next()) { int id = rs.getInt(1); addIngredients(recipe, id); MainFrame.recipePanel.update(); retVal = id; } else { retVal = -1; } } else { retVal = -1; } conn.commit(); } catch (Exception e) { conn.rollback(); MainFrame.appendStatusText("Can't add recipe, the exception was " + e.getMessage()); } finally { try { if (rs != null) rs.close(); rs = null; if (pst1 != null) pst1.close(); pst1 = null; if (pst2 != null) pst2.close(); pst2 = null; } catch (SQLException sqle) { MainFrame.appendStatusText("Can't close database connection."); } } return retVal; }
Code Sample 2:
@Override public synchronized void deletePersistenceQueryStatistics(Integer elementId, String contextName, String project, String name, Date dateFrom, Date dateTo) throws DatabaseException { final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); String queryString = "DELETE " + this.getPersistenceQueryStatisticsSchemaAndTableName() + " FROM " + this.getPersistenceQueryStatisticsSchemaAndTableName() + " INNER JOIN " + this.getPersistenceQueryElementsSchemaAndTableName() + " ON " + this.getPersistenceQueryElementsSchemaAndTableName() + ".element_id = " + this.getPersistenceQueryStatisticsSchemaAndTableName() + ".element_id WHERE "; if (elementId != null) { queryString = queryString + " elementId = ? AND "; } if (contextName != null) { queryString = queryString + " context_name LIKE ? AND "; } if ((project != null)) { queryString = queryString + " project LIKE ? AND "; } if ((name != null)) { queryString = queryString + " name LIKE ? AND "; } if (dateFrom != null) { queryString = queryString + " start_timestamp >= ? AND "; } if (dateTo != null) { queryString = queryString + " start_timestamp <= ? AND "; } queryString = DefaultDatabaseHandler.removeOrphanWhereAndAndFromSelect(queryString); final PreparedStatement preparedStatement = DebugPreparedStatement.prepareStatement(connection, queryString); int indexCounter = 1; if (elementId != null) { preparedStatement.setLong(indexCounter, elementId.longValue()); indexCounter = indexCounter + 1; } if (contextName != null) { preparedStatement.setString(indexCounter, contextName); indexCounter = indexCounter + 1; } if ((project != null)) { preparedStatement.setString(indexCounter, project); indexCounter = indexCounter + 1; } if ((name != null)) { preparedStatement.setString(indexCounter, name); indexCounter = indexCounter + 1; } if (dateFrom != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateFrom.getTime())); indexCounter = indexCounter + 1; } if (dateTo != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateTo.getTime())); indexCounter = indexCounter + 1; } preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error deleting persistence query statistics.", e); } finally { this.releaseConnection(connection); } } |
11
| Code Sample 1:
private void handleUpload(CommonsMultipartFile file, String newFileName, String uploadDir) throws IOException, FileNotFoundException { File dirPath = new File(uploadDir); if (!dirPath.exists()) { dirPath.mkdirs(); } InputStream stream = file.getInputStream(); OutputStream bos = new FileOutputStream(uploadDir + newFileName); IOUtils.copy(stream, bos); }
Code Sample 2:
public EncodedScript(PackageScript source, DpkgData data) throws IOException { _source = source; final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); OutputStream output = null; try { output = MimeUtility.encode(bytes, BASE64); } catch (final MessagingException e) { throw new IOException("Failed to uuencode script. name=[" + _source.getFriendlyName() + "], reason=[" + e.getMessage() + "]."); } IOUtils.write(HEADER, bytes, Dpkg.CHAR_ENCODING); bytes.flush(); IOUtils.copy(_source.getSource(data), output); output.flush(); IOUtils.write(FOOTER, bytes, Dpkg.CHAR_ENCODING); bytes.flush(); output.close(); bytes.close(); _encoded = bytes.toString(Dpkg.CHAR_ENCODING); } |
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 run() { try { File outDir = new File(outDirTextField.getText()); if (!outDir.exists()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "The chosen directory does not exist!", "Directory Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (!outDir.isDirectory()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "The chosen file is not a directory!", "Not a Directory Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (!outDir.canWrite()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "Cannot write to the chosen directory!", "Directory Not Writeable Error", JOptionPane.ERROR_MESSAGE); } }); return; } File archiveDir = new File("foo.bar").getAbsoluteFile().getParentFile(); URL baseUrl = UnpackWizard.class.getClassLoader().getResource(UnpackWizard.class.getName().replaceAll("\\.", "/") + ".class"); if (baseUrl.getProtocol().equals("jar")) { String jarPath = baseUrl.getPath(); jarPath = jarPath.substring(0, jarPath.indexOf('!')); if (jarPath.startsWith("file:")) { try { archiveDir = new File(new URI(jarPath)).getAbsoluteFile().getParentFile(); } catch (URISyntaxException e1) { e1.printStackTrace(System.err); } } } SortedMap<Integer, String> inputFileNames = new TreeMap<Integer, String>(); for (Entry<Object, Object> anEntry : indexProperties.entrySet()) { String key = anEntry.getKey().toString(); if (key.startsWith("archive file ")) { inputFileNames.put(Integer.parseInt(key.substring("archive file ".length())), anEntry.getValue().toString()); } } byte[] buff = new byte[64 * 1024]; try { long bytesToWrite = 0; long bytesReported = 0; long bytesWritten = 0; for (String aFileName : inputFileNames.values()) { File aFile = new File(archiveDir, aFileName); if (aFile.exists()) { if (aFile.isFile()) { bytesToWrite += aFile.length(); } else { final File wrongFile = aFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "File \"" + wrongFile.getAbsolutePath() + "\" is not a standard file!", "Non Standard File Error", JOptionPane.ERROR_MESSAGE); } }); return; } } else { final File wrongFile = aFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "File \"" + wrongFile.getAbsolutePath() + "\" does not exist!", "File Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } } MultiFileInputStream mfis = new MultiFileInputStream(archiveDir, inputFileNames.values().toArray(new String[inputFileNames.size()])); TarArchiveInputStream tis = new TarArchiveInputStream(new BufferedInputStream(mfis)); TarArchiveEntry tarEntry = tis.getNextTarEntry(); while (tarEntry != null) { File outFile = new File(outDir.getAbsolutePath() + "/" + tarEntry.getName()); if (outFile.exists()) { final File wrongFile = outFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "Was about to write out file \"" + wrongFile.getAbsolutePath() + "\" but it already " + "exists.\nPlease [re]move existing files out of the way " + "and try again.", "File Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (tarEntry.isDirectory()) { outFile.getAbsoluteFile().mkdirs(); } else { outFile.getAbsoluteFile().getParentFile().mkdirs(); OutputStream os = new BufferedOutputStream(new FileOutputStream(outFile)); int len = tis.read(buff, 0, buff.length); while (len != -1) { os.write(buff, 0, len); bytesWritten += len; if (bytesWritten - bytesReported > (10 * 1024 * 1024)) { bytesReported = bytesWritten; final int progress = (int) (bytesReported * 100 / bytesToWrite); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setValue(progress); } }); } len = tis.read(buff, 0, buff.length); } os.close(); } tarEntry = tis.getNextTarEntry(); } long expectedCrc = 0; try { expectedCrc = Long.parseLong(indexProperties.getProperty("CRC32", "0")); } catch (NumberFormatException e) { System.err.println("Error while obtaining the expected CRC"); e.printStackTrace(System.err); } if (mfis.getCRC() == expectedCrc) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "Extraction completed successfully!", "Done!", JOptionPane.INFORMATION_MESSAGE); } }); return; } else { System.err.println("CRC Error: was expecting " + expectedCrc + " but got " + mfis.getCRC()); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "CRC Error: the data extracted does not have the expected CRC!\n" + "You should probably delete the extracted files, as they are " + "likely to be invalid.", "CRC Error", JOptionPane.ERROR_MESSAGE); } }); return; } } catch (final IOException e) { e.printStackTrace(System.err); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "Input/Output Error: " + e.getLocalizedMessage(), "Input/Output Error", JOptionPane.ERROR_MESSAGE); } }); return; } } finally { SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); setEnabled(true); } }); } } |
00
| Code Sample 1:
public static String loadUrl(URL url, String charset) throws MyException { try { URLConnection conn = url.openConnection(); InputStream urlin = conn.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(urlin, charset)); StringBuffer buff = new StringBuffer(); char[] cbuf = new char[1028]; int count; while ((count = in.read(cbuf)) != -1) { buff.append(new String(cbuf, 0, count)); } return buff.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); throw new MyException(MyException.ERROR_FILENOTFOUND, e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new MyException(MyException.ERROR_IO, e.getMessage()); } }
Code Sample 2:
public static void main(String[] args) throws Exception { String ftpHostIP = System.getProperty(RuntimeConstants.FTP_HOST_IP.toString()); String ftpUsername = System.getProperty(RuntimeConstants.FTP_USERNAME.toString()); String ftpPassword = System.getProperty(RuntimeConstants.FTP_PASSWORD.toString()); String ftpWorkingDirectory = System.getProperty(RuntimeConstants.FTP_WORKING_DIRECTORY_PATH.toString()); String ftpSenderDirectory = System.getProperty(RuntimeConstants.FTP_SENDER_DIRECTORY_FULL_PATH.toString()); if (ftpHostIP == null) { System.err.println("The FTP_HOST_IP system property must be filled out."); System.exit(1); } if (ftpUsername == null) { System.err.println("The FTP_USERNAME system property must be filled out."); System.exit(1); } if (ftpPassword == null) { System.err.println("The FTP_PASSWORD system property must be filled out."); System.exit(1); } if (ftpWorkingDirectory == null) { System.err.println("The FTP_WORKING_DIRECTORY_PATH system property must be filled out."); System.exit(1); } if (ftpSenderDirectory == null) { System.err.println("The FTP_SENDER_DIRECTORY_FULL_PATH system property must be filled out."); System.exit(1); } FTPClient ftp = new FTPClient(); ftp.connect(ftpHostIP); ftp.login(ftpUsername, ftpPassword); ftp.changeWorkingDirectory(ftpWorkingDirectory); ByteArrayInputStream bais = new ByteArrayInputStream(new byte[1024]); ftp.storeFile("sampleFile.txt", bais); IFileDescriptor fileDescriptor = FileTransferUtil.readAFile(ftpSenderDirectory); bais = new ByteArrayInputStream(fileDescriptor.getFileContent()); long initTime = System.currentTimeMillis(); ftp.storeFile(fileDescriptor.getFileName(), bais); long endTime = System.currentTimeMillis(); System.out.println("File " + fileDescriptor.getFileName() + " transfer by FTP in " + (endTime - initTime) + " miliseconds."); } |
00
| Code Sample 1:
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
Code Sample 2:
public synchronized List<AnidbSearchResult> getAnimeTitles() throws Exception { URL url = new URL("http", host, "/api/animetitles.dat.gz"); ResultCache cache = getCache(); @SuppressWarnings("unchecked") List<AnidbSearchResult> anime = (List) cache.getSearchResult(null, Locale.ROOT); if (anime != null) { return anime; } Pattern pattern = Pattern.compile("^(?!#)(\\d+)[|](\\d)[|]([\\w-]+)[|](.+)$"); Map<Integer, String> primaryTitleMap = new HashMap<Integer, String>(); Map<Integer, Map<String, String>> officialTitleMap = new HashMap<Integer, Map<String, String>>(); Map<Integer, Map<String, String>> synonymsTitleMap = new HashMap<Integer, Map<String, String>>(); Scanner scanner = new Scanner(new GZIPInputStream(url.openStream()), "UTF-8"); try { while (scanner.hasNextLine()) { Matcher matcher = pattern.matcher(scanner.nextLine()); if (matcher.matches()) { int aid = Integer.parseInt(matcher.group(1)); String type = matcher.group(2); String language = matcher.group(3); String title = matcher.group(4); if (type.equals("1")) { primaryTitleMap.put(aid, title); } else if (type.equals("2") || type.equals("4")) { Map<Integer, Map<String, String>> titleMap = (type.equals("4") ? officialTitleMap : synonymsTitleMap); Map<String, String> languageTitleMap = titleMap.get(aid); if (languageTitleMap == null) { languageTitleMap = new HashMap<String, String>(); titleMap.put(aid, languageTitleMap); } languageTitleMap.put(language, title); } } } } finally { scanner.close(); } anime = new ArrayList<AnidbSearchResult>(primaryTitleMap.size()); for (Entry<Integer, String> entry : primaryTitleMap.entrySet()) { Map<String, String> localizedTitles = new HashMap<String, String>(); if (synonymsTitleMap.containsKey(entry.getKey())) { localizedTitles.putAll(synonymsTitleMap.get(entry.getKey())); } if (officialTitleMap.containsKey(entry.getKey())) { localizedTitles.putAll(officialTitleMap.get(entry.getKey())); } anime.add(new AnidbSearchResult(entry.getKey(), entry.getValue(), localizedTitles)); } return cache.putSearchResult(null, Locale.ROOT, anime); } |
00
| Code Sample 1:
@Test public void test_blueprintTypeByTypeID_StringInsteadOfID() throws Exception { URL url = new URL(baseUrl + "/blueprintTypeByTypeID/blah-blah"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(400)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(400)); }
Code Sample 2:
public void init(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8"), 0, password.length()); byte[] rawKey = md.digest(); skeySpec = new SecretKeySpec(rawKey, "AES"); ivSpec = new IvParameterSpec(rawKey); cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchPaddingException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } } |
00
| Code Sample 1:
void load(URL url) throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream())); Vector3f scale = new Vector3f(1, 1, 1); Group currentGroup = new Group(); currentGroup.name = "default"; groups.add(currentGroup); String line; while ((line = r.readLine()) != null) { String[] params = line.split(" +"); if (params.length == 0) continue; String command = params[0]; if (params[0].equals("v")) { Vector3f vertex = new Vector3f(Float.parseFloat(params[1]) * scale.x, Float.parseFloat(params[2]) * scale.y, Float.parseFloat(params[3]) * scale.z); verticies.add(vertex); radius = Math.max(radius, vertex.length()); } if (command.equals("center")) { epicenter = new Vector3f(Float.parseFloat(params[1]), Float.parseFloat(params[2]), Float.parseFloat(params[3])); } else if (command.equals("f")) { Face f = new Face(); for (int i = 1; i < params.length; i++) { String parts[] = params[i].split("/"); Vector3f v = verticies.get(Integer.parseInt(parts[0]) - 1); f.add(v); } currentGroup.faces.add(f); } else if (command.equals("l")) { Line l = new Line(); for (int i = 1; i < params.length; i++) { Vector3f v = verticies.get(Integer.parseInt(params[i]) - 1); l.add(v); } currentGroup.lines.add(l); } else if (command.equals("g") && params.length > 1) { currentGroup = new Group(); currentGroup.name = params[1]; groups.add(currentGroup); } else if (command.equals("scale")) { scale = new Vector3f(Float.parseFloat(params[1]), Float.parseFloat(params[2]), Float.parseFloat(params[3])); } } r.close(); }
Code Sample 2:
public static boolean canWeConnectToInternet() { String s = "http://www.google.com/"; URL url = null; boolean can = false; URLConnection conection = null; try { url = new URL(s); } catch (MalformedURLException e) { System.out.println("This should never happend. Error in URL name. URL specified was:" + s + "."); } try { conection = url.openConnection(); conection.connect(); can = true; } catch (IOException e) { can = false; } if (can) { } return can; } |
00
| Code Sample 1:
public HashCash(String cash) throws NoSuchAlgorithmException { myToken = cash; String[] parts = cash.split(":"); myVersion = Integer.parseInt(parts[0]); if (myVersion < 0 || myVersion > 1) throw new IllegalArgumentException("Only supported versions are 0 and 1"); if ((myVersion == 0 && parts.length != 6) || (myVersion == 1 && parts.length != 7)) throw new IllegalArgumentException("Improperly formed HashCash"); try { int index = 1; if (myVersion == 1) myValue = Integer.parseInt(parts[index++]); else myValue = 0; SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString); Calendar tempCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); tempCal.setTime(dateFormat.parse(parts[index++])); myResource = parts[index++]; myExtensions = deserializeExtensions(parts[index++]); MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(cash.getBytes()); byte[] tempBytes = md.digest(); int tempValue = numberOfLeadingZeros(tempBytes); if (myVersion == 0) myValue = tempValue; else if (myVersion == 1) myValue = (tempValue > myValue ? myValue : tempValue); } catch (java.text.ParseException ex) { throw new IllegalArgumentException("Improperly formed HashCash", ex); } }
Code Sample 2:
public boolean backupFile(File oldFile, File newFile) { boolean isBkupFileOK = false; FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(oldFile).getChannel(); targetChannel = new FileOutputStream(newFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException e) { logger.log(Level.SEVERE, "IO exception occurred while copying file", e); } finally { if ((newFile != null) && (newFile.exists()) && (newFile.length() > 0)) { isBkupFileOK = true; } try { if (sourceChannel != null) { sourceChannel.close(); } if (targetChannel != null) { targetChannel.close(); } } catch (IOException e) { logger.info("closing channels failed"); } } return isBkupFileOK; } |
00
| Code Sample 1:
public static String md5(String text, String charset) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } msgDigest.update(text.getBytes()); byte[] bytes = msgDigest.digest(); byte tb; char low; char high; char tmpChar; String md5Str = new String(); for (int i = 0; i < bytes.length; i++) { tb = bytes[i]; tmpChar = (char) ((tb >>> 4) & 0x000f); if (tmpChar >= 10) { high = (char) (('a' + tmpChar) - 10); } else { high = (char) ('0' + tmpChar); } md5Str += high; tmpChar = (char) (tb & 0x000f); if (tmpChar >= 10) { low = (char) (('a' + tmpChar) - 10); } else { low = (char) ('0' + tmpChar); } md5Str += low; } return md5Str; }
Code Sample 2:
public void transform(String style, String spec, OutputStream out) throws IOException { URL url = new URL(rootURL, spec); InputStream in = new PatchXMLSymbolsStream(new StripDoctypeStream(url.openStream())); transform(style, in, out); in.close(); } |
00
| Code Sample 1:
@Override public void execute() throws BuildException { if (this.toFile == null && this.toDir == null) throw new BuildException("Missing Destination File/Dir"); if (this.toFile != null && this.toDir != null) throw new BuildException("Both Defined Destination File/Dir"); if (this.urlStr == null) throw new BuildException("Missing URL"); URL base = null; try { if (baseStr != null) base = new URL(this.baseStr + (baseStr.endsWith("/") ? "" : "/")); } catch (MalformedURLException e) { throw new BuildException(e); } String tokens[] = this.urlStr.split("[ \t\n]+"); try { for (String nextURL : tokens) { nextURL = nextURL.trim(); if (nextURL.length() == 0) continue; URL url = null; try { url = new URL(base, nextURL); } catch (MalformedURLException e) { throw new BuildException(e); } File dest = null; if (this.toDir != null) { String file = url.getFile(); int i = file.lastIndexOf('/'); if (i != -1 && i + 1 != file.length()) file = file.substring(i + 1); dest = new File(this.toDir, file); } else { dest = this.toFile; } if (dest.exists()) continue; byte buff[] = new byte[2048]; FileOutputStream out = new FileOutputStream(dest); InputStream in = url.openStream(); int n = 0; while ((n = in.read(buff)) != -1) { out.write(buff, 0, n); } in.close(); out.flush(); out.close(); System.out.println("Downloaded " + url + " to " + dest); } } catch (IOException e) { throw new BuildException(e); } }
Code Sample 2:
private static String md5Encode(String pass) { String string; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); byte[] result = md.digest(); string = bytes2hexStr(result); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("La libreria java.security no implemente MD5"); } return string; } |
00
| Code Sample 1:
public boolean receiveFile(FileDescriptor fileDescriptor) { try { byte[] block = new byte[1024]; int sizeRead = 0; int totalRead = 0; File dir = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation()); if (!dir.exists()) { dir.mkdirs(); } File file = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation() + fileDescriptor.getName()); if (!file.exists()) { file.createNewFile(); } SSLSocket sslsocket = getFileTransferConectionConnectMode(ServerAdress.getServerAdress()); OutputStream fileOut = new FileOutputStream(file); InputStream dataIn = sslsocket.getInputStream(); while ((sizeRead = dataIn.read(block)) >= 0) { totalRead += sizeRead; fileOut.write(block, 0, sizeRead); propertyChangeSupport.firePropertyChange("fileByte", 0, totalRead); } fileOut.close(); dataIn.close(); sslsocket.close(); if (fileDescriptor.getName().contains(".snapshot")) { try { File fileData = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation() + fileDescriptor.getName()); File dirData = new File(Constants.PREVAYLER_DATA_DIRETORY + Constants.FILE_SEPARATOR); File destino = new File(dirData, fileData.getName()); boolean success = fileData.renameTo(destino); if (!success) { deleteDir(Constants.DOWNLOAD_DIR); return false; } deleteDir(Constants.DOWNLOAD_DIR); } catch (Exception e) { e.printStackTrace(); } } else { if (Server.isServerOpen()) { FileChannel inFileChannel = new FileInputStream(file).getChannel(); File dirServer = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation()); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getName()); if (!fileServer.exists()) { fileServer.createNewFile(); } inFileChannel.transferTo(0, inFileChannel.size(), new FileOutputStream(fileServer).getChannel()); inFileChannel.close(); } } if (totalRead == fileDescriptor.getSize()) { return true; } } catch (Exception e) { logger.error("Receive File:", e); } return false; }
Code Sample 2:
protected Document SendRequest(Document request) throws WsmanException { HttpURLConnection conn = null; Document response = null; stampRequest(request); boolean printDebug = System.getProperty("intel.management.wsman.debug", "false").equals("true"); int retry = 2; while (retry > 0) { try { if (conn != null) { conn.disconnect(); } URL url = new URL((String) properties.get("Address")); Proxy proxy = (Proxy) properties.get("HttpProxy"); if (proxy != null) conn = (HttpURLConnection) url.openConnection(proxy); else conn = (HttpURLConnection) url.openConnection(); if (conn instanceof HttpsURLConnection) { HttpsURLConnection sslConn = (HttpsURLConnection) conn; SSLSocketFactory factory = (SSLSocketFactory) properties.get("SSLSocketFactory"); X509TrustManager tm = (X509TrustManager) properties.get("X509TrustManager"); HostnameVerifier verifier = (HostnameVerifier) properties.get("HostnameVerifier"); X509KeyManager km = (X509KeyManager) properties.get("X509KeyManager"); if (factory == null && (km != null || tm != null)) { X509KeyManager[] keys = null; X509TrustManager[] trusts = null; SSLContext sc = SSLContext.getInstance("SSL"); if (km != null) { keys = new X509KeyManager[1]; keys[0] = km; } if (tm != null) { trusts = new X509TrustManager[1]; trusts[0] = tm; } sc.init(keys, trusts, null); factory = sc.getSocketFactory(); properties.put("SSLSocketFactory", factory); } if (factory != null) sslConn.setSSLSocketFactory(factory); if (verifier != null) sslConn.setHostnameVerifier(verifier); } Object auth = properties.get("AuthScheme"); if (auth != null && auth.equals("kerberos")) { Oid spnegoMecOid = new Oid("1.3.6.1.5.5.2"); GSSManager manager = org.ietf.jgss.GSSManager.getInstance(); String spnName = "HTTP/" + url.getHost(); int spnPort = url.getPort(); if (spnPort == 16992 || spnPort == 16993 || spnPort == 623 || spnPort == 624) { spnName = spnName + ":" + Integer.toString(spnPort); } GSSName gssName = manager.createName(spnName, null); GSSContext context = manager.createContext(gssName, spnegoMecOid, null, GSSCredential.DEFAULT_LIFETIME); context.requestCredDeleg(true); byte[] token = new byte[0]; token = context.initSecContext(token, 0, token.length); String tokenStr = WsmanUtils.getBase64String(token); conn.addRequestProperty("Authorization", "Negotiate " + tokenStr); } else if (auth != null && auth.equals("basic")) { java.net.Authenticator.requestPasswordAuthentication(url.getHost(), null, url.getPort(), url.getProtocol(), "", "basic"); String tokenStr = ""; conn.addRequestProperty("Authorization", "Basic " + tokenStr); } conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "application/soap+xml;charset=UTF-8"); conn.setDoOutput(true); if (printDebug) System.out.println(getXmlLoader().formatDocument(request)); getXmlLoader().saveDocument(request, conn.getOutputStream()); InputStream s = conn.getInputStream(); response = getXmlLoader().loadDocument(s); if (printDebug) { System.out.println(getXmlLoader().formatDocument(response)); } conn.getResponseCode(); retry = 0; conn.disconnect(); conn = null; } catch (IOException ioException) { retry--; int max = conn.getHeaderFields().size(); for (int i = 0; i < max; i++) { String t = conn.getHeaderField(i); t.toString(); } conn.getRequestProperty("Authorization"); conn.getHeaderField("Authorization"); Object errObj = getResponse(conn); if (errObj != null && errObj instanceof Document) { response = (Document) errObj; retry = 0; throw new WsmanException(this, response); } else if (errObj != null) throw new WsmanException(ioException); if (retry == 0) throw new WsmanException(ioException); } catch (Exception exception) { retry = 0; throw new WsmanException(exception); } } return response; } |
00
| Code Sample 1:
public String excute(String targetUrl, String params, String type) { URL url; HttpURLConnection connection = null; try { url = new URL(targetUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(type); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length)); connection.setRequestProperty("Content-Language", CHAR_SET); connection.setRequestProperty("Connection", "close"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); if (params != null) { if (params.length() > 0) { DataOutputStream wr; wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(params); wr.flush(); wr.close(); } } InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, CHAR_SET)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append("\r\n"); } rd.close(); return response.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
Code Sample 2:
private void gerarFaturamento() { int opt = Funcoes.mensagemConfirma(null, "Confirma o faturamento?"); if (opt == JOptionPane.OK_OPTION) { StringBuilder insert = new StringBuilder(); insert.append("INSERT INTO RPFATURAMENTO "); insert.append("(CODEMP, CODFILIAL, CODPED, CODITPED, "); insert.append("QTDFATURADO, VLRFATURADO, QTDPENDENTE, "); insert.append("PERCCOMISFAT, VLRCOMISFAT, DTFATURADO ) "); insert.append("VALUES"); insert.append("(?,?,?,?,?,?,?,?,?,?)"); PreparedStatement ps; int parameterIndex; try { for (int i = 0; i < tab.getNumLinhas(); i++) { parameterIndex = 1; ps = con.prepareStatement(insert.toString()); ps.setInt(parameterIndex++, AplicativoRep.iCodEmp); ps.setInt(parameterIndex++, ListaCampos.getMasterFilial("RPFATURAMENTO")); ps.setInt(parameterIndex++, txtCodPed.getVlrInteger()); ps.setInt(parameterIndex++, (Integer) tab.getValor(i, ETabNota.ITEM.ordinal())); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.QTDFATURADA.ordinal())); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.VLRFATURADO.ordinal())); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.QDTPENDENTE.ordinal())); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.PERCCOMIS.ordinal())); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.VLRCOMIS.ordinal())); ps.setDate(parameterIndex++, Funcoes.dateToSQLDate(Calendar.getInstance().getTime())); ps.executeUpdate(); } gerarFaturamento.setEnabled(false); gerarComissao.setEnabled(true); Funcoes.mensagemInforma(null, "Faturamento criado para pedido " + txtCodPed.getVlrInteger()); con.commit(); } catch (Exception e) { e.printStackTrace(); Funcoes.mensagemErro(this, "Erro ao gerar faturamento!\n" + e.getMessage()); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } } } |
11
| Code Sample 1:
public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } }
Code Sample 2:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { log.fatal("not a http request"); return; } HttpServletRequest httpRequest = (HttpServletRequest) request; String uri = httpRequest.getRequestURI(); int pathStartIdx = 0; String resourceName = null; pathStartIdx = uri.indexOf(path); if (pathStartIdx <= -1) { log.fatal("the url pattern must match: " + path + " found uri: " + uri); return; } resourceName = uri.substring(pathStartIdx + path.length()); int suffixIdx = uri.lastIndexOf('.'); if (suffixIdx <= -1) { log.fatal("no file suffix found for resource: " + uri); return; } String suffix = uri.substring(suffixIdx + 1).toLowerCase(); String mimeType = (String) mimeTypes.get(suffix); if (mimeType == null) { log.fatal("no mimeType found for resource: " + uri); log.fatal("valid mimeTypes are: " + mimeTypes.keySet()); return; } String themeName = getThemeName(); if (themeName == null) { themeName = this.themeName; } if (!themeName.startsWith("/")) { themeName = "/" + themeName; } InputStream is = null; is = ResourceFilter.class.getResourceAsStream(themeName + resourceName); if (is != null) { IOUtils.copy(is, response.getOutputStream()); response.setContentType(mimeType); response.flushBuffer(); IOUtils.closeQuietly(response.getOutputStream()); IOUtils.closeQuietly(is); } else { log.fatal("error loading resource: " + resourceName); } } |
00
| Code Sample 1:
public void copieFichier(String fileIn, String fileOut) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(fileIn).getChannel(); out = new FileOutputStream(fileOut).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
Code Sample 2:
public void testClickToCallOutDirection() throws Exception { init(); SipCall[] receiverCalls = new SipCall[receiversCount]; receiverCalls[0] = sipPhoneReceivers[0].createSipCall(); receiverCalls[1] = sipPhoneReceivers[1].createSipCall(); receiverCalls[0].listenForIncomingCall(); receiverCalls[1].listenForIncomingCall(); logger.info("Trying to reach url : " + CLICK2DIAL_URL + CLICK2DIAL_PARAMS); URL url = new URL(CLICK2DIAL_URL + CLICK2DIAL_PARAMS); InputStream in = url.openConnection().getInputStream(); byte[] buffer = new byte[10000]; int len = in.read(buffer); String httpResponse = ""; for (int q = 0; q < len; q++) httpResponse += (char) buffer[q]; logger.info("Received the follwing HTTP response: " + httpResponse); receiverCalls[0].waitForIncomingCall(timeout); assertTrue(receiverCalls[0].sendIncomingCallResponse(Response.RINGING, "Ringing", 0)); assertTrue(receiverCalls[0].sendIncomingCallResponse(Response.OK, "OK", 0)); receiverCalls[1].waitForIncomingCall(timeout); assertTrue(receiverCalls[1].sendIncomingCallResponse(Response.RINGING, "Ringing", 0)); assertTrue(receiverCalls[1].sendIncomingCallResponse(Response.OK, "OK", 0)); assertTrue(receiverCalls[1].waitForAck(timeout)); assertTrue(receiverCalls[0].waitForAck(timeout)); assertTrue(receiverCalls[0].disconnect()); assertTrue(receiverCalls[1].waitForDisconnect(timeout)); assertTrue(receiverCalls[1].respondToDisconnect()); } |
00
| Code Sample 1:
public void retrieveChallenges(int num) throws MalformedURLException, IOException, FBErrorException, FBConnectionException { if (num < 1 || num > 100) { error = true; FBErrorException fbee = new FBErrorException(); fbee.setErrorCode(-100); fbee.setErrorText("Invalid GetChallenges range"); throw fbee; } URL url = new URL(getHost() + getPath()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("X-FB-User", getUser()); conn.setRequestProperty("X-FB-Mode", "GetChallenges"); conn.setRequestProperty("X-FB-GetChallenges.Qty", new Integer(num).toString()); conn.connect(); Element fbresponse; try { fbresponse = readXML(conn); } catch (FBConnectionException fbce) { error = true; throw fbce; } catch (FBErrorException fbee) { error = true; throw fbee; } catch (Exception e) { error = true; FBConnectionException fbce = new FBConnectionException("XML parsing failed"); fbce.attachSubException(e); throw fbce; } NodeList nl = fbresponse.getElementsByTagName("GetChallengesResponse"); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i) instanceof Element && hasError((Element) nl.item(i))) { error = true; FBErrorException e = new FBErrorException(); e.setErrorCode(errorcode); e.setErrorText(errortext); throw e; } } NodeList challenge = fbresponse.getElementsByTagName("Challenge"); for (int i = 0; i < challenge.getLength(); i++) { NodeList children = challenge.item(i).getChildNodes(); for (int j = 0; j < children.getLength(); j++) { if (children.item(j) instanceof Text) { challenges.offer(children.item(j).getNodeValue()); } } } }
Code Sample 2:
@Override public void doHandler(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (request.getRequestURI().indexOf(".swf") != -1) { String fullUrl = (String) request.getAttribute("fullUrl"); fullUrl = urlTools.urlFilter(fullUrl, true); response.setCharacterEncoding("gbk"); response.setContentType("application/x-shockwave-flash"); PrintWriter out = response.getWriter(); try { URL url = new URL(fullUrl); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "gbk")); fileEditor.pushStream(out, in, null, true); } catch (Exception e) { } out.flush(); } else if (request.getRequestURI().indexOf(".xml") != -1) { response.setContentType("text/xml"); PrintWriter out = response.getWriter(); try { URL url = new URL("http://" + configCenter.getUcoolOnlineIp() + request.getRequestURI()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); fileEditor.pushStream(out, in, null, true); } catch (Exception e) { } out.flush(); } } |
00
| Code Sample 1:
public void testCryptHash() { Log.v("Test", "[*] testCryptHash()"); String testStr = "Hash me"; byte messageDigest[]; MessageDigest digest = null; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest.digest(testStr.getBytes()); digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest = null; digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(imei.getBytes()); messageDigest = digest.digest(); hashedImei = this.toHex(messageDigest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
Code Sample 2:
public APIResponse update(Variable variable) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/variable/update").openConnection(); connection.setDoOutput(true); connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setUseCaches(false); connection.setConnectTimeout(TIMEOUT); connection.connect(); marshaller.marshal(variable, new MappedXMLStreamWriter(new MappedNamespaceConvention(new Configuration()), new OutputStreamWriter(connection.getOutputStream(), "utf-8"))); connection.getOutputStream().flush(); connection.getOutputStream().close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { JSONObject obj = new JSONObject(new String(new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")).readLine())); response.setDone(true); response.setMessage(unmarshaller.unmarshal(new MappedXMLStreamReader(obj, new MappedNamespaceConvention(new Configuration())))); connection.getInputStream().close(); } else { response.setDone(false); response.setMessage("Update Variable Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; } |
11
| Code Sample 1:
public boolean copyTo(String targetFilePath) { try { FileInputStream srcFile = new FileInputStream(filePath); FileOutputStream target = new FileOutputStream(targetFilePath); byte[] buff = new byte[1024]; int readed = -1; while ((readed = srcFile.read(buff)) > 0) target.write(buff, 0, readed); srcFile.close(); target.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
Code Sample 2:
public static void copy(File src, File dst) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); srcChannel = null; dstChannel.close(); dstChannel = null; } catch (IOException ex) { Tools.logException(Tools.class, ex, dst.getAbsolutePath()); } } |
11
| Code Sample 1:
private JButton getButtonImagen() { if (buttonImagen == null) { buttonImagen = new JButton(); buttonImagen.setText("Cargar Imagen"); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetree.png"))); buttonImagen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setFileView(new ImageFileView()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(Resorces.this, "Seleccione una imagen"); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + file.separator + "data" + file.separator + "imagenes" + file.separator + file.getName(); String rutaRelativa = "data" + file.separator + "imagenes" + file.separator + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); } catch (IOException ex) { ex.printStackTrace(); } imagen.setImagenURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.procesadorDatos.escalaImageIcon(imagen.getImagenURL())); } else { } } }); } return buttonImagen; }
Code Sample 2:
private static URL downloadFile(URL url, File destFile) throws Exception { try { URLConnection urlConnection = url.openConnection(); File tmpFile = null; try { tmpFile = File.createTempFile("remoteLib_", null); InputStream in = null; FileOutputStream out = null; try { in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } URL localURL = destFile.toURI().toURL(); return localURL; } catch (Exception ex) { throw new RuntimeException("Could not download URL: " + url, ex); } } |
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 void handleEvent(Event event) { if (fileDialog == null) { fileDialog = new FileDialog(getShell(), SWT.OPEN); fileDialog.setText("Open device profile file..."); fileDialog.setFilterNames(new String[] { "Device profile (*.jar)" }); fileDialog.setFilterExtensions(new String[] { "*.jar" }); } fileDialog.open(); if (fileDialog.getFileName() != null) { File file; String manifestDeviceName = null; URL[] urls = new URL[1]; ArrayList descriptorEntries = new ArrayList(); try { file = new File(fileDialog.getFilterPath(), fileDialog.getFileName()); JarFile jar = new JarFile(file); Manifest manifest = jar.getManifest(); if (manifest != null) { Attributes attrs = manifest.getMainAttributes(); manifestDeviceName = attrs.getValue("Device-Name"); } for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorEntries.add(entry); } } jar.close(); urls[0] = file.toURL(); } catch (IOException ex) { Message.error("Error reading file: " + fileDialog.getFileName() + ", " + Message.getCauseMessage(ex), ex); return; } if (descriptorEntries.size() == 0) { Message.error("Cannot find any device profile in file: " + fileDialog.getFileName()); return; } if (descriptorEntries.size() > 1) { manifestDeviceName = null; } ClassLoader classLoader = Common.createExtensionsClassLoader(urls); HashMap devices = new HashMap(); for (Iterator it = descriptorEntries.iterator(); it.hasNext(); ) { JarEntry entry = (JarEntry) it.next(); try { devices.put(entry.getName(), DeviceImpl.create(emulatorContext, classLoader, entry.getName(), SwtDevice.class)); } catch (IOException ex) { Message.error("Error parsing device profile, " + Message.getCauseMessage(ex), ex); return; } } for (int i = 0; i < deviceModel.size(); i++) { DeviceEntry entry = (DeviceEntry) deviceModel.elementAt(i); if (devices.containsKey(entry.getDescriptorLocation())) { devices.remove(entry.getDescriptorLocation()); } } if (devices.size() == 0) { Message.info("Device profile already added"); return; } try { File deviceFile = new File(Config.getConfigPath(), file.getName()); if (deviceFile.exists()) { deviceFile = File.createTempFile("device", ".jar", Config.getConfigPath()); } IOUtils.copyFile(file, deviceFile); DeviceEntry entry = null; for (Iterator it = devices.keySet().iterator(); it.hasNext(); ) { String descriptorLocation = (String) it.next(); Device device = (Device) devices.get(descriptorLocation); if (manifestDeviceName != null) { entry = new DeviceEntry(manifestDeviceName, deviceFile.getName(), descriptorLocation, false); } else { entry = new DeviceEntry(device.getName(), deviceFile.getName(), descriptorLocation, false); } deviceModel.addElement(entry); for (int i = 0; i < deviceModel.size(); i++) { if (deviceModel.elementAt(i) == entry) { lsDevices.add(entry.getName()); lsDevices.select(i); } } Config.addDeviceEntry(entry); } lsDevicesListener.widgetSelected(null); } catch (IOException ex) { Message.error("Error adding device profile, " + Message.getCauseMessage(ex), ex); return; } } } |
00
| Code Sample 1:
public void copyTo(File folder) { if (!isNewFile()) { return; } if (!folder.exists()) { folder.mkdir(); } File dest = new File(folder, name); try { FileInputStream in = new FileInputStream(currentPath); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; long totalCopiedSize = 0; boolean canceled = false; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); if (canceled) { dest.delete(); } else { currentPath = dest; newFile = false; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public String runRawSearch(final String search) throws IOException { if (search == null) { return null; } StringBuilder urlString = new StringBuilder("http://ajax.googleapis.com/ajax/services/search/web?"); if (version != null) { urlString.append("v="); urlString.append(version); urlString.append("&"); } urlString.append("q="); urlString.append(StringEscapeUtils.escapeHtml(search)); URL url = new URL(urlString.toString()); Proxy proxy = null; final URLConnection connection; if (proxy != null) { connection = url.openConnection(proxy); } else { connection = url.openConnection(); } if (referer != null) { connection.addRequestProperty("Referer", referer); } String line; StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } return builder.toString(); } |
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:
protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } } |
00
| Code Sample 1:
public void play(File file) { try { URL url = new URL("http://127.0.0.1:8081/play.html?type=4&file=" + file.getAbsolutePath() + "&name=toto"); URLConnection connection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public void download(String target) { try { if (url == null) return; conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "Internet Explorer"); conn.setReadTimeout(10000); conn.connect(); httpReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); java.io.BufferedWriter out = new BufferedWriter(new FileWriter(target, false)); String str = httpReader.readLine(); while (str != null) { out.write(str); str = httpReader.readLine(); } out.close(); System.out.println("file download successfully: " + url.getHost() + url.getPath()); System.out.println("saved to: " + target); } catch (Exception e) { System.out.println("file download failed: " + url.getHost() + url.getPath()); e.printStackTrace(); } } |
11
| Code Sample 1:
public EFaxResult sendFax(ototype.SendFaxWrapper parameters) { EFaxResult efr = new EFaxResult(); if (!validFaxUser(parameters.getUserID(), parameters.getPassWord())) { efr.setResultCode(211); return efr; } Connection conn = null; String faxKey = getSegquence("t_fax_send") + ""; String sql = "insert into t_fax_send(faxKey,userID,appcode,sendername," + "sendernumber,sendercompany,sendtime,accountId, userId2, PID, moduleId, CDRType) values(?,?,?,?,?,?,?,?,?,?,?,?)"; Fax fax = parameters.getFax(); FaxContactor sender = fax.getSender(); FaxContactor[] receiver = fax.getReceiver(); try { conn = this.getJdbcTemplate().getDataSource().getConnection(); conn.setAutoCommit(false); PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, faxKey); pstmt.setString(2, parameters.getUserID()); pstmt.setString(3, parameters.getAppCode()); pstmt.setString(4, sender.getContactor()); pstmt.setString(5, sender.getFaxNumber()); pstmt.setString(6, sender.getCompany()); pstmt.setString(7, fax.getSendTime()); pstmt.setString(8, parameters.getAccountId()); pstmt.setString(9, parameters.getUserId()); pstmt.setString(10, parameters.getPID()); pstmt.setInt(11, parameters.getModuleId()); pstmt.setInt(12, parameters.getCDRType()); pstmt.executeUpdate(); sql = "insert into t_fax_contactor(faxKey,contactorID,contactor,faxnumber,company) values(?,?,?,?,?)"; pstmt = conn.prepareStatement(sql); for (int k = 0; k < receiver.length; k++) { pstmt.setString(1, faxKey); pstmt.setString(2, receiver[k].getContactorID()); pstmt.setString(3, receiver[k].getContactor()); pstmt.setString(4, receiver[k].getFaxNumber()); pstmt.setString(5, receiver[k].getCompany()); pstmt.addBatch(); } pstmt.executeBatch(); sql = "insert into t_fax_file(faxKey,fileID,filename,filetype,fileurl,faxpages) values(?,?,?,?,?,?)"; pstmt = conn.prepareStatement(sql); FaxFile[] files = fax.getFiles(); for (int h = 0; h < files.length; h++) { String fileID = getSegquence("t_Fax_file") + ""; pstmt.setString(1, faxKey); pstmt.setString(2, fileID); pstmt.setString(3, files[h].getFileName()); pstmt.setString(4, files[h].getFileType()); pstmt.setString(5, files[h].getFileURL()); pstmt.setInt(6, files[h].getFaxPages()); Service.writeByteFile(files[h].getFile(), fileID); pstmt.addBatch(); } pstmt.executeBatch(); conn.commit(); efr.setResultCode(100); efr.setResultInfo(faxKey); } catch (SQLException e) { efr.setResultCode(200); try { conn.rollback(); } catch (Exception e1) { logger.error("Error validFaxUser", e1); } logger.error("Error validFaxUser", e); } catch (IOException e) { efr.setResultCode(200); logger.error("Error write file on sendfax", e); } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { logger.error("Error sendFax on close conn", e); } } } return efr; }
Code Sample 2:
public void deleteDomain(final List<Integer> domainIds) { try { connection.setAutoCommit(false); final int defaultDomainId = ((DomainDb) cmDB.getDefaultDomain()).getDomainId(); boolean defaultDomainDeleted = (Boolean) new ProcessEnvelope().executeObject(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public Object executeProcessReturnObject() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("domain.delete")); Iterator<Integer> iter = domainIds.iterator(); int domainId; boolean defaultDomainDeleted = false; while (iter.hasNext()) { domainId = iter.next(); if (!defaultDomainDeleted) defaultDomainDeleted = defaultDomainId == domainId; psImpl.setInt(1, domainId); psImpl.executeUpdate(); } return defaultDomainDeleted; } }); if (defaultDomainDeleted) { new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("domain.setDefaultDomainId")); psImpl.setInt(1, -1); psImpl.executeUpdate(); } }); } connection.commit(); cmDB.updateDomains(null, null); if (defaultDomainDeleted) { cm.updateDefaultDomain(); } } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } } |
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 void write(File file) throws Exception { if (medooFile != null) { if (!medooFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(medooFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } } |
00
| Code Sample 1:
public InputStream getStream(Hashtable<String, String> pValue) throws IOException { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); Enumeration<String> enm = pValue.keys(); String key; while (enm.hasMoreElements()) { key = enm.nextElement(); nvps.add(new BasicNameValuePair(key, pValue.get(key))); } httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); return entity.getContent(); }
Code Sample 2:
@SuppressWarnings("unchecked") private List<String> getWordList() { IConfiguration config = Configurator.getDefaultConfigurator().getConfig(CONFIG_ID); List<String> wList = (List<String>) config.getObject("word_list"); if (wList == null) { wList = new ArrayList<String>(); InputStream resrc = null; try { resrc = new URL(list_url).openStream(); } catch (Exception e) { e.printStackTrace(); } if (resrc != null) { BufferedReader br = new BufferedReader(new InputStreamReader(resrc)); String line; try { while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() != 0) { wList.add(line); } } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } } } return wList; } |
00
| Code Sample 1:
private String endcodePassword(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); Base64 base64 = new Base64(); String hash = new String(base64.encode(raw)); return hash; }
Code Sample 2:
public static void main(String[] args) { String u = "http://portal.acm.org/results.cfm?query=%28Author%3A%22" + "Boehm%2C+Barry" + "%22%29&srt=score%20dsc&short=0&source_disp=&since_month=&since_year=&before_month=&before_year=&coll=ACM&dl=ACM&termshow=matchboolean&range_query=&CFID=22704101&CFTOKEN=37827144&start=1"; URL url = null; AcmSearchresultPageParser_2008Apr cb = new AcmSearchresultPageParser_2008Apr(); try { url = new URL(u); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setUseCaches(false); InputStream is = uc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); ParserDelegator pd = new ParserDelegator(); pd.parse(br, cb, true); br.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("all doc num= " + cb.getAllDocNum()); for (int i = 0; i < cb.getEachResultStartposisions().size(); i++) { HashMap<String, Integer> m = cb.getEachResultStartposisions().get(i); System.out.println(i + "pos= " + m); } } |
11
| Code Sample 1:
private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } }
Code Sample 2:
private void delay(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String url = request.getRequestURL().toString(); if (delayed.contains(url)) { delayed.remove(url); LOGGER.info(MessageFormat.format("Loading delayed resource at url = [{0}]", url)); chain.doFilter(request, response); } else { LOGGER.info("Returning resource = [LoaderApplication.swf]"); InputStream input = null; OutputStream output = null; try { input = getClass().getResourceAsStream("LoaderApplication.swf"); output = response.getOutputStream(); delayed.add(url); response.setHeader("Cache-Control", "no-cache"); IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } } } |
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 RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream())); File targetDirectoryAsFile = new File(targetDirectory); if (!targetDirectoryAsFile.exists()) { FileUtils.forceMkdir(targetDirectoryAsFile); } File target = new File(targetDirectory, targetFile); BufferedOutputStream dest = null; while (zis.getNextEntry() != null) { if (!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos); IOUtils.copy(zis, dest); dest.flush(); dest.close(); } zis.close(); if (!target.exists()) { throw new IllegalStateException("Could not decompress anything from the archive!"); } return RepeatStatus.FINISHED; } |
00
| Code Sample 1:
public void run() { try { String s = (new StringBuilder()).append("fName=").append(URLEncoder.encode("???", "UTF-8")).append("&lName=").append(URLEncoder.encode("???", "UTF-8")).toString(); URL url = new URL("http://snoop.minecraft.net/"); HttpURLConnection httpurlconnection = (HttpURLConnection) url.openConnection(); httpurlconnection.setRequestMethod("POST"); httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpurlconnection.setRequestProperty("Content-Length", (new StringBuilder()).append("").append(Integer.toString(s.getBytes().length)).toString()); httpurlconnection.setRequestProperty("Content-Language", "en-US"); httpurlconnection.setUseCaches(false); httpurlconnection.setDoInput(true); httpurlconnection.setDoOutput(true); DataOutputStream dataoutputstream = new DataOutputStream(httpurlconnection.getOutputStream()); dataoutputstream.writeBytes(s); dataoutputstream.flush(); dataoutputstream.close(); java.io.InputStream inputstream = httpurlconnection.getInputStream(); BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(inputstream)); StringBuffer stringbuffer = new StringBuffer(); String s1; while ((s1 = bufferedreader.readLine()) != null) { stringbuffer.append(s1); stringbuffer.append('\r'); } bufferedreader.close(); } catch (Exception exception) { } }
Code Sample 2:
private void sort() { boolean unsortiert = true; Datei tmp = null; while (unsortiert) { unsortiert = false; for (int i = 0; i < this.size - 1; i++) { if (dateien[i] != null && dateien[i + 1] != null) { if (dateien[i].compareTo(dateien[i + 1]) < 0) { tmp = dateien[i]; dateien[i] = dateien[i + 1]; dateien[i + 1] = tmp; unsortiert = true; } } } } } |
11
| Code Sample 1:
public static Model downloadModel(String url) { Model model = ModelFactory.createDefaultModel(); try { URLConnection connection = new URL(url).openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestProperty("Accept", "application/rdf+xml, */*;q=.1"); httpConnection.setRequestProperty("Accept-Language", "en"); } InputStream in = connection.getInputStream(); model.read(in, url); in.close(); return model; } catch (MalformedURLException e) { logger.debug("Unable to download model from " + url, e); throw new RuntimeException(e); } catch (IOException e) { logger.debug("Unable to download model from " + url, e); throw new RuntimeException(e); } }
Code Sample 2:
@Test public void testDocumentDownloadExcel() throws IOException { if (uploadedExcelDocumentID == null) { fail("Document Upload Test should run first"); } String downloadLink = GoogleDownloadLinkGenerator.generateXlDownloadLink(uploadedExcelDocumentID); URL url = new URL(downloadLink); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); InputStream input = url.openStream(); FileWriter fw = new FileWriter("tmpOutput.kb"); Reader reader = new InputStreamReader(input); BufferedReader bufferedReader = new BufferedReader(reader); String strLine = ""; int count = 0; while (count < 10000) { strLine = bufferedReader.readLine(); if (strLine != null && strLine != "") { fw.write(strLine); } count++; } } |
11
| Code Sample 1:
private final boolean copy_to_file_nio(File src, File dst) throws IOException { FileChannel srcChannel = null, dstChannel = null; try { srcChannel = new FileInputStream(src).getChannel(); dstChannel = new FileOutputStream(dst).getChannel(); { int safe_max = (64 * 1024 * 1024) / 4; long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, safe_max, dstChannel); } } return true; } finally { try { if (srcChannel != null) srcChannel.close(); } catch (IOException e) { Debug.debug(e); } try { if (dstChannel != null) dstChannel.close(); } catch (IOException e) { Debug.debug(e); } } }
Code Sample 2:
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath, String myImagesBehaviour) { File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); File fileXML = new File(directoryPath + "images.xml"); SAXBuilder builder = new SAXBuilder(false); try { Document docXML = builder.build(fileXML); Element root = docXML.getRootElement(); List images = root.getChildren("image"); Iterator j = images.iterator(); int i = 0; TIGDataBase.activateTransactions(); while (j.hasNext() && !stop && !cancel) { current = i; i++; Element image = (Element) j.next(); String name = image.getAttributeValue("name"); List categories = image.getChildren("category"); Iterator k = categories.iterator(); if (exists(list, name)) { String pathSrc = directoryPath.concat(name); String pathDst = System.getProperty("user.dir") + File.separator + "images" + File.separator + name.substring(0, 1).toUpperCase() + File.separator; String folder = System.getProperty("user.dir") + File.separator + "images" + File.separator + name.substring(0, 1).toUpperCase(); if (myImagesBehaviour.equals(TLanguage.getString("TIGImportDBDialog.REPLACE_IMAGES"))) { Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.'))); if (aux.size() != 0) { int idImage = TIGDataBase.imageKeySearchName(name.substring(0, name.lastIndexOf('.'))); TIGDataBase.deleteAsociatedOfImage(idImage); } pathDst = pathDst.concat(name); } if (myImagesBehaviour.equals(TLanguage.getString("TIGImportDBDialog.ADD_IMAGES"))) { Vector aux = new Vector(); aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.'))); int fileCount = 0; if (aux.size() != 0) { while (aux.size() != 0) { fileCount++; aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.')) + "_" + fileCount); } pathDst = pathDst + name.substring(0, name.lastIndexOf('.')) + '_' + fileCount + name.substring(name.lastIndexOf('.'), name.length()); name = name.substring(0, name.lastIndexOf('.')) + '_' + fileCount + name.substring(name.lastIndexOf('.'), name.length()); } else { pathDst = pathDst.concat(name); } } String pathThumbnail = (pathDst.substring(0, pathDst.lastIndexOf("."))).concat("_th.jpg"); File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } TIGDataBase.insertImageDB(name.substring(0, name.lastIndexOf('.')), name); int idImage = TIGDataBase.imageKeySearchName(name.substring(0, name.lastIndexOf('.'))); while (k.hasNext()) { Element category = (Element) k.next(); int idCategory = TIGDataBase.insertConceptDB(category.getValue()); TIGDataBase.insertAsociatedDB(idCategory, idImage); } } else { errorImages = errorImages + System.getProperty("line.separator") + name; } } TIGDataBase.executeQueries(); current = lengthOfTask; } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } |
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 copy(final File from, final File to) { if (from.isDirectory()) { to.mkdirs(); for (final String name : Arrays.asList(from.list())) { if (!copy(from, to, name)) { if (COPY_DEBUG) { System.out.println("Failed to copy " + name + " from " + from + " to " + to); } return false; } } } else { try { final FileInputStream is = new FileInputStream(from); final FileChannel ifc = is.getChannel(); final FileOutputStream os = makeFile(to); if (USE_NIO) { final FileChannel ofc = os.getChannel(); ofc.transferFrom(ifc, 0, from.length()); } else { pipe(is, os, false); } is.close(); os.close(); } catch (final IOException ex) { if (COPY_DEBUG) { System.out.println("Failed to copy " + from + " to " + to + ": " + ex); } return false; } } final long time = from.lastModified(); setLastModified(to, time); final long newtime = to.lastModified(); if (COPY_DEBUG) { if (newtime != time) { System.out.println("Failed to set timestamp for file " + to + ": tried " + new Date(time) + ", have " + new Date(newtime)); to.setLastModified(time); final long morenewtime = to.lastModified(); return false; } else { System.out.println("Timestamp for " + to + " set successfully."); } } return time == newtime; } |
11
| Code Sample 1:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
Code Sample 2:
public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(imageFile.separator) + 1, path.length())); File imageFile = new File(path); directoryPath = "Images" + imageFile.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + imageFile.separator + "Images" + imageFile.separator + imageName.substring(0, 1).toUpperCase() + imageFile.separator + imageName; File newFile = new File(imagePath); int i = 1; while (newFile.exists()) { imagePath = "." + imageFile.separator + "Images" + imageFile.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); newFile = new File(imagePath); i++; } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); dataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { try { int thumbWidth = PREVIEW_WIDTH; int thumbHeight = PREVIEW_HEIGHT; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getIconWidth(); int imageHeight = image.getIconHeight(); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image.getImage(), 0, 0, thumbWidth, thumbHeight, null); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imagePathThumb)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = 100; quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float) quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } } } } |
00
| Code Sample 1:
@Override protected URLConnection openConnection(URL url) throws IOException { try { final HttpServlet servlet; String path = url.getPath(); if (path.matches("reg:.+")) { String registerName = path.replaceAll("reg:([^/]*)/.*", "$1"); servlet = register.get(registerName); if (servlet == null) throw new RuntimeException("No servlet registered with name " + registerName); } else { String servletClassName = path.replaceAll("([^/]*)/.*", "$1"); servlet = (HttpServlet) Class.forName(servletClassName).newInstance(); } final MockHttpServletRequest req = new MockHttpServletRequest().setMethod("GET"); final MockHttpServletResponse resp = new MockHttpServletResponse(); return new HttpURLConnection(url) { @Override public int getResponseCode() throws IOException { serviceIfNeeded(); return resp.status; } @Override public InputStream getInputStream() throws IOException { serviceIfNeeded(); if (resp.status == 500) throw new IOException("Server responded with error 500"); byte[] array = resp.out.toByteArray(); return new ByteArrayInputStream(array); } @Override public InputStream getErrorStream() { try { serviceIfNeeded(); } catch (IOException e) { throw new RuntimeException(e); } if (resp.status != 500) return null; return new ByteArrayInputStream(resp.out.toByteArray()); } @Override public OutputStream getOutputStream() throws IOException { return req.tmp; } @Override public void addRequestProperty(String key, String value) { req.addHeader(key, value); } @Override public void connect() throws IOException { } @Override public boolean usingProxy() { return false; } @Override public void disconnect() { } private boolean called; private void serviceIfNeeded() throws IOException { try { if (!called) { called = true; req.setMethod(getRequestMethod()); servlet.service(req, resp); } } catch (ServletException e) { throw new RuntimeException(e); } } }; } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }
Code Sample 2:
public boolean check(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(username.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(realm.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(password.getBytes("ISO-8859-1")); byte[] ha1 = md.digest(); String hexHa1 = new String(Hex.encodeHex(ha1)); md.reset(); md.update(method.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(uri.getBytes("ISO-8859-1")); byte[] ha2 = md.digest(); String hexHa2 = new String(Hex.encodeHex(ha2)); md.reset(); md.update(hexHa1.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(nonce.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(nc.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(cnonce.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(qop.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(hexHa2.getBytes("ISO-8859-1")); byte[] digest = md.digest(); String hexDigest = new String(Hex.encodeHex(digest)); return (hexDigest.equalsIgnoreCase(response)); } |
00
| Code Sample 1:
@Override public void delCategoria(Integer codigo) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "delete from categoria where id_categoria = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, codigo); ps.executeUpdate(); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } }
Code Sample 2:
public static ISimpleChemObjectReader createReader(URL url, String urlString, String type) throws CDKException { if (type == null) { type = "mol"; } ISimpleChemObjectReader cor = null; try { Reader input = new BufferedReader(getReader(url)); FormatFactory formatFactory = new FormatFactory(8192); IChemFormat format = formatFactory.guessFormat(input); if (format != null) { if (format instanceof RGroupQueryFormat) { cor = new RGroupQueryReader(); cor.setReader(input); } else if (format instanceof CMLFormat) { cor = new CMLReader(urlString); cor.setReader(url.openStream()); } else if (format instanceof MDLV2000Format) { cor = new MDLV2000Reader(getReader(url)); cor.setReader(input); } } } catch (Exception exc) { exc.printStackTrace(); } if (cor == null) { if (type.equals(JCPFileFilter.cml) || type.equals(JCPFileFilter.xml)) { cor = new CMLReader(urlString); } else if (type.equals(JCPFileFilter.sdf)) { cor = new MDLV2000Reader(getReader(url)); } else if (type.equals(JCPFileFilter.mol)) { cor = new MDLV2000Reader(getReader(url)); } else if (type.equals(JCPFileFilter.inchi)) { try { cor = new INChIReader(new URL(urlString).openStream()); } catch (Exception e) { e.printStackTrace(); } } else if (type.equals(JCPFileFilter.rxn)) { cor = new MDLRXNV2000Reader(getReader(url)); } else if (type.equals(JCPFileFilter.smi)) { cor = new SMILESReader(getReader(url)); } } if (cor == null) { throw new CDKException(GT._("Could not determine file format")); } if (cor instanceof MDLV2000Reader) { try { BufferedReader in = new BufferedReader(getReader(url)); String line; while ((line = in.readLine()) != null) { if (line.equals("$$$$")) { String message = GT._("It seems you opened a mol or sdf" + " file containing several molecules. " + "Only the first one will be shown"); JOptionPane.showMessageDialog(null, message, GT._("sdf-like file"), JOptionPane.INFORMATION_MESSAGE); break; } } } catch (IOException ex) { ex.printStackTrace(); } } return cor; } |
11
| Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
private static void copyFile(File src, File dst) throws IOException { FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dst).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } |
11
| Code Sample 1:
public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); 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(); } }
Code Sample 2:
public static void copyFile(String sourceFilePath, String destFilePath) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sourceFilePath).getChannel(); out = new FileOutputStream(destFilePath).getChannel(); long inputSize = in.size(); in.transferTo(0, inputSize, out); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, inputSize); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } |
Subsets and Splits