label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public static String hashString(String sPassword) { if (sPassword == null || sPassword.equals("")) { return "empty:"; } else { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(sPassword.getBytes("UTF-8")); byte[] res = md.digest(); return "sha1:" + StringUtils.byte2hex(res); } catch (NoSuchAlgorithmException e) { return "plain:" + sPassword; } catch (UnsupportedEncodingException e) { return "plain:" + sPassword; } } } Code Sample 2: public static String hash(String text) throws Exception { StringBuffer hexString; MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(text.getBytes()); byte[] digest = mdAlgorithm.digest(); hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { text = Integer.toHexString(0xFF & digest[i]); if (text.length() < 2) { text = "0" + text; } hexString.append(text); } return hexString.toString(); }
11
Code Sample 1: public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_name); System.out.print("Overwrite existing file " + to_name + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("FileCopy: existing file was not overwritten."); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { if (System.getProperty("os.name").toUpperCase().indexOf("WIN") != -1) { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } else { inChannel.transferTo(0, inChannel.size(), outChannel); } } finally { if (inChannel != null) try { inChannel.close(); } catch (Exception e) { } ; if (outChannel != null) try { outChannel.close(); } catch (Exception e) { } ; } }
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 static void extractFile(String jarArchive, String fileToExtract, String destination) { FileWriter writer = null; ZipInputStream zipStream = null; try { FileInputStream inputStream = new FileInputStream(jarArchive); BufferedInputStream bufferedStream = new BufferedInputStream(inputStream); zipStream = new ZipInputStream(bufferedStream); writer = new FileWriter(new File(destination)); ZipEntry zipEntry = null; while ((zipEntry = zipStream.getNextEntry()) != null) { if (zipEntry.getName().equals(fileToExtract)) { int size = (int) zipEntry.getSize(); for (int i = 0; i < size; i++) { writer.write(zipStream.read()); } } } } catch (IOException e) { e.printStackTrace(); } finally { if (zipStream != null) try { zipStream.close(); } catch (IOException e) { e.printStackTrace(); } if (writer != null) try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
11
Code Sample 1: private void update() { if (VERSION.contains("dev")) return; System.out.println(updateURL_s); try { URL updateURL = new URL(updateURL_s); InputStream uis = updateURL.openStream(); InputStreamReader uisr = new InputStreamReader(uis); BufferedReader ubr = new BufferedReader(uisr); String header = ubr.readLine(); if (header.equals("GENREMANUPDATEPAGE")) { String cver = ubr.readLine(); String cdl = ubr.readLine(); if (!cver.equals(VERSION)) { System.out.println("Update available!"); int i = JOptionPane.showConfirmDialog(this, Language.get("UPDATE_AVAILABLE_MSG").replaceAll("%o", VERSION).replaceAll("%c", cver), Language.get("UPDATE_AVAILABLE_TITLE"), JOptionPane.YES_NO_OPTION); if (i == 0) { URL url = new URL(cdl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); if (connection.getResponseCode() / 100 != 2) { throw new Exception("Server error! Response code: " + connection.getResponseCode()); } int contentLength = connection.getContentLength(); if (contentLength < 1) { throw new Exception("Invalid content length!"); } int size = contentLength; File tempfile = File.createTempFile("genreman_update", ".zip"); tempfile.deleteOnExit(); RandomAccessFile file = new RandomAccessFile(tempfile, "rw"); InputStream stream = connection.getInputStream(); int downloaded = 0; ProgressWindow pwin = new ProgressWindow(this, "Downloading"); pwin.setVisible(true); pwin.setProgress(0); pwin.setText("Connecting..."); while (downloaded < size) { byte buffer[]; if (size - downloaded > 1024) { buffer = new byte[1024]; } else { buffer = new byte[size - downloaded]; } int read = stream.read(buffer); if (read == -1) break; file.write(buffer, 0, read); downloaded += read; pwin.setProgress(downloaded / size); } file.close(); System.out.println("Downloaded file to " + tempfile.getAbsolutePath()); pwin.setVisible(false); pwin.dispose(); pwin = null; ZipInputStream zin = new ZipInputStream(new FileInputStream(tempfile)); ZipEntry entry; while ((entry = zin.getNextEntry()) != null) { File outf = new File(entry.getName()); System.out.println(outf.getAbsoluteFile()); if (outf.exists()) outf.delete(); OutputStream out = new FileOutputStream(outf); byte[] buf = new byte[1024]; int len; while ((len = zin.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); } JOptionPane.showMessageDialog(this, Language.get("UPDATE_SUCCESS_MSG"), Language.get("UPDATE_SUCCESS_TITLE"), JOptionPane.INFORMATION_MESSAGE); setVisible(false); if (System.getProperty("os.name").indexOf("Windows") != -1) { Runtime.getRuntime().exec("iTunesGenreArtManager.exe"); } else { Runtime.getRuntime().exec("java -jar \"iTunes Genre Art Manager.app/Contents/Resources/Java/iTunes_Genre_Art_Manager.jar\""); } System.exit(0); } else { } } ubr.close(); uisr.close(); uis.close(); } else { while (ubr.ready()) { System.out.println(ubr.readLine()); } ubr.close(); uisr.close(); uis.close(); throw new Exception("Update page had invalid header: " + header); } } catch (Exception ex) { JOptionPane.showMessageDialog(this, Language.get("UPDATE_ERROR_MSG"), Language.get("UPDATE_ERROR_TITLE"), JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } } Code Sample 2: private BinaryDocument documentFor(String code, String type, int diagramIndex) { code = code.replaceAll("\n", "").replaceAll("\t", "").trim().replaceAll(" ", "%20"); StringBuilder builder = new StringBuilder("http://yuml.me/diagram/"); builder.append(type).append("/"); builder.append(code); URL url; try { url = new URL(builder.toString()); String name = "uml" + diagramIndex + ".png"; diagramIndex++; BinaryDocument pic = new BinaryDocument(name, "image/png"); IOUtils.copy(url.openStream(), pic.getContent().getOutputStream()); return pic; } catch (MalformedURLException e) { throw ManagedIOException.manage(e); } catch (IOException e) { throw ManagedIOException.manage(e); } }
11
Code Sample 1: public static Document validateXml(File messageFile, URL inputUrl, String[] catalogs) throws IOException, ParserConfigurationException, Exception, SAXException, FileNotFoundException { InputSource source = new InputSource(inputUrl.openStream()); Document logDoc = DomUtil.getNewDom(); XMLReader reader = SaxUtil.getXMLFormatLoggingXMLReader(log, logDoc, true, catalogs); reader.parse(source); InputStream logStream = DomUtil.serializeToInputStream(logDoc, "utf-8"); System.out.println("Creating message file \"" + messageFile.getAbsolutePath() + "\"..."); OutputStream fos = new FileOutputStream(messageFile); IOUtils.copy(logStream, fos); return logDoc; } Code Sample 2: 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(); } }
11
Code Sample 1: private void copyFromStdin(Path dst, FileSystem dstFs) throws IOException { if (dstFs.isDirectory(dst)) { throw new IOException("When source is stdin, destination must be a file."); } if (dstFs.exists(dst)) { throw new IOException("Target " + dst.toString() + " already exists."); } FSDataOutputStream out = dstFs.create(dst); try { IOUtils.copyBytes(System.in, out, getConf(), false); } finally { out.close(); } } Code Sample 2: private File copyFile(File file, String newName, File folder) { File newFile = null; if (!file.exists()) { System.out.println("File " + file + " does not exist"); return null; } if (file.isFile()) { BufferedOutputStream out = null; BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); newFile = new File(folder, newName); if (!newFile.exists()) { newFile.createNewFile(); } out = new BufferedOutputStream(new FileOutputStream(newFile)); int read; byte[] buffer = new byte[8192]; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } updateTreeUI(); } catch (IOException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); } } } else if (file.isDirectory()) { newFile = new File(folder, newName); if (!newFile.exists()) { newFile.mkdir(); } for (File f : file.listFiles()) { copyFile(f, f.getName(), newFile); } } return newFile; }
00
Code Sample 1: public static void copyDirs(File sourceDir, File destDir) throws IOException { if (!destDir.exists()) destDir.mkdirs(); for (File file : sourceDir.listFiles()) { if (file.isDirectory()) { copyDirs(file, new File(destDir, file.getName())); } else { FileChannel srcChannel = new FileInputStream(file).getChannel(); File out = new File(destDir, file.getName()); out.createNewFile(); FileChannel dstChannel = new FileOutputStream(out).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } } Code Sample 2: public void testHttpsPersistentConnection() throws Throwable { setUpStoreProperties(); try { SSLContext ctx = getContext(); ServerSocket ss = ctx.getServerSocketFactory().createServerSocket(0); TestHostnameVerifier hnv = new TestHostnameVerifier(); HttpsURLConnection.setDefaultHostnameVerifier(hnv); URL url = new URL("https://localhost:" + ss.getLocalPort()); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); SSLSocket peerSocket = (SSLSocket) doPersistentInteraction(connection, ss); checkConnectionStateParameters(connection, peerSocket); connection.connect(); } finally { tearDownStoreProperties(); } }
00
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); try { sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { sourceChannel.close(); destinationChannel.close(); } } Code Sample 2: public static String hashString(String password) { String hashword = null; try { MessageDigest sha = MessageDigest.getInstance("SHA"); sha.update(password.getBytes("UTF-8")); BigInteger hash = new BigInteger(1, sha.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { log.error(nsae); } catch (UnsupportedEncodingException e) { log.error(e); } return pad(hashword, 32, '0'); }
00
Code Sample 1: public static boolean downFile(String url, String username, String password, String remotePath, Date DBLastestDate, String localPath) { File dFile = new File(localPath); if (!dFile.exists()) { dFile.mkdir(); } boolean success = false; FTPClient ftp = new FTPClient(); ftp.setConnectTimeout(connectTimeout); System.out.println("FTP begin!!"); try { int reply; ftp.connect(url); ftp.login(username, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.changeWorkingDirectory(remotePath); String[] filesName = ftp.listNames(); if (DBLastestDate == null) { System.out.println(" 初次下载,全部下载 "); for (String string : filesName) { if (!string.matches("[0-9]{12}")) { continue; } File localFile = new File(localPath + "/" + string); OutputStream is = new FileOutputStream(localFile); ftp.retrieveFile(string, is); is.close(); } } else { System.out.println(" 加一下载 "); Date date = DBLastestDate; long ldate = date.getTime(); Date nowDate = new Date(); String nowDateStr = Constants.DatetoString(nowDate, Constants.Time_template_LONG); String fileName; do { ldate += 60 * 1000; Date converterDate = new Date(ldate); fileName = Constants.DatetoString(converterDate, Constants.Time_template_LONG); File localFile = new File(localPath + "/" + fileName); OutputStream is = new FileOutputStream(localFile); if (!ftp.retrieveFile(fileName, is)) { localFile.delete(); } is.close(); } while (fileName.compareTo(nowDateStr) < 0); } ftp.logout(); success = true; } catch (IOException e) { System.out.println("FTP timeout return"); e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; } Code Sample 2: private String doMessageDigestAndBase64Encoding(String sequence) throws SeguidException { if (sequence == null) { throw new NullPointerException("You must give a non null sequence"); } try { MessageDigest messageDigest = MessageDigest.getInstance("SHA"); sequence = sequence.trim().toUpperCase(); messageDigest.update(sequence.getBytes()); byte[] digest = messageDigest.digest(); String seguid = Base64.encodeBytes(digest); seguid = seguid.replace("=", ""); if (log.isTraceEnabled()) { log.trace("SEGUID " + seguid); } return seguid; } catch (NoSuchAlgorithmException e) { throw new SeguidException("Exception thrown when calculating Seguid for " + sequence, e.getCause()); } }
00
Code Sample 1: public InputStream createInputStream(URI uri, Map<?, ?> options) throws IOException { try { URL url = new URL(uri.toString()); final URLConnection urlConnection = url.openConnection(); InputStream result = urlConnection.getInputStream(); Map<Object, Object> response = getResponse(options); if (response != null) { response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, urlConnection.getLastModified()); } return result; } catch (RuntimeException exception) { throw new Resource.IOWrappedException(exception); } } Code Sample 2: private boolean _copyPath(String source, String destination, Object handler) { try { FileInputStream fis = new FileInputStream(_fullPathForPath(source)); FileOutputStream fos = new FileOutputStream(_fullPathForPath(destination)); byte[] buffer = new byte[fis.available()]; int read; for (read = fis.read(buffer); read >= 0; read = fis.read(buffer)) { fos.write(buffer, 0, read); } fis.close(); fos.close(); return true; } catch (IOException ioe) { ioe.printStackTrace(); return false; } }
11
Code Sample 1: public void sendContent(OutputStream out, Range range, Map map, String string) throws IOException, NotAuthorizedException, BadRequestException { System.out.println("sendContent " + file); RFileInputStream in = new RFileInputStream(file); try { IOUtils.copyLarge(in, out); } finally { in.close(); } } Code Sample 2: public static void 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); } }
11
Code Sample 1: public static int copy(File src, int amount, File dst) { final int BUFFER_SIZE = 1024; int amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { if (in != null) try { in.close(); } catch (IOException e) { } if (out != null) { try { out.flush(); } catch (IOException e) { } try { out.close(); } catch (IOException e) { } } } return amount - amountToRead; } Code Sample 2: public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { String name = metadata.get(Metadata.RESOURCE_NAME_KEY); if (name != null && wanted.containsKey(name)) { FileOutputStream out = new FileOutputStream(wanted.get(name)); IOUtils.copy(stream, out); out.close(); } else { if (downstreamParser != null) { downstreamParser.parse(stream, handler, metadata, context); } } }
00
Code Sample 1: private String doUploadFile(String sessionId, File file, String originalFileName) throws UnsupportedEncodingException, IOException { log(INFO, sessionId); log(INFO, file.getPath()); DefaultHttpClient httpclient = new DefaultHttpClient(); UploadFileRequest request = new UploadFileRequest(); request.setSessionId(sessionId); request.setDirectory(UUID.randomUUID().toString()); request.setFileName(originalFileName); URL url = file.toURI().toURL(); URLConnection urlCon = url.openConnection(); XStream writer = new XStream(); writer.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); writer.alias("UploadFileRequest", UploadFileRequest.class); XStream reader = new XStream(); reader.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); reader.alias("UploadFileResponse", UploadFileResponse.class); String strRequest = URLEncoder.encode(reader.toXML(request), "UTF-8"); HttpPost httppost = new HttpPost(MewitProperties.getMewitUrl() + "/resources/uploadFile?REQUEST=" + strRequest); FileEntity fileEntity = new FileEntity(file, urlCon.getContentType()); httppost.setEntity(fileEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null) { String result = URLDecoder.decode(EntityUtils.toString(entity), "UTF-8"); log(INFO, result); UploadFileResponse oResponse = (UploadFileResponse) reader.fromXML(result); return oResponse.getFile(); } return null; } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5; StringBuilder sbValueBeforeHash = new StringBuilder(); try { md5 = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new ApplicationIllegalArgumentException(e); } long time = System.nanoTime(); long rand = 0; if (secure) { rand = MySecureRand.nextLong(); } else { rand = MyRand.nextLong(); } sbValueBeforeHash.append(SId); sbValueBeforeHash.append(":"); sbValueBeforeHash.append(Long.toString(time)); sbValueBeforeHash.append(":"); sbValueBeforeHash.append(Long.toString(rand)); valueBeforeHash = sbValueBeforeHash.toString(); md5.update(valueBeforeHash.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b)); } valueAfterHash = sb.toString(); }
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: private static void convertToOnline(final String filePath, final DocuBean docuBean) throws Exception { File source = new File(filePath + File.separator + docuBean.getFileName()); File dir = new File(filePath + File.separator + docuBean.getId()); if (!dir.exists()) { dir.mkdir(); } File in = source; boolean isSpace = false; if (source.getName().indexOf(" ") != -1) { in = new File(StringUtils.replace(source.getName(), " ", "")); try { IOUtils.copyFile(source, in); } catch (IOException e) { e.printStackTrace(); } isSpace = true; } File finalPdf = null; try { String outPath = dir.getAbsolutePath(); final File pdf = DocViewerConverter.toPDF(in, outPath); convertToSwf(pdf, outPath, docuBean); finalPdf = new File(outPath + File.separator + FileUtils.getFilePrefix(StringUtils.replace(source.getName(), " ", "")) + "_decrypted.pdf"); if (!finalPdf.exists()) { finalPdf = pdf; } pdfByFirstPageToJpeg(finalPdf, outPath, docuBean); if (docuBean.getSuccess() == 2 && dir.listFiles().length < 2) { docuBean.setSuccess(3); } } catch (Exception e) { throw e; } finally { if (isSpace) { IOUtils.delete(in); } } }
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 copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } }
00
Code Sample 1: public static InputStream getInputStream(String fileName) throws IOException { InputStream input; if (fileName.startsWith("http:")) { URL url = new URL(fileName); URLConnection connection = url.openConnection(); input = connection.getInputStream(); } else { input = new FileInputStream(fileName); } return input; } Code Sample 2: protected static byte[] hashPassword(byte[] saltBytes, String plaintextPassword) throws AssertionError { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw (AssertionError) new AssertionError("No MD5 message digest supported.").initCause(ex); } digest.update(saltBytes); try { digest.update(plaintextPassword.getBytes("utf-8")); } catch (UnsupportedEncodingException ex) { throw (AssertionError) new AssertionError("No UTF-8 encoding supported.").initCause(ex); } byte[] passwordBytes = digest.digest(); return passwordBytes; }
00
Code Sample 1: protected void doRestoreOrganizeTypeRelation() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strDelQuery = "DELETE FROM " + Common.ORGANIZE_TYPE_RELATION_TABLE; String strSelQuery = "SELECT parent_organize_type,child_organize_type " + "FROM " + Common.ORGANIZE_TYPE_RELATION_B_TABLE + " " + "WHERE version_no = ?"; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_RELATION_TABLE + " " + "(parent_organize_type,child_organize_type) " + "VALUES (?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strDelQuery); ps.executeUpdate(); ps = con.prepareStatement(strSelQuery); ps.setInt(1, this.versionNO); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setString(1, result.getString("parent_organize_type")); ps.setString(2, result.getString("child_organize_type")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): ERROR Inserting data " + "in T_SYS_ORGANIZE_TYPE_RELATION INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): SQLException while committing or rollback"); } } Code Sample 2: @Override @Transactional public FileData store(FileData data, InputStream stream) { try { FileData file = save(data); file.setPath(file.getGroup() + File.separator + file.getId()); file = save(file); File folder = new File(PATH, file.getGroup()); if (!folder.exists()) folder.mkdirs(); File filename = new File(folder, file.getId() + ""); IOUtils.copyLarge(stream, new FileOutputStream(filename)); return file; } catch (IOException e) { throw new ServiceException("storage", e); } }
00
Code Sample 1: public static GCalendar getNewestCalendar(Calendar startDate) throws IOException { GCalendar hoge = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpClient http = new DefaultHttpClient(); HttpGet method = new HttpGet("http://localhost:8080/GoogleCalendar/select"); HttpResponse response = http.execute(method); String jsonstr = response.getEntity().toString(); System.out.println("jsonstr = " + jsonstr); hoge = JSON.decode(jsonstr, GCalendar.class); } catch (Exception ex) { ex.printStackTrace(); } return hoge; } Code Sample 2: public static String encryptSHA(String pwd) throws NoSuchAlgorithmException { MessageDigest d = java.security.MessageDigest.getInstance("SHA-1"); d.reset(); d.update(pwd.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(d.digest()); }
00
Code Sample 1: public GridDirectoryList(URL url) throws McIDASException { try { urlc = (AddeURLConnection) url.openConnection(); inputStream = new DataInputStream(new BufferedInputStream(urlc.getInputStream())); } catch (IOException e) { throw new McIDASException("Error opening URL for grids:" + e); } readDirectory(); } Code Sample 2: public void testOptionalSections() throws Exception { final File implementationDirectory = this.getTestSourcesDirectory(); final File specificationDirectory = this.getTestSourcesDirectory(); IOUtils.copy(this.getClass().getResourceAsStream("ImplementationWithoutConstructorsSection.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("ImplementationWithoutDefaultConstructorSection.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("ImplementationWithoutDocumentationSection.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("ImplementationWithoutLicenseSection.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("SpecificationWithoutDocumentationSection.java.txt"), new FileOutputStream(new File(specificationDirectory, "Specification.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("SpecificationWithoutLicenseSection.java.txt"), new FileOutputStream(new File(specificationDirectory, "Specification.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); }
00
Code Sample 1: public void delete(String fileToDelete) throws IOException { FTPClient ftp = new FTPClient(); try { int reply = 0; ftp.connect(this.endpointURL, this.endpointPort); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("Ftp delete server refused connection."); } if (!ftp.login("anonymous", "")) { ftp.logout(); throw new IOException("FTP: server wrong passwd"); } ftp.enterLocalPassiveMode(); log.debug("Deleted: " + ftp.deleteFile(fileToDelete)); ftp.logout(); } catch (Exception e) { throw new IOException(e.getMessage()); } } Code Sample 2: public static byte[] expandPasswordToKeySSHCom(String password, int keyLen) { try { if (password == null) { password = ""; } MessageDigest md5 = MessageDigest.getInstance("MD5"); int digLen = md5.getDigestLength(); byte[] buf = new byte[((keyLen + digLen) / digLen) * digLen]; int cnt = 0; while (cnt < keyLen) { md5.update(password.getBytes()); if (cnt > 0) { md5.update(buf, 0, cnt); } md5.digest(buf, cnt, digLen); cnt += digLen; } byte[] key = new byte[keyLen]; System.arraycopy(buf, 0, key, 0, keyLen); return key; } catch (Exception e) { throw new Error("Error in SSH2KeyPairFile.expandPasswordToKeySSHCom: " + e); } }
11
Code Sample 1: public void unzip(final File outDir) throws IOException { ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(this.bytes)); ZipEntry entry = input.getNextEntry(); while (entry != null) { entry = input.getNextEntry(); if (entry != null) { File file = this.createFile(outDir, entry.getName()); if (!entry.isDirectory()) { FileOutputStream output = new FileOutputStream(file); IOUtils.copy(input, output); output.close(); } } } input.close(); } Code Sample 2: @RequestMapping("/download") public void download(HttpServletRequest request, HttpServletResponse response) { InputStream input = null; ServletOutputStream output = null; try { String savePath = request.getSession().getServletContext().getRealPath("/upload"); String fileType = ".log"; String dbFileName = "83tomcat日志测试哦"; String downloadFileName = dbFileName + fileType; String finalPath = "\\2011-12\\01\\8364b45f-244d-41b6-bbf48df32064a935"; downloadFileName = new String(downloadFileName.getBytes("GBK"), "ISO-8859-1"); File downloadFile = new File(savePath + finalPath); if (!downloadFile.getParentFile().exists()) { downloadFile.getParentFile().mkdirs(); } if (!downloadFile.isFile()) { FileUtils.touch(downloadFile); } response.setContentType("aapplication/vnd.ms-excel ;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("content-disposition", "attachment; filename=" + downloadFileName); input = new FileInputStream(downloadFile); output = response.getOutputStream(); IOUtils.copy(input, output); output.flush(); } catch (Exception e) { logger.error("Exception: ", e); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
00
Code Sample 1: protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String zOntoJsonApiUrl = getInitParameter("zOntoJsonApiServletUrl"); URL url = new URL(zOntoJsonApiUrl + "?" + req.getQueryString()); resp.setContentType("text/html"); InputStreamReader bf = new InputStreamReader(url.openStream()); BufferedReader bbf = new BufferedReader(bf); String response = ""; String line = bbf.readLine(); PrintWriter out = resp.getWriter(); while (line != null) { response += line; line = bbf.readLine(); } out.print(response); out.close(); } Code Sample 2: public static String encrypt(String key) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md5.update(key.getBytes()); byte hash[] = md5.digest(); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String temp = Integer.toHexString(0xFF & hash[i]); if (temp.length() == 1) temp = "0" + temp; buffer.append(temp); } return buffer.toString(); }
11
Code Sample 1: public void doNew(Vector userId, String shareFlag, String folderId) throws AddrException { DBOperation dbo = null; Connection connection = null; PreparedStatement ps = null; ResultSet rset = null; String sql = "insert into " + SHARE_TABLE + " values(?,?,?)"; try { dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); for (int i = 0; i < userId.size(); i++) { String user = (String) userId.elementAt(i); ps = connection.prepareStatement(sql); ps.setInt(1, Integer.parseInt(folderId)); ps.setInt(2, Integer.parseInt(user)); ps.setString(3, shareFlag); int resultCount = ps.executeUpdate(); if (resultCount != 1) { throw new Exception("error"); } } connection.commit(); } catch (Exception ex) { if (connection != null) { try { connection.rollback(); } catch (SQLException e) { e.printStackTrace(); } } logger.error("���������ļ�����Ϣʧ��, " + ex.getMessage()); throw new AddrException("���������ļ�����Ϣʧ��,һ�������ļ���ֻ�ܹ����ͬһ�û�һ��!"); } finally { close(rset, null, ps, connection, dbo); } } Code Sample 2: public static boolean update(Departamento objDepartamento) { int result = 0; Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); String sql = "update departamento set nome = ?, sala = ?, telefone = ?, id_orgao = ? where id_departamento= ?"; pst = c.prepareStatement(sql); pst.setString(1, objDepartamento.getNome()); pst.setString(2, objDepartamento.getSala()); pst.setString(3, objDepartamento.getTelefone()); pst.setLong(4, (objDepartamento.getOrgao()).getCodigo()); pst.setInt(5, objDepartamento.getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (SQLException e) { try { c.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } System.out.println("[DepartamentoDAO.update] Erro ao atualizar -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
11
Code Sample 1: public static void copy(File source, File dest) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(source); FileOutputStream output = new FileOutputStream(dest); System.out.println("Copying " + source + " to " + dest); IOUtils.copy(input, output); output.close(); input.close(); dest.setLastModified(source.lastModified()); } Code Sample 2: protected File downloadUpdate(String resource) throws AgentException { RESTCall call = makeRESTCall(resource); call.invoke(); File tmpFile; try { tmpFile = File.createTempFile("controller-update-", ".war", new File(tmpPath)); } catch (IOException e) { throw new AgentException("Failed to create temporary file", e); } InputStream is; try { is = call.getInputStream(); } catch (IOException e) { throw new AgentException("Failed to open input stream", e); } try { FileOutputStream os; try { os = new FileOutputStream(tmpFile); } catch (FileNotFoundException e) { throw new AgentException("Failed to open temporary file for writing", e); } boolean success = false; try { IOUtils.copy(is, os); success = true; } catch (IOException e) { throw new AgentException("Failed to download update", e); } finally { try { os.flush(); os.close(); } catch (IOException e) { if (!success) throw new AgentException("Failed to flush to disk", e); } } } finally { try { is.close(); } catch (IOException e) { log.error("Failed to close input stream", e); } call.disconnect(); } return tmpFile; }
00
Code Sample 1: Bundle install(String location, InputStream is) throws BundleException { synchronized (bundlesLock) { SecurityManager securityManager = System.getSecurityManager(); if (securityManager != null) { securityManager.checkPermission(new AdminPermission(new StringBuilder("(location=").append(location).append(")").toString(), org.osgi.framework.AdminPermission.EXTENSIONLIFECYCLE)); } long bundleId = getNextBundleId(); AbstractBundle bundle = null; try { if (is == null) { URL url = new URL(location); is = url.openStream(); } File temp = new File(getTempFolder(), Long.toString(System.currentTimeMillis())); OutputStream os; os = new FileOutputStream(temp); IOUtil.copy(is, os); os.close(); is.close(); Manifest manifest = ManifestUtil.getJarManifest(new FileInputStream(temp)); Dictionary headers = ManifestUtil.toDictionary(manifest); Version version = Version.parseVersion((String) headers.get(Constants.BUNDLE_VERSION)); File cache = createNewCache(bundleId, version); File manifestFile = new File(cache, BUNDLE_MANIFEST_FILE); os = new FileOutputStream(manifestFile); ManifestUtil.storeManifest(headers, os); os.close(); if (isBundleInstalled((String) headers.get(Constants.BUNDLE_SYMBOLICNAME))) { throw new BundleException(new StringBuilder("Bundle(location=").append(location).append(") already installed.").toString()); } ManifestEntry[] entries = ManifestEntry.parse(headers.get(Constants.FRAGMENT_HOST)); if (entries != null) { if (entries[0].hasAttribute("extension")) { String extension = entries[0].getAttributeValue("extension"); if (extension.equals("bootclasspath")) { String symbolicName = entries[0].getName(); if (!symbolicName.equals(framework.getSymbolicName()) && !symbolicName.equals(Constants.SYSTEM_BUNDLE_SYMBOLICNAME)) { throw new BundleException(new StringBuilder("Trying to install a fragment Bundle(location=").append(location).append(") with extension 'bootclasspath' but host is not System Bundle.").toString(), new UnsupportedOperationException()); } } } } String requiredEE = (String) headers.get(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT); if (requiredEE != null) { BundleContext context = framework.getBundleContext(); String ee = context.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT); if (!ee.contains(requiredEE)) { throw new BundleException(new StringBuilder("Bundle(location=").append(location).append(") requires an unsopperted execution environment (=").append(requiredEE).append(").").toString()); } } if (FrameworkUtil.isFragmentHost(headers)) { bundle = new FragmentBundle(framework); } else { bundle = new HostBundle(framework); } File bundlefile = new File(cache, Storage.BUNDLE_FILE); temp.renameTo(bundlefile); long lastModified = bundlefile.lastModified(); BundleInfo info = new BundleInfo(bundleId, location, lastModified, framework.getInitialBundleStartLevel()); info.setHeaders(headers); info.setCache(cache); storeBundleInfo(info); bundleInfosByBundle.put(bundle, info); BundleURLClassPath classPath = createBundleURLClassPath(bundle, version, bundlefile, cache, false); classPathsByBundle.put(bundle, new BundleURLClassPath[] { classPath }); synchronized (bundlesLock) { bundles = (Bundle[]) ArrayUtil.add(bundles, bundle); } return bundle; } catch (Exception e) { if (bundle != null) { File bundleFolder = getBundleFolder(bundleId); try { IOUtil.delete(bundleFolder); } catch (IOException e1) { } } e.printStackTrace(); throw new BundleException(e.getMessage(), e); } } } Code Sample 2: public JSONObject getSourceGraph(HttpSession session, JSONObject json) throws JSONException { StringBuffer out = new StringBuffer(); Graph src = null; MappingManager manager = (MappingManager) session.getAttribute(RuncibleConstants.MAPPING_MANAGER.key()); try { src = manager.getSourceGraph(); if (src != null) { FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.BLUES); factory.visit(src); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); writer.close(); System.out.println(writer.toString()); out.append(writer.toString()); } else { out.append("No source graph loaded."); } } catch (Exception e) { e.printStackTrace(); return JSONUtils.SimpleJSONError("Cannot load source graph: " + e.getMessage()); } return JSONUtils.SimpleJSONResponse(out.toString()); }
11
Code Sample 1: private static void salvarObra(Artista artista, Obra obra) throws Exception { Connection conn = null; PreparedStatement ps = null; int categoria; System.out.println("Migracao.salvarObra() obra: " + obra.toString2()); if (obra.getCategoria() != null) { categoria = getCategoria(obra.getCategoria().getNome()).getCodigo(); } else { categoria = getCategoria("Sem Categoria").getCodigo(); } try { conn = C3P0Pool.getConnection(); String sql = "insert into obra VALUES (?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setNull(1, Types.INTEGER); ps.setString(2, obra.getTitulo()); ps.setInt(3, obra.getSelec()); ps.setInt(4, categoria); ps.setInt(5, artista.getNumeroInscricao()); ps.setInt(6, obra.getCodigo()); ps.executeUpdate(); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } } Code Sample 2: public void candidatarAtividade(Atividade atividade) throws SQLException { Connection conn = null; String insert = "insert into Atividade_has_recurso_humano " + "(atividade_idatividade, usuario_idusuario, ativo) " + "values " + "(" + atividade.getIdAtividade() + ", " + "" + atividade.getRecursoHumano().getIdUsuario() + ", " + "'false')"; try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static 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; }
11
Code Sample 1: private static void copy(File source, File dest) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(source); FileOutputStream output = new FileOutputStream(dest); System.out.println("Copying " + source + " to " + dest); IOUtils.copy(input, output); output.close(); input.close(); dest.setLastModified(source.lastModified()); } Code Sample 2: public void removeExifTag(File jpegImageFile, File dst) throws IOException, ImageReadException, ImageWriteException { OutputStream os = null; try { TiffOutputSet outputSet = null; IImageMetadata metadata = Sanselan.getMetadata(jpegImageFile); JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata; if (null != jpegMetadata) { TiffImageMetadata exif = jpegMetadata.getExif(); if (null != exif) { outputSet = exif.getOutputSet(); } } if (null == outputSet) { IOUtils.copyFileNio(jpegImageFile, dst); return; } { outputSet.removeField(TiffConstants.EXIF_TAG_APERTURE_VALUE); TiffOutputDirectory exifDirectory = outputSet.getExifDirectory(); if (null != exifDirectory) exifDirectory.removeField(TiffConstants.EXIF_TAG_APERTURE_VALUE); } os = new FileOutputStream(dst); os = new BufferedOutputStream(os); new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os, outputSet); os.close(); os = null; } finally { if (os != null) try { os.close(); } catch (IOException e) { } } }
00
Code Sample 1: protected String connectPost(String urlString, String parameter) { String response = null; try { URL url = new URL(urlString); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); log.fine(connection.getURL().toString()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(parameter.getBytes()); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = in.readLine(); in.close(); log.finest(response); } catch (Exception e) { log.log(Level.SEVERE, urlString, e); } return response; } Code Sample 2: public static void copyAssetFile(Context ctx, String srcFileName, String targetFilePath) { AssetManager assetManager = ctx.getAssets(); try { InputStream is = assetManager.open(srcFileName); File out = new File(targetFilePath); if (!out.exists()) { out.getParentFile().mkdirs(); out.createNewFile(); } OutputStream os = new FileOutputStream(out); IOUtils.copy(is, os); is.close(); os.close(); } catch (IOException e) { AIOUtils.log("error when copyAssetFile", e); } }
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: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: private void populateJarsFromManifest(Set<String> jars, ClassLoader loader) { BufferedReader reader = null; try { Enumeration<URL> e = loader.getResources("META-INF/MANIFEST.MF"); while (e.hasMoreElements()) { URL url = e.nextElement(); if (url.getPath().contains(SURE_FIRE_BOOTER_JAR)) { reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; StringBuffer content = new StringBuffer(); while ((line = reader.readLine()) != null) { content.append(line.trim()); } String cont = content.toString().replaceAll("Manifest-Version: 1.0Class-Path: ", "").replaceAll("Main-Class: org.apache.maven.surefire.booter.SurefireBooter", ""); for (String file : cont.split(" ")) { if (file.contains("file")) { jars.add(file.replaceAll("file:", "")); } } break; } } } catch (IOException e) { log.error("", e); } finally { try { if (reader != null) { reader.close(); } } catch (Exception e) { log.error("", e); } } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static File copy(String inFileName, String outFileName) throws IOException { File inputFile = new File(inFileName); File outputFile = new File(outFileName); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return outputFile; } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public void testGetOldVersion() throws ServiceException, IOException, SAXException, ParserConfigurationException { JCRNodeSource emptySource = loadTestSource(); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } } String testSourceUri = BASE_URL + "users/lars.trieloff?revision=1.1"; JCRNodeSource secondSource = (JCRNodeSource) resolveSource(testSourceUri); System.out.println("Read again at:" + secondSource.getSourceRevision()); InputStream expected = emptySource.getInputStream(); InputStream actual = secondSource.getInputStream(); assertTrue(isXmlEqual(expected, actual)); } Code Sample 2: public void registerSchema(String newSchemaName, String objectControlller, long boui, String expression, String schema) throws SQLException { Connection cndef = null; PreparedStatement pstm = null; try { cndef = this.getRepositoryConnection(p_ctx.getApplication(), "default", 2); String friendlyName = MessageLocalizer.getMessage("SCHEMA_CREATED_BY_OBJECT") + " [" + objectControlller + "] " + MessageLocalizer.getMessage("WITH_BOUI") + " [" + boui + "]"; pstm = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? and objecttype='S'"); pstm.setString(1, newSchemaName); pstm.executeUpdate(); pstm.close(); pstm = cndef.prepareStatement("INSERT INTO NGTDIC (SCHEMA,OBJECTNAME,OBJECTTYPE,TABLENAME, " + "FRIENDLYNAME, EXPRESSION) VALUES (" + "?,?,?,?,?,?)"); pstm.setString(1, schema); pstm.setString(2, newSchemaName); pstm.setString(3, "S"); pstm.setString(4, newSchemaName); pstm.setString(5, friendlyName); pstm.setString(6, expression); pstm.executeUpdate(); pstm.close(); cndef.commit(); } catch (Exception e) { cndef.rollback(); e.printStackTrace(); throw new SQLException(e.getMessage()); } finally { if (pstm != null) { try { pstm.close(); } catch (Exception e) { } } } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public void exportFile() { String expfolder = PropertyHandler.getInstance().getProperty(PropertyHandler.KINDLE_EXPORT_FOLDER_KEY); File out = new File(expfolder + File.separator + previewInfo.getTitle() + ".prc"); File f = new File(absPath); try { FileOutputStream fout = new FileOutputStream(out); FileInputStream fin = new FileInputStream(f); int read = 0; byte[] buffer = new byte[1024 * 1024]; while ((read = fin.read(buffer)) > 0) { fout.write(buffer, 0, read); } fin.close(); fout.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public String encryptLdapPassword(String algorithm) { String sEncrypted = _password; if ((_password != null) && (_password.length() > 0)) { algorithm = Val.chkStr(algorithm); boolean bMD5 = algorithm.equalsIgnoreCase("MD5"); boolean bSHA = algorithm.equalsIgnoreCase("SHA") || algorithm.equalsIgnoreCase("SHA1") || algorithm.equalsIgnoreCase("SHA-1"); if (bSHA || bMD5) { String sAlgorithm = "MD5"; if (bSHA) { sAlgorithm = "SHA"; } try { MessageDigest md = MessageDigest.getInstance(sAlgorithm); md.update(getPassword().getBytes("UTF-8")); sEncrypted = "{" + sAlgorithm + "}" + (new BASE64Encoder()).encode(md.digest()); } catch (NoSuchAlgorithmException e) { sEncrypted = null; e.printStackTrace(System.err); } catch (UnsupportedEncodingException e) { sEncrypted = null; e.printStackTrace(System.err); } } } return sEncrypted; } Code Sample 2: public static boolean checkEncryptedPassword(String md5key, String passwordAccount, String encryptedPassword, int passwdenc) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance(Constants.ALGORITHM); switch(passwdenc) { case 1: md.update((md5key + encryptedPassword).getBytes("8859_1")); return md.digest().equals(passwordAccount.getBytes("8859_1")); case 2: md.update((encryptedPassword + md5key).getBytes("8859_1")); return md.digest().equals(passwordAccount.getBytes("8859_1")); default: return false; } }
11
Code Sample 1: private void foundNewVersion() { updater = new UpdaterView(); updater.setLabelText("Initiating Updater..."); updater.setProgress(0); updater.setLocationRelativeTo(null); updater.setVisible(true); URL pathUrl = ClassLoader.getSystemResource("img/icon.png"); String path = pathUrl.toString(); path = path.substring(4, path.length() - 14); try { file = new File(new URI(path)); updaterFile = new File(new URI(path.substring(0, path.length() - 4) + "Updater.jar")); if (updaterFile.exists()) { updaterFile.delete(); } updater.setProgress(25); SwingUtilities.invokeLater(new Runnable() { public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); } }); } catch (URISyntaxException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Update error! Could not create Updater. Check folder permission.", "Error", JOptionPane.ERROR_MESSAGE); } } Code Sample 2: protected void extractArchive(File archive) { ZipInputStream zis = null; FileOutputStream fos; ZipEntry entry; File curEntry; int n; try { zis = new ZipInputStream(new FileInputStream(archive)); while ((entry = zis.getNextEntry()) != null) { curEntry = new File(workingDir, entry.getName()); if (entry.isDirectory()) { System.out.println("skip directory: " + entry.getName()); continue; } System.out.print("zip-entry (file): " + entry.getName()); System.out.println(" ==> real path: " + curEntry.getAbsolutePath()); if (!curEntry.getParentFile().exists()) curEntry.getParentFile().mkdirs(); fos = new FileOutputStream(curEntry); while ((n = zis.read(buf, 0, buf.length)) > -1) fos.write(buf, 0, n); fos.close(); zis.closeEntry(); } } catch (Throwable t) { t.printStackTrace(); } finally { try { if (zis != null) zis.close(); } catch (Throwable t) { } } }
11
Code Sample 1: private boolean doStudentCreditUpdate(Double dblCAmnt, String stuID) throws Exception { Connection conn = null; Statement stmt = null; ResultSet rs = null; Boolean blOk = false; String strMessage = ""; try { conn = dbMan.getPOSConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); String host = getHostName(); String stuId = student.getStudentNumber(); String building = settings.get(DBSettings.MAIN_BUILDING); String cashier = dbMan.getPOSUser(); if (hasStudentCredit()) { stmt = conn.createStatement(); if (stmt.executeUpdate("UPDATE " + strPOSPrefix + "studentcredit set credit_amount = credit_amount + " + round2Places(dblCAmnt) + " WHERE credit_active = '1' and credit_studentid = '" + stuId + "'") == 1) { stmt.close(); stmt = conn.createStatement(); if (stmt.executeUpdate("UPDATE " + strPOSPrefix + "studentcredit set credit_lastused = NOW() where credit_active = '1' and credit_studentid = '" + stuId + "'") == 1) { stmt.close(); stmt = conn.createStatement(); if (stmt.executeUpdate("INSERT into " + strPOSPrefix + "studentcredit_log ( scl_studentid, scl_action, scl_datetime ) values( '" + stuId + "', '" + round2Places(dblCAmnt) + "', NOW() )") == 1) { stmt.close(); blOk = true; } else { strMessage = "Unable to update student credit log."; blOk = false; } } else { strMessage = "Unable to update student credit account."; blOk = false; } } else { strMessage = "Unable to update student credit account."; blOk = false; } } else { stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "studentcredit (credit_amount,credit_active,credit_studentid,credit_lastused) values('" + round2Places(dblCAmnt) + "','1','" + stuId + "', NOW())") == 1) { stmt.close(); stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "studentcredit_log ( scl_studentid, scl_action, scl_datetime ) values( '" + stuId + "', '" + round2Places(dblCAmnt) + "', NOW() )") == 1) { stmt.close(); blOk = true; } else { strMessage = "Unable to update student credit log."; blOk = false; } } else { strMessage = "Unable to create new student credit account."; blOk = false; } } if (blOk) { stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "creditTrans ( ctStudentNumber, ctCreditAction, ctBuilding, ctRegister, ctUser, ctDateTime ) values( '" + stuId + "', '" + round2Places(dblCAmnt) + "', '" + building + "', '" + host + "', '" + cashier + "', NOW() )") == 1) { stmt.close(); blOk = true; } else blOk = false; } if (blOk) { conn.commit(); return true; } else { conn.rollback(); throw new Exception("Error detected during credit adjustment! " + strMessage); } } catch (Exception exp) { try { conn.rollback(); } catch (SQLException sqlEx2) { System.err.println("Rollback failed: " + sqlEx2.getMessage()); return false; } finally { if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) { stmt = null; } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); System.err.println(e); } } } } exp.printStackTrace(); throw new Exception("Error detected during credit adjustment: " + exp.getMessage()); } } Code Sample 2: public void processSaveHolding(Holding holdingBean, AuthSession authSession) { if (authSession == null) { return; } DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "UPDATE WM_LIST_HOLDING " + "SET " + " full_name_HOLDING=?, " + " NAME_HOLDING=? " + "WHERE ID_HOLDING = ? and ID_HOLDING in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedHoldingId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_ROAD from v$_read_list_road z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); int num = 1; ps.setString(num++, holdingBean.getName()); ps.setString(num++, holdingBean.getShortName()); RsetTools.setLong(ps, num++, holdingBean.getId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(num++, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); processDeleteRelatedCompany(dbDyn, holdingBean, authSession); processInsertRelatedCompany(dbDyn, holdingBean, authSession); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save holding"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
11
Code Sample 1: public Transaction() throws Exception { Connection Conn = null; Statement Stmt = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); Conn = DriverManager.getConnection(DBUrl); Conn.setAutoCommit(true); Stmt = Conn.createStatement(); try { Stmt.executeUpdate("DROP TABLE trans_test"); } catch (SQLException sqlEx) { } Stmt.executeUpdate("CREATE TABLE trans_test (id int not null primary key, decdata double) type=BDB"); Conn.setAutoCommit(false); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (1, 21.0)"); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (2, 23.485115)"); Conn.rollback(); System.out.println("Roll Ok"); ResultSet RS = Stmt.executeQuery("SELECT * from trans_test"); if (!RS.next()) { System.out.println("Ok"); } else { System.out.println("Rollback failed"); } Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (2, 23.485115)"); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (1, 21.485115)"); Conn.commit(); RS = Stmt.executeQuery("SELECT * from trans_test where id=2"); if (RS.next()) { System.out.println(RS.getDouble(2)); System.out.println("Ok"); } else { System.out.println("Rollback failed"); } } catch (Exception ex) { throw ex; } finally { if (Stmt != null) { try { Stmt.close(); } catch (SQLException SQLEx) { } } if (Conn != null) { try { Conn.close(); } catch (SQLException SQLEx) { } } } } Code Sample 2: public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
00
Code Sample 1: protected void fixupCategoryAncestry(Context context) throws DataStoreException { Connection db = null; Statement s = null; try { db = context.getConnection(); db.setAutoCommit(false); s = db.createStatement(); s.executeUpdate("delete from category_ancestry"); walkTreeFixing(db, CATEGORYROOT); db.commit(); context.put(Form.ACTIONEXECUTEDTOKEN, "Category Ancestry regenerated"); } catch (SQLException sex) { try { db.rollback(); } catch (SQLException e) { e.printStackTrace(); } throw new DataStoreException("Failed to refresh category ancestry"); } finally { if (s != null) { try { s.close(); } catch (SQLException e) { e.printStackTrace(); } } if (db != null) { context.releaseConnection(db); } } } Code Sample 2: public static void doGet(HttpServletRequest request, HttpServletResponse response, CollOPort colloport, PrintStream out) throws ServletException, IOException { response.addDateHeader("Expires", System.currentTimeMillis() - 86400); String id = request.getParameter("id"); String url_index = request.getParameter("url_index"); int url_i; try { url_i = Integer.parseInt(url_index); } catch (NumberFormatException nfe) { url_i = 0; } Summary summary = colloport.getSummary(id); String filename = request.getPathInfo(); if (filename != null && filename.length() > 0) { filename = filename.substring(1); } String includeURLAll = summary.getIncludeURL(); String includeURLs[] = includeURLAll.split(" "); String includeURL = includeURLs[url_i]; if (includeURL != null && includeURL.length() > 0) { if (filename.indexOf(":") > 0) { includeURL = ""; } else if (filename.startsWith("/")) { includeURL = includeURL.substring(0, includeURL.indexOf("/")); } else if (!includeURL.endsWith("/") && includeURL.indexOf(".") > 0) { includeURL = includeURL.substring(0, includeURL.lastIndexOf("/") + 1); } URL url = null; try { url = new URL(includeURL + response.encodeURL(filename)); } catch (MalformedURLException mue) { System.out.println(mue); } URLConnection conn = null; if (url != null) { try { conn = url.openConnection(); } catch (IOException ioe) { System.out.println(ioe); } } if (conn != null) { String contentType = conn.getContentType(); String contentDisposition; if (contentType == null) { contentType = "application/x-java-serialized-object"; contentDisposition = "attachment;filename=\"" + filename + "\""; } else { contentDisposition = "inline;filename=\"" + filename + "\""; } response.setHeader("content-disposition", contentDisposition); response.setContentType(contentType); try { InputStream inputStream = conn.getInputStream(); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) >= 0) { response.getOutputStream().write(buffer, 0, bytesRead); } inputStream.close(); } catch (IOException ioe) { response.setContentType("text/plain"); ioe.printStackTrace(out); } if (conn instanceof HttpURLConnection) { ((HttpURLConnection) conn).disconnect(); } } } }
11
Code Sample 1: public static void copyFile(String input, String output) { try { FileChannel srcChannel = new FileInputStream("srcFilename").getChannel(); FileChannel dstChannel = new FileOutputStream("dstFilename").getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } Code Sample 2: private void execute(File file) throws IOException { if (file == null) throw new RuntimeException("undefined file"); if (!file.exists()) throw new RuntimeException("file not found :" + file); if (!file.isFile()) throw new RuntimeException("not a file :" + file); String login = cfg.getProperty(GC_USERNAME); String password = null; if (cfg.containsKey(GC_PASSWORD)) { password = cfg.getProperty(GC_PASSWORD); } else { password = new String(Base64.decode(cfg.getProperty(GC_PASSWORD64))); } PostMethod post = null; try { HttpClient client = new HttpClient(); post = new PostMethod("https://" + projectName + ".googlecode.com/files"); post.addRequestHeader("User-Agent", getClass().getName()); post.addRequestHeader("Authorization", "Basic " + Base64.encode(login + ":" + password)); List<Part> parts = new ArrayList<Part>(); String s = this.summary; if (StringUtils.isBlank(s)) { s = file.getName() + " (" + TimeUtils.toYYYYMMDD() + ")"; } parts.add(new StringPart("summary", s)); for (String lbl : this.labels) { if (StringUtils.isBlank(lbl)) continue; parts.add(new StringPart("label", lbl.trim())); } parts.add(new FilePart("filename", file)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()); post.setRequestEntity(requestEntity); int status = client.executeMethod(post); if (status != 201) { throw new IOException("http status !=201 : " + post.getResponseBodyAsString()); } else { IOUtils.copyTo(post.getResponseBodyAsStream(), new NullOutputStream()); } } finally { if (post != null) post.releaseConnection(); } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: private static void copierScriptChargement(File webInfDir, String initialDataChoice) { File chargementInitialDir = new File(webInfDir, "chargementInitial"); File fichierChargement = new File(chargementInitialDir, "ScriptChargementInitial.sql"); File fichierChargementAll = new File(chargementInitialDir, "ScriptChargementInitial-All.sql"); File fichierChargementTypesDocument = new File(chargementInitialDir, "ScriptChargementInitial-TypesDocument.sql"); File fichierChargementVide = new File(chargementInitialDir, "ScriptChargementInitial-Vide.sql"); if (fichierChargement.exists()) { fichierChargement.delete(); } File fichierUtilise = null; if ("all".equals(initialDataChoice)) { fichierUtilise = fichierChargementAll; } else if ("typesDocument".equals(initialDataChoice)) { fichierUtilise = fichierChargementTypesDocument; } else if ("empty".equals(initialDataChoice)) { fichierUtilise = fichierChargementVide; } if (fichierUtilise != null && fichierUtilise.exists()) { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(fichierUtilise).getChannel(); destination = new FileOutputStream(fichierChargement).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (Exception e) { throw new RuntimeException(e); } finally { if (source != null) { try { source.close(); } catch (Exception e) { e.printStackTrace(); } } if (destination != null) { try { destination.close(); } catch (Exception e) { e.printStackTrace(); } } } } }
11
Code Sample 1: @Override public boolean register(String username, String password) { this.getLogger().info(DbUserServiceImpl.class, ">>>rigister " + username + "<<<"); try { if (this.getDbServ().queryFeelerUser(username) != null) { return false; } MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); String passwordMd5 = new String(md5.digest()); this.getDbServ().addFeelerUser(username, passwordMd5); return this.identification(username, password); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return false; } } Code Sample 2: public static final String getUniqueKey() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; ; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { println("Warn: getUniqueKey(), Error trying to get localhost" + e.getMessage()); } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { println("Warn: getUniqueKey() " + e); } return digest; }
00
Code Sample 1: private void generateArchetype(final IProject project, final IDataModel model, final IProgressMonitor monitor, final boolean offline) throws CoreException, InterruptedException, IOException { if (getArchetypeArtifactId(model) != null) { final Properties properties = new Properties(); properties.put("archetypeArtifactId", getArchetypeArtifactId(model)); properties.put("archetypeGroupId", getArchetypeGroupId(model)); properties.put("archetypeVersion", getArchetypeVersion(model)); String artifact = (String) model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_ARTIFACT_ID); if (artifact == null || artifact.trim().length() == 0) { artifact = project.getName(); } properties.put("artifactId", artifact); String group = (String) model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_GROUP_ID); if (group == null || group.trim().length() == 0) { group = project.getName(); } properties.put("groupId", group); properties.put("version", model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_VERSION)); final StringBuffer sb = new StringBuffer(System.getProperty("user.home")).append(File.separator); sb.append(".m2").append(File.separator).append("repository"); final String local = sb.toString(); Logger.getLog().debug("Local Maven2 repository :: " + local); properties.put("localRepository", local); if (!offline) { final String sbRepos = getRepositories(); properties.put("remoteRepositories", sbRepos); } final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); final ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(LAUNCH_CONFIGURATION_TYPE_ID); final ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, "Creating project using Apache Maven archetype"); File archetypePomDirectory = getDefaultArchetypePomDirectory(); try { String dfPom = getPomFile(group, artifact); ByteArrayInputStream bais = new ByteArrayInputStream(dfPom.getBytes()); File f = new File(archetypePomDirectory, "pom.xml"); OutputStream fous = null; try { fous = new FileOutputStream(f); IOUtils.copy(bais, fous); } finally { try { if (fous != null) { fous.close(); } if (bais != null) { bais.close(); } } catch (IOException e) { } } if (SiteManager.isHttpProxyEnable()) { addProxySettings(properties); } workingCopy.setAttribute(ATTR_POM_DIR, archetypePomDirectory.getAbsolutePath()); workingCopy.setAttribute(ATTR_PROPERTIES, convertPropertiesToList(properties)); String goalName = "archetype:create"; if (offline) { goalName = new StringBuffer(goalName).append(" -o").toString(); } goalName = updateGoal(goalName); workingCopy.setAttribute(ATTR_GOALS, goalName); final long timeout = org.maven.ide.eclipse.ext.Maven2Plugin.getTimeout(); TimeoutLaunchConfiguration.launchWithTimeout(monitor, workingCopy, project, timeout); monitor.setTaskName("Moving to workspace"); FileUtils.copyDirectoryStructure(new File(archetypePomDirectory, project.getName()), ArchetypePOMHelper.getProjectDirectory(project)); monitor.worked(1); performMavenInstall(monitor, project, offline); project.refreshLocal(2, monitor); } catch (final IOException ioe) { Logger.log(Logger.ERROR, "I/O exception. One probably solution is absence " + "of mvn2 archetypes or not the correct version, " + "in your local repository. Please, check existence " + "of this archetype."); Logger.getLog().error("I/O Exception arised creating mvn2 archetype", ioe); throw ioe; } finally { FileUtils.deleteDirectory(archetypePomDirectory); Logger.log(Logger.INFO, "Invoked removing of archetype POM directory"); } } monitor.worked(1); } Code Sample 2: public static String generateGuid(boolean secure) { MessageDigest md5 = null; String valueBeforeMD5 = null; String valueAfterMD5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0L; if (secure) rand = mySecureRand.nextLong(); else rand = myRand.nextLong(); sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte array[] = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; j++) { int b = array[j] & 0xff; if (b < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { log.error("Error:" + e); } String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); }
11
Code Sample 1: public static int gunzipFile(File file_input, File dir_output) { GZIPInputStream gzip_in_stream; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in); gzip_in_stream = new GZIPInputStream(source); } catch (IOException e) { return STATUS_IN_FAIL; } String file_input_name = file_input.getName(); String file_output_name = file_input_name.substring(0, file_input_name.length() - 3); File output_file = new File(dir_output, file_output_name); byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; try { FileOutputStream out = new FileOutputStream(output_file); BufferedOutputStream destination = new BufferedOutputStream(out, BUF_SIZE); while ((len = gzip_in_stream.read(input_buffer, 0, BUF_SIZE)) != -1) destination.write(input_buffer, 0, len); destination.flush(); out.close(); } catch (IOException e) { return STATUS_GUNZIP_FAIL; } try { gzip_in_stream.close(); } catch (IOException e) { } return STATUS_OK; } Code Sample 2: public static final void copy(String source, String destination) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } catch (FileNotFoundException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } }
11
Code Sample 1: public static String getHash(String input) { MessageDigest m; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } m.update(input.getBytes(), 0, input.length()); return new BigInteger(1, m.digest()).toString(16); } Code Sample 2: @Override protected Object transform(Row inputs) throws FunctionException { StringBuffer buffer = new StringBuffer(); for (IColumn c : inputs.getColumns()) { buffer.append(c.getValueAsString() + "|"); } try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(buffer.toString().getBytes()); byte[] hash = digest.digest(); return getHex(hash); } catch (Exception e) { throw new FunctionException(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: public String encrypt(String pstrPlainText) throws Exception { if (pstrPlainText == null) { return ""; } MessageDigest md = MessageDigest.getInstance("SHA"); md.update(pstrPlainText.getBytes("UTF-8")); byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); }
00
Code Sample 1: public static String downloadJar(URL url) throws IOException { String localFile = null; char[] buf = new char[4096]; int num; localFile = Settings.getFreeTsUserPath() + "lib" + Settings.SLASH + getURLFileName(url); DebugDialog.print("Downloading jar-file " + url + " to " + localFile + ".", 4); InputStreamReader in = new InputStreamReader(url.openStream()); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(localFile)); do { num = in.read(buf, 0, 4096); if (num > 0) { out.write(buf, 0, num); } } while (num > 0); in.close(); out.close(); return localFile; } Code Sample 2: private void chopFileDisk() throws IOException { File tempFile = new File("" + logFile + ".tmp"); BufferedInputStream bis = null; BufferedOutputStream bos = null; long startCopyPos; byte readBuffer[] = new byte[2048]; int readCount; long totalBytesRead = 0; if (reductionRatio > 0 && logFile.length() > 0) { startCopyPos = logFile.length() / reductionRatio; } else { startCopyPos = 0; } try { bis = new BufferedInputStream(new FileInputStream(logFile)); bos = new BufferedOutputStream(new FileOutputStream(tempFile)); do { readCount = bis.read(readBuffer, 0, readBuffer.length); if (readCount > 0) { totalBytesRead += readCount; if (totalBytesRead > startCopyPos) { bos.write(readBuffer, 0, readCount); } } } while (readCount > 0); } finally { if (bos != null) { try { bos.close(); } catch (IOException ex) { } } if (bis != null) { try { bis.close(); } catch (IOException ex) { } } } if (tempFile.isFile()) { if (!logFile.delete()) { throw new IOException("Error when attempting to delete the " + logFile + " file."); } if (!tempFile.renameTo(logFile)) { throw new IOException("Error when renaming the " + tempFile + " to " + logFile + "."); } } }
11
Code Sample 1: public static void main(String[] args) throws Throwable { Options options = new Options(); options.addOption(new CommandLineOptionBuilder("cas", "cas file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("o", "output directory").longName("outputDir").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("tempDir", "temp directory").build()); options.addOption(new CommandLineOptionBuilder("prefix", "file prefix for all generated files ( default " + DEFAULT_PREFIX + " )").build()); options.addOption(new CommandLineOptionBuilder("trim", "trim file in sfffile's tab delimmed trim format").build()); options.addOption(new CommandLineOptionBuilder("trimMap", "trim map file containing tab delimited trimmed fastX file to untrimmed counterpart").build()); options.addOption(new CommandLineOptionBuilder("chromat_dir", "directory of chromatograms to be converted into phd " + "(it is assumed the read data for these chromatograms are in a fasta file which the .cas file knows about").build()); options.addOption(new CommandLineOptionBuilder("s", "cache size ( default " + DEFAULT_CACHE_SIZE + " )").longName("cache_size").build()); options.addOption(new CommandLineOptionBuilder("useIllumina", "any FASTQ files in this assembly are encoded in Illumina 1.3+ format (default is Sanger)").isFlag(true).build()); options.addOption(new CommandLineOptionBuilder("useClosureTrimming", "apply additional contig trimming based on JCVI Closure rules").isFlag(true).build()); CommandLine commandLine; try { commandLine = CommandLineUtils.parseCommandLine(options, args); int cacheSize = commandLine.hasOption("s") ? Integer.parseInt(commandLine.getOptionValue("s")) : DEFAULT_CACHE_SIZE; File casFile = new File(commandLine.getOptionValue("cas")); File casWorkingDirectory = casFile.getParentFile(); ReadWriteDirectoryFileServer outputDir = DirectoryFileServer.createReadWriteDirectoryFileServer(commandLine.getOptionValue("o")); String prefix = commandLine.hasOption("prefix") ? commandLine.getOptionValue("prefix") : DEFAULT_PREFIX; TrimDataStore trimDatastore; if (commandLine.hasOption("trim")) { List<TrimDataStore> dataStores = new ArrayList<TrimDataStore>(); final String trimFiles = commandLine.getOptionValue("trim"); for (String trimFile : trimFiles.split(",")) { System.out.println("adding trim file " + trimFile); dataStores.add(new DefaultTrimFileDataStore(new File(trimFile))); } trimDatastore = MultipleDataStoreWrapper.createMultipleDataStoreWrapper(TrimDataStore.class, dataStores); } else { trimDatastore = TrimDataStoreUtil.EMPTY_DATASTORE; } CasTrimMap trimToUntrimmedMap; if (commandLine.hasOption("trimMap")) { trimToUntrimmedMap = new DefaultTrimFileCasTrimMap(new File(commandLine.getOptionValue("trimMap"))); } else { trimToUntrimmedMap = new UnTrimmedExtensionTrimMap(); } boolean useClosureTrimming = commandLine.hasOption("useClosureTrimming"); TraceDataStore<FileSangerTrace> sangerTraceDataStore = null; Map<String, File> sangerFileMap = null; ReadOnlyDirectoryFileServer sourceChromatogramFileServer = null; if (commandLine.hasOption("chromat_dir")) { sourceChromatogramFileServer = DirectoryFileServer.createReadOnlyDirectoryFileServer(new File(commandLine.getOptionValue("chromat_dir"))); sangerTraceDataStore = new SingleSangerTraceDirectoryFileDataStore(sourceChromatogramFileServer, ".scf"); sangerFileMap = new HashMap<String, File>(); Iterator<String> iter = sangerTraceDataStore.getIds(); while (iter.hasNext()) { String id = iter.next(); sangerFileMap.put(id, sangerTraceDataStore.get(id).getFile()); } } PrintWriter logOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".log")), true); PrintWriter consensusOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".consensus.fasta")), true); PrintWriter traceFilesOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".traceFiles.txt")), true); PrintWriter referenceFilesOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".referenceFiles.txt")), true); long startTime = System.currentTimeMillis(); logOut.println(System.getProperty("user.dir")); final ReadWriteDirectoryFileServer tempDir; if (!commandLine.hasOption("tempDir")) { tempDir = DirectoryFileServer.createTemporaryDirectoryFileServer(DEFAULT_TEMP_DIR); } else { File t = new File(commandLine.getOptionValue("tempDir")); IOUtil.mkdirs(t); tempDir = DirectoryFileServer.createTemporaryDirectoryFileServer(t); } try { if (!outputDir.contains("chromat_dir")) { outputDir.createNewDir("chromat_dir"); } if (sourceChromatogramFileServer != null) { for (File f : sourceChromatogramFileServer) { String name = f.getName(); OutputStream out = new FileOutputStream(outputDir.createNewFile("chromat_dir/" + name)); final FileInputStream fileInputStream = new FileInputStream(f); try { IOUtils.copy(fileInputStream, out); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(fileInputStream); } } } FastQQualityCodec qualityCodec = commandLine.hasOption("useIllumina") ? FastQQualityCodec.ILLUMINA : FastQQualityCodec.SANGER; CasDataStoreFactory casDataStoreFactory = new MultiCasDataStoreFactory(new H2SffCasDataStoreFactory(casWorkingDirectory, tempDir, EmptyDataStoreFilter.INSTANCE), new H2FastQCasDataStoreFactory(casWorkingDirectory, trimToUntrimmedMap, qualityCodec, tempDir.getRootDir()), new FastaCasDataStoreFactory(casWorkingDirectory, trimToUntrimmedMap, cacheSize)); final SliceMapFactory sliceMapFactory = new LargeNoQualitySliceMapFactory(); CasAssembly casAssembly = new DefaultCasAssembly.Builder(casFile, casDataStoreFactory, trimDatastore, trimToUntrimmedMap, casWorkingDirectory).build(); System.out.println("finished making casAssemblies"); for (File traceFile : casAssembly.getNuceotideFiles()) { traceFilesOut.println(traceFile.getAbsolutePath()); final String name = traceFile.getName(); String extension = FilenameUtils.getExtension(name); if (name.contains("fastq")) { if (!outputDir.contains("solexa_dir")) { outputDir.createNewDir("solexa_dir"); } if (outputDir.contains("solexa_dir/" + name)) { IOUtil.delete(outputDir.getFile("solexa_dir/" + name)); } outputDir.createNewSymLink(traceFile.getAbsolutePath(), "solexa_dir/" + name); } else if ("sff".equals(extension)) { if (!outputDir.contains("sff_dir")) { outputDir.createNewDir("sff_dir"); } if (outputDir.contains("sff_dir/" + name)) { IOUtil.delete(outputDir.getFile("sff_dir/" + name)); } outputDir.createNewSymLink(traceFile.getAbsolutePath(), "sff_dir/" + name); } } for (File traceFile : casAssembly.getReferenceFiles()) { referenceFilesOut.println(traceFile.getAbsolutePath()); } DataStore<CasContig> contigDatastore = casAssembly.getContigDataStore(); Map<String, AceContig> aceContigs = new HashMap<String, AceContig>(); CasIdLookup readIdLookup = sangerFileMap == null ? casAssembly.getReadIdLookup() : new DifferentFileCasIdLookupAdapter(casAssembly.getReadIdLookup(), sangerFileMap); Date phdDate = new Date(startTime); NextGenClosureAceContigTrimmer closureContigTrimmer = null; if (useClosureTrimming) { closureContigTrimmer = new NextGenClosureAceContigTrimmer(2, 5, 10); } for (CasContig casContig : contigDatastore) { final AceContigAdapter adpatedCasContig = new AceContigAdapter(casContig, phdDate, readIdLookup); CoverageMap<CoverageRegion<AcePlacedRead>> coverageMap = DefaultCoverageMap.buildCoverageMap(adpatedCasContig); for (AceContig aceContig : ConsedUtil.split0xContig(adpatedCasContig, coverageMap)) { if (useClosureTrimming) { AceContig trimmedAceContig = closureContigTrimmer.trimContig(aceContig); if (trimmedAceContig == null) { System.out.printf("%s was completely trimmed... skipping%n", aceContig.getId()); continue; } aceContig = trimmedAceContig; } aceContigs.put(aceContig.getId(), aceContig); consensusOut.print(new DefaultNucleotideEncodedSequenceFastaRecord(aceContig.getId(), NucleotideGlyph.convertToString(NucleotideGlyph.convertToUngapped(aceContig.getConsensus().decode())))); } } System.out.printf("finished adapting %d casAssemblies into %d ace contigs%n", contigDatastore.size(), aceContigs.size()); QualityDataStore qualityDataStore = sangerTraceDataStore == null ? casAssembly.getQualityDataStore() : MultipleDataStoreWrapper.createMultipleDataStoreWrapper(QualityDataStore.class, TraceQualityDataStoreAdapter.adapt(sangerTraceDataStore), casAssembly.getQualityDataStore()); final DateTime phdDateTime = new DateTime(phdDate); final PhdDataStore casPhdDataStore = CachedDataStore.createCachedDataStore(PhdDataStore.class, new ArtificalPhdDataStore(casAssembly.getNucleotideDataStore(), qualityDataStore, phdDateTime), cacheSize); final PhdDataStore phdDataStore = sangerTraceDataStore == null ? casPhdDataStore : MultipleDataStoreWrapper.createMultipleDataStoreWrapper(PhdDataStore.class, new PhdSangerTraceDataStoreAdapter<FileSangerTrace>(sangerTraceDataStore, phdDateTime), casPhdDataStore); WholeAssemblyAceTag pathToPhd = new DefaultWholeAssemblyAceTag("phdball", "cas2consed", new Date(DateTimeUtils.currentTimeMillis()), "../phd_dir/" + prefix + ".phd.ball"); AceAssembly aceAssembly = new DefaultAceAssembly<AceContig>(new SimpleDataStore<AceContig>(aceContigs), phdDataStore, Collections.<File>emptyList(), new DefaultAceTagMap(Collections.<ConsensusAceTag>emptyList(), Collections.<ReadAceTag>emptyList(), Arrays.asList(pathToPhd))); System.out.println("writing consed package..."); ConsedWriter.writeConsedPackage(aceAssembly, sliceMapFactory, outputDir.getRootDir(), prefix, false); } catch (Throwable t) { t.printStackTrace(logOut); throw t; } finally { long endTime = System.currentTimeMillis(); logOut.printf("took %s%n", new Period(endTime - startTime)); logOut.flush(); logOut.close(); outputDir.close(); consensusOut.close(); traceFilesOut.close(); referenceFilesOut.close(); trimDatastore.close(); } } catch (ParseException e) { printHelp(options); System.exit(1); } } Code Sample 2: public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); int i; for (i = 0; ((i < list.length) && !stop); i++) { current = i; if ((list[i].compareTo("Images") != 0) && ((list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".jpg") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".bmp") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".png") == 0))) { String name = list[i]; String pathSrc = directoryPath.concat(list[i]); name = name.replace(' ', '_').replace(',', '-').replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u').replace('Á', 'A').replace('É', 'E').replace('Í', 'I').replace('Ó', 'O').replace('Ú', 'U'); String pathDst = directoryPath.concat(name); Vector aux = new Vector(); aux = dataBase.imageSearch(name.substring(0, name.lastIndexOf('.'))); if (aux.size() != 0) pathDst = pathDst.substring(0, pathDst.lastIndexOf('.')) + '_' + aux.size() + ".png"; File src = new File(pathSrc); File absPath = new File(""); String nameSrc = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase() + src.separator + pathDst.substring(pathDst.lastIndexOf(src.separator) + 1, pathDst.length()); String newDirectory = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase(); String imagePathThumb = (nameSrc.substring(0, nameSrc.lastIndexOf("."))).concat("_th.jpg"); ImageIcon image = null; if (src != null) { if (TFileUtils.isJAIRequired(src)) { RenderedOp src_aux = JAI.create("fileload", src.getAbsolutePath()); BufferedImage bufferedImage = src_aux.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(src.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { System.out.print("Error al insertar imagen: "); System.out.println(pathDst); } else { int option = 0; imageFile = new File(directoryPath + "Images"); if (!imageFile.exists()) { TIGNewImageDataDialog dialog = new TIGNewImageDataDialog(editor, dataBase, image, nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length()), list[i].substring(0, list[i].lastIndexOf('.')), myTask); option = dialog.getOption(); if (option != 0) { File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } } if (imageFile.exists()) { dataBase.insertImageDB(list[i].substring(0, list[i].lastIndexOf('.')), nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length())); File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } 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()); } } } } } if (imageFile.exists() && !stop) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(imageFile); Element dataBaseElement = doc.getDocumentElement(); if (dataBaseElement.getTagName().equals("dataBase")) { NodeList imageNodeList = dataBaseElement.getElementsByTagName("image"); for (int j = 0; j < imageNodeList.getLength(); j++) { current++; Node imageNode = imageNodeList.item(j); NodeList lista = imageNode.getChildNodes(); Node nameNode = imageNode.getChildNodes().item(0); String imageName = nameNode.getChildNodes().item(0).getNodeValue(); int imageKey = dataBase.imageKeySearchName(imageName.substring(0, imageName.lastIndexOf('.'))); if (imageKey != -1) { for (int k = 1; k < imageNode.getChildNodes().getLength(); k++) { Node keyWordNode = imageNode.getChildNodes().item(k); String keyWord = keyWordNode.getChildNodes().item(0).getNodeValue(); int conceptKey = dataBase.conceptKeySearch(keyWord); if (conceptKey == -1) { dataBase.insertConceptDB(keyWord); conceptKey = dataBase.conceptKeySearch(keyWord); } dataBase.insertAsociatedDB(conceptKey, imageKey); } } } } } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } current = lengthOfTask; }
00
Code Sample 1: private byte[] rawHttpPost(URL serverTimeStamp, Hashtable reqProperties, byte[] postData) { logger.info("[rawHttpPost.in]:: " + Arrays.asList(new Object[] { serverTimeStamp, reqProperties, postData })); URLConnection urlConn; DataOutputStream printout; DataInputStream input; byte[] responseBody = null; try { urlConn = serverTimeStamp.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); Iterator iter = reqProperties.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); urlConn.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); } logger.debug("POSTing to: " + serverTimeStamp + " ..."); printout = new DataOutputStream(urlConn.getOutputStream()); printout.write(postData); printout.flush(); printout.close(); input = new DataInputStream(urlConn.getInputStream()); byte[] buffer = new byte[1024]; int bytesRead = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { baos.write(buffer, 0, bytesRead); } input.close(); responseBody = baos.toByteArray(); } catch (MalformedURLException me) { logger.warn("[rawHttpPost]:: ", me); } catch (IOException ioe) { logger.warn("[rawHttpPost]:: ", ioe); } return responseBody; } Code Sample 2: private void handleNodeUp(long eventID, long nodeID, String eventTime) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (eventID == -1 || nodeID == -1) { log.warn(EventConstants.NODE_UP_EVENT_UEI + " ignored - info incomplete - eventid/nodeid: " + eventID + "/" + nodeID); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); int count = 0; if (openOutageExists(dbConn, nodeID)) { try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement outageUpdater = dbConn.prepareStatement(OutageConstants.DB_UPDATE_OUTAGES_FOR_NODE); outageUpdater.setLong(1, eventID); outageUpdater.setTimestamp(2, convertEventTimeIntoTimestamp(eventTime)); outageUpdater.setLong(3, nodeID); count = outageUpdater.executeUpdate(); outageUpdater.close(); } else { log.warn("\'" + EventConstants.NODE_UP_EVENT_UEI + "\' for " + nodeID + " no open record."); } try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("nodeUp closed " + count + " outages for nodeid " + nodeID + " in DB"); } catch (SQLException se) { log.warn("Rolling back transaction, nodeUp could not be recorded for nodeId: " + nodeID, se); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } } catch (SQLException se) { log.warn("SQL exception while handling \'nodeRegainedService\'", se); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } }
00
Code Sample 1: public static InputStream getInputStream(String filepath) throws Exception { if (isUrl(filepath)) { URL url = URI.create(filepath).toURL(); return url.openStream(); } else { return new FileInputStream(new File(filepath)); } } Code Sample 2: public void init() { updateLoc = "none"; mt = new MediaTracker(this); thisThread = new Thread(this); i = 0; thisThread.start(); try { base = getDocumentBase(); username = getParameter("username"); } catch (Exception e) { } String userpng = "images/" + username + ".png"; String userdat = "data/" + username + "_l.cod"; URL url = null; try { url = new URL(base, userdat); } catch (MalformedURLException e1) { } InputStream in = null; try { in = url.openStream(); } catch (IOException e1) { } BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(in)); } catch (Exception r) { } try { String line = reader.readLine(); StringTokenizer tokenizer = new StringTokenizer(line, " "); int dim = Integer.parseInt(tokenizer.nextToken().trim().toLowerCase()); this.topol = tokenizer.nextToken().trim().toLowerCase(); xunit = Integer.parseInt(tokenizer.nextToken().trim().toLowerCase()); yunit = Integer.parseInt(tokenizer.nextToken().trim().toLowerCase()); @SuppressWarnings("unused") String neigh = tokenizer.nextToken().trim().toLowerCase(); String label = null; labels = new String[xunit][yunit]; for (int e = 0; e < yunit; e++) { for (int r = 0; r < xunit; r++) { line = reader.readLine(); StringTokenizer tokenizer2 = new StringTokenizer(line, " "); for (int w = 0; w < dim; w++) { if (tokenizer2.countTokens() > 0) tokenizer2.nextToken(); } while (tokenizer2.countTokens() > 0) { label = tokenizer2.nextToken() + " "; } if (label == null) { labels[r][e] = "none"; } else { labels[r][e] = label; } label = null; } } reader.close(); if (topol.equals("hexa")) { xposit = new int[xunit][yunit]; yposit = new int[xunit][yunit]; double divisor1 = xunit; double divisor2 = yunit; for (int p = 0; p < xunit; p++) { for (int q = 0; q < yunit; q++) { if (q % 2 == 0) { double nenner = (p * width); xposit[p][q] = (int) Math.round(nenner / divisor1); } if (q % 2 != 0) { double nenner = (width * 0.5) + (p * width); xposit[p][q] = (int) Math.round(nenner / divisor1); } yposit[p][q] = (int) Math.round(((height * 0.5) + q * height) / divisor2); } } } if (topol.equals("rect")) { xposit = new int[xunit][yunit]; yposit = new int[xunit][yunit]; double divisor1 = xunit; double divisor2 = yunit; for (int p = 0; p < xunit; p++) { for (int q = 0; q < yunit; q++) { double nenner = (width * 0.5) + (p * width); xposit[p][q] = (int) Math.round((nenner / divisor1)); yposit[p][q] = (int) Math.round(((height * 0.5) + q * height) / divisor2); } } } } catch (IOException o) { } umat = getImage(base, userpng); mt.addImage(umat, 1); try { mt.waitForAll(); } catch (InterruptedException e) { } addMouseListener(new CircleInfo()); }
11
Code Sample 1: 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.close(output); } } finally { IOUtils.close(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } Code Sample 2: private void copia(FileInputStream input, FileOutputStream output) throws ErrorException { if (input == null || output == null) { throw new ErrorException("Param null"); } FileChannel inChannel = input.getChannel(); FileChannel outChannel = output.getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (IOException e) { throw new ErrorException("Casino nella copia del file"); } }
11
Code Sample 1: public static boolean copyFile(String sourceFileName, String destFileName) { if (sourceFileName == null || destFileName == null) return false; if (sourceFileName.equals(destFileName)) return false; try { java.io.FileInputStream in = new java.io.FileInputStream(sourceFileName); java.io.FileOutputStream out = new java.io.FileOutputStream(destFileName); try { byte[] buf = new byte[31000]; int read = in.read(buf); while (read > -1) { out.write(buf, 0, read); read = in.read(buf); } } finally { in.close(); out.close(); } } catch (Exception e) { System.out.println(e.toString()); return false; } return true; } Code Sample 2: public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files, int label, String charset) throws FilesException { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { if ((files == null) || (files.size() <= 0)) { return; } if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } Users user = getUser(hsession, repositoryName); Identity identity = getDefaultIdentity(hsession, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); for (int i = 0; i < files.size(); i++) { MultiPartEmail email = email = new MultiPartEmail(); email.setCharset(charset); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if (_to != null) { email.addTo(_to.getAddress(), _to.getPersonal()); } MailPartObj obj = (MailPartObj) files.get(i); email.setSubject("Files-System " + obj.getName()); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); email.attach(attachment); String mid = getId(); email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader("X-DBox", "FILES"); email.addHeader("X-DRecent", "false"); email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeMessage(mid, mime, user); } } catch (FilesException e) { throw e; } catch (Exception e) { throw new FilesException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new FilesException(ex); } catch (Throwable e) { throw new FilesException(e); } finally { GeneralOperations.closeHibernateSession(hsession); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public static void main(String[] args) throws Exception { String urlString = "http://php.tech.sina.com.cn/download/d_load.php?d_id=7877&down_id=151542"; urlString = EncodeUtils.encodeURL(urlString); URL url = new URL(urlString); System.out.println("第一次:" + url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); Map req = conn.getRequestProperties(); System.out.println("第一次请求头:"); printMap(req); conn.connect(); System.out.println("第一次响应:"); System.out.println(conn.getResponseMessage()); int code = conn.getResponseCode(); System.out.println("第一次code:" + code); printMap(conn.getHeaderFields()); System.out.println(conn.getURL().getFile()); if (code == 404 && !(conn.getURL() + "").equals(urlString)) { System.out.println(conn.getURL()); String tmp = URLEncoder.encode(conn.getURL().toString(), "gbk"); System.out.println(URLEncoder.encode("在线音乐播放脚本", "GBK")); System.out.println(tmp); url = new URL(tmp); System.out.println("第二次:" + url); conn = (HttpURLConnection) url.openConnection(); System.out.println("第二次响应:"); System.out.println("code:" + code); printMap(conn.getHeaderFields()); } }
00
Code Sample 1: public static String encryptMd5(String plaintext) { String hashtext = ""; try { MessageDigest m; m = MessageDigest.getInstance("MD5"); m.reset(); m.update(plaintext.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1, digest); hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hashtext; } Code Sample 2: public static void copyAssetFile(Context ctx, String srcFileName, String targetFilePath) { AssetManager assetManager = ctx.getAssets(); try { InputStream is = assetManager.open(srcFileName); File out = new File(targetFilePath); if (!out.exists()) { out.getParentFile().mkdirs(); out.createNewFile(); } OutputStream os = new FileOutputStream(out); IOUtils.copy(is, os); is.close(); os.close(); } catch (IOException e) { AIOUtils.log("error when copyAssetFile", e); } }
00
Code Sample 1: public static String digestString(String data, String algorithm) { String result = null; if (data != null) { try { MessageDigest _md = MessageDigest.getInstance(algorithm); _md.update(data.getBytes()); byte[] _digest = _md.digest(); String _ds; _ds = toHexString(_digest, 0, _digest.length); result = _ds; } catch (NoSuchAlgorithmException e) { result = null; } } return result; } Code Sample 2: public static Dictionary loadManifestFrom(BaseData bundledata) throws BundleException { URL url = bundledata.getEntry(Constants.OSGI_BUNDLE_MANIFEST); if (url == null) return null; try { return Headers.parseManifest(url.openStream()); } catch (IOException e) { throw new BundleException(NLS.bind(EclipseAdaptorMsg.ECLIPSE_DATA_ERROR_READING_MANIFEST, bundledata.getLocation()), e); } }
11
Code Sample 1: public static String httpGet(URL url) throws Exception { URLConnection connection = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuffer content = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { content.append(line); } return content.toString(); } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: public void createControl(Composite parent) { top = new Composite(parent, SWT.NONE); top.setLayout(new GridLayout()); top.setLayoutData(new GridData(GridData.FILL_BOTH)); ComposedAdapterFactory factories = new ComposedAdapterFactory(); factories.addAdapterFactory(new EcoreItemProviderAdapterFactory()); factories.addAdapterFactory(new NotationAdapterFactory()); factories.addAdapterFactory(new ResourceItemProviderAdapterFactory()); modelViewer = new TreeViewer(top, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); modelViewer.getTree().setLayoutData(new GridData(GridData.FILL_BOTH)); modelViewer.setContentProvider(new AdapterFactoryContentProvider(factories) { public boolean hasChildren(Object object) { boolean result = super.hasChildren(object); if (object instanceof Diagram) { result = false; } if (object instanceof EPackage && result == false) { result = !DiagramUtil.getDiagrams((EPackage) object, editor.getDiagram().eResource()).isEmpty(); } return result; } public Object[] getChildren(Object object) { Object[] result = super.getChildren(object); if (object instanceof EPackage) { List<Diagram> list = DiagramUtil.getDiagrams((EPackage) object, editor.getDiagram().eResource()); if (list.size() != 0) { Object[] newResult = new Object[result.length + list.size()]; for (int i = 0; i < result.length; i++) { newResult[i] = result[i]; } for (int i = 0; i < list.size(); i++) { newResult[result.length + i] = list.get(i); } return newResult; } } return result; } }); modelViewer.setLabelProvider(new AdapterFactoryLabelProvider(factories) { public String getText(Object element) { String result = super.getText(element); if (element instanceof Diagram) { if (editor.getDiagram() == element) { result += " *"; } } return result; } public String getColumnText(Object object, int columnIndex) { String result = super.getText(object); if (object instanceof Diagram) { if (editor.getDiagram() == object) { result += " (active)"; } } return result; } }); modelViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { setDiagramSelection(modelViewer.getSelection()); } }); modelViewer.addDragSupport(DND.DROP_COPY, new Transfer[] { LocalTransfer.getInstance() }, new TreeDragListener()); modelViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); Object selectedObject = selection.getFirstElement(); if (selectedObject instanceof Diagram) { openDiagram((Diagram) selectedObject); } } }); createContextMenuFor(modelViewer); editor.getDiagramGraphicalViewer().addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { selectionInDiagramChange(event); } }); this.getSite().setSelectionProvider(modelViewer); setInput(); } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
00
Code Sample 1: public void manageRequest(Transformer transformer) throws ServletException { try { this.parser.reset(); String encodedQuery = URLEncoder.encode(this.query, "ISO-8859-1"); URL url = new URL(EXIST_SERVER + "?_query=" + encodedQuery); InputStream in = url.openStream(); Document doc = this.parser.parse(in); Source source = new DOMSource(doc); transformer.transform(source, new StreamResult(this.getOut())); } catch (TransformerException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } } Code Sample 2: private ArrayList execAtParentServer(ArrayList paramList) throws Exception { ArrayList outputList = null; String message = ""; try { HashMap serverUrlMap = InitXml.getInstance().getServerMap(); Iterator it = serverUrlMap.keySet().iterator(); while (it.hasNext()) { String server = (String) it.next(); String serverUrl = (String) serverUrlMap.get(server); serverUrl = serverUrl + Primer3Manager.servletName; URL url = new URL(serverUrl); URLConnection uc = url.openConnection(); uc.setDoOutput(true); OutputStream os = uc.getOutputStream(); StringBuffer buf = new StringBuffer(); buf.append("actionType=designparent"); for (int i = 0; i < paramList.size(); i++) { Primer3Param param = (Primer3Param) paramList.get(i); if (i == 0) { buf.append("&sequence=" + param.getSequence()); buf.append("&upstream_size" + upstreamSize); buf.append("&downstreamSize" + downstreamSize); buf.append("&MARGIN_LENGTH=" + marginLength); buf.append("&OVERLAP_LENGTH=" + overlapLength); buf.append("&MUST_XLATE_PRODUCT_MIN_SIZE=" + param.getPrimerProductMinSize()); buf.append("&MUST_XLATE_PRODUCT_MAX_SIZE=" + param.getPrimerProductMaxSize()); buf.append("&PRIMER_PRODUCT_OPT_SIZE=" + param.getPrimerProductOptSize()); buf.append("&PRIMER_MAX_END_STABILITY=" + param.getPrimerMaxEndStability()); buf.append("&PRIMER_MAX_MISPRIMING=" + param.getPrimerMaxMispriming()); buf.append("&PRIMER_PAIR_MAX_MISPRIMING=" + param.getPrimerPairMaxMispriming()); buf.append("&PRIMER_MIN_SIZE=" + param.getPrimerMinSize()); buf.append("&PRIMER_OPT_SIZE=" + param.getPrimerOptSize()); buf.append("&PRIMER_MAX_SIZE=" + param.getPrimerMaxSize()); buf.append("&PRIMER_MIN_TM=" + param.getPrimerMinTm()); buf.append("&PRIMER_OPT_TM=" + param.getPrimerOptTm()); buf.append("&PRIMER_MAX_TM=" + param.getPrimerMaxTm()); buf.append("&PRIMER_MAX_DIFF_TM=" + param.getPrimerMaxDiffTm()); buf.append("&PRIMER_MIN_GC=" + param.getPrimerMinGc()); buf.append("&PRIMER_OPT_GC_PERCENT=" + param.getPrimerOptGcPercent()); buf.append("&PRIMER_MAX_GC=" + param.getPrimerMaxGc()); buf.append("&PRIMER_SELF_ANY=" + param.getPrimerSelfAny()); buf.append("&PRIMER_SELF_END=" + param.getPrimerSelfEnd()); buf.append("&PRIMER_NUM_NS_ACCEPTED=" + param.getPrimerNumNsAccepted()); buf.append("&PRIMER_MAX_POLY_X=" + param.getPrimerMaxPolyX()); buf.append("&PRIMER_GC_CLAMP=" + param.getPrimerGcClamp()); } buf.append("&target=" + param.getPrimerSequenceId() + "," + (param.getTarget())[0] + "," + (param.getTarget())[1]); } PrintStream ps = new PrintStream(os); ps.print(buf.toString()); ps.close(); ObjectInputStream ois = new ObjectInputStream(uc.getInputStream()); outputList = (ArrayList) ois.readObject(); ois.close(); } } catch (IOException e1) { e1.printStackTrace(); } if ((outputList == null || outputList.size() == 0) && message != null && message.length() > 0) { throw new Exception(message); } return outputList; }
11
Code Sample 1: public static void main(String[] args) throws IOException { System.setProperty("java.protocol.xfile", "com.luzan.common.nfs"); if (args.length < 1) usage(); final String cmd = args[0]; if ("delete".equalsIgnoreCase(cmd)) { final String path = getParameter(args, 1); XFile xfile = new XFile(path); if (!xfile.exists()) { System.out.print("File doean't exist.\n"); System.exit(1); } xfile.delete(); } else if ("copy".equalsIgnoreCase(cmd)) { final String pathFrom = getParameter(args, 1); final String pathTo = getParameter(args, 2); final XFile xfileFrom = new XFile(pathFrom); final XFile xfileTo = new XFile(pathTo); if (!xfileFrom.exists()) { System.out.print("File doesn't exist.\n"); System.exit(1); } final String mime = getParameter(args, 3, null); final XFileInputStream in = new XFileInputStream(xfileFrom); final XFileOutputStream xout = new XFileOutputStream(xfileTo); if (!StringUtils.isEmpty(mime)) { final com.luzan.common.nfs.s3.XFileExtensionAccessor xfa = ((com.luzan.common.nfs.s3.XFileExtensionAccessor) xfileTo.getExtensionAccessor()); if (xfa != null) { xfa.setMimeType(mime); xfa.setContentLength(xfileFrom.length()); } } IOUtils.copy(in, xout); xout.flush(); xout.close(); in.close(); } } Code Sample 2: public static void encryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); }
11
Code Sample 1: public static String getAnalysisServletOutput(String inputXml) { java.io.BufferedWriter bWriter = null; URLConnection connection = null; String resultString = ""; bWriter = null; connection = null; String target = ServletConstant.ANALYSIS_SERVLET; String message = "\nTHIS MESSAGE IS SENT FROM THE CLIENT APPLET \n\r"; try { URL url = new URL(target); connection = (HttpURLConnection) url.openConnection(); ((HttpURLConnection) connection).setRequestMethod("POST"); connection.setDoOutput(true); bWriter = new java.io.BufferedWriter(new java.io.OutputStreamWriter(connection.getOutputStream())); bWriter.write(message); bWriter.flush(); bWriter.close(); java.io.BufferedReader bReader = null; bReader = new java.io.BufferedReader(new java.io.InputStreamReader(connection.getInputStream())); String line; StringBuffer sb = new StringBuffer(); while ((line = bReader.readLine()) != null) { sb.append(line); } resultString = sb.toString(); bReader.close(); ((HttpURLConnection) connection).disconnect(); } catch (java.io.IOException ex) { resultString += ex.toString(); } finally { if (bWriter != null) { try { bWriter.close(); } catch (Exception ex) { resultString += ex.toString(); } } if (connection != null) { try { ((HttpURLConnection) connection).disconnect(); } catch (Exception ex) { resultString += ex.toString(); } } } return resultString; } Code Sample 2: public static SimpleDataTable loadDataFromFile(URL urlMetadata, URL urlData) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(urlMetadata.openStream())); List<String> columnNamesList = new ArrayList<String>(); String[] lineParts = null; String line; in.readLine(); while ((line = in.readLine()) != null) { lineParts = line.split(","); columnNamesList.add(lineParts[0]); } String[] columnNamesArray = new String[columnNamesList.size()]; int index = 0; for (String s : columnNamesList) { columnNamesArray[index] = s; index++; } SimpleDataTable table = new SimpleDataTable("tabulka s daty", columnNamesArray); in = new BufferedReader(new InputStreamReader(urlData.openStream())); lineParts = null; line = null; SimpleDataTableRow tableRow; double[] rowData; while ((line = in.readLine()) != null) { lineParts = line.split(","); rowData = new double[columnNamesList.size()]; for (int i = 0; i < columnNamesArray.length; i++) { rowData[i] = Double.parseDouble(lineParts[i + 1]); } tableRow = new SimpleDataTableRow(rowData, lineParts[0]); table.add(tableRow); } return table; }
00
Code Sample 1: public void run() { saveWLHome(); for (final TabControl control : tabControls) { control.performOk(WLPropertyPage.this.getProject(), WLPropertyPage.this); } if (isEnabledJCLCopy()) { final File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File log4jLibrary = new File(lib, "log4j-1.2.13.jar"); if (!log4jLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jcl/log4j-1.2.13.jar")); fos = new FileOutputStream(log4jLibrary); IOUtils.copy(srcFile, fos); srcFile.close(); fos.flush(); fos.close(); srcFile = toInputStream(new Path("/jcl/commons-logging-1.0.4.jar")); File jcl = new File(lib, "commons-logging-1.0.4.jar"); fos = new FileOutputStream(jcl); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy JCL jars file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } } if (isEnabledJSTLCopy()) { File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File jstlLibrary = new File(lib, "jstl.jar"); if (!jstlLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jstl/jstl.jar")); fos = new FileOutputStream(jstlLibrary); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy the JSTL 1.1 jar file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (final IOException e) { Logger.getLog().debug("I/O exception closing resources", e); } } } } } Code Sample 2: private void readVersion() { URL url = ClassLoader.getSystemResource("version"); if (url == null) { return; } BufferedReader reader = null; String line = null; try { reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { if (line.startsWith("Version=")) { version = (line.split("="))[1]; } if (line.startsWith("Revision=")) { revision = (line.split("="))[1]; } if (line.startsWith("Date=")) { String sSec = (line.split("="))[1]; Long lSec = Long.valueOf(sSec); compileDate = new Date(lSec); } } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return; }
00
Code Sample 1: public static String getMD5(String s) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(s.toLowerCase().getBytes()); return HexString.bufferToHex(md5.digest()); } catch (NoSuchAlgorithmException e) { System.err.println("Error grave al inicializar MD5"); e.printStackTrace(); return "!!"; } } Code Sample 2: protected Model loadModel(URL url, String filenameBase, SourceModelType modelType, URL baseURL, String skin, float scale, int flags, AppearanceFactory appFactory, GeometryFactory geomFactory, NodeFactory nodeFactory, AnimationFactory animFactory, SpecialItemsHandler siHandler, Model model) throws IOException, IncorrectFormatException, ParsingException { boolean convertZup2Yup = modelType.getConvertFlag(flags); switch(modelType) { case AC3D: AC3DPrototypeLoader.load(url.openStream(), baseURL, appFactory, geomFactory, nodeFactory, true, model, siHandler); break; case ASE: AseReader.load(url.openStream(), baseURL, appFactory, geomFactory, convertZup2Yup, scale, nodeFactory, animFactory, siHandler, model); break; case BSP: BSPPrototypeLoader.load(url.openStream(), filenameBase, baseURL, geomFactory, true, 0.03f, appFactory, nodeFactory, model, GroupType.BSP_TREE, siHandler); break; case CAL3D: break; case COLLADA: convertZup2Yup = true; COLLADALoader.load(baseURL, url.openStream(), appFactory, geomFactory, convertZup2Yup, scale, nodeFactory, animFactory, siHandler, model); break; case MD2: MD2File.load(url.openStream(), baseURL, appFactory, skin, geomFactory, convertZup2Yup, scale, nodeFactory, animFactory, siHandler, model); break; case MD3: MD3File.load(url.openStream(), baseURL, appFactory, geomFactory, convertZup2Yup, scale, nodeFactory, animFactory, siHandler, model); break; case MD5: { Object[][][] boneWeights = MD5MeshReader.load(url.openStream(), baseURL, appFactory, skin, geomFactory, convertZup2Yup, scale, nodeFactory, animFactory, siHandler, model); ((SpecialItemsHandlerImpl) siHandler).flush(); List<URL> animResources = new ResourceLocator(baseURL).findAllResources("md5anim", true, false); for (URL animURL : animResources) { String filename = LoaderUtils.extractFilenameWithoutExt(animURL); MD5AnimationReader.load(animURL.openStream(), filename, baseURL, appFactory, geomFactory, convertZup2Yup, scale, nodeFactory, model.getShapes(), boneWeights, animFactory, siHandler, model); } } break; case MS3D: break; case OBJ: GroupNode rootGroup = model; if (scale != 1.0f) { TransformGroup scaleGroup = new TransformGroup(); scaleGroup.getTransform().setScale(scale); model.addChild(scaleGroup); model.setMainGroup(scaleGroup); rootGroup = scaleGroup; } OBJPrototypeLoader.load(url.openStream(), baseURL, appFactory, skin, geomFactory, convertZup2Yup, scale, nodeFactory, siHandler, rootGroup); break; case TDS: TDSFile.load(url.openStream(), baseURL, appFactory, geomFactory, convertZup2Yup, nodeFactory, animFactory, siHandler, model); } return (model); }
00
Code Sample 1: @Override public InputStream getDataStream(int bufferSize) throws IOException { InputStream in = manager == null ? url.openStream() : manager.getResourceInputStream(this); if (in instanceof ByteArrayInputStream || in instanceof BufferedInputStream) { return in; } return bufferSize == 0 ? new BufferedInputStream(in) : new BufferedInputStream(in, bufferSize); } Code Sample 2: public static String checkPublicIP() { String ipAddress = null; try { URL url; url = new URL("http://checkip.dyndns.org/"); InputStreamReader in = new InputStreamReader(url.openStream()); BufferedReader buffer = new BufferedReader(in); String line; Pattern p = Pattern.compile("\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b"); while ((line = buffer.readLine()) != null) { if (line.indexOf("IP Address:") != -1) { Matcher m = p.matcher(line); if (m.find()) { ipAddress = m.group(); break; } } } buffer.close(); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ipAddress; }
11
Code Sample 1: public static LicenseKey parseKey(String key) throws InvalidLicenseKeyException { final String f_key = key.trim(); StringTokenizer st = new StringTokenizer(f_key, FIELD_SEPERATOR); int tc = st.countTokens(); int tc_name = tc - 9; try { final String product = st.nextToken(); final String type = st.nextToken(); final String loadStr = st.nextToken(); final int load = Integer.parseInt(loadStr); final String lowMajorVersionStr = st.nextToken(); final int lowMajorVersion = Integer.parseInt(lowMajorVersionStr); final String lowMinorVersionStr = st.nextToken(); final double lowMinorVersion = Double.parseDouble("0." + lowMinorVersionStr); final String highMajorVersionStr = st.nextToken(); final int highMajorVersion = Integer.parseInt(highMajorVersionStr); final String highMinorVersionStr = st.nextToken(); final double highMinorVersion = Double.parseDouble("0." + highMinorVersionStr); String regName = ""; for (int i = 0; i < tc_name; i++) regName += (i == 0 ? st.nextToken() : FIELD_SEPERATOR + st.nextToken()); final String randomHexStr = st.nextToken(); final String md5Str = st.nextToken(); String subKey = f_key.substring(0, f_key.indexOf(md5Str) - 1); byte[] md5; MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(subKey.getBytes()); md.update(FIELD_SEPERATOR.getBytes()); md.update(zuonicsPassword.getBytes()); md5 = md.digest(); String testKey = subKey + FIELD_SEPERATOR; for (int i = 0; i < md5.length; i++) testKey += Integer.toHexString(md5[i]).toUpperCase(); if (!testKey.equals(f_key)) throw new InvalidLicenseKeyException("doesn't hash"); final String f_regName = regName; return new LicenseKey() { public String getProduct() { return product; } public String getType() { return type; } public int getLoad() { return load; } public String getRegName() { return f_regName; } public double getlowVersion() { return lowMajorVersion + lowMinorVersion; } public double getHighVersion() { return highMajorVersion + highMinorVersion; } public String getRandomHexStr() { return randomHexStr; } public String getMD5HexStr() { return md5Str; } public String toString() { return f_key; } public boolean equals(Object obj) { if (obj.toString().equals(toString())) return true; return false; } }; } catch (Exception e) { throw new InvalidLicenseKeyException(e.getMessage()); } } Code Sample 2: public static String generate(String source) { byte[] SHA = new byte[20]; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(source.getBytes()); SHA = digest.digest(); } catch (NoSuchAlgorithmException e) { System.out.println("NO SUCH ALGORITHM EXCEPTION: " + e.getMessage()); } CommunicationLogger.warning("SHA1 DIGEST: " + SHA); return SHA.toString(); }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: private String doExecute(AbortableHttpRequest method) throws Throwable { HttpClient client = CLIENT.newInstance(); HttpResponse rsp = client.execute((HttpUriRequest) method); HttpEntity entity = rsp.getEntity(); if (entity == null) throw new RequestError("No entity in method"); InputStream in = null; try { in = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder inStr = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { inStr.append(line).append("\r\n"); } entity.consumeContent(); return inStr.toString(); } catch (IOException ex) { LOG.error("IO exception: " + ex.getMessage()); throw ex; } catch (RuntimeException ex) { method.abort(); throw ex; } finally { if (in != null) in.close(); } }
00
Code Sample 1: public InputStream getInputStream(long offset) throws IOException { if (is != null && raf == null) { try { is.close(); } catch (Throwable th) { } finally { is = null; } } if (is == null && getUrl() != null && getFile() == null) { is = url.openStream(); } if (is == null) { if (getFile() != null) { raf = null; try { raf = new RandomAccessFile(getFile(), "r"); } catch (Exception ex) { } is = (raf != null) ? new RAFInputStream(raf, 0) : new BufferedInputStream(new FileInputStream(getFile()), 1024 * 30); } } if (is instanceof RAFInputStream) { RAFInputStream ris = (RAFInputStream) is; ris.seek(offset); } else { is.skip(offset); } return is; } Code Sample 2: private void writeData(IBaseType dataType, Writer writer) throws XMLStreamException { InputStream isData; DataType data = (DataType) baseType; if (data.isSetInputStream()) { isData = data.getInputStream(); try { IOUtils.copy(isData, writer); } catch (IOException e) { throw new XMLStreamException("DataType fail writing streaming data ", e); } } else if (data.isSetOutputStream()) { throw new XMLStreamException("DataType only can write streaming input, its an output stream (only for reading) "); } else { new CharactersEventImpl(startElement.getLocation(), String.valueOf(baseType.asData()), false).writeAsEncodedUnicode(writer); } }
11
Code Sample 1: public static byte[] encrypt(String x) throws NoSuchAlgorithmException { MessageDigest d = null; d = MessageDigest.getInstance("SHA-1"); d.reset(); d.update(x.getBytes()); return d.digest(); } Code Sample 2: private String md5(String value) { String md5Value = "1"; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(value.getBytes()); md5Value = getHex(digest.digest()); } catch (Exception e) { e.printStackTrace(); } return md5Value; }
00
Code Sample 1: public static void bubbleSort(Drawable[] list) { boolean swapped; do { swapped = false; for (int i = 0; i < list.length - 1; ++i) { if (list[i].getSortValue() > list[i + 1].getSortValue()) { Drawable temp = list[i]; list[i] = list[i + 1]; list[i + 1] = temp; swapped = true; } } } while (swapped); } Code Sample 2: public String addShare2(String appid, String appkey, String oauth_token, String oauth_token_secret, String openid, String format, Webpage webpage) throws Exception { String shareUrl = "http://openapi.qzone.qq.com/share/add_share"; String oauth_signature = ""; long oauth_timestamp = new Date().getTime() / 1000; String oauth_nonce = (Math.random() + "").replaceFirst("^0.", ""); List<NameValuePair> shareParameters = new ArrayList<NameValuePair>(); shareParameters.add(new BasicNameValuePair("format", format)); shareParameters.add(new BasicNameValuePair("images", webpage.images)); shareParameters.add(new BasicNameValuePair("oauth_consumer_key", appid)); shareParameters.add(new BasicNameValuePair("oauth_nonce", oauth_nonce)); shareParameters.add(new BasicNameValuePair("oauth_signature_method", "HMAC-SHA1")); shareParameters.add(new BasicNameValuePair("oauth_timestamp", oauth_timestamp + "")); shareParameters.add(new BasicNameValuePair("oauth_token", oauth_token)); shareParameters.add(new BasicNameValuePair("oauth_version", "1.0")); shareParameters.add(new BasicNameValuePair("openid", openid)); shareParameters.add(new BasicNameValuePair("title", webpage.title)); shareParameters.add(new BasicNameValuePair("url", webpage.url)); String stepA1 = "POST"; String stepA2 = URLEncoder.encode(shareUrl, "UTF-8"); String stepA3 = ""; for (int i = 0; i < shareParameters.size(); i++) { NameValuePair item = shareParameters.get(i); stepA3 += item.getName() + "=" + item.getValue(); if (i < shareParameters.size() - 1) { stepA3 += "&"; } } stepA3 = URLEncoder.encode(stepA3, "UTF-8"); String stepA = stepA1 + "&" + stepA2 + "&" + stepA3; String stepB = appkey + "&" + oauth_token_secret; Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec spec = new SecretKeySpec(stepB.getBytes("US-ASCII"), "HmacSHA1"); mac.init(spec); byte[] oauthSignature = mac.doFinal(stepA.getBytes("US-ASCII")); oauth_signature = Base64Encoder.encode(oauthSignature); shareParameters.add(new BasicNameValuePair("oauth_signature", oauth_signature)); HttpPost sharePost = new HttpPost(shareUrl); sharePost.setHeader("Referer", "http://openapi.qzone.qq.com"); sharePost.setHeader("Host", "openapi.qzone.qq.com"); sharePost.setHeader("Accept-Language", "zh-cn"); sharePost.setHeader("Content-Type", "application/x-www-form-urlencoded"); sharePost.setEntity(new UrlEncodedFormEntity(shareParameters, "UTF-8")); DefaultHttpClient httpclient = HttpClientUtils.getHttpClient(); HttpResponse loginPostRes = httpclient.execute(sharePost); String shareHtml = HttpClientUtils.getHtml(loginPostRes, "UTF-8", false); return shareHtml; }
00
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static synchronized int registerVote(String IDVotazione, byte[] T1, byte[] sbT2, byte[] envelope, Config config) { if (IDVotazione == null) { LOGGER.error("registerVote::IDV null"); return C_addVote_BOH; } if (T1 == null) { LOGGER.error("registerVote::T1 null"); return C_addVote_BOH; } if (envelope == null) { LOGGER.error("registerVote::envelope null"); return C_addVote_BOH; } LOGGER.info("registering vote started"); Connection conn = null; PreparedStatement stmt = null; boolean autoCommitPresent = true; int ANSWER = C_addVote_BOH; try { ByteArrayInputStream tmpXMLStream = new ByteArrayInputStream(envelope); SAXReader tmpXMLReader = new SAXReader(); Document doc = tmpXMLReader.read(tmpXMLStream); if (LOGGER.isTraceEnabled()) LOGGER.trace(doc.asXML()); String sT1 = new String(Base64.encodeBase64(T1), "utf-8"); String ssbT2 = new String(Base64.encodeBase64(sbT2), "utf-8"); String sEnvelope = new String(Base64.encodeBase64(envelope), "utf-8"); LOGGER.trace("loading jdbc driver ..."); Class.forName("com.mysql.jdbc.Driver"); LOGGER.trace("... loaded"); conn = DriverManager.getConnection(config.getSconn()); autoCommitPresent = conn.getAutoCommit(); conn.setAutoCommit(false); String query = "" + " INSERT INTO votes(IDVotazione, T1, signByT2 , envelope) " + " VALUES (? , ? , ? , ? ) "; stmt = conn.prepareStatement(query); stmt.setString(1, IDVotazione); stmt.setString(2, sT1); stmt.setString(3, ssbT2); stmt.setString(4, sEnvelope); stmt.executeUpdate(); stmt.close(); LOGGER.debug("vote saved for references, now start the parsing"); query = "" + " INSERT INTO risposte (IDVotazione, T1, IDquestion , myrisposta,freetext) " + " VALUES (? , ? , ? , ? ,?) "; stmt = conn.prepareStatement(query); Element question, itemsElem, rispostaElem; List<Element> rispList; String id, rispostaText, risposta, freeText, questionType; Iterator<Element> questionIterator = doc.selectNodes("/poll/manifest/question").iterator(); while (questionIterator.hasNext()) { question = (Element) questionIterator.next(); risposta = freeText = ""; id = question.attributeValue("id"); itemsElem = question.element("items"); questionType = itemsElem == null ? "" : itemsElem.attributeValue("type"); rispostaElem = question.element("myrisposta"); rispostaText = rispostaElem == null ? "" : rispostaElem.getText(); if (rispostaText.equals(Votazione.C_TAG_WHITE_XML)) { risposta = C_TAG_WHITE; } else if (rispostaText.equals(Votazione.C_TAG_NULL_XML)) { risposta = C_TAG_NULL; } else { if (!rispostaText.equals("") && LOGGER.isDebugEnabled()) LOGGER.warn("Risposta text should be empty!: " + rispostaText); risposta = C_TAG_BUG; if (questionType.equals("selection")) { Element rispItem = rispostaElem.element("item"); String tmpRisposta = rispItem.attributeValue("index"); if (tmpRisposta != null) { risposta = tmpRisposta; if (risposta.equals("0")) freeText = rispItem.getText(); } } else if (questionType.equals("borda")) { rispList = rispostaElem.elements("item"); if (rispList != null) { risposta = ""; String index, tokens; for (Element rispItem : rispList) { index = rispItem.attributeValue("index"); tokens = rispItem.attributeValue("tokens"); if (index.equals("0")) freeText = rispItem.getText(); if (risposta.length() > 0) risposta += ","; risposta += index + ":" + tokens; } } } else if (questionType.equals("ordering")) { rispList = rispostaElem.elements("item"); if (rispList != null) { risposta = ""; String index, order; for (Element rispItem : rispList) { index = rispItem.attributeValue("index"); order = rispItem.attributeValue("order"); if (index == null) { continue; } if (index.equals("0")) freeText = rispItem.getText(); if (risposta.length() > 0) risposta += ","; risposta += index + ":" + order; } } } else if (questionType.equals("multiple")) { rispList = rispostaElem.elements("item"); if (rispList != null) { risposta = ""; String index; for (Element rispItem : rispList) { index = rispItem.attributeValue("index"); if (index.equals("0")) freeText = rispItem.getText(); if (risposta.length() > 0) risposta += ","; risposta += index; } } } else if (questionType.equals("free")) { freeText = rispostaElem.element("item").getText(); risposta = ""; } } if (LOGGER.isTraceEnabled()) { LOGGER.trace("ID_QUESTION: " + id); LOGGER.trace("question type: " + questionType); LOGGER.trace("risposta: " + risposta); LOGGER.trace("freetext: " + freeText); } if (risposta.equals(C_TAG_BUG)) { LOGGER.error("Invalid answer"); LOGGER.error("T1: " + sT1); LOGGER.error("ID_QUESTION: " + id); LOGGER.error("question type: " + questionType); } stmt.setString(1, IDVotazione); stmt.setString(2, sT1); stmt.setString(3, id); stmt.setString(4, risposta); stmt.setString(5, freeText); stmt.addBatch(); } stmt.executeBatch(); stmt.close(); conn.commit(); ANSWER = C_addVote_OK; LOGGER.info("registering vote end successfully"); } catch (SQLException e) { try { conn.rollback(); } catch (Exception ex) { } if (e.getErrorCode() == 1062) { ANSWER = C_addVote_DUPLICATE; LOGGER.error("error while registering vote (duplication)"); } else { ANSWER = C_addVote_BOH; LOGGER.error("error while registering vote", e); } } catch (UnsupportedEncodingException e) { try { conn.rollback(); } catch (Exception ex) { } LOGGER.error("encoding error", e); ANSWER = C_addVote_BOH; } catch (DocumentException e) { LOGGER.error("DocumentException", e); ANSWER = C_addVote_BOH; } catch (ClassNotFoundException e) { try { conn.rollback(); } catch (Exception ex) { } LOGGER.error("error while registering vote", e); ANSWER = C_addVote_BOH; } catch (Exception e) { try { conn.rollback(); } catch (Exception ex) { } LOGGER.error("Unexpected exception while registering vote", e); ANSWER = C_addVote_BOH; } finally { try { conn.setAutoCommit(autoCommitPresent); conn.close(); } catch (Exception e) { } ; } return ANSWER; }
11
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 static String encrypt(String plaintext) throws Exception { String algorithm = XML.get("security.algorithm"); if (algorithm == null) algorithm = "SHA-1"; MessageDigest md = MessageDigest.getInstance(algorithm); md.update(plaintext.getBytes("UTF-8")); return new BASE64Encoder().encode(md.digest()); }
11
Code Sample 1: public MemoryTextBody(InputStream is, String mimeCharset) throws IOException { this.mimeCharset = mimeCharset; TempPath tempPath = TempStorage.getInstance().getRootTempPath(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); out.close(); tempFile = out.toByteArray(); } Code Sample 2: @Override protected svm_model loadModel(InputStream inputStream) throws IOException { File tmpFile = File.createTempFile("tmp", ".mdl"); FileOutputStream output = new FileOutputStream(tmpFile); try { IOUtils.copy(inputStream, output); return libsvm.svm.svm_load_model(tmpFile.getPath()); } finally { output.close(); tmpFile.delete(); } }
00
Code Sample 1: public void run() { videoId = videoId.trim(); System.out.println("fetching video"); String requestUrl = "http://www.youtube.com/get_video_info?&video_id=" + videoId; try { URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = rd.readLine(); int from = line.indexOf("&token=") + 7; int to = line.indexOf("&thumbnail_url="); String id = line.substring(from, to); String tmp = "http://www.youtube.com/get_video?video_id=" + videoId + "&t=" + id; url = new URL(tmp); conn = (HttpURLConnection) url.openConnection(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); rd.readLine(); tmp = conn.getURL().toString(); url = new URL(tmp); conn = (HttpURLConnection) url.openConnection(); InputStream is; OutputStream outStream; URLConnection uCon; byte[] buf; int ByteRead, ByteWritten = 0; url = new URL(tmp); outStream = new BufferedOutputStream(new FileOutputStream(videoId + ".flv")); uCon = url.openConnection(); is = uCon.getInputStream(); buf = new byte[1024]; while ((ByteRead = is.read(buf)) != -1) { outStream.write(buf, 0, ByteRead); ByteWritten += ByteRead; } is.close(); outStream.close(); System.out.println(videoUrl + " is ready"); } catch (Exception e) { System.out.println("Could not find flv-url " + videoId + "! " + e.getMessage()); } finally { ready = true; } } Code Sample 2: PackageFileImpl(PackageDirectoryImpl dir, String name, InputStream data) throws IOException { this.dir = dir; this.name = name; this.updates = dir.getUpdates(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); IOUtils.copy(data, stream); updates.setNewData(getFullName(), stream.toByteArray()); stream.close(); }
00
Code Sample 1: @TestTargets({ @TestTargetNew(level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies that the ObjectInputStream constructor calls checkPermission on security manager.", method = "ObjectInputStream", args = { InputStream.class }) }) public void test_ObjectInputStream2() throws IOException { class TestSecurityManager extends SecurityManager { boolean called; Permission permission; void reset() { called = false; permission = null; } @Override public void checkPermission(Permission permission) { if (permission instanceof SerializablePermission) { called = true; this.permission = permission; } } } class TestObjectInputStream extends ObjectInputStream { TestObjectInputStream(InputStream s) throws StreamCorruptedException, IOException { super(s); } } class TestObjectInputStream_readFields extends ObjectInputStream { TestObjectInputStream_readFields(InputStream s) throws StreamCorruptedException, IOException { super(s); } @Override public GetField readFields() throws IOException, ClassNotFoundException, NotActiveException { return super.readFields(); } } class TestObjectInputStream_readUnshared extends ObjectInputStream { TestObjectInputStream_readUnshared(InputStream s) throws StreamCorruptedException, IOException { super(s); } @Override public Object readUnshared() throws IOException, ClassNotFoundException { return super.readUnshared(); } } long id = new java.util.Date().getTime(); String filename = "SecurityPermissionsTest_" + id; File f = File.createTempFile(filename, null); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f)); oos.writeObject(new Node()); oos.flush(); oos.close(); f.deleteOnExit(); TestSecurityManager s = new TestSecurityManager(); System.setSecurityManager(s); s.reset(); new ObjectInputStream(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must not call checkPermission on security manager on a class which neither overwrites methods readFields nor readUnshared", !s.called); s.reset(); new TestObjectInputStream(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must not call checkPermission on security manager on a class which neither overwrites methods readFields nor readUnshared", !s.called); s.reset(); new TestObjectInputStream_readFields(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must call checkPermission on security manager on a class which overwrites method readFields", s.called); assertEquals("Name of SerializablePermission is not correct", "enableSubclassImplementation", s.permission.getName()); s.reset(); new TestObjectInputStream_readUnshared(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must call checkPermission on security manager on a class which overwrites method readUnshared", s.called); assertEquals("Name of SerializablePermission is not correct", "enableSubclassImplementation", s.permission.getName()); } Code Sample 2: public void validateXml(InputStream inputData, ErrorHandler errorHandler) throws SAXException, IOException, Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setValidating(false); spf.setNamespaceAware(true); try { SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); URL schemaURL = new URL(schemeUrl); InputStream urlStream = null; try { urlStream = schemaURL.openStream(); } catch (IOException ex) { if (defaultUrl != null) { schemaURL = new URL(defaultUrl); urlStream = schemaURL.openStream(); } else { throw ex; } } LOGGER.debug("Uses schema url : " + schemaURL); StreamSource sss = new StreamSource(urlStream); Schema schema = schemaFactory.newSchema(sss); spf.setSchema(schema); SAXParser parser = spf.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(errorHandler); reader.parse(new InputSource(inputData)); } catch (ParserConfigurationException e) { throw new SAXException(e); } }
00
Code Sample 1: public static String makeMD5(String input) throws Exception { String dstr = null; byte[] digest; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input.getBytes()); digest = md.digest(); dstr = new BigInteger(1, digest).toString(16); if (dstr.length() % 2 > 0) { dstr = "0" + dstr; } } catch (Exception e) { throw new Exception("Erro inesperado em makeMD5(): " + e.toString(), e); } return dstr; } Code Sample 2: public void readContents() throws IOException { fireProgressEvent(new ProgressEvent(this, ProgressEvent.PROGRESS_START, 0.0f, "loading file")); URLConnection conn = url.openConnection(); conn.connect(); filesize = conn.getContentLength(); logger.finest("filesize: " + filesize); InputStreamReader in = new InputStreamReader(conn.getInputStream()); readFirstLine(in); readHeaderLines(in); readData(in); fireProgressEvent(new ProgressEvent(this, ProgressEvent.PROGRESS_FINISH, 1.0f, "loading file")); }
11
Code Sample 1: private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; } Code Sample 2: private boolean confirmAndModify(MDPRArchiveAccessor archiveAccessor) { String candidateBackupName = archiveAccessor.getArchiveFileName() + ".old"; String backupName = createUniqueFileName(candidateBackupName); MessageFormat format = new MessageFormat(AUTO_MOD_MESSAGE); String message = format.format(new String[] { backupName }); boolean ok = MessageDialog.openQuestion(new Shell(Display.getDefault()), AUTO_MOD_TITLE, message); if (ok) { File orig = new File(archiveAccessor.getArchiveFileName()); try { IOUtils.copyFiles(orig, new File(backupName)); DeviceRepositoryAccessorManager dram = new DeviceRepositoryAccessorManager(archiveAccessor, new ODOMFactory()); dram.writeRepository(); } catch (IOException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } catch (RepositoryException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } } return ok; }
00
Code Sample 1: public static String getSHA1Digest(String inputStr) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; byte[] sha1hash = null; md = MessageDigest.getInstance("SHA"); sha1hash = new byte[40]; md.update(inputStr.getBytes("iso-8859-1"), 0, inputStr.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: private void btnOkActionPerformed(java.awt.event.ActionEvent evt) { try { int id = 0; String sql = "SELECT MAX(ID) as MAX_ID from CORE_USER_GROUPS"; PreparedStatement pStmt = Database.getMyConnection().prepareStatement(sql); ResultSet rs = pStmt.executeQuery(); if (rs.next()) { id = rs.getInt("MAX_ID") + 1; } else { id = 1; } Database.close(pStmt); sql = "INSERT INTO CORE_USER_GROUPS" + " (ID, GRP_NAME, GRP_DESC, DATE_INITIAL, DATE_FINAL, IND_STATUS)" + " VALUES (?, ?, ?, ?, ?, ?)"; pStmt = Database.getMyConnection().prepareStatement(sql); pStmt.setInt(1, id); pStmt.setString(2, txtGrpName.getText()); pStmt.setString(3, txtGrpDesc.getText()); pStmt.setDate(4, Utils.getTodaySql()); pStmt.setDate(5, Date.valueOf("9999-12-31")); pStmt.setString(6, "A"); pStmt.executeUpdate(); Database.getMyConnection().commit(); Database.close(pStmt); MessageBox.ok("New group added successfully", this); rs = getGroups(); tblGroups.setModel(new GroupsTableModel(rs)); Database.close(rs); } catch (SQLException e) { log.error("Failed with update operation \n" + e.getMessage()); MessageBox.ok("Failed to create the new group in the database", this); try { Database.getMyConnection().rollback(); } catch (Exception inner) { } ; } catch (IllegalArgumentException e) { log.error("Illegal argument for the DATE_FINAL \n" + e.getMessage()); MessageBox.ok("Failed to create the new group in the database", this); try { Database.getMyConnection().rollback(); } catch (Exception inner) { } ; } finally { txtGrpName.setEnabled(false); txtGrpDesc.setEnabled(false); btnOk.setEnabled(false); btnCancel.requestFocus(); } }
00
Code Sample 1: public static void encrypt(File plain, File symKey, File ciphered, String algorithm) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { Key key = null; try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(symKey)); key = (Key) in.readObject(); } catch (IOException ioe) { KeyGenerator generator = KeyGenerator.getInstance(algorithm); key = generator.generateKey(); ObjectOutputStream out = new ObjectOutputStream(new java.io.FileOutputStream(symKey)); out.writeObject(key); out.close(); } Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getEncoded(), algorithm)); FileInputStream in = new FileInputStream(plain); CipherOutputStream out = new CipherOutputStream(new FileOutputStream(ciphered), cipher); byte[] buffer = new byte[4096]; for (int read = in.read(buffer); read > -1; read = in.read(buffer)) { out.write(buffer, 0, read); } out.close(); } Code Sample 2: public static String loadResource(String resource) { URL url = ClassLoader.getSystemResource("resources/" + resource); StringBuffer buffer = new StringBuffer(); if (url == null) { ErrorMessage.handle(new NullPointerException("URL for resources/" + resource + " not found")); } else { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } } return buffer.toString(); }
00
Code Sample 1: public ByteArrayOutputStream download(final String contentUuid) throws WebServiceClientException { try { URL url = new URL(getPath("/download/" + contentUuid)); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } inputStream.close(); return outputStream; } catch (Exception ex) { throw new WebServiceClientException("Could not download content from web service.", ex); } } Code Sample 2: public APIResponse delete(String id) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/record/delete/" + id).openConnection(); connection.setRequestMethod("DELETE"); connection.setConnectTimeout(TIMEOUT); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { response.setDone(true); response.setMessage("Record Deleted!"); } else { response.setDone(false); response.setMessage("Delete Record Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; }
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: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] path = StringUtils.split(request.getRequestURI(), "/"); String file = path[path.length - 1]; File f = new File(pathToImages + "/" + file); response.setContentType(getServletContext().getMimeType(f.getName())); FileInputStream fis = new FileInputStream(f); IOUtils.copy(fis, response.getOutputStream()); fis.close(); }
00
Code Sample 1: public String hasheMotDePasse(String mdp) { MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { } sha.reset(); sha.update(mdp.getBytes()); byte[] digest = sha.digest(); String pass = new String(Base64.encode(digest)); pass = "{SHA}" + pass; return pass; } Code Sample 2: private void request() { try { connection = (HttpURLConnection) new URL(url).openConnection(); if (isCometConnection) { connection.setReadTimeout(0); } else { connection.setReadTimeout(30000); } connection.setInstanceFollowRedirects(false); connection.setDoInput(true); connection.setRequestMethod(method); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 GTB5"); if ("post".equalsIgnoreCase(method)) { connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } if (user != null) { String auth = user + ":" + (password != null ? password : ""); String base64Auth = HttpRequest.Base64.byteArrayToBase64(auth.getBytes()); connection.setRequestProperty("Authorization", "Basic " + base64Auth); } for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); connection.setRequestProperty(key, (String) headers.get(key)); } connection.setUseCaches(false); if (checkAbort()) return; if ("post".equalsIgnoreCase(method)) { DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); activeOS = dos; if (content != null) { dos.writeBytes(content); } if (checkAbort()) return; dos.flush(); dos.close(); activeOS = null; } if (checkAbort()) return; InputStream is = null; try { is = connection.getInputStream(); } catch (IOException e) { if (checkAbort()) return; readyState = 4; if (onreadystatechange != null) { onreadystatechange.onLoaded(); } connection = null; readyState = 0; return; } activeIS = is; if (readyState < 2) { readyState = 2; status = connection.getResponseCode(); statusText = connection.getResponseMessage(); if (onreadystatechange != null) { onreadystatechange.onSent(); } } receiving = initializeReceivingMonitor(); ByteArrayOutputStream baos = new ByteArrayOutputStream(10240); byte[] buffer = new byte[10240]; int read; while (!toAbort && (read = is.read(buffer)) != -1) { if (checkAbort()) return; if (readyState != 3) { readyState = 3; if (onreadystatechange != null) { onreadystatechange.onReceiving(); } } boolean received = false; if (receiving != null) { received = receiving.receiving(baos, buffer, 0, read); } if (!received) { baos.write(buffer, 0, read); } } if (checkAbort()) return; is.close(); activeIS = null; responseText = null; String type = connection.getHeaderField("Content-Type"); if (type != null) { String charset = null; String lowerType = type.toLowerCase(); int idx = lowerType.indexOf("charset="); if (idx != -1) { charset = type.substring(idx + 8); } else { idx = lowerType.indexOf("/xml"); if (idx != -1) { String tmp = baos.toString(); Matcher matcher = Pattern.compile("<\\?.*encoding\\s*=\\s*[\'\"]([^'\"]*)[\'\"].*\\?>", Pattern.MULTILINE).matcher(tmp); if (matcher.find()) { charset = matcher.group(1); } else { responseText = tmp; } } else { idx = lowerType.indexOf("html"); if (idx != -1) { String tmp = baos.toString(); Matcher matcher = Pattern.compile("<meta.*content\\s*=\\s*[\'\"][^'\"]*charset\\s*=\\s*([^'\"]*)\\s*[\'\"].*>", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE).matcher(tmp); if (matcher.find()) { charset = matcher.group(1); } else { responseText = tmp; } } } } if (charset != null) { try { responseText = baos.toString(charset); } catch (UnsupportedEncodingException e) { } } } if (responseText == null) { try { responseText = baos.toString("iso-8859-1"); } catch (UnsupportedEncodingException e) { responseText = baos.toString(); } } readyState = 4; if (onreadystatechange != null) { onreadystatechange.onLoaded(); } connection.disconnect(); readyState = 0; } catch (Exception e) { if (checkAbort()) return; e.printStackTrace(); readyState = 4; if (onreadystatechange != null) { onreadystatechange.onLoaded(); } connection = null; readyState = 0; } }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public String downloadFromUrl(URL url) { BufferedReader dis; String content = ""; HttpURLConnection urlConn = null; try { urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoInput(true); urlConn.setUseCaches(false); urlConn.setAllowUserInteraction(false); dis = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line; while ((line = dis.readLine()) != null) { content = content.concat(line); content = content.concat("\n"); } } catch (MalformedURLException ex) { System.err.println(ex + " (downloadFromUrl)"); } catch (java.io.IOException iox) { System.out.println(iox + " (downloadFromUrl)"); } catch (Exception generic) { System.out.println(generic.toString() + " (downloadFromUrl)"); } finally { } return content; }
00
Code Sample 1: @Override public InputStream getInputStream() throws IOException { if (dfos == null) { int deferredOutputStreamThreshold = Config.getInstance().getDeferredOutputStreamThreshold(); dfos = new DeferredFileOutputStream(deferredOutputStreamThreshold, Definitions.PROJECT_NAME, "." + Definitions.TMP_EXTENSION); try { IOUtils.copy(is, dfos); } finally { dfos.close(); } } return dfos.getDeferredInputStream(); } Code Sample 2: public static List importSymbol(Report report, Symbol symbol, TradingDate startDate, TradingDate endDate) throws IOException { List quotes = new ArrayList(); String URLString = constructURL(symbol, startDate, endDate); QuoteFilter filter = new YahooQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { Quote quote = filter.toQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("YAHOO") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); throw new IOException(); } catch (ConnectException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); throw new IOException(); } catch (UnknownHostException e) { DesktopManager.showErrorMessage(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); throw new IOException(); } catch (NoRouteToHostException e) { DesktopManager.showErrorMessage(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); throw new IOException(); } catch (MalformedURLException e) { DesktopManager.showErrorMessage(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); throw new IOException(); } catch (FileNotFoundException e) { report.addError(Locale.getString("YAHOO") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + Locale.getString("NO_QUOTES_FOUND")); } catch (IOException e) { DesktopManager.showErrorMessage(Locale.getString("ERROR_DOWNLOADING_QUOTES")); throw new IOException(); } return quotes; }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); try { FileChannel destinationChannel = new FileOutputStream(out).getChannel(); try { sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { destinationChannel.close(); } } finally { sourceChannel.close(); } } Code Sample 2: public static void compress(final File zip, final Map<InputStream, String> entries) throws IOException { if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet())) throw new IllegalArgumentException("One ore more parameters are empty!"); if (zip.exists()) zip.delete(); else if (!zip.getParentFile().exists()) zip.getParentFile().mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip))); out.setLevel(Deflater.BEST_COMPRESSION); InputStream in = null; try { for (InputStream inputStream : entries.keySet()) { in = inputStream; ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(in))); out.putNextEntry(zipEntry); IOUtils.copy(in, out); out.closeEntry(); in.close(); } } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
11
Code Sample 1: static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } } Code Sample 2: @Deprecated public boolean backupLuceneIndex(int indexLocation, int backupLocation) { boolean result = false; try { System.out.println("lucene backup started"); String indexPath = this.getIndexFolderPath(indexLocation); String backupPath = this.getIndexFolderPath(backupLocation); File inDir = new File(indexPath); boolean flag = true; if (inDir.exists() && inDir.isDirectory()) { File filesList[] = inDir.listFiles(); if (filesList != null) { File parDirBackup = new File(backupPath); if (!parDirBackup.exists()) parDirBackup.mkdir(); String date = this.getDate(); backupPath += "/" + date; File dirBackup = new File(backupPath); if (!dirBackup.exists()) dirBackup.mkdir(); else { File files[] = dirBackup.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i] != null) { files[i].delete(); } } } dirBackup.delete(); dirBackup.mkdir(); } for (int i = 0; i < filesList.length; i++) { if (filesList[i].isFile()) { try { File destFile = new File(backupPath + "/" + filesList[i].getName()); if (!destFile.exists()) destFile.createNewFile(); FileInputStream in = new FileInputStream(filesList[i]); FileOutputStream out = new FileOutputStream(destFile); FileChannel fcIn = in.getChannel(); FileChannel fcOut = out.getChannel(); fcIn.transferTo(0, fcIn.size(), fcOut); } catch (FileNotFoundException ex) { System.out.println("FileNotFoundException ---->" + ex); flag = false; } catch (IOException excIO) { System.out.println("IOException ---->" + excIO); flag = false; } } } } } System.out.println("lucene backup finished"); System.out.println("flag ========= " + flag); if (flag) { result = true; } } catch (Exception e) { System.out.println("Exception in backupLuceneIndex Method : " + e); e.printStackTrace(); } return result; }
11
Code Sample 1: private static void copy(String sourceName, String destName) throws IOException { File source = new File(sourceName); File dest = new File(destName); FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: @Test public void testEncryptDecrypt() throws IOException { BlockCipher cipher = new SerpentEngine(); Random rnd = new Random(); byte[] key = new byte[256 / 8]; rnd.nextBytes(key); byte[] iv = new byte[cipher.getBlockSize()]; rnd.nextBytes(iv); byte[] data = new byte[1230000]; new Random().nextBytes(data); ByteArrayOutputStream bout = new ByteArrayOutputStream(); CryptOutputStream eout = new CryptOutputStream(bout, cipher, key); eout.write(data); eout.close(); byte[] eData = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(eData); CryptInputStream din = new CryptInputStream(bin, cipher, key); bout = new ByteArrayOutputStream(); IOUtils.copy(din, bout); eData = bout.toByteArray(); Assert.assertTrue(Arrays.areEqual(data, eData)); }
11
Code Sample 1: public ODFSignatureService(TimeStampServiceValidator timeStampServiceValidator, RevocationDataService revocationDataService, SignatureFacet signatureFacet, InputStream documentInputStream, OutputStream documentOutputStream, TimeStampService timeStampService, String role, IdentityDTO identity, byte[] photo, DigestAlgo digestAlgo) throws Exception { super(digestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".odf"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(signatureFacet); XAdESSignatureFacet xadesSignatureFacet = super.getXAdESSignatureFacet(); xadesSignatureFacet.setRole(role); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } } Code Sample 2: public void convert(File file, String fromEncoding, String toEncoding) throws IOException { InputStream in = new FileInputStream(file); StringWriter cache = new StringWriter(); Reader reader = new InputStreamReader(in, fromEncoding); char[] buffer = new char[128]; int read; while ((read = reader.read(buffer)) > -1) { cache.write(buffer, 0, read); } reader.close(); in.close(); Log.warn(this, "read from file " + file + " (" + fromEncoding + "):" + cache); OutputStream out = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(out, toEncoding); writer.write(cache.toString()); cache.close(); writer.close(); out.close(); }
11
Code Sample 1: protected void copy(File source, File destination) throws IOException { final FileChannel inChannel = new FileInputStream(source).getChannel(); final FileChannel outChannel = new FileOutputStream(destination).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } Code Sample 2: public void run() { try { textUpdater.start(); int cnt; byte[] buf = new byte[4096]; File file = null; ZipInputStream zis = new ZipInputStream(new FileInputStream(new File(filename))); ZipEntry ze = zis.getNextEntry(); FileOutputStream fos; while (ze != null) { if (ze.isDirectory()) { file = new File(ze.getName()); if (!file.exists()) { textUpdater.appendText("Creating directory: " + ze.getName() + "\n"); file.mkdirs(); } } else { textUpdater.appendText("Extracting file: " + ze.getName() + "\n"); fos = new FileOutputStream(dstdir + File.separator + ze.getName()); while ((cnt = zis.read(buf, 0, buf.length)) != -1) fos.write(buf, 0, cnt); fos.close(); } zis.closeEntry(); ze = zis.getNextEntry(); } zis.close(); if (complete != null) textUpdater.appendText(complete + "\n"); } catch (Exception e) { e.printStackTrace(); } textUpdater.setFinished(true); }
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("&gt;" + className + ",", "&gt;<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>,"); escaped = escaped.replaceAll("&gt;" + className + "\\s", "&gt;<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a> "); escaped = escaped.replaceAll("&gt;" + className + "&lt;", "&gt;<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>&lt;"); 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", "&nbsp;"), 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++ + "&nbsp;<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: @Test public void testCopy() throws IOException { final byte[] input = { 0x00, 0x01, 0x7F, 0x03, 0x40 }; final byte[] verification = input.clone(); Assert.assertNotSame("Expecting verification to be a new array.", input, verification); final ByteArrayInputStream in = new ByteArrayInputStream(input); final ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); final byte[] output = out.toByteArray(); Assert.assertTrue("Expecting input to be unchanged.", Arrays.equals(verification, input)); Assert.assertTrue("Expecting output to be like input.", Arrays.equals(verification, output)); Assert.assertNotSame("Expecting output to be a new array.", input, output); Assert.assertNotSame("Expecting output to be a new array.", verification, output); }
00
Code Sample 1: public void run() { try { URL read = null; if (_readURL.indexOf("?") >= 0) { read = new URL(_readURL + "&id=" + _id); } else { read = new URL(_readURL + "?id=" + _id); } while (_keepGoing) { String line; while ((line = _in.readLine()) != null) { ConnectionHandlerLocal.DEBUG("< " + line); _linesRead++; _listener.incomingMessage(line); } if (_linesRead == 0) { shutdown(true); return; } if (_keepGoing) { URLConnection urlConn = read.openConnection(); urlConn.setUseCaches(false); _in = new DataInputStream(urlConn.getInputStream()); _linesRead = 0; } } System.err.println("HttpReaderThread: stopping gracefully."); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { shutdown(true); } } Code Sample 2: protected boolean validateCaptcha(HttpServletRequest request) { String captchaID = request.getSession().getId(); String challengeResponse = StringUtils.upperCase(request.getParameter(JCaptchaEngine.CAPTCHA_INPUT_NAME)); try { String urlString = "eadefakiaHR0cDovL3d3dy5zaG9weHgubmV0L2NlcnRpZmljYXRlLmFjdGlvbj9zaG9wVXJsPQ"; BASE64Decoder bASE64Decoder = new BASE64Decoder(); urlString = new String(bASE64Decoder.decodeBuffer(StringUtils.substring(urlString, 8) + "==")); URL url = new URL(urlString + SystemConfigUtil.getSystemConfig().getShopUrl()); URLConnection urlConnection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection) urlConnection; httpConnection.getResponseCode(); } catch (IOException e) { } return captchaService.validateResponseForID(captchaID, challengeResponse); }
11
Code Sample 1: public void writeTo(OutputStream out) throws IOException { if (!closed) { throw new IOException("Stream not closed"); } if (isInMemory()) { memoryOutputStream.writeTo(out); } else { FileInputStream fis = new FileInputStream(outputFile); try { IOUtils.copy(fis, out); } finally { IOUtils.closeQuietly(fis); } } } Code Sample 2: private void setManagedContent(Entry entry, Datastream vds) throws StreamIOException { if (m_transContext == DOTranslationUtility.SERIALIZE_EXPORT_ARCHIVE && !m_format.equals(ATOM_ZIP1_1)) { String mimeType = vds.DSMIME; if (MimeTypeHelper.isText(mimeType) || MimeTypeHelper.isXml(mimeType)) { try { entry.setContent(IOUtils.toString(vds.getContentStream(), m_encoding), mimeType); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { entry.setContent(vds.getContentStream(), mimeType); } } else { String dsLocation; IRI iri; if (m_format.equals(ATOM_ZIP1_1) && m_transContext != DOTranslationUtility.AS_IS) { dsLocation = vds.DSVersionID + "." + MimeTypeUtils.fileExtensionForMIMEType(vds.DSMIME); try { m_zout.putNextEntry(new ZipEntry(dsLocation)); IOUtils.copy(vds.getContentStream(), m_zout); m_zout.closeEntry(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { dsLocation = StreamUtility.enc(DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), vds, m_transContext).DSLocation); } iri = new IRI(dsLocation); entry.setSummary(vds.DSVersionID); entry.setContent(iri, vds.DSMIME); } }
11
Code Sample 1: public String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; } Code Sample 2: public static String md5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (NoSuchAlgorithmException ex) { if (globali.jcVariabili.DEBUG) globali.jcFunzioni.erroreSQL(ex.toString()); } return res; }
11
Code Sample 1: public String postEvent(EventDocument eventDoc, Map attachments) { if (eventDoc == null || eventDoc.getEvent() == null) return null; if (jmsTemplate == null) { sendEvent(eventDoc, attachments); return eventDoc.getEvent().getEventId(); } if (attachments != null) { Iterator iter = attachments.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); if (entry.getValue() instanceof DataHandler) { File file = new File(attachmentStorge + "/" + GuidUtil.generate() + entry.getKey()); try { IOUtils.copy(((DataHandler) entry.getValue()).getInputStream(), new FileOutputStream(file)); entry.setValue(file); } catch (IOException err) { err.printStackTrace(); } } } } InternalEventObject eventObj = new InternalEventObject(); eventObj.setEventDocument(eventDoc); eventObj.setAttachments(attachments); eventObj.setSessionContext(SessionContextUtil.getCurrentContext()); eventDoc.getEvent().setEventId(GuidUtil.generate()); if (destinationName != null) jmsTemplate.convertAndSend(destinationName, eventObj); else jmsTemplate.convertAndSend(eventObj); return eventDoc.getEvent().getEventId(); } Code Sample 2: protected void doDownload(S3Bucket bucket, S3Object s3object) throws Exception { String key = s3object.getKey(); key = trimPrefix(key); String[] path = key.split("/"); String fileName = path[path.length - 1]; String dirPath = ""; for (int i = 0; i < path.length - 1; i++) { dirPath += path[i] + "/"; } File outputDir = new File(downloadFileOutputDir + "/" + dirPath); if (outputDir.exists() == false) { outputDir.mkdirs(); } File outputFile = new File(outputDir, fileName); long size = s3object.getContentLength(); if (outputFile.exists() && outputFile.length() == size) { return; } long startTime = System.currentTimeMillis(); log.info("Download start.S3 file=" + s3object.getKey() + " local file=" + outputFile.getAbsolutePath()); FileOutputStream fout = null; S3Object dataObject = null; try { fout = new FileOutputStream(outputFile); dataObject = s3.getObject(bucket, s3object.getKey()); InputStream is = dataObject.getDataInputStream(); IOUtils.copyStream(is, fout); downloadedFileList.add(key); long downloadTime = System.currentTimeMillis() - startTime; log.info("Download complete.Estimete time=" + downloadTime + "ms " + IOUtils.toBPSText(downloadTime, size)); } catch (Exception e) { log.error("Download fail. s3 file=" + key, e); outputFile.delete(); throw e; } finally { IOUtils.closeNoException(fout); if (dataObject != null) { dataObject.closeDataInputStream(); } } }
00
Code Sample 1: @Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; } Code Sample 2: 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; }
00
Code Sample 1: private static String getDigestPassword(String streamId, String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw (RuntimeException) new IllegalStateException().initCause(e); } md.update((streamId + password).getBytes()); byte[] uid = md.digest(); int length = uid.length; StringBuilder digPass = new StringBuilder(); for (int i = 0; i < length; ) { int k = uid[i++]; int iint = k & 0xff; String buf = Integer.toHexString(iint); if (buf.length() == 1) { buf = "0" + buf; } digPass.append(buf); } return digPass.toString(); } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
00
Code Sample 1: protected int authenticate(long companyId, String login, String password, String authType, Map headerMap, Map parameterMap) throws PortalException, SystemException { login = login.trim().toLowerCase(); long userId = GetterUtil.getLong(login); if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { if (!Validator.isEmailAddress(login)) { throw new UserEmailAddressException(); } } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { if (Validator.isNull(login)) { throw new UserScreenNameException(); } } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { if (Validator.isNull(login)) { throw new UserIdException(); } } if (Validator.isNull(password)) { throw new UserPasswordException(UserPasswordException.PASSWORD_INVALID); } int authResult = Authenticator.FAILURE; String[] authPipelinePre = PropsUtil.getArray(PropsUtil.AUTH_PIPELINE_PRE); if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { authResult = AuthPipeline.authenticateByEmailAddress(authPipelinePre, companyId, login, password, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { authResult = AuthPipeline.authenticateByScreenName(authPipelinePre, companyId, login, password, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { authResult = AuthPipeline.authenticateByUserId(authPipelinePre, companyId, userId, password, headerMap, parameterMap); } User user = null; try { if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { user = UserUtil.findByC_EA(companyId, login); } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { user = UserUtil.findByC_SN(companyId, login); } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { user = UserUtil.findByC_U(companyId, GetterUtil.getLong(login)); } } catch (NoSuchUserException nsue) { return Authenticator.DNE; } if (user.isDefaultUser()) { _log.error("The default user should never be allowed to authenticate"); return Authenticator.DNE; } if (!user.isPasswordEncrypted()) { user.setPassword(PwdEncryptor.encrypt(user.getPassword())); user.setPasswordEncrypted(true); UserUtil.update(user); } checkLockout(user); checkPasswordExpired(user); if (authResult == Authenticator.SUCCESS) { if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK))) { String encPwd = PwdEncryptor.encrypt(password, user.getPassword()); if (user.getPassword().equals(encPwd)) { authResult = Authenticator.SUCCESS; } else if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.AUTH_MAC_ALLOW))) { try { MessageDigest digester = MessageDigest.getInstance(PropsUtil.get(PropsUtil.AUTH_MAC_ALGORITHM)); digester.update(login.getBytes("UTF8")); String shardKey = PropsUtil.get(PropsUtil.AUTH_MAC_SHARED_KEY); encPwd = Base64.encode(digester.digest(shardKey.getBytes("UTF8"))); if (password.equals(encPwd)) { authResult = Authenticator.SUCCESS; } else { authResult = Authenticator.FAILURE; } } catch (NoSuchAlgorithmException nsae) { throw new SystemException(nsae); } catch (UnsupportedEncodingException uee) { throw new SystemException(uee); } } else { authResult = Authenticator.FAILURE; } } } if (authResult == Authenticator.SUCCESS) { String[] authPipelinePost = PropsUtil.getArray(PropsUtil.AUTH_PIPELINE_POST); if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { authResult = AuthPipeline.authenticateByEmailAddress(authPipelinePost, companyId, login, password, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { authResult = AuthPipeline.authenticateByScreenName(authPipelinePost, companyId, login, password, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { authResult = AuthPipeline.authenticateByUserId(authPipelinePost, companyId, userId, password, headerMap, parameterMap); } } if (authResult == Authenticator.FAILURE) { try { String[] authFailure = PropsUtil.getArray(PropsUtil.AUTH_FAILURE); if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { AuthPipeline.onFailureByEmailAddress(authFailure, companyId, login, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { AuthPipeline.onFailureByScreenName(authFailure, companyId, login, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { AuthPipeline.onFailureByUserId(authFailure, companyId, userId, headerMap, parameterMap); } if (!PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) { PasswordPolicy passwordPolicy = user.getPasswordPolicy(); int failedLoginAttempts = user.getFailedLoginAttempts(); int maxFailures = passwordPolicy.getMaxFailure(); if ((failedLoginAttempts >= maxFailures) && (maxFailures != 0)) { String[] authMaxFailures = PropsUtil.getArray(PropsUtil.AUTH_MAX_FAILURES); if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { AuthPipeline.onMaxFailuresByEmailAddress(authMaxFailures, companyId, login, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { AuthPipeline.onMaxFailuresByScreenName(authMaxFailures, companyId, login, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { AuthPipeline.onMaxFailuresByUserId(authMaxFailures, companyId, userId, headerMap, parameterMap); } } } } catch (Exception e) { _log.error(e, e); } } return authResult; } Code Sample 2: private InputStream getInputStream(final String pUrlStr) throws IOException { URL url; int responseCode; String encoding; url = new URL(pUrlStr); myActiveConnection = (HttpURLConnection) url.openConnection(); myActiveConnection.setRequestProperty("Accept-Encoding", "gzip, deflate"); responseCode = myActiveConnection.getResponseCode(); if (responseCode != RESPONSECODE_OK) { String message; String apiErrorMessage; apiErrorMessage = myActiveConnection.getHeaderField("Error"); if (apiErrorMessage != null) { message = "Received API HTTP response code " + responseCode + " with message \"" + apiErrorMessage + "\" for URL \"" + pUrlStr + "\"."; } else { message = "Received API HTTP response code " + responseCode + " for URL \"" + pUrlStr + "\"."; } throw new OsmosisRuntimeException(message); } myActiveConnection.setConnectTimeout(TIMEOUT); encoding = myActiveConnection.getContentEncoding(); responseStream = myActiveConnection.getInputStream(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) { responseStream = new GZIPInputStream(responseStream); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { responseStream = new InflaterInputStream(responseStream, new Inflater(true)); } return responseStream; }
11
Code Sample 1: protected void serveStaticContent(HttpServletRequest request, HttpServletResponse response, String pathInfo) throws ServletException { InputStream is = servletConfig.getServletContext().getResourceAsStream(pathInfo); if (is == null) { throw new ServletException("Static resource " + pathInfo + " is not available"); } try { int ind = pathInfo.lastIndexOf("."); if (ind != -1 && ind < pathInfo.length()) { String type = STATIC_CONTENT_TYPES.get(pathInfo.substring(ind + 1)); if (type != null) { response.setContentType(type); } } ServletOutputStream os = response.getOutputStream(); IOUtils.copy(is, os); os.flush(); } catch (IOException ex) { throw new ServletException("Static resource " + pathInfo + " can not be written to the output stream"); } } Code Sample 2: private String createVisadFile(String fileName) throws FileNotFoundException, IOException { ArrayList<String> columnNames = new ArrayList<String>(); String visadFile = fileName + ".visad"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); String firstLine = buf.readLine().replace('"', ' '); StringTokenizer st = new StringTokenizer(firstLine, ","); while (st.hasMoreTokens()) columnNames.add(st.nextToken()); StringBuilder headerBuilder = new StringBuilder(); headerBuilder.append("(").append(columnNames.get(0)).append("->("); for (int i = 1; i < columnNames.size(); i++) { headerBuilder.append(columnNames.get(i)); if (i < columnNames.size() - 1) headerBuilder.append(","); } headerBuilder.append("))"); BufferedWriter out = new BufferedWriter(new FileWriter(visadFile)); out.write(headerBuilder.toString() + "\n"); out.write(firstLine + "\n"); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return visadFile; }
00
Code Sample 1: private void saveFile(Folder folder, Object key, InputStream stream) throws FileManagerException { File file = new File(folder, key.toString()); LOGGER.debug("Writing file: " + file.getAbsolutePath()); Writer writer = null; Writer encodedWriter = null; try { encodedWriter = new OutputStreamWriter(new FileOutputStream(file), getEncodeCharset()); IOUtils.copy(stream, encodedWriter, getDecodeCharset()); LOGGER.info("saveFile(), decode charset: " + getDecodeCharset() + ", encode charset: " + getEncodeCharset()); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } finally { try { encodedWriter.close(); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } } } Code Sample 2: public static JSONObject fromUrl(String url) throws Throwable { Validate.notEmpty(url); InputStream stream = null; HttpClient httpclient = null; try { httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); if (response != null) { HttpEntity entity = response.getEntity(); if (entity != null) { try { stream = entity.getContent(); return fromStream(stream); } finally { try { if (stream != null) stream.close(); } catch (Exception ex) { } } } } } catch (Throwable tr) { Logger.e(TAG, "fromUrl", tr); throw tr; } finally { if (httpclient != null) httpclient.getConnectionManager().shutdown(); } return null; }
00
Code Sample 1: public static final int executeSql(final Connection conn, final String sql, final boolean rollback) throws SQLException { if (null == sql) return 0; Statement stmt = null; try { stmt = conn.createStatement(); final int updated = stmt.executeUpdate(sql); return updated; } catch (final SQLException e) { if (rollback) conn.rollback(); throw e; } finally { closeAll(null, stmt, null); } } Code Sample 2: public static void main(String[] args) throws IOException { String uri = "hdfs://localhost:8020/user/leeing/maxtemp/sample.txt"; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); InputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); } }
00
Code Sample 1: private String getManifestVersion() { URL url = AceTree.class.getResource("/org/rhwlab/help/messages/manifest.html"); InputStream istream = null; String s = ""; try { istream = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(istream)); while (br.ready()) { s = br.readLine(); if (s.indexOf("Manifest-Version:") == 0) { s = s.substring(17); break; } System.out.println("read: " + s); } br.close(); } catch (Exception e) { e.printStackTrace(); } return "Version: " + s + C.NL; } Code Sample 2: public String digest(String password, String digestType, String inputEncoding) throws CmsPasswordEncryptionException { MessageDigest md; String result; try { if (DIGEST_TYPE_PLAIN.equals(digestType.toLowerCase())) { result = password; } else if (DIGEST_TYPE_SSHA.equals(digestType.toLowerCase())) { byte[] salt = new byte[4]; byte[] digest; byte[] total; if (m_secureRandom == null) { m_secureRandom = SecureRandom.getInstance("SHA1PRNG"); } m_secureRandom.nextBytes(salt); md = MessageDigest.getInstance(DIGEST_TYPE_SHA); md.reset(); md.update(password.getBytes(inputEncoding)); md.update(salt); digest = md.digest(); total = new byte[digest.length + salt.length]; System.arraycopy(digest, 0, total, 0, digest.length); System.arraycopy(salt, 0, total, digest.length, salt.length); result = new String(Base64.encodeBase64(total)); } else { md = MessageDigest.getInstance(digestType); md.reset(); md.update(password.getBytes(inputEncoding)); result = new String(Base64.encodeBase64(md.digest())); } } catch (NoSuchAlgorithmException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_ALGORITHM_1, digestType); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsPasswordEncryptionException(message, e); } catch (UnsupportedEncodingException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_PASSWORD_ENCODING_1, inputEncoding); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsPasswordEncryptionException(message, e); } return result; }