label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: private void writeFile(File file, String fileName) { try { FileInputStream fin = new FileInputStream(file); FileOutputStream fout = new FileOutputStream(dirTableModel.getDirectory().getAbsolutePath() + File.separator + fileName); int val; while ((val = fin.read()) != -1) fout.write(val); fin.close(); fout.close(); dirTableModel.reset(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { message = ("���Ƶ����ļ���������"); } }
11
Code Sample 1: public static void putNextJarEntry(JarOutputStream modelStream, String name, File file) throws IOException { JarEntry entry = new JarEntry(name); entry.setSize(file.length()); modelStream.putNextEntry(entry); InputStream fileStream = new BufferedInputStream(new FileInputStream(file)); IOUtils.copy(fileStream, modelStream); fileStream.close(); } Code Sample 2: public boolean chequearMarca(int a, int m, int d) { boolean existe = false; try { cantidadArchivos = obtenerCantidad() + 1; String filenametxt = ""; String filenamezip = ""; int dia = 0; int mes = 0; int ano = 0; for (int i = 1; i < cantidadArchivos; i++) { filenamezip = "recordatorio" + i + ".zip"; filenametxt = "recordatorio" + i + ".txt"; BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(filenamezip); Enumeration e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[buffer]; FileOutputStream fos = new FileOutputStream(entry.getName()); dest = new BufferedOutputStream(fos, buffer); while ((count = is.read(data, 0, buffer)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); is.close(); } DataInputStream input = new DataInputStream(new FileInputStream(filenametxt)); dia = Integer.parseInt(input.readLine()); mes = Integer.parseInt(input.readLine()); ano = Integer.parseInt(input.readLine()); if (ano == a && mes == m && dia == d) existe = true; input.close(); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } return (existe); }
00
Code Sample 1: private String hashPassword(String password) { if (password != null && password.trim().length() > 0) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.trim().getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } } return null; } Code Sample 2: public osid.shared.Id ingest(String fileName, String templateFileName, String fileType, File file, Properties properties) throws osid.dr.DigitalRepositoryException, java.net.SocketException, java.io.IOException, osid.shared.SharedException, javax.xml.rpc.ServiceException { long sTime = System.currentTimeMillis(); if (DEBUG) System.out.println("INGESTING FILE TO FEDORA:fileName =" + fileName + "fileType =" + fileType + "t = 0"); String host = FedoraUtils.getFedoraProperty(this, "admin.ftp.address"); String url = FedoraUtils.getFedoraProperty(this, "admin.ftp.url"); int port = Integer.parseInt(FedoraUtils.getFedoraProperty(this, "admin.ftp.port")); String userName = FedoraUtils.getFedoraProperty(this, "admin.ftp.username"); String password = FedoraUtils.getFedoraProperty(this, "admin.ftp.password"); String directory = FedoraUtils.getFedoraProperty(this, "admin.ftp.directory"); FTPClient client = new FTPClient(); client.connect(host, port); client.login(userName, password); client.changeWorkingDirectory(directory); client.setFileType(FTP.BINARY_FILE_TYPE); client.storeFile(fileName, new FileInputStream(file.getAbsolutePath().replaceAll("%20", " "))); client.logout(); client.disconnect(); if (DEBUG) System.out.println("INGESTING FILE TO FEDORA: Writting to FTP Server:" + (System.currentTimeMillis() - sTime)); fileName = url + fileName; int BUFFER_SIZE = 10240; StringBuffer sb = new StringBuffer(); String s = new String(); BufferedInputStream fis = new BufferedInputStream(new FileInputStream(new File(getResource(templateFileName).getFile().replaceAll("%20", " ")))); byte[] buf = new byte[BUFFER_SIZE]; int ch; int len; while ((len = fis.read(buf)) > 0) { s = s + new String(buf); } fis.close(); if (DEBUG) System.out.println("INGESTING FILE TO FEDORA: Read Mets File:" + (System.currentTimeMillis() - sTime)); String r = updateMetadata(s, fileName, file.getName(), fileType, properties); if (DEBUG) System.out.println("INGESTING FILE TO FEDORA: Resplaced Metadata:" + (System.currentTimeMillis() - sTime)); File METSfile = File.createTempFile("vueMETSMap", ".xml"); FileOutputStream fos = new FileOutputStream(METSfile); fos.write(r.getBytes()); fos.close(); if (DEBUG) System.out.println("INGESTING FILE TO FEDORA: Ingest complete:" + (System.currentTimeMillis() - sTime)); String pid = "Method Not Supported any more"; System.out.println(" METSfile= " + METSfile.getPath() + " PID = " + pid); return new PID(pid); }
11
Code Sample 1: public boolean copyTo(String targetFilePath) { try { FileInputStream srcFile = new FileInputStream(filePath); FileOutputStream target = new FileOutputStream(targetFilePath); byte[] buff = new byte[1024]; int readed = -1; while ((readed = srcFile.read(buff)) > 0) target.write(buff, 0, readed); srcFile.close(); target.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } Code Sample 2: public static void unzip(final File file, final ZipFile zipFile, final File targetDirectory) throws PtException { LOG.info("Unzipping zip file '" + file.getAbsolutePath() + "' to directory " + "'" + targetDirectory.getAbsolutePath() + "'."); assert (file.exists() && file.isFile()); if (targetDirectory.exists() == false) { LOG.debug("Creating target directory."); if (targetDirectory.mkdirs() == false) { throw new PtException("Could not create target directory at " + "'" + targetDirectory.getAbsolutePath() + "'!"); } } ZipInputStream zipin = null; try { zipin = new ZipInputStream(new FileInputStream(file)); ZipEntry nextZipEntry = zipin.getNextEntry(); while (nextZipEntry != null) { LOG.debug("Unzipping entry '" + nextZipEntry.getName() + "'."); if (nextZipEntry.isDirectory()) { LOG.debug("Skipping directory."); continue; } final File targetFile = new File(targetDirectory, nextZipEntry.getName()); final File parentTargetFile = targetFile.getParentFile(); if (parentTargetFile.exists() == false) { LOG.debug("Creating directory '" + parentTargetFile.getAbsolutePath() + "'."); if (parentTargetFile.mkdirs() == false) { throw new PtException("Could not create target directory at " + "'" + parentTargetFile.getAbsolutePath() + "'!"); } } InputStream input = null; FileOutputStream output = null; try { input = zipFile.getInputStream(nextZipEntry); if (targetFile.createNewFile() == false) { throw new PtException("Could not create target file " + "'" + targetFile.getAbsolutePath() + "'!"); } output = new FileOutputStream(targetFile); byte[] buffer = new byte[BUFFER_SIZE]; int readBytes = input.read(buffer, 0, buffer.length); while (readBytes > 0) { output.write(buffer, 0, readBytes); readBytes = input.read(buffer, 0, buffer.length); } } finally { PtCloseUtil.close(input, output); } nextZipEntry = zipin.getNextEntry(); } } catch (IOException e) { throw new PtException("Could not unzip file '" + file.getAbsolutePath() + "'!", e); } finally { PtCloseUtil.close(zipin); } }
11
Code Sample 1: private void processData(InputStream raw) { String fileName = remoteName; if (localName != null) { fileName = localName; } try { FileOutputStream fos = new FileOutputStream(new File(fileName), true); IOUtils.copy(raw, fos); LOG.info("ok"); } catch (IOException e) { LOG.error("error writing file", e); } } Code Sample 2: public static void toZip(File zippedFile, File[] filesToZip, String zipComment, boolean savePath, int compressionLevel) throws IOException, FileNotFoundException, ZipException { if (zippedFile != null && filesToZip != null) { new File(zippedFile.getParent()).mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new CheckedOutputStream(new FileOutputStream(zippedFile), new CRC32()))); if (ZIP_NO_COMPRESSION <= compressionLevel && compressionLevel <= ZIP_MAX_COMPRESSION) out.setLevel(compressionLevel); else out.setLevel(ZIP_MAX_COMPRESSION); if (zipComment != null) out.setComment(zipComment); for (int i = 0; i < filesToZip.length; i++) { BufferedInputStream in; if (savePath) { in = new BufferedInputStream(new FileInputStream(filesToZip[i])); out.putNextEntry(new ZipEntry(cleanPath(filesToZip[i].getAbsolutePath()))); } else { in = new BufferedInputStream(new FileInputStream(filesToZip[i])); out.putNextEntry(new ZipEntry(filesToZip[i].getName())); } for (int c = in.read(); c != -1; c = in.read()) out.write(c); in.close(); } out.close(); } else throw new ZipException(MAIN_RESOURCE_BUNDLE.getString("default.ZipException.text")); }
11
Code Sample 1: @Override public void actionPerformed(ActionEvent event) { if (event.getSource() == btnChange) { Error.log(7002, "Bot�o alterar pressionado por " + login + "."); if (new String(passwordUser1.getPassword()).compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo senha requerido"); passwordUser1.setFocusable(true); return; } String password1 = new String(passwordUser1.getPassword()); String password2 = new String(passwordUser2.getPassword()); if (password1.compareTo(password2) != 0) { JOptionPane.showMessageDialog(null, "Senhas n�o casam"); passwordUser1.setText(""); passwordUser2.setText(""); passwordUser1.setFocusable(true); return; } char c = passwordUser1.getPassword()[0]; int j = 1; for (j = 1; j < password1.length(); j++) { if (passwordUser1.getPassword()[j] != c) { break; } c = passwordUser1.getPassword()[j]; } if (j == password1.length()) { JOptionPane.showMessageDialog(null, "Senha fraca"); return; } if (password1.length() < 6) { JOptionPane.showMessageDialog(null, "Senha deve ter mais que 6 digitos"); return; } if (numPasswordOneUseUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo n�mero de senhas de uso �nico requerido"); return; } if (!(Integer.parseInt(numPasswordOneUseUser.getText()) > 0 && Integer.parseInt(numPasswordOneUseUser.getText()) < 41)) { JOptionPane.showMessageDialog(null, "N�mero de senhas de uso �nico entre 1 e 40"); return; } String outputDigest = ""; try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password1.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); outputDigest = bigInt.toString(16); } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } Statement stmt; String sql; sql = "update Usuarios set password = '" + outputDigest + "' where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } sql = "delete from Senhas_De_Unica_Vez where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r; Vector<Integer> passwordVector = new Vector<Integer>(); for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(login + ".txt", false)); for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + login + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException exception) { exception.printStackTrace(); } JOptionPane.showMessageDialog(null, "Usu�rio " + login + " foi alterado com sucesso."); dispose(); } if (event.getSource() == btnCancel) { Error.log(7003, "Bot�o voltar de alterar para o menu principal pressionado por " + login + "."); dispose(); } } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
00
Code Sample 1: private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException { FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(srcFile); FileChannel iChannel = is.getChannel(); os = new FileOutputStream(destFile, false); FileChannel oChannel = os.getChannel(); long doneBytes = 0L; long todoBytes = srcFile.length(); while (todoBytes != 0L) { long iterationBytes = Math.min(todoBytes, chunkSize); long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes); if (iterationBytes != transferredLength) { throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only " + transferredLength + " bytes copied."); } doneBytes += transferredLength; todoBytes -= transferredLength; } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified()); if (!successTimestampOp) { log.warn("Could not change timestamp for {}. Index synchronization may be slow.", destFile); } } Code Sample 2: private void redownloadResource(SchemaResource resource) { if (_redownloadSet != null) { if (_redownloadSet.contains(resource)) return; _redownloadSet.add(resource); } String filename = resource.getFilename(); String schemaLocation = resource.getSchemaLocation(); String digest = null; if (schemaLocation == null || filename == null) return; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { URL url = new URL(schemaLocation); URLConnection conn = url.openConnection(); conn.addRequestProperty("User-Agent", USER_AGENT); conn.addRequestProperty("Accept", "application/xml, text/xml, */*"); DigestInputStream input = digestInputStream(conn.getInputStream()); IOUtil.copyCompletely(input, buffer); digest = HexBin.bytesToString(input.getMessageDigest().digest()); } catch (Exception e) { warning("Could not copy remote resource " + schemaLocation + ":" + e.getMessage()); return; } if (digest.equals(resource.getSha1()) && fileExists(filename)) { warning("Resource " + filename + " is unchanged from " + schemaLocation + "."); return; } try { InputStream source = new ByteArrayInputStream(buffer.toByteArray()); writeInputStreamToFile(source, filename); } catch (IOException e) { warning("Could not write to file " + filename + " for " + schemaLocation + ":" + e.getMessage()); return; } warning("Refreshed " + filename + " from " + schemaLocation); }
00
Code Sample 1: public static void main(String[] args) throws IOException { FileOutputStream f = new FileOutputStream("test.zip"); CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32()); ZipOutputStream zos = new ZipOutputStream(csum); BufferedOutputStream out = new BufferedOutputStream(zos); zos.setComment("A test of Java Zipping"); for (String arg : args) { print("Writing file " + arg); BufferedReader in = new BufferedReader(new FileReader(arg)); zos.putNextEntry(new ZipEntry(arg)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.flush(); } out.close(); print("Checksum: " + csum.getChecksum().getValue()); print("Reading file"); FileInputStream fi = new FileInputStream("test.zip"); CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32()); ZipInputStream in2 = new ZipInputStream(csumi); BufferedInputStream bis = new BufferedInputStream(in2); ZipEntry ze; while ((ze = in2.getNextEntry()) != null) { print("Reading file " + ze); int x; while ((x = bis.read()) != -1) System.out.write(x); } if (args.length == 1) print("Checksum: " + csumi.getChecksum().getValue()); bis.close(); ZipFile zf = new ZipFile("test.zip"); Enumeration e = zf.entries(); while (e.hasMoreElements()) { ZipEntry ze2 = (ZipEntry) e.nextElement(); print("File: " + ze2); } } Code Sample 2: private static BreakIterator createBreakInstance(Locale where, int kind, String rulesName, String dictionaryName) { ResourceBundle bundle = ICULocaleData.getResourceBundle("BreakIteratorRules", where); String[] classNames = bundle.getStringArray("BreakIteratorClasses"); String rules = bundle.getString(rulesName); if (classNames[kind].equals("RuleBasedBreakIterator")) { return new RuleBasedBreakIterator(rules); } else if (classNames[kind].equals("DictionaryBasedBreakIterator")) { try { Object t = bundle.getObject(dictionaryName); URL url = (URL) t; InputStream dictionary = url.openStream(); return new DictionaryBasedBreakIterator(rules, dictionary); } catch (IOException e) { } catch (MissingResourceException e) { } return new RuleBasedBreakIterator(rules); } else { throw new IllegalArgumentException("Invalid break iterator class \"" + classNames[kind] + "\""); } }
11
Code Sample 1: private String getHash(String string) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md5.reset(); md5.update(string.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString(0xFF & result[i])); } String str = hexString.toString(); return str; } Code Sample 2: public static String getMd5Hash(String text) { StringBuffer result = new StringBuffer(32); try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(text.getBytes()); Formatter f = new Formatter(result); byte[] digest = md5.digest(); for (int i = 0; i < digest.length; i++) { f.format("%02x", new Object[] { new Byte(digest[i]) }); } } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return result.toString(); }
00
Code Sample 1: public static String post(String strUrl, String data) throws Exception { URL url = new URL(strUrl); final String method = "POST"; final String host = url.getHost(); final String contentType = "application/x-www-form-urlencoded"; final int contentLength = getContentLength(data); final String encoding = "UTF-8"; final String connection = "Close"; Config.log(DEBUG, "Sending data to: " + url + " (host=" + host + ", encoding=" + encoding + ", method=" + method + ", Content-Type=" + contentType + ", Content-Length=" + contentLength + ", Connection=" + connection + "):" + "\r\n" + data); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod(method); conn.setRequestProperty("host", host); conn.setRequestProperty("content-type", contentType); conn.setRequestProperty("Content-Encoding", encoding); conn.setRequestProperty("content-length", contentLength + ""); conn.setRequestProperty("connection", connection); if (tools.valid(Config.JSON_RPC_WEBSERVER_USERNAME) && tools.valid(Config.JSON_RPC_WEBSERVER_PASSWORD)) { String authString = Config.JSON_RPC_WEBSERVER_USERNAME + ":" + Config.JSON_RPC_WEBSERVER_PASSWORD; String authStringEnc = new sun.misc.BASE64Encoder().encode(authString.getBytes()); conn.setRequestProperty("Authorization", "Basic " + authStringEnc); } conn.setReadTimeout((int) (Config.JSON_RPC_TIMEOUT_SECONDS * 1000)); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); writer.close(); int responseCode = 400; try { responseCode = conn.getResponseCode(); } catch (Exception x) { Config.log(ERROR, "Failed to get response code from HTTP Server. Check your URL and username/password.", x); } String response = readStream(responseCode == 200 ? conn.getInputStream() : conn.getErrorStream()); if (response == null) { return null; } Config.log(DEBUG, "Raw response from POST. Response Code = " + conn.getResponseCode() + " (" + conn.getResponseMessage() + "):\r\n" + response); return response.toString(); } Code Sample 2: public static synchronized void repartition(File[] sourceFiles, File targetDirectory, String prefix, long maxUnitBases, long maxUnitEntries) throws Exception { if (!targetDirectory.exists()) { if (!targetDirectory.mkdirs()) throw new Exception("Could not create directory " + targetDirectory.getAbsolutePath()); } File tmpFile = new File(targetDirectory, "tmp.fasta"); FileOutputStream fos = new FileOutputStream(tmpFile); FileChannel fco = fos.getChannel(); for (File file : sourceFiles) { FileInputStream fis = new FileInputStream(file); FileChannel fci = fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(64000); while (fci.read(buffer) > 0) { buffer.flip(); fco.write(buffer); buffer.clear(); } fci.close(); } fco.close(); FastaFile fastaFile = new FastaFile(tmpFile); fastaFile.split(targetDirectory, prefix, maxUnitBases, maxUnitEntries); tmpFile.delete(); }
11
Code Sample 1: public static boolean copy(File source, File target, boolean owrite) { if (!source.exists()) { log.error("Invalid input to copy: source " + source + "doesn't exist"); return false; } else if (!source.isFile()) { log.error("Invalid input to copy: source " + source + "isn't a file."); return false; } else if (target.exists() && !owrite) { log.error("Invalid input to copy: target " + target + " exists."); return false; } try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target)); byte buffer[] = new byte[1024]; int read = -1; while ((read = in.read(buffer, 0, 1024)) != -1) out.write(buffer, 0, read); out.flush(); out.close(); in.close(); return true; } catch (IOException e) { log.error("Copy failed: ", e); return false; } } Code Sample 2: public void saveUploadFile(String toFileName, UploadFile uploadFile, SysConfig sysConfig) throws IOException { OutputStream bos = new FileOutputStream(toFileName); IOUtils.copy(uploadFile.getInputStream(), bos); if (sysConfig.isAttachImg(uploadFile.getFileName()) && sysConfig.getReduceAttachImg() == 1) { ImgUtil.reduceImg(toFileName, toFileName + Constant.IMG_SMALL_FILEPREFIX, sysConfig.getReduceAttachImgSize(), sysConfig.getReduceAttachImgSize(), 1); } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static int proxy(java.net.URI uri, HttpServletRequest req, HttpServletResponse res) throws IOException { final HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost(uri.getHost()); HttpMethodBase httpMethod = null; if (HttpRpcServer.METHOD_GET.equalsIgnoreCase(req.getMethod())) { httpMethod = new GetMethod(uri.toString()); httpMethod.setFollowRedirects(true); } else if (HttpRpcServer.METHOD_POST.equalsIgnoreCase(req.getMethod())) { httpMethod = new PostMethod(uri.toString()); final Enumeration parameterNames = req.getParameterNames(); if (parameterNames != null) while (parameterNames.hasMoreElements()) { final String parameterName = (String) parameterNames.nextElement(); for (String parameterValue : req.getParameterValues(parameterName)) ((PostMethod) httpMethod).addParameter(parameterName, parameterValue); } ((PostMethod) httpMethod).setRequestEntity(new InputStreamRequestEntity(req.getInputStream())); } if (httpMethod == null) throw new IllegalArgumentException("Unsupported http request method"); final int responseCode; final Enumeration headers = req.getHeaderNames(); if (headers != null) while (headers.hasMoreElements()) { final String headerName = (String) headers.nextElement(); final Enumeration headerValues = req.getHeaders(headerName); while (headerValues.hasMoreElements()) { httpMethod.setRequestHeader(headerName, (String) headerValues.nextElement()); } } final HttpState httpState = new HttpState(); if (req.getCookies() != null) for (Cookie cookie : req.getCookies()) { String host = req.getHeader("Host"); if (StringUtils.isEmpty(cookie.getDomain())) cookie.setDomain(StringUtils.isEmpty(host) ? req.getServerName() + ":" + req.getServerPort() : host); if (StringUtils.isEmpty(cookie.getPath())) cookie.setPath("/"); httpState.addCookie(new org.apache.commons.httpclient.Cookie(cookie.getDomain(), cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getMaxAge(), cookie.getSecure())); } httpMethod.setQueryString(req.getQueryString()); responseCode = (new HttpClient()).executeMethod(hostConfig, httpMethod, httpState); if (responseCode < 0) { httpMethod.releaseConnection(); return responseCode; } if (httpMethod.getResponseHeaders() != null) for (Header header : httpMethod.getResponseHeaders()) res.setHeader(header.getName(), header.getValue()); final InputStream in = httpMethod.getResponseBodyAsStream(); final OutputStream out = res.getOutputStream(); IOUtils.copy(in, out); out.flush(); out.close(); in.close(); httpMethod.releaseConnection(); return responseCode; }
11
Code Sample 1: private static boolean computeMovieAverages(String completePath, String MovieAveragesOutputFileName, String MovieIndexFileName) { try { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); TShortObjectHashMap MovieLimitsTHash = new TShortObjectHashMap(17770, 1); int i = 0, totalcount = 0; short movie; int startIndex, endIndex; TIntArrayList a; while (mappedfile.hasRemaining()) { movie = mappedfile.getShort(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); MovieLimitsTHash.put(movie, a); } inC.close(); mappedfile = null; System.out.println("Loaded movie index hash"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieAveragesOutputFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); int totalMovies = MovieLimitsTHash.size(); File movieMMAPDATAFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CustomerRatingBinaryFile.txt"); inC = new FileInputStream(movieMMAPDATAFile).getChannel(); short[] itr = MovieLimitsTHash.keys(); Arrays.sort(itr); ByteBuffer buf; for (i = 0; i < totalMovies; i++) { short currentMovie = itr[i]; a = (TIntArrayList) MovieLimitsTHash.get(currentMovie); startIndex = a.get(0); endIndex = a.get(1); if (endIndex > startIndex) { buf = ByteBuffer.allocate((endIndex - startIndex + 1) * 5); inC.read(buf, (startIndex - 1) * 5); } else { buf = ByteBuffer.allocate(5); inC.read(buf, (startIndex - 1) * 5); } buf.flip(); int bufsize = buf.capacity() / 5; float sum = 0; for (int q = 0; q < bufsize; q++) { buf.getInt(); sum += buf.get(); } ByteBuffer outbuf = ByteBuffer.allocate(6); outbuf.putShort(currentMovie); outbuf.putFloat(sum / bufsize); outbuf.flip(); outC.write(outbuf); buf.clear(); buf = null; a.clear(); a = null; } inC.close(); outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } Code Sample 2: public void copy(File src, File dest) throws FileNotFoundException, IOException { FileInputStream srcStream = new FileInputStream(src); FileOutputStream destStream = new FileOutputStream(dest); FileChannel srcChannel = srcStream.getChannel(); FileChannel destChannel = destStream.getChannel(); srcChannel.transferTo(0, srcChannel.size(), destChannel); destChannel.close(); srcChannel.close(); destStream.close(); srcStream.close(); }
11
Code Sample 1: private static byte[] sha2(String... data) { byte[] digest = new byte[32]; StringBuilder buffer = new StringBuilder(); for (String s : data) { buffer.append(s); } MessageDigest sha256 = null; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException ex) { assert false; } sha256.update(buffer.toString().getBytes()); try { sha256.digest(digest, 0, digest.length); } catch (DigestException ex) { assert false; } return digest; } Code Sample 2: public static String getHash(String text) { String ret = null; try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(text.getBytes()); ret = getHex(md.digest()); } catch (NoSuchAlgorithmException e) { log.error(e); throw new OopsException(e, "Hash Error."); } return ret; }
00
Code Sample 1: public void checkAndDownload(String statsUrl, RDFStatsUpdatableModelExt stats, Date lastDownload, boolean onlyIfNewer) throws DataSourceMonitorException { if (log.isInfoEnabled()) log.info("Checking if update required for statistics of " + ds + "..."); HttpURLConnection urlConnection; try { URL url = new URL(statsUrl); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(CONNECT_TIMEOUT); urlConnection.setReadTimeout(READ_TIMEOUT); int statusCode = urlConnection.getResponseCode(); if (statusCode / 100 != 2) { String msg = urlConnection.getResponseMessage(); throw new DataSourceMonitorException(statsUrl + " returned HTTP " + statusCode + (msg != null ? msg : "") + "."); } } catch (Exception e) { throw new DataSourceMonitorException("Failed to connect to " + statsUrl + ".", e); } long lastModified = urlConnection.getLastModified(); boolean newer = lastDownload == null || lastModified == 0 || lastModified - TIMING_GAP > lastDownload.getTime(); if (newer || !onlyIfNewer) { Model newStats = retrieveModelData(urlConnection, ds); Date retrievedTimestamp = Calendar.getInstance().getTime(); Date modifiedTimestamp = (urlConnection.getLastModified() > 0) ? new Date(urlConnection.getLastModified()) : null; if (log.isInfoEnabled()) log.info("Attempt to import up-to-date " + ((modifiedTimestamp != null) ? "(from " + modifiedTimestamp + ") " : "") + "statistics for " + ds + "."); try { if (stats.updateFrom(RDFStatsModelFactory.create(newStats), onlyIfNewer)) stats.setLastDownload(ds.getSPARQLEndpointURL(), retrievedTimestamp); } catch (Exception e) { throw new DataSourceMonitorException("Failed to import statistics and set last download for " + ds + ".", e); } } else { if (log.isInfoEnabled()) log.info("Statistics for " + ds + " are up-to-date" + ((lastDownload != null) ? " (" + lastDownload + ")" : "")); } } Code Sample 2: public void refreshFileItem(YahooInfo legroup) throws Exception { String lapage = new String(""); String ledir = new String(""); Pattern pat; Matcher mat; Pattern pat2; Matcher mat2; int data; URL myurl = new URL("http://groups.yahoo.com/mygroups"); URLConnection conn; URI myuri = new URI("http://groups.yahoo.com/mygroups"); YahooInfo yi; clearItem(legroup); for (int i = 0; i < UrlList.size(); i++) { if (UrlList.get(i).getGroup().equals(legroup.getGroup()) && UrlList.get(i).getDir().startsWith(legroup.getDir())) { if (UrlList.get(i).isGroup()) { System.out.print(UrlList.get(i).getGroup() + " : "); myuri = new URI(UrlList.get(i).getUrl()); myurl = new URL(UrlList.get(i).getUrl()); conn = myurl.openConnection(); conn.connect(); System.out.println(conn.getHeaderField(0).toString()); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<li> <a href=\"(.+?)\".*?>Files</a></li>"); mat = pat.matcher(lapage); if (mat.find()) { yi = new YahooInfo(UrlList.get(i).getGroup(), "/", "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } } if (UrlList.get(i).isDir()) { System.out.println(UrlList.get(i).getGroup() + UrlList.get(i).getDir()); myuri = new URI(UrlList.get(i).getUrl()); myurl = new URL(UrlList.get(i).getUrl()); do { myurl = new URL(myurl.toString()); conn = myurl.openConnection(); conn.connect(); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } System.out.print("p"); InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<span class=\"title\">\n<a href=\"(.+?/)\">(.+?)</a>"); mat = pat.matcher(lapage); while (mat.find()) { ledir = new String(UrlList.get(i).getDir()); pat2 = Pattern.compile("([A-Za-z0-9]+)"); mat2 = pat2.matcher(mat.group(2)); while (mat2.find()) { ledir += mat2.group(1); } ledir += "/"; yi = new YahooInfo(UrlList.get(i).getGroup(), ledir, "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } pat = Pattern.compile("<span class=\"title\">\n<a href=\"(.+?yahoofs.+?)\".*?>(.+?)</a>"); mat = pat.matcher(lapage); while (mat.find()) { yi = new YahooInfo(UrlList.get(i).getGroup(), UrlList.get(i).getDir(), mat.group(2), myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } System.out.println(""); pat = Pattern.compile("<a href=\"(.+?)\">Next"); mat = pat.matcher(lapage); myurl = null; if (mat.find()) { myurl = myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL(); } } while (myurl != null); } } } }
00
Code Sample 1: @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "getJarFile", args = { }) public void test_getJarFile() throws MalformedURLException, IOException { URL url = null; url = createContent("lf.jar", "missing"); JarURLConnection connection = null; connection = (JarURLConnection) url.openConnection(); try { connection.connect(); fail("Did not throw exception on connect"); } catch (IOException e) { } try { connection.getJarFile(); fail("Did not throw exception after connect"); } catch (IOException e) { } URL invURL = createContent("InvalidJar.jar", "Test.class"); JarURLConnection juConn = (JarURLConnection) invURL.openConnection(); try { juConn.getJarFile(); fail("IOException was not thrown."); } catch (java.io.IOException io) { } File resources = Support_Resources.createTempFolder(); Support_Resources.copyFile(resources, null, "hyts_att.jar"); File file = new File(resources.toString() + "/hyts_att.jar"); URL fUrl1 = new URL("jar:file:" + file.getPath() + "!/"); JarURLConnection con1 = (JarURLConnection) fUrl1.openConnection(); ZipFile jf1 = con1.getJarFile(); JarURLConnection con2 = (JarURLConnection) fUrl1.openConnection(); ZipFile jf2 = con2.getJarFile(); assertTrue("file: JarFiles not the same", jf1 == jf2); jf1.close(); assertTrue("File should exist", file.exists()); fUrl1 = createContent("lf.jar", ""); con1 = (JarURLConnection) fUrl1.openConnection(); jf1 = con1.getJarFile(); con2 = (JarURLConnection) fUrl1.openConnection(); jf2 = con2.getJarFile(); assertTrue("http: JarFiles not the same", jf1 == jf2); jf1.close(); } Code Sample 2: private void doIt() throws Throwable { GenericDAO<User> dao = DAOFactory.createDAO(User.class); try { final User user = dao.findUniqueByCriteria(Expression.eq("login", login)); if (user == null) throw new IllegalArgumentException("Specified user isn't exist"); if (srcDir.isDirectory() && srcDir.exists()) { final String[] fileList = srcDir.list(new XFilenameFilter() { public boolean accept(XFile dir, String file) { String[] fNArr = file.split("\\."); return (fNArr.length > 1 && (fNArr[fNArr.length - 1].equalsIgnoreCase("map") || fNArr[fNArr.length - 1].equalsIgnoreCase("plt") || fNArr[fNArr.length - 1].equalsIgnoreCase("wpt"))); } }); int pointsCounter = 0; int tracksCounter = 0; int mapsCounter = 0; for (final String fName : fileList) { try { TransactionManager.beginTransaction(); } catch (Throwable e) { logger.error(e); throw e; } final XFile file = new XFile(srcDir, fName); InputStream in = new XFileInputStream(file); try { ArrayList<UserMapOriginal> maps = new ArrayList<UserMapOriginal>(); ArrayList<MapTrackPointsScaleRequest> tracks = new ArrayList<MapTrackPointsScaleRequest>(); final byte[] headerBuf = new byte[1024]; if (in.read(headerBuf) <= 0) continue; final String fileHeader = new String(headerBuf); final boolean isOziWPT = (fileHeader.indexOf("OziExplorer Waypoint File") >= 0); final boolean isOziPLT = (fileHeader.indexOf("OziExplorer Track Point File") >= 0); final boolean isOziMAP = (fileHeader.indexOf("OziExplorer Map Data File") >= 0); final boolean isKML = (fileHeader.indexOf("<kml xmlns=") >= 0); if (isOziMAP || isOziPLT || isOziWPT || isKML) { in.close(); in = new XFileInputStream(file); } else continue; WPTPoint wp; if (isOziWPT) { try { wp = new WPTPointParser(in, "Cp1251").parse(); } catch (Throwable t) { wp = null; } if (wp != null) { Set<WayPointRow> rows = wp.getPoints(); for (WayPointRow row : rows) { final UserMapPoint p = BeanFactory.createUserPoint(row, user); logger.info("point:" + p.getGuid()); } pointsCounter += rows.size(); } } else if (isOziPLT) { PLTTrack plt; try { plt = new PLTTrackParser(in, "Cp1251").parse(); } catch (Throwable t) { plt = null; } if (plt != null) { final UserMapTrack t = BeanFactory.createUserTrack(plt, user); tracks.add(new MapTrackPointsScaleRequest(t)); tracksCounter++; logger.info("track:" + t.getGuid()); } } else if (isOziMAP) { MapProjection projection; MAPParser parser = new MAPParser(in, "Cp1251"); try { projection = parser.parse(); } catch (Throwable t) { projection = null; } if (projection != null && projection.getPoints() != null && projection.getPoints().size() >= 2) { GenericDAO<UserMapOriginal> mapDao = DAOFactory.createDAO(UserMapOriginal.class); final UserMapOriginal mapOriginal = new UserMapOriginal(); mapOriginal.setName(projection.getTitle()); mapOriginal.setUser(user); mapOriginal.setState(UserMapOriginal.State.UPLOAD); mapOriginal.setSubstate(UserMapOriginal.SubState.COMPLETE); MapManager.updateProjection(projection, mapOriginal); final XFile srcFile = new XFile(srcDir, projection.getPath()); if (!srcFile.exists() || !srcFile.isFile()) throw new IllegalArgumentException("file: " + srcFile.getPath() + " not found"); final XFile mapStorage = new XFile(new XFile(Configuration.getInstance().getPrivateMapStorage().toString()), mapOriginal.getGuid()); mapStorage.mkdir(); XFile dstFile = new XFile(mapStorage, mapOriginal.getGuid()); XFileOutputStream out = new XFileOutputStream(dstFile); XFileInputStream inImg = new XFileInputStream(srcFile); IOUtils.copy(inImg, out); out.flush(); out.close(); inImg.close(); mapDao.save(mapOriginal); maps.add(mapOriginal); srcFile.delete(); mapsCounter++; logger.info("map:" + mapOriginal.getGuid()); } } else logger.warn("unsupported file format: " + file.getName()); TransactionManager.commitTransaction(); for (MapTrackPointsScaleRequest track : tracks) { if (track != null) { try { PoolClientInterface pool = PoolFactory.getInstance().getClientPool(); if (pool == null) throw new IllegalStateException("pool not found"); pool.put(track, new StatesStack(new byte[] { 0x00, 0x11 }), GeneralCompleteStrategy.class); } catch (Throwable t) { logger.error(t); } } } } catch (Throwable e) { logger.error("Error importing", e); TransactionManager.rollbackTransaction(); } finally { in.close(); file.delete(); } } logger.info("waypoints: " + pointsCounter + "\ntracks: " + tracksCounter + "\nmaps: " + mapsCounter); } } catch (Throwable e) { logger.error("Error importing", e); } }
00
Code Sample 1: public XMLPieChartDemo(final String title) { super(title); PieDataset dataset = null; final URL url = getClass().getResource("/org/jfree/chart/demo/piedata.xml"); try { final InputStream in = url.openStream(); dataset = DatasetReader.readPieDatasetFromXML(in); } catch (IOException ioe) { System.out.println(ioe.getMessage()); } final JFreeChart chart = ChartFactory.createPieChart("Pie Chart Demo 1", dataset, true, true, false); chart.setBackgroundPaint(Color.yellow); final PiePlot plot = (PiePlot) chart.getPlot(); plot.setNoDataMessage("No data available"); final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); setContentPane(chartPanel); } Code Sample 2: public static void main(String[] args) { try { boolean readExp = Utils.getFlag('l', args); final boolean writeExp = Utils.getFlag('s', args); final String expFile = Utils.getOption('f', args); if ((readExp || writeExp) && (expFile.length() == 0)) { throw new Exception("A filename must be given with the -f option"); } Experiment exp = null; if (readExp) { FileInputStream fi = new FileInputStream(expFile); ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(fi)); exp = (Experiment) oi.readObject(); oi.close(); } else { exp = new Experiment(); } System.err.println("Initial Experiment:\n" + exp.toString()); final JFrame jf = new JFrame("Weka Experiment Setup"); jf.getContentPane().setLayout(new BorderLayout()); final SetupPanel sp = new SetupPanel(); jf.getContentPane().add(sp, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.err.println("\nFinal Experiment:\n" + sp.m_Exp.toString()); if (writeExp) { try { FileOutputStream fo = new FileOutputStream(expFile); ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(fo)); oo.writeObject(sp.m_Exp); oo.close(); } catch (Exception ex) { ex.printStackTrace(); System.err.println("Couldn't write experiment to: " + expFile + '\n' + ex.getMessage()); } } jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); System.err.println("Short nap"); Thread.currentThread().sleep(3000); System.err.println("Done"); sp.setExperiment(exp); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } }
00
Code Sample 1: public static String md5Encode16(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes("utf-8")); byte b[] = md.digest(); int i; StringBuilder buf = new StringBuilder(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } return buf.toString().substring(8, 24); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } } Code Sample 2: public static void copyAll(URL url, StringBuilder ret) { Reader in = null; try { in = new InputStreamReader(new BufferedInputStream(url.openStream())); copyAll(in, ret); } catch (IOException e) { throw new RuntimeException(e); } finally { close(in); } }
11
Code Sample 1: public String doUpload(@ParamName(name = "file") MultipartFile file, @ParamName(name = "uploadDirectory") String _uploadDirectory) throws IOException { String sessionId = (String) RuntimeAccess.getInstance().getSession().getAttribute("SESSION_ID"); String tempUploadDir = MewitProperties.getTemporaryUploadDirectory(); if (!tempUploadDir.endsWith("/") && !tempUploadDir.endsWith("\\")) { tempUploadDir += "\\"; } String fileName = null; int position = file.getOriginalFilename().lastIndexOf("."); if (position <= 0) { fileName = java.util.UUID.randomUUID().toString(); } else { fileName = java.util.UUID.randomUUID().toString() + file.getOriginalFilename().substring(position); } File outputFile = new File(tempUploadDir, fileName); log(INFO, "writing the content of uploaded file to: " + outputFile); FileOutputStream fos = new FileOutputStream(outputFile); IOUtils.copy(file.getInputStream(), fos); file.getInputStream().close(); fos.close(); return doUploadFile(sessionId, outputFile, file.getOriginalFilename()); } Code Sample 2: public void createNewFile(String filePath, InputStream in) throws IOException { FileOutputStream out = null; try { File file = newFileRef(filePath); FileHelper.createNewFile(file, true); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
11
Code Sample 1: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final FileManager fmanager = FileManager.getFileManager(request, leechget); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (!item.isFormField()) { final FileObject file = fmanager.getFile(name); if (!file.exists()) { IOUtils.copyLarge(stream, file.getContent().getOutputStream()); } } } } catch (FileUploadException e1) { e1.printStackTrace(); } } Code Sample 2: public static boolean copy(File src, FileSystem dstFS, Path dst, boolean deleteSource, Configuration conf) throws IOException { dst = checkDest(src.getName(), dstFS, dst, false); if (src.isDirectory()) { if (!dstFS.mkdirs(dst)) { return false; } File contents[] = src.listFiles(); for (int i = 0; i < contents.length; i++) { copy(contents[i], dstFS, new Path(dst, contents[i].getName()), deleteSource, conf); } } else if (src.isFile()) { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = dstFS.create(dst); IOUtils.copyBytes(in, out, conf); } catch (IOException e) { IOUtils.closeStream(out); IOUtils.closeStream(in); throw e; } } else { throw new IOException(src.toString() + ": No such file or directory"); } if (deleteSource) { return FileUtil.fullyDelete(src); } else { return true; } }
11
Code Sample 1: public static void copyFile(File sourceFile, File targetFile) throws IOException { if (sourceFile == null || targetFile == null) { throw new NullPointerException("Source file and target file must not be null"); } File directory = targetFile.getParentFile(); if (!directory.exists() && !directory.mkdirs()) { throw new IOException("Could not create directory '" + directory + "'"); } InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(sourceFile)); outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)); try { byte[] buffer = new byte[32768]; for (int readBytes = inputStream.read(buffer); readBytes > 0; readBytes = inputStream.read(buffer)) { outputStream.write(buffer, 0, readBytes); } } catch (IOException ex) { targetFile.delete(); throw ex; } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { } } if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { } } } } Code Sample 2: public static void copyFromHDFSMerge(String hdfsDir, String local) throws IOException { rmr(local); File f = new File(local); f.getAbsoluteFile().getParentFile().mkdirs(); HDFSDirInputStream inp = new HDFSDirInputStream(hdfsDir); FileOutputStream oup = new FileOutputStream(local); IOUtils.copyBytes(inp, oup, 65 * 1024 * 1024, true); }
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.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } Code Sample 2: private static boolean hardCopy(File sourceFile, File destinationFile, StringBuffer errorLog) { boolean result = true; try { notifyCopyStart(destinationFile); destinationFile.getParentFile().mkdirs(); byte[] buffer = new byte[4096]; int len = 0; FileInputStream in = new FileInputStream(sourceFile); FileOutputStream out = new FileOutputStream(destinationFile); while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len); in.close(); out.close(); } catch (Exception e) { result = false; handleException("\n Error in method: copy!\n", e, errorLog); } finally { notifyCopyEnd(destinationFile); } return result; }
11
Code Sample 1: private void addAllSpecialPages(Environment env, ZipOutputStream zipout, int progressStart, int progressLength) throws Exception, IOException { ResourceBundle messages = ResourceBundle.getBundle("ApplicationResources", locale); String tpl; int count = 0; int numberOfSpecialPages = 7; progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; String cssContent = wb.readRaw(virtualWiki, "StyleSheet"); addZipEntry(zipout, "css/vqwiki.css", cssContent); progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; tpl = getTemplateFilledWithContent("search"); addTopicEntry(zipout, tpl, "WikiSearch", "WikiSearch.html"); progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; zipout.putNextEntry(new ZipEntry("applets/export2html-applet.jar")); IOUtils.copy(new FileInputStream(ctx.getRealPath("/WEB-INF/classes/export2html/export2html-applet.jar")), zipout); zipout.closeEntry(); zipout.flush(); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); JarOutputStream indexjar = new JarOutputStream(bos); JarEntry jarEntry; File searchDir = new File(wb.getSearchEngine().getSearchIndexPath(virtualWiki)); String files[] = searchDir.list(); StringBuffer listOfAllFiles = new StringBuffer(); for (int i = 0; i < files.length; i++) { if (listOfAllFiles.length() > 0) { listOfAllFiles.append(","); } listOfAllFiles.append(files[i]); jarEntry = new JarEntry("lucene/index/" + files[i]); indexjar.putNextEntry(jarEntry); IOUtils.copy(new FileInputStream(new File(searchDir, files[i])), indexjar); indexjar.closeEntry(); } indexjar.flush(); indexjar.putNextEntry(new JarEntry("lucene/index.dir")); IOUtils.copy(new StringReader(listOfAllFiles.toString()), indexjar); indexjar.closeEntry(); indexjar.flush(); indexjar.close(); zipout.putNextEntry(new ZipEntry("applets/index.jar")); zipout.write(bos.toByteArray()); zipout.closeEntry(); zipout.flush(); bos.reset(); } catch (Exception e) { logger.log(Level.FINE, "Exception while adding lucene index: ", e); } progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; StringBuffer content = new StringBuffer(); content.append("<table><tr><th>" + messages.getString("common.date") + "</th><th>" + messages.getString("common.topic") + "</th><th>" + messages.getString("common.user") + "</th></tr>" + IOUtils.LINE_SEPARATOR); Collection all = null; try { Calendar cal = Calendar.getInstance(); ChangeLog cl = wb.getChangeLog(); int n = env.getIntSetting(Environment.PROPERTY_RECENT_CHANGES_DAYS); if (n == 0) { n = 5; } all = new ArrayList(); for (int i = 0; i < n; i++) { Collection col = cl.getChanges(virtualWiki, cal.getTime()); if (col != null) { all.addAll(col); } cal.add(Calendar.DATE, -1); } } catch (Exception e) { } DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale); for (Iterator iter = all.iterator(); iter.hasNext(); ) { Change change = (Change) iter.next(); content.append("<tr><td class=\"recent\">" + df.format(change.getTime()) + "</td><td class=\"recent\"><a href=\"" + safename(change.getTopic()) + ".html\">" + change.getTopic() + "</a></td><td class=\"recent\">" + change.getUser() + "</td></tr>"); } content.append("</table>" + IOUtils.LINE_SEPARATOR); tpl = getTemplateFilledWithContent(null); tpl = tpl.replaceAll("@@CONTENTS@@", content.toString()); addTopicEntry(zipout, tpl, "RecentChanges", "RecentChanges.html"); logger.fine("Done adding all special topics."); } Code Sample 2: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String contentId = req.getParameter(CONTENT_ID); String contentType = req.getParameter(CONTENT_TYPE); if (contentId == null || contentType == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Content id or content type not specified"); return; } try { switch(ContentType.valueOf(contentType)) { case IMAGE: resp.setContentType("image/jpeg"); break; case AUDIO: resp.setContentType("audio/mp3"); break; case VIDEO: resp.setContentType("video/mpeg"); break; default: throw new IllegalStateException("Invalid content type specified"); } } catch (IllegalArgumentException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid content type specified"); return; } String baseUrl = this.getServletContext().getInitParameter(BASE_URL); URL url = new URL(baseUrl + "/" + contentType.toLowerCase() + "/" + contentId); URLConnection conn = url.openConnection(); resp.setContentLength(conn.getContentLength()); IOUtils.copy(conn.getInputStream(), resp.getOutputStream()); }
11
Code Sample 1: protected String getLibJSCode() throws IOException { if (cachedLibJSCode == null) { InputStream is = getClass().getResourceAsStream(JS_LIB_FILE); StringWriter output = new StringWriter(); IOUtils.copy(is, output); cachedLibJSCode = output.toString(); } return cachedLibJSCode; } Code Sample 2: private boolean write(File file) { String filename = file.getPath(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PrintStream out = new PrintStream(byteArrayOutputStream); try { StringBuffer xml = null; if (MainFrame.getInstance().getAnimation() != null) { MainFrame.getInstance().getAnimation().xml(out, "\t"); } else { xml = MainFrame.getInstance().getModel().xml("\t"); } if (file.exists()) { BufferedReader reader = new BufferedReader(new FileReader(filename)); BufferedWriter writer = new BufferedWriter(new FileWriter(filename + "~")); char[] buffer = new char[65536]; int charsRead = 0; while ((charsRead = reader.read(buffer)) > 0) writer.write(buffer, 0, charsRead); reader.close(); writer.close(); } BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writer.write("<jpatch version=\"" + VersionInfo.ver + "\">\n"); if (xml != null) writer.write(xml.toString()); else writer.write(byteArrayOutputStream.toString()); writer.write("</jpatch>\n"); writer.close(); MainFrame.getInstance().getUndoManager().setChange(false); if (MainFrame.getInstance().getAnimation() != null) MainFrame.getInstance().getAnimation().setFile(file); else MainFrame.getInstance().getModel().setFile(file); MainFrame.getInstance().setFilename(file.getName()); return true; } catch (IOException ioException) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "Unable to save file \"" + filename + "\"\n" + ioException, "Error", JOptionPane.ERROR_MESSAGE); return false; } }
11
Code Sample 1: public void salva(UploadedFile imagem, Usuario usuario) { File destino = new File(pastaImagens, usuario.getId() + ".imagem"); try { IOUtils.copyLarge(imagem.getFile(), new FileOutputStream(destino)); } catch (IOException e) { throw new RuntimeException("Erro ao copiar imagem", e); } } Code Sample 2: private static boolean prepareQualifyingFile(String completePath, String outputFile) { try { File inFile = new File(completePath + fSep + "qualifying.txt"); FileChannel inC = new FileInputStream(inFile).getChannel(); BufferedReader br = new BufferedReader(new FileReader(inFile)); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + outputFile); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); boolean endOfFile = true; short movieName = 0; int customer = 0; while (endOfFile) { String line = br.readLine(); if (line != null) { if (line.indexOf(":") >= 0) { movieName = new Short(line.substring(0, line.length() - 1)).shortValue(); } else { customer = new Integer(line.substring(0, line.indexOf(","))).intValue(); ByteBuffer outBuf = ByteBuffer.allocate(6); outBuf.putShort(movieName); outBuf.putInt(customer); outBuf.flip(); outC.write(outBuf); } } else endOfFile = false; } br.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } }
00
Code Sample 1: protected Source getStylesheetSource(Resource stylesheetLocation) throws ApplicationContextException { if (logger.isDebugEnabled()) { logger.debug("Loading XSLT stylesheet from " + stylesheetLocation); } try { URL url = stylesheetLocation.getURL(); String urlPath = url.toString(); String systemId = urlPath.substring(0, urlPath.lastIndexOf('/') + 1); return new StreamSource(url.openStream(), systemId); } catch (IOException ex) { throw new ApplicationContextException("Can't load XSLT stylesheet from " + stylesheetLocation, ex); } } Code Sample 2: public InputStream resolve(String uri) throws SAJException { try { URI url = new URI(uri); InputStream stream = url.toURL().openStream(); if (stream == null) throw new SAJException("URI " + uri + " can't be resolved"); return stream; } catch (SAJException e) { throw e; } catch (Exception e) { throw new SAJException("Invalid uri to resolve " + uri, e); } }
00
Code Sample 1: public boolean compile(URL url, String name) { try { final InputStream stream = url.openStream(); final InputSource input = new InputSource(stream); input.setSystemId(url.toString()); return compile(input, name); } catch (IOException e) { _parser.reportError(Constants.FATAL, new ErrorMsg(e)); return false; } } Code Sample 2: @Override public ImageData getImageData(URL url) { InputStream in = null; try { URLConnection conn = url.openConnection(); conn.setRequestProperty("user-agent", "Tahiti/Alpha5x"); conn.setRequestProperty("agent-system", "aglets"); conn.setAllowUserInteraction(true); conn.connect(); in = conn.getInputStream(); String type = conn.getContentType(); int len = conn.getContentLength(); if (len < 0) { len = in.available(); } byte[] b = new byte[len]; int off = 0; int n = 0; while (n < len) { int count = in.read(b, off + n, len - n); if (count < 0) { throw new java.io.EOFException(); } n += count; } in.close(); return new AgletImageData(url, b, type); } catch (Exception ex) { ex.printStackTrace(); return null; } }
00
Code Sample 1: public static void main(String[] args) throws Exception { String infile = "C:\\copy.sql"; String outfile = "C:\\copy.txt"; FileInputStream fin = new FileInputStream(infile); FileOutputStream fout = new FileOutputStream(outfile); FileChannel fcin = fin.getChannel(); FileChannel fcout = fout.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { buffer.clear(); int r = fcin.read(buffer); if (r == -1) { break; } buffer.flip(); fcout.write(buffer); } } Code Sample 2: public void testDoPost() throws Exception { URL url = null; url = new URL("http://127.0.0.1:" + connector.getLocalPort() + "/test/dump/info?query=foo"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.addRequestProperty(HttpHeaders.CONTENT_TYPE, MimeTypes.FORM_ENCODED); connection.addRequestProperty(HttpHeaders.CONTENT_LENGTH, "10"); connection.getOutputStream().write("abcd=1234\n".getBytes()); connection.getOutputStream().flush(); connection.connect(); String s0 = IO.toString(connection.getInputStream()); assertTrue(s0.startsWith("<html>")); assertTrue(s0.indexOf("<td>POST</td>") > 0); assertTrue(s0.indexOf("abcd:&nbsp;</th><td>1234") > 0); }
11
Code Sample 1: protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } } Code Sample 2: String extractTiffFile(String path) throws IOException { ZipInputStream in = new ZipInputStream(new FileInputStream(path)); OutputStream out = new FileOutputStream(dir + TEMP_NAME); byte[] buf = new byte[1024]; int len; ZipEntry entry = in.getNextEntry(); if (entry == null) return null; String name = entry.getName(); if (!name.endsWith(".tif")) throw new IOException("This ZIP archive does not appear to contain a TIFF file"); while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); return name; }
00
Code Sample 1: protected static String fileName2md5(String input) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(input.getBytes("iso-8859-1")); byte[] byteHash = md.digest(); md.reset(); StringBuffer resultString = new StringBuffer(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); } catch (Exception ex) { Logger.error(ex.getClass() + " " + ex.getMessage()); for (int i = 0; i < ex.getStackTrace().length; i++) Logger.error(" " + ex.getStackTrace()[i].toString()); ex.printStackTrace(); } return String.valueOf(Math.random() * Long.MAX_VALUE); } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public long copyDirAllFilesToDirectory(String baseDirStr, String destDirStr) throws Exception { long plussQuotaSize = 0; if (baseDirStr.endsWith(sep)) { baseDirStr = baseDirStr.substring(0, baseDirStr.length() - 1); } if (destDirStr.endsWith(sep)) { destDirStr = destDirStr.substring(0, destDirStr.length() - 1); } FileUtils.getInstance().createDirectory(destDirStr); BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File baseDir = new File(baseDirStr); baseDir.mkdirs(); if (!baseDir.exists()) { createDirectory(baseDirStr); } if ((baseDir.exists()) && (baseDir.isDirectory())) { String[] entryList = baseDir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String oldPathFileName = baseDirStr + sep + entryName; File entryFile = new File(oldPathFileName); if (entryFile.isFile()) { String newPathFileName = destDirStr + sep + entryName; File newFile = new File(newPathFileName); if (newFile.exists()) { plussQuotaSize -= newFile.length(); newFile.delete(); } in = new BufferedInputStream(new FileInputStream(oldPathFileName), bufferSize); out = new BufferedOutputStream(new FileOutputStream(newPathFileName), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } } } } else { throw new Exception("Base dir not exist ! baseDirStr = (" + baseDirStr + ")"); } return plussQuotaSize; } Code Sample 2: public static long[] getUids(String myUid) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpGet get = new HttpGet(UIDS_URI); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); JSONArray result = new JSONArray(res); long[] friends = new long[result.length()]; long uid = Long.parseLong(myUid); for (int i = 0; i < result.length(); i++) { if (uid != result.getLong(i)) { friends[i] = result.getLong(i); } } return friends; } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); }
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 zip(ZipArchiveOutputStream zos, File efile, String base) throws IOException { if (efile.isDirectory()) { File[] lf = efile.listFiles(); base = base + File.separator + efile.getName(); for (File file : lf) { zip(zos, file, base); } } else { ZipArchiveEntry entry = new ZipArchiveEntry(efile, base + File.separator + efile.getName()); zos.setEncoding("utf-8"); zos.putArchiveEntry(entry); InputStream is = new FileInputStream(efile); IOUtils.copy(is, zos); is.close(); zos.closeArchiveEntry(); } }
11
Code Sample 1: @org.junit.Test public void testReadWrite() throws Exception { final String reference = "testString"; final Reader reader = new StringReader(reference); final StringWriter osString = new StringWriter(); final Reader teeStream = new TeeReaderWriter(reader, osString); IOUtils.copy(teeStream, new NullWriter()); teeStream.close(); osString.toString(); } Code Sample 2: public static File insertFileInto(File zipFile, File toInsert, String targetPath) { Zip64File zip64File = null; try { boolean compress = false; zip64File = new Zip64File(zipFile); FileEntry testEntry = getFileEntry(zip64File, targetPath); if (testEntry != null && testEntry.getMethod() == FileEntry.iMETHOD_DEFLATED) { compress = true; } processAndCreateFolderEntries(zip64File, parseTargetPath(targetPath, toInsert), compress); if (testEntry != null) { log.info("[insertFileInto] Entry exists: " + testEntry.getName()); log.info("[insertFileInto] Will delete this entry before inserting: " + toInsert.getName()); if (!testEntry.isDirectory()) { zip64File.delete(testEntry.getName()); } else { log.info("[insertFileInto] Entry is a directory. " + "Will delete all files contained in this entry and insert " + toInsert.getName() + "and all nested files."); if (!targetPath.contains("/")) { targetPath = targetPath + "/"; } deleteFileEntry(zip64File, testEntry); log.info("[insertFileInto] Entry successfully deleted."); } log.info("[insertFileInto] Writing new Entry: " + targetPath); EntryOutputStream out = null; if (!compress) { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_STORED, new Date(toInsert.lastModified())); } else { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_DEFLATED, new Date(toInsert.lastModified())); } if (toInsert.isDirectory()) { out.flush(); out.close(); log.info("[insertFileInto] Finished writing entry: " + targetPath); List<String> containedPaths = normalizePaths(toInsert); List<File> containedFiles = listAllFilesAndFolders(toInsert, new ArrayList<File>()); log.info("[insertFileInto] Added entry is a folder."); log.info("[insertFileInto] Adding all nested files: "); for (int i = 0; i < containedPaths.size(); i++) { File currentFile = containedFiles.get(i); String currentPath = targetPath.replace("/", "") + File.separator + containedPaths.get(i); EntryOutputStream loop_out = null; if (!compress) { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_STORED, new Date(currentFile.lastModified())); } else { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_DEFLATED, new Date(currentFile.lastModified())); } if (currentFile.isFile()) { InputStream loop_in = new FileInputStream(currentFile); IOUtils.copyLarge(loop_in, loop_out); loop_in.close(); } log.info("[insertFileInto] Added: " + currentPath); loop_out.flush(); loop_out.close(); } } else { InputStream in = new FileInputStream(toInsert); IOUtils.copyLarge(in, out); in.close(); out.flush(); out.close(); } } else { EntryOutputStream out = null; if (!compress) { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_STORED, new Date(toInsert.lastModified())); } else { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_DEFLATED, new Date(toInsert.lastModified())); } if (toInsert.isDirectory()) { out.flush(); out.close(); log.info("[insertFileInto] Finished writing entry: " + targetPath); List<String> containedPaths = normalizePaths(toInsert); List<File> containedFiles = listAllFilesAndFolders(toInsert, new ArrayList<File>()); log.info("[insertFileInto] Added entry is a folder."); log.info("[insertFileInto] Adding all nested files: "); for (int i = 0; i < containedPaths.size(); i++) { File currentFile = containedFiles.get(i); String currentPath = targetPath.replace("/", "") + File.separator + containedPaths.get(i); EntryOutputStream loop_out = null; if (!compress) { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_STORED, new Date(currentFile.lastModified())); } else { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_DEFLATED, new Date(currentFile.lastModified())); } if (currentFile.isFile()) { InputStream loop_in = new FileInputStream(currentFile); IOUtils.copyLarge(loop_in, loop_out); loop_in.close(); } log.info("[insertFileInto] Added: " + currentPath); loop_out.flush(); loop_out.close(); } } else { InputStream in = new FileInputStream(toInsert); IOUtils.copyLarge(in, out); in.close(); out.flush(); out.close(); } } log.info("[insertFileInto] Done! Added " + toInsert.getName() + " to zip."); zip64File.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return new File(zip64File.getDiskFile().getFileName()); }
11
Code Sample 1: void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } Code Sample 2: public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new SoundFilter()); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.17")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "sonidos/" + file.getName(); String rutaRelativa = rutaDatos + "sonidos/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setSonidoURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonSonido.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); gui.getAudio().reproduceAudio(imagen); } catch (IOException ex) { ex.printStackTrace(); } } else { } }
00
Code Sample 1: private int getCountFromUrl(String url) { HttpGet request = new HttpGet(url); try { HttpResponse response = httpClient.execute(request); int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { ByteArrayOutputStream ostream = new ByteArrayOutputStream(); response.getEntity().writeTo(ostream); Log.e(TAG, ostream.toString()); } else { InputStream content = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content), 10); String count = reader.readLine(); content.close(); return Integer.parseInt(count); } } catch (IOException e) { Log.e(TAG, Log.getStackTraceString(e)); } return -1; } Code Sample 2: private static int get(URL url, byte[] content) throws IOException { int len = -1; InputStream in = null; try { in = new BufferedInputStream(url.openStream()); String type = URLConnection.guessContentTypeFromStream(in); if (type == null || type.compareTo("text/html") != 0) { return -1; } len = read(in, content); } catch (IOException e) { throw e; } finally { close(in); } return len; }
11
Code Sample 1: public static void main(String[] args) { if (args.length < 2) { System.out.println(" *** DDL (creates) and DML (inserts) script importer from DB ***"); System.out.println(" You must specify name of the file with script importing data"); System.out.println(" Fisrt rows of this file must be:"); System.out.println(" 1) JDBC driver class for your DBMS"); System.out.println(" 2) URL for your database instance"); System.out.println(" 3) user in that database (with sufficient priviliges)"); System.out.println(" 4) password of that user"); System.out.println(" Next rows can have:"); System.out.println(" '}' before table to create,"); System.out.println(" '{' before schema to create tables in,"); System.out.println(" ')' before table to insert into,"); System.out.println(" '(' before schema to insert into tables in."); System.out.println(" '!' before row means that it is a comment."); System.out.println(" If some exception is occured, all script is rolled back."); System.out.println(" 2nd command line argument is name of output file;"); System.out.println(" if its extension is *.sql, its format is standard SQL"); System.out.println(" otherwize format is short one, understanded by SQLScript tool"); System.out.println(" Connection information remains unchanged in the last format"); System.out.println(" but in the first one it takes form 'connect user/password@URL'"); System.out.println(" where URL can be formed with different rools for different DBMSs"); System.out.println(" If file (with short format header) already exists and you specify"); System.out.println(" 3rd command line argument -db, we generate objects in the database"); System.out.println(" (known from the file header; must differ from 1st DB) but not in file"); System.out.println(" Note: when importing to a file of short format, line separators"); System.out.println(" in VARCHARS will be lost; LOBs will be empty for any file"); System.exit(0); } try { String[] info = new String[4]; BufferedReader reader = new BufferedReader(new FileReader(new File(args[0]))); Writer writer = null; Connection outConnection = null; try { for (int i = 0; i < info.length; i++) info[i] = reader.readLine(); try { Class.forName(info[0]); Connection connection = DriverManager.getConnection(info[1], info[2], info[3]); int format = args[1].toLowerCase().endsWith("sql") ? SQL_FORMAT : SHORT_FORMAT; File file = new File(args[1]); if (format == SHORT_FORMAT) { if (file.exists() && args.length > 2 && args[2].equalsIgnoreCase("-db")) { String[] outInfo = new String[info.length]; BufferedReader outReader = new BufferedReader(new FileReader(file)); for (int i = 0; i < outInfo.length; i++) outInfo[i] = reader.readLine(); outReader.close(); if (!(outInfo[1].equals(info[1]) && outInfo[2].equals(info[2]))) { Class.forName(info[0]); outConnection = DriverManager.getConnection(outInfo[1], outInfo[2], outInfo[3]); format = SQL_FORMAT; } } } if (outConnection == null) writer = new BufferedWriter(new FileWriter(file)); SQLImporter script = new SQLImporter(outConnection, connection); script.setFormat(format); if (format == SQL_FORMAT) { writer.write("connect " + info[2] + "/" + info[3] + "@" + script.getDatabaseURL(info[1]) + script.statementTerminator); } else { for (int i = 0; i < info.length; i++) writer.write(info[i] + lineSep); writer.write(lineSep); } try { System.out.println(script.executeScript(reader, writer) + " operations with tables has been generated during import"); } catch (SQLException e4) { reader.close(); if (writer != null) writer.close(); else outConnection.close(); System.out.println(" Script generation error: " + e4); } connection.close(); } catch (Exception e3) { reader.close(); if (writer != null) writer.close(); System.out.println(" Connection error: " + e3); } } catch (IOException e2) { System.out.println("Error in file " + args[0]); } } catch (FileNotFoundException e1) { System.out.println("File " + args[0] + " not found"); } } Code Sample 2: public static boolean copy(File from, File to) { if (from.isDirectory()) { for (String name : Arrays.asList(from.list())) { if (!copy(from, to, name)) { LogUtils.info("Failed to copy " + name + " from " + from + " to " + to, null); return false; } } } else { try { FileInputStream is = new FileInputStream(from); FileChannel ifc = is.getChannel(); FileOutputStream os = makeFile(to); if (USE_NIO) { FileChannel ofc = os.getChannel(); ofc.transferFrom(ifc, 0, from.length()); } else { pipe(is, os, false); } is.close(); os.close(); } catch (IOException ex) { LogUtils.warning("Failed to copy " + from + " to " + to, ex); return false; } } long time = from.lastModified(); setLastModified(to, time); long newtime = to.lastModified(); if (newtime != time) { LogUtils.info("Failed to set timestamp for file " + to + ": tried " + new Date(time) + ", have " + new Date(newtime), null); to.setLastModified(time); long morenewtime = to.lastModified(); return false; } return time == newtime; }
00
Code Sample 1: protected List<String[]> execute(String queryString, String sVar1, String sVar2, String filter) throws Exception { String query = URLEncoder.encode(queryString, "UTF-8"); String urlString = "http://sparql.bibleontology.com/sparql.jsp?sparql=" + query + "&type1=xml"; URL url; BufferedReader br = null; ArrayList<String[]> values = new ArrayList<String[]>(); try { url = new URL(urlString); URLConnection conn = url.openConnection(); br = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; String sURI1 = null; String sURI2 = null; boolean b1 = false; boolean b2 = false; while ((line = br.readLine()) != null) { if (line.indexOf("</result>") != -1) { if (sURI1 != null && sURI2 != null) { String pair[] = { sURI1, sURI2 }; values.add(pair); } sURI1 = null; sURI2 = null; b1 = false; b2 = false; } if (line.indexOf("binding name=\"" + sVar1 + "\"") != -1) { b1 = true; continue; } else if (b1) { String s1 = getURI(line); if (s1 != null) { s1 = checkURISyntax(s1); if (filter == null || s1.startsWith(filter)) { sURI1 = s1; } } b1 = false; continue; } if (line.indexOf("binding name=\"" + sVar2 + "\"") != -1) { b2 = true; continue; } else if (b2) { String s2 = getURI(line); if (s2 != null) { s2 = checkURISyntax(s2); if (filter == null || s2.startsWith(filter)) { sURI2 = s2; } } b2 = false; continue; } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { br.close(); } return values; } Code Sample 2: public void copyFile(String from, String to) throws IOException { FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } Code Sample 2: public boolean validateZipFile(File zipFile) { String tempdir = Config.CONTEXT.getRealPath(getBackupTempFilePath()); try { deleteTempFiles(); File ftempDir = new File(tempdir); ftempDir.mkdirs(); File tempZip = new File(tempdir + File.separator + zipFile.getName()); tempZip.createNewFile(); FileChannel ic = new FileInputStream(zipFile).getChannel(); FileChannel oc = new FileOutputStream(tempZip).getChannel(); for (long i = 0; i <= ic.size(); i++) { ic.transferTo(0, 1000000, oc); i = i + 999999; } ic.close(); oc.close(); if (zipFile != null && zipFile.getName().toLowerCase().endsWith(".zip")) { ZipFile z = new ZipFile(zipFile); ZipUtil.extract(z, new File(Config.CONTEXT.getRealPath(backupTempFilePath))); } return true; } catch (Exception e) { Logger.error(this, "Error with file", e); return false; } }
11
Code Sample 1: protected void setUp() throws Exception { this.testOutputDirectory = new File(getClass().getResource("/").getPath()); this.pluginFile = new File(this.testOutputDirectory, "/plugin.zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(pluginFile)); zos.putNextEntry(new ZipEntry("WEB-INF/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/lib/")); zos.putNextEntry(new ZipEntry("WEB-INF/lib/plugin.jar")); File jarFile = new File(this.testOutputDirectory.getPath() + "/plugin.jar"); JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile)); jos.putNextEntry(new ZipEntry("vqwiki/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/system.properties")); System.getProperties().store(jos, null); jos.closeEntry(); jos.close(); IOUtils.copy(new FileInputStream(jarFile), zos); zos.closeEntry(); zos.close(); jarFile.delete(); pcl = new PluginClassLoader(new File(testOutputDirectory, "/work")); pcl.addPlugin(pluginFile); } Code Sample 2: public static 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(); } }
00
Code Sample 1: private void copyFiles(File oldFolder, File newFolder) { for (File fileToCopy : oldFolder.listFiles()) { File copiedFile = new File(newFolder.getAbsolutePath() + "\\" + fileToCopy.getName()); try { FileInputStream source = new FileInputStream(fileToCopy); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.printStackTrace(); } } } Code Sample 2: public String doGet() throws MalformedURLException, IOException { uc = (HttpURLConnection) url.openConnection(); BufferedInputStream buffer = new BufferedInputStream(uc.getInputStream()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int c; while ((c = buffer.read()) != -1) { bos.write(c); } bos.close(); headers = uc.getHeaderFields(); status = uc.getResponseCode(); return bos.toString(); }
11
Code Sample 1: public static String hashPassword(String password) { String passwordHash = ""; try { MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); sha1.reset(); sha1.update(password.getBytes()); Base64 encoder = new Base64(); passwordHash = new String(encoder.encode(sha1.digest())); } catch (NoSuchAlgorithmException e) { LoggerFactory.getLogger(UmsAuthenticationProcessingFilter.class.getClass()).error("Failed to generate password hash: " + e.getMessage()); } return passwordHash; } Code Sample 2: public static final String getUniqueId() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { throw new RuntimeException("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) { throw new RuntimeException("NoSuchAlgorithmException : " + e.getMessage()); } return digest; }
00
Code Sample 1: public byte[] getHTTPByte(String sUrl) { HttpURLConnection connection = null; InputStream inputStream = null; ByteArrayOutputStream os = null; try { URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(); connection.connect(); int httpStatus = connection.getResponseCode(); if (httpStatus != 200) log.info("getHTTPConent error httpStatus - " + httpStatus); inputStream = new BufferedInputStream(connection.getInputStream()); os = new ByteArrayOutputStream(); InputStream is = new BufferedInputStream(inputStream); byte bytes[] = new byte[40960]; int nRead = -1; while ((nRead = is.read(bytes, 0, 40960)) > 0) { os.write(bytes, 0, nRead); } os.close(); is.close(); inputStream.close(); } catch (IOException e) { log.warn("SpiderUtil getHTTPConent IOException -> ", e); } finally { if (inputStream != null) try { os.close(); inputStream.close(); } catch (IOException e) { } } return os.toByteArray(); } Code Sample 2: public static void retrieveAttachments(RemoteAttachment[] attachments, String id, String projectName, String key, SimpleDateFormat formatter, java.sql.Connection connect) { if (attachments.length != 0) { for (RemoteAttachment attachment : attachments) { attachmentAuthor = attachment.getAuthor(); if (attachment.getCreated() != null) { attachmentCreated = formatter.format(attachment.getCreated().getTime()); } attachmentFileName = attachment.getFilename(); attachmentFileSize = attachment.getFilesize(); attachmentId = attachment.getId(); attachmentMimeType = attachment.getMimetype(); if (attachmentMimeType.startsWith("text")) { URL attachmentUrl; try { attachmentUrl = new URL("https://issues.apache.org/jira/secure/attachment/" + attachmentId + "/" + attachmentFileName); urlConnection = (HttpURLConnection) attachmentUrl.openConnection(); urlConnection.connect(); serverCode = urlConnection.getResponseCode(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (serverCode == 200) { actual = new File("../attachments/" + projectName + "/" + key); if (!actual.exists()) { actual.mkdirs(); } attachmentPath = "../attachments/" + projectName + "/" + key + "/" + attachmentFileName; BufferedInputStream bis; try { bis = new BufferedInputStream(urlConnection.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(attachmentPath)); byte[] b = new byte[1024]; int len = -1; while ((len = bis.read(b)) != -1) { if (len == 1024) { bos.write(b); } else { bos.write(b, 0, len); } } bos.close(); bis.close(); insertAttachment(connect, id); } catch (IOException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } } } }
11
Code Sample 1: public Object run() { List correctUsers = (List) JsonPath.query("select * from ? where name=?", usersTable(), username); if (correctUsers.size() == 0) { return new LoginException("user " + username + " not found"); } Persistable userObject = (Persistable) correctUsers.get(0); boolean alreadyHashed = false; boolean passwordMatch = password.equals(userObject.get(PASSWORD_FIELD)); if (!passwordMatch) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(((String) userObject.get(PASSWORD_FIELD)).getBytes()); passwordMatch = password.equals(new String(new Base64().encode(md.digest()))); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } alreadyHashed = true; } if (passwordMatch) { Logger.getLogger(User.class.toString()).info("User " + username + " has been authenticated"); User user = (User) userObject; try { if (alreadyHashed) user.currentTicket = password; else { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); user.currentTicket = new String(new Base64().encode(md.digest())); } } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return user; } else { Logger.getLogger(User.class.toString()).info("The password was incorrect for " + username); return new LoginException("The password was incorrect for user " + username + ". "); } } Code Sample 2: private static byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(frase.getBytes()); return md.digest(); } catch (Exception e) { return null; } }
00
Code Sample 1: public void connect() throws FTPException { try { ftp = new FTPClient(); ftp.connect(host); if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.login(this.username, this.password); } else { ftp.disconnect(); throw new FTPException("Não foi possivel se conectar no servidor FTP"); } isConnected = true; } catch (Exception ex) { throw new FTPException(ex); } } Code Sample 2: public static String executePost(String urlStr, String content) { StringBuffer result = new StringBuffer(); try { Authentication.doIt(); URL url = new URL(urlStr); System.out.println("Host: " + url.getHost()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); System.out.println("got connection "); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); connection.setRequestProperty("Content-Length", "" + content.length()); connection.setRequestProperty("SOAPAction", "\"http://niki-bt.act.cmis.csiro.org/SMSService/SendText\""); connection.setRequestMethod("POST"); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print(content); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { result.append(inputLine); } in.close(); out.close(); connection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String msg = result.toString(); if (msg != null) { int beginCut = msg.indexOf('>'); int endCut = msg.lastIndexOf('<'); if (beginCut != -1 && endCut != -1) { return msg.substring(beginCut + 1, endCut); } } return null; }
00
Code Sample 1: public APIResponse delete(String id) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/user/delete/" + id).openConnection(); connection.setRequestMethod("DELETE"); connection.setConnectTimeout(TIMEOUT); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { response.setDone(true); response.setMessage("User Deleted!"); } else { response.setDone(false); response.setMessage("Delete User Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; } Code Sample 2: private void readCard() { try { final String urlString = createURLStringExistRESTGetXQuery("//scheda[cata = \"" + cata + "\"]"); InputStream inputStream = new URL(urlString).openStream(); uiSchedaXml.read(inputStream); inputStream.close(); } catch (MalformedURLException e) { System.out.println(e); } catch (IOException e) { System.out.println(e); } }
00
Code Sample 1: public static void reset() throws Exception { Session session = DataStaticService.getHibernateSessionFactory().openSession(); try { Connection connection = session.connection(); try { Statement statement = connection.createStatement(); try { statement.executeUpdate("delete from Post"); connection.commit(); } finally { statement.close(); } } catch (HibernateException e) { connection.rollback(); throw new Exception(e); } catch (SQLException e) { connection.rollback(); throw new Exception(e); } } catch (SQLException e) { throw new Exception(e); } finally { session.close(); } } Code Sample 2: public static void convertEncoding(File infile, File outfile, String from, String to) throws IOException, UnsupportedEncodingException { InputStream in; if (infile != null) in = new FileInputStream(infile); else in = System.in; OutputStream out; outfile.createNewFile(); if (outfile != null) out = new FileOutputStream(outfile); else out = System.out; if (from == null) from = System.getProperty("file.encoding"); if (to == null) to = "Unicode"; Reader r = new BufferedReader(new InputStreamReader(in, from)); Writer w = new BufferedWriter(new OutputStreamWriter(out, to)); char[] buffer = new char[4096]; int len; while ((len = r.read(buffer)) != -1) w.write(buffer, 0, len); r.close(); w.close(); }
11
Code Sample 1: public boolean backupLastAuditSchema(File lastAuditSchema) { boolean isBkupFileOK = false; String writeTimestamp = DateFormatUtils.format(new java.util.Date(), configFile.getTimestampPattern()); File target = new File(configFile.getAuditSchemaFileDir() + File.separator + configFile.getAuditSchemaFileName() + ".bkup_" + writeTimestamp); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(lastAuditSchema).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException e) { logger.log(Level.SEVERE, "IO exception occurred while copying file", e); } finally { if ((target != null) && (target.exists()) && (target.length() > 0)) { isBkupFileOK = true; } try { if (sourceChannel != null) { sourceChannel.close(); } if (targetChannel != null) { targetChannel.close(); } } catch (IOException e) { logger.warning("closing channels failed"); } } return isBkupFileOK; } Code Sample 2: public BufferedWriter createWriter(File outfile, String encoding) throws UnsupportedEncodingException, IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outfile)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot; ZipInputStream zis = new ZipInputStream(new FileInputStream(infile)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit; 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(); return new BufferedWriter(new OutputStreamWriter(zos, "UTF-8")); }
11
Code Sample 1: public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>"); System.exit(1); } try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream in = new FileInputStream(args[1]); int len = 0; byte buf[] = new byte[1024]; while ((len = in.read(buf)) > 0) os.write(buf, 0, len); in.close(); os.close(); byte[] data = null; if (args[0].equals("dec")) data = decode(os.toString()); else { String strData = encode(os.toByteArray()); data = strData.getBytes(); } FileOutputStream fos = new FileOutputStream(args[2]); fos.write(data); fos.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static String getStringResponse(String urlString) throws Exception { URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; StringBuilder buffer = new StringBuilder(); while ((inputLine = in.readLine()) != null) { buffer.append(inputLine); } in.close(); return buffer.toString(); } Code Sample 2: private ArrayList<String> loadProperties(String filename) throws DevFailed, IOException { java.net.URL url = getClass().getResource(filename); if (url == null) { Except.throw_exception("LOAD_PROPERTY_FAILED", "URL for property file (" + filename + ") is null !", "PogoProperty.loadProperties()"); return null; } InputStream is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); ArrayList<String> vs = new ArrayList<String>(); String str; while ((str = br.readLine()) != null) { str = str.trim(); if (!str.startsWith("#")) if (str.length() > 0) vs.add(str); } br.close(); return vs; }
11
Code Sample 1: public int delete(BusinessObject o) throws DAOException { int delete = 0; Bill bill = (Bill) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_BILL")); pst.setInt(1, bill.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; } Code Sample 2: @Override public String addUser(UserInfoItem user) throws DatabaseException { if (user == null) throw new NullPointerException("user"); if (user.getSurname() == null || "".equals(user.getSurname())) throw new NullPointerException("user.getSurname()"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } String retID = "exist"; PreparedStatement insSt = null, updSt = null, seqSt = null; try { int modified = 0; if (user.getId() != null) { long id = Long.parseLong(user.getId()); updSt = getConnection().prepareStatement(UPDATE_USER_STATEMENT); updSt.setString(1, user.getName()); updSt.setString(2, user.getSurname()); updSt.setLong(3, id); modified = updSt.executeUpdate(); } else { insSt = getConnection().prepareStatement(INSERT_USER_STATEMENT); insSt.setString(1, user.getName()); insSt.setString(2, user.getSurname()); insSt.setBoolean(3, "m".equalsIgnoreCase(user.getSex())); modified = insSt.executeUpdate(); seqSt = getConnection().prepareStatement(USER_CURR_VALUE); ResultSet rs = seqSt.executeQuery(); while (rs.next()) { retID = rs.getString(1); } } if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + seqSt + "\" and \"" + (user.getId() != null ? updSt : insSt) + "\""); } else { getConnection().rollback(); LOGGER.debug("DB has not been updated. -> rollback! Queries: \"" + seqSt + "\" and \"" + (user.getId() != null ? updSt : insSt) + "\""); retID = "error"; } } catch (SQLException e) { LOGGER.error(e); retID = "error"; } finally { closeConnection(); } return retID; }
00
Code Sample 1: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } Code Sample 2: public static File copyFile(File file, String dirName) { File destDir = new File(dirName); if (!destDir.exists() || !destDir.isDirectory()) { destDir.mkdirs(); } File src = file; File dest = new File(dirName, src.getName()); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
00
Code Sample 1: public boolean authenticate(String user, String pass) throws IOException { MessageDigest hash = null; try { MessageDigest.getInstance("BrokenMD4"); } catch (NoSuchAlgorithmException x) { throw new Error(x); } hash.update(new byte[4], 0, 4); try { hash.update(pass.getBytes("US-ASCII"), 0, pass.length()); hash.update(challenge.getBytes("US-ASCII"), 0, challenge.length()); } catch (java.io.UnsupportedEncodingException shouldNeverHappen) { } String response = Util.base64(hash.digest()); Util.writeASCII(out, user + " " + response + '\n'); String reply = Util.readLine(in); if (reply.startsWith(RSYNCD_OK)) { authReqd = false; return true; } connected = false; error = reply; return false; } Code Sample 2: public static void copyFile(File destFile, File src) throws IOException { File destDir = destFile.getParentFile(); File tempFile = new File(destFile + "_tmp"); destDir.mkdirs(); InputStream is = new FileInputStream(src); try { FileOutputStream os = new FileOutputStream(tempFile); try { byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); } finally { os.close(); } } finally { is.close(); } destFile.delete(); if (!tempFile.renameTo(destFile)) throw new IOException("Unable to rename " + tempFile + " to " + destFile); }
00
Code Sample 1: public static String getHash(String text) { if (text == null) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); byte[] hashedTextBytes = md.digest(); BigInteger hashedTextBigInteger = new BigInteger(1, hashedTextBytes); String hashedTextString = hashedTextBigInteger.toString(16); return hashedTextString; } catch (NoSuchAlgorithmException e) { LOG.warning(e.toString()); return null; } } Code Sample 2: public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: public static boolean insert(final Cargo cargo) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into cargo (nome) values (?)"; pst = c.prepareStatement(sql); pst.setString(1, cargo.getNome()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { e1.printStackTrace(); } System.out.println("[CargoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } } Code Sample 2: private Object query(String json) throws IOException, ParseException { String envelope = "{\"qname1\":{\"query\":" + json + "}}"; String urlStr = MQLREADURL + "?queries=" + URLEncoder.encode(envelope, "UTF-8"); if (isDebugging()) { if (echoRequest) System.err.println("Sending:" + envelope); } URL url = new URL(urlStr); URLConnection con = url.openConnection(); con.setRequestProperty("Cookie", COOKIE + "=" + "\"" + getMetawebCookie() + "\""); con.connect(); InputStream in = con.getInputStream(); Object item = new JSONParser(echoRequest ? new EchoReader(in) : in).object(); in.close(); String code = getString(item, "code"); if (!"/api/status/ok".equals(code)) { throw new IOException("Bad code " + item); } code = getString(item, "qname1.code"); if (!"/api/status/ok".equals(code)) { throw new IOException("Bad code " + item); } return item; }
11
Code Sample 1: private static String getData(String myurl) throws Exception { System.out.println("getdata"); URL url = new URL(myurl); uc = (HttpURLConnection) url.openConnection(); br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String temp = "", k = ""; while ((temp = br.readLine()) != null) { System.out.println(temp); k += temp; } br.close(); return k; } Code Sample 2: protected boolean registerFromFile(URI providerList) { boolean registeredSomething = false; InputStream urlStream = null; try { urlStream = providerList.toURL().openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlStream, "UTF-8")); String provider; while ((provider = reader.readLine()) != null) { int comment = provider.indexOf('#'); if (comment != -1) { provider = provider.substring(0, comment); } provider = provider.trim(); if (provider.length() > 0) { try { registeredSomething |= registerAssoc(provider); } catch (Exception allElse) { if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { LOG.log(Level.WARNING, "Failed to register \'" + provider + "\'", allElse); } } } } } catch (IOException ex) { LOG.log(Level.WARNING, "Failed to read provider list " + providerList, ex); return false; } finally { if (null != urlStream) { try { urlStream.close(); } catch (IOException ignored) { } } } return registeredSomething; }
00
Code Sample 1: @Test public void testDocumentDownloadKnowledgeBase() throws IOException { if (uploadedKbDocumentID == null) { fail("Document Upload Test should run first"); } String downloadLink = GoogleDownloadLinkGenerator.generateTextDownloadLink(uploadedKbDocumentID); URL url = new URL(downloadLink); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); InputStream input = url.openStream(); FileWriter fw = new FileWriter("tmpOutput.kb"); Reader reader = new InputStreamReader(input); BufferedReader bufferedReader = new BufferedReader(reader); String strLine = ""; int count = 0; while (count < 10000) { strLine = bufferedReader.readLine(); if (strLine != null && strLine != "") { fw.write(strLine); } count++; } } Code Sample 2: 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; }
11
Code Sample 1: public static String hash(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(text.getBytes()); byte[] digest = md.digest(); StringBuffer sb = new StringBuffer(digest.length * 2); for (int i = 0; i < digest.length; ++i) { byte b = digest[i]; int high = (b & 0xF0) >> 4; int low = b & 0xF; sb.append(DECIMAL_HEX[high]); sb.append(DECIMAL_HEX[low]); } return sb.toString(); } catch (NoSuchAlgorithmException e) { throw new NonBusinessException("Error hashing string", e); } } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(128); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(32); for (int j = 0; j < array.length; ++j) { int b = array[j] & TWO_BYTES; if (b < PAD_BELOW) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { } }
00
Code Sample 1: private void weightAndPlaceClasses() { int rows = getRows(); for (int curRow = _maxPackageRank; curRow < rows; curRow++) { xPos = getHGap() / 2; BOTLRuleDiagramNode[] rowObject = getObjectsInRow(curRow); for (int i = 0; i < rowObject.length; i++) { if (curRow == _maxPackageRank) { int nDownlinks = rowObject[i].getDownlinks().size(); rowObject[i].setWeight((nDownlinks > 0) ? (1 / nDownlinks) : 2); } else { Vector uplinks = rowObject[i].getUplinks(); int nUplinks = uplinks.size(); if (nUplinks > 0) { float average_col = 0; for (int j = 0; j < uplinks.size(); j++) { average_col += ((BOTLRuleDiagramNode) (uplinks.elementAt(j))).getColumn(); } average_col /= nUplinks; rowObject[i].setWeight(average_col); } else { rowObject[i].setWeight(1000); } } } int[] pos = new int[rowObject.length]; for (int i = 0; i < pos.length; i++) { pos[i] = i; } boolean swapped = true; while (swapped) { swapped = false; for (int i = 0; i < pos.length - 1; i++) { if (rowObject[pos[i]].getWeight() > rowObject[pos[i + 1]].getWeight()) { int temp = pos[i]; pos[i] = pos[i + 1]; pos[i + 1] = temp; swapped = true; } } } for (int i = 0; i < pos.length; i++) { rowObject[pos[i]].setColumn(i); if ((i > _vMax) && (rowObject[pos[i]].getUplinks().size() == 0) && (rowObject[pos[i]].getDownlinks().size() == 0)) { if (getColumns(rows - 1) > _vMax) { rows++; } rowObject[pos[i]].setRank(rows - 1); } else { rowObject[pos[i]].setLocation(new Point(xPos, yPos)); xPos += rowObject[pos[i]].getSize().getWidth() + getHGap(); } } yPos += getRowHeight(curRow) + getVGap(); } } Code Sample 2: private static Reader getReader(String fname) throws IOException { InputStream is; if (isUrl(fname)) { URL url = new URL(fname); is = url.openStream(); } else { is = new FileInputStream(fname); } if (fname.endsWith(".zip")) { is = new ZipInputStream(is); } else if (fname.endsWith(".gz") || fname.endsWith(".gzip")) { is = new GZIPInputStream(is); } return new InputStreamReader(is); }
00
Code Sample 1: protected void createValueListAnnotation(IProgressMonitor monitor, IPackageFragment pack, Map model) throws CoreException { IProject pj = pack.getJavaProject().getProject(); QualifiedName qn = new QualifiedName(JstActivator.PLUGIN_ID, JstActivator.PACKAGE_INFO_LOCATION); String location = pj.getPersistentProperty(qn); if (location != null) { IFolder javaFolder = pj.getFolder(new Path(NexOpenFacetInstallDataModelProvider.WEB_SRC_MAIN_JAVA)); IFolder packageInfo = javaFolder.getFolder(location); if (!packageInfo.exists()) { Logger.log(Logger.INFO, "package-info package [" + location + "] does not exists."); Logger.log(Logger.INFO, "ValueList annotation will not be added by this wizard. " + "You must add manually in your package-info class if exist " + "or create a new one at location " + location); return; } IFile pkginfo = packageInfo.getFile("package-info.java"); if (!pkginfo.exists()) { Logger.log(Logger.INFO, "package-info class at location [" + location + "] does not exists."); return; } InputStream in = pkginfo.getContents(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { IOUtils.copy(in, baos); String content = new String(baos.toByteArray()); VelocityEngine engine = VelocityEngineHolder.getEngine(); model.put("adapterType", getAdapterType()); model.put("packageInfo", location.replace('/', '.')); model.put("defaultNumberPerPage", "5"); model.put("defaultSortDirection", "asc"); if (isFacadeAdapter()) { model.put("facadeType", "true"); } if (content.indexOf("@ValueLists({})") > -1) { appendValueList(monitor, model, pkginfo, content, engine, true); return; } else if (content.indexOf("@ValueLists") > -1) { appendValueList(monitor, model, pkginfo, content, engine, false); return; } String vl = VelocityEngineUtils.mergeTemplateIntoString(engine, "ValueList.vm", model); ByteArrayInputStream bais = new ByteArrayInputStream(vl.getBytes()); try { pkginfo.setContents(bais, true, false, monitor); } finally { bais.close(); } return; } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "I/O exception", e); throw new CoreException(status); } catch (VelocityException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "Velocity exception", e); throw new CoreException(status); } finally { try { baos.close(); in.close(); } catch (IOException e) { } } } Logger.log(Logger.INFO, "package-info location property does not exists."); } Code Sample 2: public void run() { OutputStream out = null; InputStream in = null; boolean success = false; String absoluteFileName = ""; try { String fileName = getFileName(softwareLocation); File downloadFolder = new File(Properties.downloadFolder); if (downloadFolder.exists()) { if (downloadFolder.isDirectory()) { fileName = downloadFolder.getPath() + File.separator + fileName; } } else { downloadFolder.mkdir(); fileName = downloadFolder.getPath() + File.separator + fileName; } File softwareFile = new File(fileName); absoluteFileName = softwareFile.getAbsolutePath(); if (softwareFile.exists() && softwareFile.length() == softwareSize) { XohmLogger.debugPrintln("Software file already exists. Exiting..."); listener.downloadComplete(true, softwareName, absoluteFileName); return; } else { try { File[] oldFiles = downloadFolder.listFiles(); for (int i = 0; i < oldFiles.length; i++) { oldFiles[i].delete(); } } catch (Exception ex) { } } File softwareTempFile = File.createTempFile("XOHMCM", null); URL url = new URL(softwareLocation); out = new BufferedOutputStream(new FileOutputStream(softwareTempFile)); URLConnection connection = url.openConnection(); in = connection.getInputStream(); listener.downloadStarted(softwareName); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; listener.downloadProgressNotification(softwareName, numWritten, softwareSize); } out.flush(); out.close(); in.close(); if (copyFile(softwareTempFile, softwareFile)) { XohmLogger.debugPrintln("Download complete: " + absoluteFileName + "\t" + numWritten); success = true; softwareTempFile.delete(); } } catch (Exception ex) { XohmLogger.warningPrintln("Software Update download failed - " + ex.getMessage(), null, null); ex.printStackTrace(); } listener.downloadComplete(success, softwareName, absoluteFileName); }
11
Code Sample 1: public long copyDirAllFilesToDirectory(String baseDirStr, String destDirStr) throws Exception { long plussQuotaSize = 0; if (baseDirStr.endsWith(sep)) { baseDirStr = baseDirStr.substring(0, baseDirStr.length() - 1); } if (destDirStr.endsWith(sep)) { destDirStr = destDirStr.substring(0, destDirStr.length() - 1); } FileUtils.getInstance().createDirectory(destDirStr); BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File baseDir = new File(baseDirStr); baseDir.mkdirs(); if (!baseDir.exists()) { createDirectory(baseDirStr); } if ((baseDir.exists()) && (baseDir.isDirectory())) { String[] entryList = baseDir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String oldPathFileName = baseDirStr + sep + entryName; File entryFile = new File(oldPathFileName); if (entryFile.isFile()) { String newPathFileName = destDirStr + sep + entryName; File newFile = new File(newPathFileName); if (newFile.exists()) { plussQuotaSize -= newFile.length(); newFile.delete(); } in = new BufferedInputStream(new FileInputStream(oldPathFileName), bufferSize); out = new BufferedOutputStream(new FileOutputStream(newPathFileName), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } } } } else { throw new Exception("Base dir not exist ! baseDirStr = (" + baseDirStr + ")"); } return plussQuotaSize; } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public void uploadFile(String filename) throws RQLException { checkFtpClient(); OutputStream out = null; try { out = ftpClient.storeFileStream(filename); IOUtils.copy(new FileReader(filename), out); out.close(); ftpClient.completePendingCommand(); } catch (IOException ex) { throw new RQLException("Upload of local file with name " + filename + " via FTP to server " + server + " failed.", ex); } } 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 void fileCopy(File sourceFile, File destFile) throws IOException { FileChannel source = null; FileChannel destination = null; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(sourceFile); fos = new FileOutputStream(destFile); source = fis.getChannel(); destination = fos.getChannel(); destination.transferFrom(source, 0, source.size()); } finally { fis.close(); fos.close(); if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: @Test public void testCopyOverSize() throws IOException { final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(TEST_DATA.length); final int cpySize = ExtraIOUtils.copy(in, out, TEST_DATA.length + Long.SIZE); assertEquals("Mismatched copy size", TEST_DATA.length, cpySize); final byte[] outArray = out.toByteArray(); assertArrayEquals("Mismatched data", TEST_DATA, outArray); }
11
Code Sample 1: public void run() { long starttime = (new Date()).getTime(); Matcher m = Pattern.compile("(\\S+);(\\d+)").matcher(Destination); boolean completed = false; if (OutFile.length() > IncommingProcessor.MaxPayload) { logger.warn("Payload is too large!"); close(); } else { if (m.find()) { Runnable cl = new Runnable() { public void run() { WaitToClose(); } }; Thread t = new Thread(cl); t.start(); S = null; try { String ip = m.group(1); int port = Integer.valueOf(m.group(2)); SerpentEngine eng = new SerpentEngine(); byte[] keybytes = new byte[eng.getBlockSize()]; byte[] ivbytes = new byte[eng.getBlockSize()]; Random.nextBytes(keybytes); Random.nextBytes(ivbytes); KeyParameter keyparm = new KeyParameter(keybytes); ParametersWithIV keyivparm = new ParametersWithIV(keyparm, ivbytes); byte[] parmbytes = BCUtils.writeParametersWithIV(keyivparm); OAEPEncoding enc = new OAEPEncoding(new ElGamalEngine(), new RIPEMD128Digest()); enc.init(true, PublicKey); byte[] encbytes = enc.encodeBlock(parmbytes, 0, parmbytes.length); PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new SerpentEngine())); cipher.init(true, keyivparm); byte[] inbuffer = new byte[128]; byte[] outbuffer = new byte[256]; int readlen = 0; int cryptlen = 0; FileInputStream fis = new FileInputStream(OutFile); FileOutputStream fos = new FileOutputStream(TmpFile); readlen = fis.read(inbuffer); while (readlen >= 0) { if (readlen > 0) { cryptlen = cipher.processBytes(inbuffer, 0, readlen, outbuffer, 0); fos.write(outbuffer, 0, cryptlen); } readlen = fis.read(inbuffer); } cryptlen = cipher.doFinal(outbuffer, 0); if (cryptlen > 0) { fos.write(outbuffer, 0, cryptlen); } fos.close(); fis.close(); S = new Socket(ip, port); DataOutputStream dos = new DataOutputStream(S.getOutputStream()); dos.writeInt(encbytes.length); dos.write(encbytes); dos.writeLong(TmpFile.length()); fis = new FileInputStream(TmpFile); readlen = fis.read(inbuffer); while (readlen >= 0) { dos.write(inbuffer, 0, readlen); readlen = fis.read(inbuffer); } DataInputStream dis = new DataInputStream(S.getInputStream()); byte[] encipbytes = StreamUtils.readBytes(dis); cipher.init(false, keyivparm); byte[] decipbytes = new byte[encipbytes.length]; int len = cipher.processBytes(encipbytes, 0, encipbytes.length, decipbytes, 0); len += cipher.doFinal(decipbytes, len); byte[] realbytes = new byte[len]; System.arraycopy(decipbytes, 0, realbytes, 0, len); String ipstr = new String(realbytes, "ISO-8859-1"); Callback.Success(ipstr); completed = true; dos.write(0); dos.flush(); close(); } catch (Exception e) { close(); if (!completed) { e.printStackTrace(); Callback.Fail(e.getMessage()); } } } else { close(); logger.warn("Improper destination string. " + Destination); Callback.Fail("Improper destination string. " + Destination); } } CloseWait(); long newtime = (new Date()).getTime(); long timediff = newtime - starttime; logger.debug("Outgoing processor took: " + timediff); } Code Sample 2: public static void copy(String sourceName, String destName) throws IOException { File src = new File(sourceName); File dest = new File(destName); BufferedInputStream source = null; BufferedOutputStream destination = null; byte[] buffer; int bytes_read; long byteCount = 0; if (!src.exists()) throw new IOException("Source not found: " + src); if (!src.canRead()) throw new IOException("Source is unreadable: " + src); if (src.isFile()) { if (!dest.exists()) { File parentdir = parent(dest); if (!parentdir.exists()) parentdir.mkdir(); } else if (dest.isDirectory()) { if (src.isDirectory()) dest = new File(dest + File.separator + src); else dest = new File(dest + File.separator + src.getName()); } } else if (src.isDirectory()) { if (dest.isFile()) throw new IOException("Cannot copy directory " + src + " to file " + dest); if (!dest.exists()) dest.mkdir(); } if ((!dest.canWrite()) && (dest.exists())) throw new IOException("Destination is unwriteable: " + dest); if (src.isFile()) { try { source = new BufferedInputStream(new FileInputStream(src)); destination = new BufferedOutputStream(new FileOutputStream(dest)); buffer = new byte[4096]; byteCount = 0; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } else if (src.isDirectory()) { String targetfile, target, targetdest; String[] files = src.list(); for (int i = 0; i < files.length; i++) { targetfile = files[i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File(target)).isDirectory()) { copy(new File(target).getCanonicalPath(), new File(targetdest).getCanonicalPath()); } else { try { byteCount = 0; source = new BufferedInputStream(new FileInputStream(target)); destination = new BufferedOutputStream(new FileOutputStream(targetdest)); buffer = new byte[4096]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } } } }
11
Code Sample 1: public static void copyFile(File from, File to) throws FileNotFoundException, IOException { requireFile(from); requireFile(to); if (to.isDirectory()) { to = new File(to, getFileName(from)); } FileChannel sourceChannel = new FileInputStream(from).getChannel(); FileChannel destinationChannel = new FileOutputStream(to).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public static String getTextFromPart(Part part) { try { if (part != null && part.getBody() != null) { InputStream in = part.getBody().getInputStream(); String mimeType = part.getMimeType(); if (mimeType != null && MimeUtility.mimeTypeMatches(mimeType, "text/*")) { ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); in = null; String charset = getHeaderParameter(part.getContentType(), "charset"); if (charset != null) { charset = CharsetUtil.toJavaCharset(charset); } if (charset == null) { charset = "ASCII"; } String result = out.toString(charset); out.close(); return result; } } } catch (OutOfMemoryError oom) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + oom.toString()); } catch (Exception e) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + e.toString()); } return null; }
11
Code Sample 1: public NamedList<Object> request(final SolrRequest request, ResponseParser processor) throws SolrServerException, IOException { HttpMethod method = null; InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = "/select"; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = _parser; } ModifiableSolrParams wparams = new ModifiableSolrParams(); wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); if (params == null) { params = wparams; } else { params = new DefaultSolrParams(wparams, params); } if (_invariantParams != null) { params = new DefaultSolrParams(_invariantParams, params); } int tries = _maxRetries + 1; try { while (tries-- > 0) { try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = _baseURL + path; boolean isMultipart = (streams != null && streams.size() > 1); if (streams == null || isMultipart) { PostMethod post = new PostMethod(url); post.getParams().setContentCharset("UTF-8"); if (!this.useMultiPartPost && !isMultipart) { post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = params.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = params.getParams(p); if (vals != null) { for (String v : vals) { if (this.useMultiPartPost || isMultipart) { parts.add(new StringPart(p, v, "UTF-8")); } else { post.addParameter(p, v); } } } } if (isMultipart) { int i = 0; for (ContentStream content : streams) { final ContentStream c = content; String charSet = null; String transferEncoding = null; parts.add(new PartBase(c.getName(), c.getContentType(), charSet, transferEncoding) { @Override protected long lengthOfData() throws IOException { return c.getSize(); } @Override protected void sendData(OutputStream out) throws IOException { Reader reader = c.getReader(); try { IOUtils.copy(reader, out); } finally { reader.close(); } } }); } } if (parts.size() > 0) { post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams())); } method = post; } else { String pstr = ClientUtils.toQueryString(params, false); PostMethod post = new PostMethod(url + pstr); final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setRequestEntity(new RequestEntity() { public long getContentLength() { return -1; } public String getContentType() { return contentStream[0].getContentType(); } public boolean isRepeatable() { return false; } public void writeRequest(OutputStream outputStream) throws IOException { ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream); } }); } else { is = contentStream[0].getStream(); post.setRequestEntity(new InputStreamRequestEntity(is, contentStream[0].getContentType())); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { method.releaseConnection(); method = null; if (is != null) { is.close(); } if ((tries < 1)) { throw r; } } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } method.setFollowRedirects(_followRedirects); method.addRequestHeader("User-Agent", AGENT); if (_allowCompression) { method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate")); } try { int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { StringBuilder msg = new StringBuilder(); msg.append(method.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append(method.getStatusText()); msg.append("\n\n"); msg.append("request: " + method.getURI()); throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8")); } String charset = "UTF-8"; if (method instanceof HttpMethodBase) { charset = ((HttpMethodBase) method).getResponseCharSet(); } InputStream respBody = method.getResponseBodyAsStream(); if (_allowCompression) { Header contentEncodingHeader = method.getResponseHeader("Content-Encoding"); if (contentEncodingHeader != null) { String contentEncoding = contentEncodingHeader.getValue(); if (contentEncoding.contains("gzip")) { respBody = new GZIPInputStream(respBody); } else if (contentEncoding.contains("deflate")) { respBody = new InflaterInputStream(respBody); } } else { Header contentTypeHeader = method.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { String contentType = contentTypeHeader.getValue(); if (contentType != null) { if (contentType.startsWith("application/x-gzip-compressed")) { respBody = new GZIPInputStream(respBody); } else if (contentType.startsWith("application/x-deflate")) { respBody = new InflaterInputStream(respBody); } } } } } return processor.processResponse(respBody, charset); } catch (HttpException e) { throw new SolrServerException(e); } catch (IOException e) { throw new SolrServerException(e); } finally { method.releaseConnection(); if (is != null) { is.close(); } } } 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 contextInitialized(ServletContextEvent event) { try { String osName = System.getProperty("os.name"); if (osName != null && osName.toLowerCase().contains("windows")) { URL url = new URL("http://localhost/"); URLConnection urlConn = url.openConnection(); urlConn.setDefaultUseCaches(false); } } catch (Throwable t) { } } Code Sample 2: private void initSerializerFiles(String fileName, HashSet<String> fileList, HashMap<Class, Class> classMap, Class type) { try { ClassLoader classLoader = getClassLoader(); if (classLoader == null) return; Enumeration iter; iter = classLoader.getResources(fileName); while (iter.hasMoreElements()) { URL url = (URL) iter.nextElement(); if (fileList.contains(url.toString())) continue; fileList.add(url.toString()); InputStream is = null; try { is = url.openStream(); Properties props = new Properties(); props.load(is); for (Map.Entry entry : props.entrySet()) { String apiName = (String) entry.getKey(); String serializerName = (String) entry.getValue(); Class apiClass = null; Class serializerClass = null; try { apiClass = Class.forName(apiName, false, classLoader); } catch (ClassNotFoundException e) { log.fine(url + ": " + apiName + " is not available in this context: " + getClassLoader()); continue; } try { serializerClass = Class.forName(serializerName, false, classLoader); } catch (ClassNotFoundException e) { log.fine(url + ": " + serializerName + " is not available in this context: " + getClassLoader()); continue; } if (!type.isAssignableFrom(serializerClass)) throw new HessianException(url + ": " + serializerClass.getName() + " is invalid because it does not implement " + type.getName()); classMap.put(apiClass, serializerClass); } } finally { if (is != null) is.close(); } } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new HessianException(e); } }
11
Code Sample 1: public static String generateMD5(String str) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { logger.log(Level.SEVERE, null, nsae); } return hashword; } Code Sample 2: protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletConfig config = getServletConfig(); ServletContext context = config.getServletContext(); try { String driver = context.getInitParameter("driver"); Class.forName(driver); String dbURL = context.getInitParameter("db"); String username = context.getInitParameter("username"); String password = ""; connection = DriverManager.getConnection(dbURL, username, password); } catch (ClassNotFoundException e) { System.out.println("Database driver not found."); } catch (SQLException e) { System.out.println("Error opening the db connection: " + e.getMessage()); } String action = ""; HttpSession session = request.getSession(); session.setMaxInactiveInterval(300); if (request.getParameter("action") != null) { action = request.getParameter("action"); } else { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/login.jsp"); dispatcher.forward(request, response); return; } if (action.equals("login")) { String username = request.getParameter("username"); String password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { error = "There was an error encrypting password."; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } try { md.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { error = "There was an error encrypting password."; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } String encrypted_password = (new BASE64Encoder()).encode(md.digest()); try { String sql = "SELECT * FROM person WHERE email LIKE '" + username + "' AND password='" + encrypted_password + "'"; dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); if (dbResultSet.next()) { Person person = new Person(dbResultSet.getString("fname"), dbResultSet.getString("lname"), dbResultSet.getString("address1"), dbResultSet.getString("address2"), dbResultSet.getString("city"), dbResultSet.getString("state"), dbResultSet.getString("zip"), dbResultSet.getString("email"), dbResultSet.getString("password"), dbResultSet.getInt("is_admin")); String member_type = dbResultSet.getString("member_type"); String person_id = Integer.toString(dbResultSet.getInt("id")); session.setAttribute("person", person); session.setAttribute("member_type", member_type); session.setAttribute("person_id", person_id); } else { notice = "Your username and/or password is incorrect."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } catch (SQLException e) { error = "There was an error trying to login. (SQL Statement)"; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Unable to log you in. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/login.jsp"); dispatcher.forward(request, response); return; } }
00
Code Sample 1: private void copy(File in, File out) { log.info("Copying yam file from: " + in.getName() + " to: " + out.getName()); try { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (IOException ioe) { fail("Failed testing while copying modified file: " + ioe.getMessage()); } } Code Sample 2: public void test_digest() throws UnsupportedEncodingException { MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA"); assertNotNull(sha); } catch (NoSuchAlgorithmException e) { fail("getInstance did not find algorithm"); } sha.update(MESSAGE.getBytes("UTF-8")); byte[] digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST)); sha.reset(); for (int i = 0; i < 63; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_63_As)); sha.reset(); for (int i = 0; i < 64; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_64_As)); sha.reset(); for (int i = 0; i < 65; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_65_As)); testSerializationSHA_DATA_1(sha); testSerializationSHA_DATA_2(sha); }
11
Code Sample 1: public static void copyCompletely(InputStream input, OutputStream output) throws IOException { if ((output instanceof FileOutputStream) && (input instanceof FileInputStream)) { try { FileChannel target = ((FileOutputStream) output).getChannel(); FileChannel source = ((FileInputStream) input).getChannel(); source.transferTo(0, Integer.MAX_VALUE, target); source.close(); target.close(); return; } catch (Exception e) { } } byte[] buf = new byte[8192]; while (true) { int length = input.read(buf); if (length < 0) break; output.write(buf, 0, length); } try { input.close(); } catch (IOException ignore) { } try { output.close(); } catch (IOException ignore) { } } Code Sample 2: private void copy(File srouceFile, File destinationFile) throws IOException { FileChannel sourceChannel = new FileInputStream(srouceFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
00
Code Sample 1: private void validateODFDoc(String url, String ver, ValidationReport commentary) throws IOException, MalformedURLException { logger.debug("Beginning document validation ..."); synchronized (ODFValidationSession.class) { PropertyMapBuilder builder = new PropertyMapBuilder(); String[] segments = url.split("/"); CommentatingErrorHandler h = new CommentatingErrorHandler(commentary, segments[segments.length - 1]); ValidateProperty.ERROR_HANDLER.put(builder, h); ValidationDriver driver = new ValidationDriver(builder.toPropertyMap()); InputStream candidateStream = null; try { logger.debug("Loading schema version " + ver); byte[] schemaBytes = getSchemaForVersion(ver); driver.loadSchema(new InputSource(new ByteArrayInputStream(schemaBytes))); URLConnection conn = new URL(url).openConnection(); candidateStream = conn.getInputStream(); logger.debug("Calling validate()"); commentary.incIndent(); boolean isValid = driver.validate(new InputSource(candidateStream)); logger.debug("Errors in instance:" + h.getInstanceErrCount()); if (h.getInstanceErrCount() > CommentatingErrorHandler.THRESHOLD) { commentary.addComment("(<i>" + (h.getInstanceErrCount() - CommentatingErrorHandler.THRESHOLD) + " error(s) omitted for the sake of brevity</i>)"); } commentary.decIndent(); if (isValid) { commentary.addComment("The document is valid"); } else { commentary.addComment("ERROR", "The document is invalid"); } } catch (SAXException e) { commentary.addComment("FATAL", "The resource is not conformant XML: " + e.getMessage()); logger.error(e.getMessage()); } finally { Utils.streamClose(candidateStream); } } } Code Sample 2: protected static Certificate[] getCurrentCertificates() throws Exception { Certificate[] certificate = AppletLoader.class.getProtectionDomain().getCodeSource().getCertificates(); if (certificate == null) { URL location = AppletLoader.class.getProtectionDomain().getCodeSource().getLocation(); JarURLConnection jurl = (JarURLConnection) (new URL("jar:" + location.toString() + "!/org/lwjgl/util/applet/AppletLoader.class").openConnection()); jurl.setDefaultUseCaches(true); certificate = jurl.getCertificates(); } return certificate; }
00
Code Sample 1: private void send(java.awt.event.ActionEvent evt) { String url = this.getURL(); if (url != null) { String tinyurl = ""; try { URLConnection conn = new URL("http://tinyurl.com/api-create.php?url=" + url).openConnection(); conn.setDoInput(true); conn.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); tinyurl = br.readLine(); } catch (SocketTimeoutException ste) { ste.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } String addresses = (String) this._model.getElementAt(0); for (int i = 1; i < this._model.getSize(); i++) addresses += "," + (String) this._model.getElementAt(i); SendDialog dialog = new SendDialog("Web Image Browser view", "To view, click the URL below\n\n" + url + "\n\n" + ((tinyurl != null) ? ("or\n\n" + tinyurl) : ""), addresses); dialog.setVisible(true); } else JOptionPane.showMessageDialog(this, "<html><center>" + "Sorry, but the file in<br>" + "\"" + this.path.getText() + "\"<br>" + "doesn't seem to be a valid " + "WIBShare-able file." + "</center></html>", "WIBShare Error", JOptionPane.ERROR_MESSAGE); } Code Sample 2: public Properties load() { Properties lvProperties = new Properties(); try { InputStream lvInputStream = url.openStream(); lvProperties.load(lvInputStream); } catch (Exception e) { throw new PropertiesLoadException("Error in load-method:", e); } return lvProperties; }
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 BasePolicy(String flaskPath) throws Exception { SWIGTYPE_p_p_policy p_p_pol = apol.new_policy_t_p_p(); if (!flaskPath.endsWith("/")) flaskPath += "/"; File tmpPolConf = File.createTempFile("tmpBasePolicy", ".conf"); BufferedWriter tmpPolFile = new BufferedWriter(new FileWriter(tmpPolConf)); BufferedReader secClassFile = new BufferedReader(new FileReader(flaskPath + "security_classes")); int bufSize = 1024; char[] buffer = new char[bufSize]; int read; while ((read = secClassFile.read(buffer)) > 0) { tmpPolFile.write(buffer, 0, read); } secClassFile.close(); BufferedReader sidsFile = new BufferedReader(new FileReader(flaskPath + "initial_sids")); while ((read = sidsFile.read(buffer)) > 0) { tmpPolFile.write(buffer, 0, read); } sidsFile.close(); BufferedReader axxVecFile = new BufferedReader(new FileReader(flaskPath + "access_vectors")); while ((read = axxVecFile.read(buffer)) > 0) { tmpPolFile.write(buffer, 0, read); } axxVecFile.close(); tmpPolFile.write("attribute ricka; \ntype rick_t; \nrole rick_r types rick_t; \nuser rick_u roles rick_r;\nsid kernel rick_u:rick_r:rick_t\nfs_use_xattr ext3 rick_u:rick_r:rick_t;\ngenfscon proc / rick_u:rick_r:rick_t\n"); tmpPolFile.flush(); tmpPolFile.close(); if (apol.open_policy(tmpPolConf.getAbsolutePath(), p_p_pol) == 0) { Policy = apol.policy_t_p_p_value(p_p_pol); if (Policy == null) { throw new Exception("Failed to allocate memory for policy_t struct."); } tmpPolConf.delete(); } else { throw new IOException("Failed to open/parse base policy file: " + tmpPolConf.getAbsolutePath()); } }
11
Code Sample 1: public static final void main(String[] args) throws FileNotFoundException, IOException { ArrayList<String[]> result = new ArrayList<String[]>(); IStream is = new StreamImpl(); IOUtils.copy(new FileInputStream("H:\\7-项目预算表.xlsx"), is.getOutputStream()); int count = loadExcel(result, is, 0, 0, -1, 16, 1); System.out.println(count); for (String[] rs : result) { for (String r : rs) { System.out.print(r + "\t"); } System.out.println(); } } Code Sample 2: public static void copyFile(IPath fromFileName, IPath toFileName) throws IOException { File fromFile = fromFileName.toFile(); File toFile = toFileName.toFile(); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } InputStream from = null; OutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(fromFile)); to = new BufferedOutputStream(new FileOutputStream(toFile)); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { } if (to != null) try { to.close(); } catch (IOException e) { } } }
11
Code Sample 1: public static void main(String[] args) throws Exception { PatternLayout pl = new PatternLayout("%d{ISO8601} %-5p %c: %m\n"); ConsoleAppender ca = new ConsoleAppender(pl); Logger.getRoot().addAppender(ca); Logger.getRoot().setLevel(Level.INFO); Options options = new Options(); options.addOption("p", "put", false, "put a file in the DHT overlay"); options.addOption("g", "get", false, "get a file from the DHT"); options.addOption("r", "remove", false, "remove a file from the DHT"); options.addOption("u", "update", false, "updates the lease"); options.addOption("j", "join", false, "join the DHT overlay"); options.addOption("c", "config", true, "the configuration file"); options.addOption("k", "key", true, "the key to read a file from"); options.addOption("f", "file", true, "the file to read or write"); options.addOption("a", "app", true, "the application ID"); options.addOption("s", "secret", true, "the secret used to hide data"); options.addOption("t", "ttl", true, "how long in seconds data should persist"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); String configFile = null; String mode = null; String secretStr = null; int ttl = 9999; String keyStr = null; String file = null; int appId = 0; if (cmd.hasOption("j")) { mode = "join"; } if (cmd.hasOption("p")) { mode = "put"; } if (cmd.hasOption("g")) { mode = "get"; } if (cmd.hasOption("r")) { mode = "remove"; } if (cmd.hasOption("u")) { mode = "update"; } if (cmd.hasOption("c")) { configFile = cmd.getOptionValue("c"); } if (cmd.hasOption("k")) { keyStr = cmd.getOptionValue("k"); } if (cmd.hasOption("f")) { file = cmd.getOptionValue("f"); } if (cmd.hasOption("s")) { secretStr = cmd.getOptionValue("s"); } if (cmd.hasOption("t")) { ttl = Integer.parseInt(cmd.getOptionValue("t")); } if (cmd.hasOption("a")) { appId = Integer.parseInt(cmd.getOptionValue("a")); } if (mode == null) { System.err.println("ERROR: --put or --get or --remove or --join or --update is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (configFile == null) { System.err.println("ERROR: --config is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } Properties conf = new Properties(); conf.load(new FileInputStream(configFile)); DHT dht = new DHT(conf); if (mode.equals("join")) { dht.join(); } else if (mode.equals("put")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("putting file " + file); FileInputStream in = new FileInputStream(file); byte[] tmp = new byte[1000000]; int num = in.read(tmp); byte[] value = new byte[num]; System.arraycopy(tmp, 0, value, 0, num); in.close(); if (dht.put((short) appId, keyStr.getBytes(), value, ttl, secretStr.getBytes()) < 0) { logger.info("There was an error while putting a key-value."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("get")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("getting file " + file); ArrayList<byte[]> values = new ArrayList<byte[]>(); if (dht.get((short) appId, keyStr.getBytes(), Integer.MAX_VALUE, values) < 0) { logger.info("There was an error while getting a value."); System.exit(0); } if (values.size() == 0 || values == null) { System.out.println("No values returned."); System.exit(0); } FileOutputStream out = new FileOutputStream(file); System.out.println("Found " + values.size() + " values -- saving the first one only."); out.write(values.get(0)); out.close(); System.out.println("Ok!"); } else if (mode.equals("remove")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("removing <key,value> for key=" + keyStr); if (dht.remove((short) appId, keyStr.getBytes(), secretStr.getBytes()) < 0) { logger.info("There was an error while removing a key."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("update")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("updating <key,value> for key=" + keyStr); if (dht.updateLease((short) appId, keyStr.getBytes(), ttl) < 0) { logger.info("There was an error while updating data lease."); System.exit(0); } System.out.println("Ok!"); } DHT.getInstance().stop(); } Code Sample 2: private static void copyFile(String srFile, String dtFile) { try { File f1 = new File(srFile); File f2 = new File(dtFile); InputStream in = new FileInputStream(f1); OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } catch (FileNotFoundException ex) { System.out.println("Error copying " + srFile + " to " + dtFile); System.out.println(ex.getMessage() + " in the specified directory."); } catch (IOException e) { System.out.println(e.getMessage()); } }
00
Code Sample 1: protected static String fileName2md5(String input) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(input.getBytes("iso-8859-1")); byte[] byteHash = md.digest(); md.reset(); StringBuffer resultString = new StringBuffer(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); } catch (Exception ex) { Logger.error(ex.getClass() + " " + ex.getMessage()); for (int i = 0; i < ex.getStackTrace().length; i++) Logger.error(" " + ex.getStackTrace()[i].toString()); ex.printStackTrace(); } return String.valueOf(Math.random() * Long.MAX_VALUE); } Code Sample 2: public static void main(String[] args) { Usage u = new ccngetmeta(); for (int i = 0; i < args.length - 3; i++) { if (!CommonArguments.parseArguments(args, i, u)) { u.usage(); System.exit(1); } if (CommonParameters.startArg > i + 1) i = CommonParameters.startArg - 1; } if (args.length != CommonParameters.startArg + 3) { u.usage(); System.exit(1); } try { int readsize = 1024; CCNHandle handle = CCNHandle.open(); String metaArg = args[CommonParameters.startArg + 1]; if (!metaArg.startsWith("/")) metaArg = "/" + metaArg; ContentName fileName = MetadataProfile.getLatestVersion(ContentName.fromURI(args[CommonParameters.startArg]), ContentName.fromNative(metaArg), CommonParameters.timeout, handle); if (fileName == null) { System.out.println("File " + args[CommonParameters.startArg] + " does not exist"); System.exit(1); } if (VersioningProfile.hasTerminalVersion(fileName)) { } else { System.out.println("File " + fileName + " does not exist... exiting"); System.exit(1); } File theFile = new File(args[CommonParameters.startArg + 2]); if (theFile.exists()) { System.out.println("Overwriting file: " + args[CommonParameters.startArg + 1]); } FileOutputStream output = new FileOutputStream(theFile); long starttime = System.currentTimeMillis(); CCNInputStream input; if (CommonParameters.unversioned) input = new CCNInputStream(fileName, handle); else input = new CCNFileInputStream(fileName, handle); if (CommonParameters.timeout != null) { input.setTimeout(CommonParameters.timeout); } byte[] buffer = new byte[readsize]; int readcount = 0; long readtotal = 0; while ((readcount = input.read(buffer)) != -1) { readtotal += readcount; output.write(buffer, 0, readcount); output.flush(); } if (CommonParameters.verbose) System.out.println("ccngetfile took: " + (System.currentTimeMillis() - starttime) + "ms"); System.out.println("Retrieved content " + args[CommonParameters.startArg + 1] + " got " + readtotal + " bytes."); System.exit(0); } catch (ConfigurationException e) { System.out.println("Configuration exception in ccngetfile: " + e.getMessage()); e.printStackTrace(); } catch (MalformedContentNameStringException e) { System.out.println("Malformed name: " + args[CommonParameters.startArg] + " " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println("Cannot write file or read content. " + e.getMessage()); e.printStackTrace(); } System.exit(1); }
00
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void testAutoIncrement() { final int count = 3; final Object lock = new Object(); for (int i = 0; i < count; i++) { new Thread(new Runnable() { @Override public void run() { while (true) { StringBuilder buffer = new StringBuilder(128); buffer.append("insert into DOMAIN ( ").append(LS); buffer.append(" DOMAIN_ID, TOP_DOMAIN_ID, DOMAIN_HREF, ").append(LS); buffer.append(" DOMAIN_RANK, DOMAIN_TYPE, DOMAIN_STATUS, ").append(LS); buffer.append(" DOMAIN_ICO_CREATED, DOMAIN_CDATE ").append(LS); buffer.append(") values ( ").append(LS); buffer.append(" null ,null, ?,").append(LS); buffer.append(" 1, 2, 1, ").append(LS); buffer.append(" 0, now() ").append(LS); buffer.append(") ").append(LS); String sqlInsert = buffer.toString(); boolean isAutoCommit = false; int i = 0; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = ConnHelper.getConnection(); conn.setAutoCommit(isAutoCommit); pstmt = conn.prepareStatement(sqlInsert); for (i = 0; i < 10; i++) { String lock = "" + ((int) (Math.random() * 100000000)) % 100; pstmt.setString(1, lock); pstmt.executeUpdate(); } if (!isAutoCommit) conn.commit(); rs = pstmt.executeQuery("select max(DOMAIN_ID) from DOMAIN"); if (rs.next()) { String str = System.currentTimeMillis() + " " + rs.getLong(1); } } catch (Exception e) { try { if (!isAutoCommit) conn.rollback(); } catch (SQLException ex) { ex.printStackTrace(System.out); } String msg = System.currentTimeMillis() + " " + Thread.currentThread().getName() + " - " + i + " " + e.getMessage() + LS; FileIO.writeToFile("D:/DEAD_LOCK.txt", msg, true, "GBK"); } finally { ConnHelper.close(conn, pstmt, rs); } } } }).start(); } }
11
Code Sample 1: public boolean updatenum(int num, String pid) { boolean flag = false; Connection conn = null; PreparedStatement pm = null; try { conn = Pool.getConnection(); conn.setAutoCommit(false); pm = conn.prepareStatement("update addwuliao set innum=? where pid=?"); pm.setInt(1, num); pm.setString(2, pid); int a = pm.executeUpdate(); if (a == 0) { flag = false; } else { flag = true; } conn.commit(); Pool.close(pm); Pool.close(conn); } catch (Exception e) { e.printStackTrace(); flag = false; try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } Pool.close(pm); Pool.close(conn); } finally { Pool.close(pm); Pool.close(conn); } return flag; } Code Sample 2: public ProgramSymbol createNewProgramSymbol(int programID, String module, String symbol, int address, int size) throws AdaptationException { ProgramSymbol programSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "INSERT INTO ProgramSymbols " + "(programID, module, symbol, address, size)" + " VALUES (" + programID + ", '" + module + "', '" + symbol + "', " + address + ", " + size + ")"; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * FROM ProgramSymbols WHERE " + "programID = " + programID + " AND " + "module = '" + module + "' AND " + "symbol = '" + symbol + "'"; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to create program symbol failed."; log.error(msg); throw new AdaptationException(msg); } programSymbol = getProgramSymbol(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in createNewProgramSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return programSymbol; }
11
Code Sample 1: public Object execute(ExecutionEvent event) throws ExecutionException { try { Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); QuizTreeView view = (QuizTreeView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("org.rcpquizengine.views.quizzes"); Folder rootFolder = view.getRootFolder(); if (!rootFolder.isEncrypted()) { PasswordDialog dialog = new PasswordDialog(shell); if (dialog.open() == Window.OK) { String password = dialog.getPassword(); if (!password.equals("")) { String md5 = ""; MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); md5 = new BigInteger(md.digest()).toString(); rootFolder.setMd5Digest(md5); rootFolder.setEncrypted(true); MessageDialog.openInformation(shell, "Quiz bank locked", "The current quiz bank has been locked"); password = ""; md5 = ""; } } } else { MessageDialog.openError(shell, "Error locking quiz bank", "Quiz bank already locked"); } } catch (PartInitException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } Code Sample 2: public static String generate(String documentSelector) { if (documentSelector == null) { return null; } String date = Long.toString(System.currentTimeMillis()); try { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(documentSelector.getBytes()); md.update(date.getBytes()); byte[] digest = md.digest(); return toHexString(digest); } catch (NoSuchAlgorithmException e) { return null; } }
00
Code Sample 1: public void update() { if (url == null) { throw new IllegalArgumentException("URL cannot be null!"); } try { URLConnection urlConnection = url.openConnection(); urlConnection.setRequestProperty("User-Agent", Settings.INSTANCE.getUserAgent()); SyndFeedInput input = new SyndFeedInput(); SyndFeed syndFeed = input.build(new XmlReader(url)); Channel channel = (Channel) syndFeed.createWireFeed(syndFeed.getFeedType()); long lastModified = urlConnection.getLastModified(); if (feed.getLastModified() != lastModified) { Server.print("Updating: " + feed.getName()); feed.setLastModified(lastModified); ArrayList<String> cachedItems = getCachedItems(); List<Item> items = channel.getItems(); if (items.isEmpty()) { return; } if (cachedItems.isEmpty()) { Database.INSTANCE.addItems(feed, items); } else { for (Item item : items) { if (!cachedItems.contains(item.getTitle())) { Database.INSTANCE.addItem(feed, item); } } } cacheItems(items); Settings.INSTANCE.persist(); Server.print("Done updating: " + feed.getName()); } } catch (ConnectException e) { Server.print("Could not connect to \"" + feed.getName() + "\""); } catch (SocketException e) { Server.print("Could not connect to \"" + feed.getName() + "\""); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: void execute(Connection conn, Component parent, String context, final ProgressMonitor progressMonitor, ProgressWrapper progressWrapper) throws Exception { int noOfComponents = m_components.length; Statement statement = null; StringBuffer pmNoteBuf = new StringBuffer(m_update ? "Updating " : "Creating "); pmNoteBuf.append(m_itemNameAbbrev); pmNoteBuf.append(" "); pmNoteBuf.append(m_itemNameValue); final String pmNote = pmNoteBuf.toString(); progressMonitor.setNote(pmNote); try { conn.setAutoCommit(false); int id = -1; if (m_update) { statement = conn.createStatement(); String sql = getUpdateSql(noOfComponents, m_id); statement.executeUpdate(sql); id = m_id; if (m_indexesChanged) deleteComponents(conn, id); } else { PreparedStatement pStmt = getInsertPrepStmt(conn, noOfComponents); pStmt.executeUpdate(); Integer res = DbCommon.getAutoGenId(parent, context, pStmt); if (res == null) return; id = res.intValue(); } if (!m_update || m_indexesChanged) { PreparedStatement insertCompPrepStmt = conn.prepareStatement(getInsertComponentPrepStmtSql()); for (int i = 0; i < noOfComponents; i++) { createComponent(progressMonitor, m_components, pmNote, id, i, insertCompPrepStmt); } } conn.commit(); m_itemTable.getPrimaryId().setVal(m_item, id); m_itemCache.updateCache(m_item, id); } catch (SQLException ex) { try { conn.rollback(); } catch (SQLException e) { e.printStackTrace(); } throw ex; } finally { if (statement != null) { statement.close(); } } }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { BufferedInputStream is = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[1024]; int count = 0; while ((count = is.read(buf, 0, 1024)) != -1) os.write(buf, 0, count); is.close(); os.close(); } Code Sample 2: JcrFile createBody(Part part) throws IOException, MessagingException { JcrFile body = new JcrFile(); body.setName("part"); ByteArrayOutputStream pout = new ByteArrayOutputStream(); IOUtils.copy(part.getInputStream(), pout); body.setDataProvider(new JcrDataProviderImpl(TYPE.BYTES, pout.toByteArray())); body.setMimeType(part.getContentType()); body.setLastModified(java.util.Calendar.getInstance()); return body; }
00
Code Sample 1: @Override protected void processImport() throws SudokuInvalidFormatException { importFolder(mUri.getLastPathSegment()); try { URL url = new URL(mUri.toString()); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = null; try { br = new BufferedReader(isr); String s; while ((s = br.readLine()) != null) { if (!s.equals("")) { importGame(s); } } } finally { if (br != null) br.close(); } } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } Code Sample 2: @Override public void run() { try { IOUtils.copy(_is, processOutStr); } catch (final IOException ioe) { proc.destroy(); } finally { IOUtils.closeQuietly(_is); IOUtils.closeQuietly(processOutStr); } }
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 void readData() throws IOException { i = 0; j = 0; URL url = getClass().getResource("resources/tuneGridMaster.dat"); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); s = br.readLine(); StringTokenizer st = new StringTokenizer(s); tune_x[i][j] = Double.parseDouble(st.nextToken()); gridmin = tune_x[i][j]; temp_prev = tune_x[i][j]; tune_y[i][j] = Double.parseDouble(st.nextToken()); kd[i][j] = Double.parseDouble(st.nextToken()); kfs[i][j] = Double.parseDouble(st.nextToken()); kfl[i][j] = Double.parseDouble(st.nextToken()); kdee[i][j] = Double.parseDouble(st.nextToken()); kdc[i][j] = Double.parseDouble(st.nextToken()); kfc[i][j] = Double.parseDouble(st.nextToken()); j++; int k = 0; while ((s = br.readLine()) != null) { st = new StringTokenizer(s); temp_new = Double.parseDouble(st.nextToken()); if (temp_new != temp_prev) { temp_prev = temp_new; i++; j = 0; } tune_x[i][j] = temp_new; tune_y[i][j] = Double.parseDouble(st.nextToken()); kd[i][j] = Double.parseDouble(st.nextToken()); kfs[i][j] = Double.parseDouble(st.nextToken()); kfl[i][j] = Double.parseDouble(st.nextToken()); kdee[i][j] = Double.parseDouble(st.nextToken()); kdc[i][j] = Double.parseDouble(st.nextToken()); kfc[i][j] = Double.parseDouble(st.nextToken()); imax = i; jmax = j; j++; k++; } gridmax = tune_x[i][j - 1]; }
00
Code Sample 1: public void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } } Code Sample 2: public static void main(String[] args) { boolean rotateLeft = false; boolean rotateRight = false; boolean exclude = false; boolean reset = false; float quality = 0f; int thumbArea = 12000; for (int i = 0; i < args.length; i++) { if (args[i].equals("-rotl")) rotateLeft = true; else if (args[i].equals("-rotr")) rotateRight = true; else if (args[i].equals("-exclude")) exclude = true; else if (args[i].equals("-reset")) reset = true; else if (args[i].equals("-quality")) quality = Float.parseFloat(args[++i]); else if (args[i].equals("-area")) thumbArea = Integer.parseInt(args[++i]); else { File f = new File(args[i]); try { Tools t = new Tools(f); if (exclude) { URL url = t.getClass().getResource("exclude.jpg"); InputStream is = url.openStream(); File dest = t.getExcludeFile(); OutputStream os = new FileOutputStream(dest); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); t.getOutFile().delete(); t.getThumbFile().delete(); System.exit(0); } if (reset) { t.getOutFile().delete(); t.getThumbFile().delete(); t.getExcludeFile().delete(); System.exit(0); } if (quality > 0) t.setQuality(quality); if (t.getType() == Tools.THUMB || t.getType() == Tools.EXCLUDE) t.load(t.getBaseFile()); else t.load(t.getSourceFile()); File out = t.getOutFile(); if (rotateLeft) t.rotateLeft(); else if (rotateRight) t.rotateRight(); t.save(out); t.getExcludeFile().delete(); t.getThumbFile().delete(); System.exit(0); } catch (Throwable e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "The operation could not be performed", "JPhotoAlbum", JOptionPane.ERROR_MESSAGE); System.exit(1); } } } }
11
Code Sample 1: @Override public void run() { try { File[] inputFiles = new File[this.previousFiles != null ? this.previousFiles.length + 1 : 1]; File copiedInput = new File(this.randomFolder, this.inputFile.getName()); IOUtils.copyFile(this.inputFile, copiedInput); inputFiles[inputFiles.length - 1] = copiedInput; if (previousFiles != null) { for (int i = 0; i < this.previousFiles.length; i++) { File prev = this.previousFiles[i]; File copiedPrev = new File(this.randomFolder, prev.getName()); IOUtils.copyFile(prev, copiedPrev); inputFiles[i] = copiedPrev; } } org.happycomp.radiog.Activator activator = org.happycomp.radiog.Activator.getDefault(); if (this.exportedMP3File != null) { EncodingUtils.encodeToWavAndThenMP3(inputFiles, this.exportedWavFile, this.exportedMP3File, this.deleteOnExit, this.randomFolder, activator.getCommandsMap()); } else { EncodingUtils.encodeToWav(inputFiles, this.exportedWavFile, randomFolder, activator.getCommandsMap()); } if (encodeMonitor != null) { encodeMonitor.setEncodingFinished(true); } } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } Code Sample 2: private long generateUnixInstallShell(File unixShellFile, String instTemplate, File instClassFile) throws IOException { FileOutputStream byteWriter = new FileOutputStream(unixShellFile); InputStream is = getClass().getResourceAsStream("/" + instTemplate); InputStreamReader isr = new InputStreamReader(is); LineNumberReader reader = new LineNumberReader(isr); String content = ""; String installClassStartStr = "000000000000"; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(installClassStartStr.length()); int installClassStartPos = 0; long installClassOffset = 0; System.out.println(VAGlobals.i18n("VAArchiver_GenerateInstallShell")); String line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassStart"))) { content += line + "\n"; line = reader.readLine(); } content += "InstallClassStart=" + installClassStartStr + "\n"; installClassStartPos = content.length() - 1 - 1 - installClassStartStr.length(); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassSize"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassSize=" + instClassFile.length() + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassName"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassName=" + instClassName_ + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# Install class"))) { content += line + "\n"; line = reader.readLine(); } if (line != null) content += line + "\n"; byteWriter.write(content.substring(0, installClassStartPos + 1).getBytes()); byteWriter.write(nf.format(content.length()).getBytes()); byteWriter.write(content.substring(installClassStartPos + 1 + installClassStartStr.length()).getBytes()); installClassOffset = content.length(); content = null; FileInputStream classStream = new FileInputStream(instClassFile); byte[] buf = new byte[2048]; int read = classStream.read(buf); while (read > 0) { byteWriter.write(buf, 0, read); read = classStream.read(buf); } classStream.close(); reader.close(); byteWriter.close(); return installClassOffset; }
00
Code Sample 1: public void importarHistoricoDeCotacoesDosPapeis(File[] pArquivosTXT, boolean pApagarDadosImportadosAnteriormente, Andamento pAndamento) throws FileNotFoundException, SQLException { if (pApagarDadosImportadosAnteriormente) { Statement stmtLimpezaInicialDestino = conDestino.createStatement(); String sql = "TRUNCATE TABLE TMP_TB_COTACAO_AVISTA_LOTE_PDR"; stmtLimpezaInicialDestino.executeUpdate(sql); sql = "TRUNCATE TABLE TMP_TB_COTACAO_OUTROS_MERCADOS"; stmtLimpezaInicialDestino.executeUpdate(sql); } final int TAMANHO_DO_REGISTRO = 245; long TAMANHO_DOS_METADADOS_DO_ARQUIVO = 2 * TAMANHO_DO_REGISTRO; long tamanhoDosArquivos = 0; for (File arquivoTXT : pArquivosTXT) { long tamanhoDoArquivo = arquivoTXT.length(); tamanhoDosArquivos += tamanhoDoArquivo; } int quantidadeEstimadaDeRegistros = (int) ((tamanhoDosArquivos - (pArquivosTXT.length * TAMANHO_DOS_METADADOS_DO_ARQUIVO)) / TAMANHO_DO_REGISTRO); String sqlMercadoAVistaLotePadrao = "INSERT INTO TMP_TB_COTACAO_AVISTA_LOTE_PDR(DATA_PREGAO, CODBDI, CODNEG, TPMERC, NOMRES, ESPECI, PRAZOT, MODREF, PREABE, PREMAX, PREMIN, PREMED, PREULT, PREOFC, PREOFV, TOTNEG, QUATOT, VOLTOT, PREEXE, INDOPC, DATVEN, FATCOT, PTOEXE, CODISI, DISMES) VALUES(:DATA_PREGAO, :CODBDI, :CODNEG, :TPMERC, :NOMRES, :ESPECI, :PRAZOT, :MODREF, :PREABE, :PREMAX, :PREMIN, :PREMED, :PREULT, :PREOFC, :PREOFV, :TOTNEG, :QUATOT, :VOLTOT, :PREEXE, :INDOPC, :DATVEN, :FATCOT, :PTOEXE, :CODISI, :DISMES)"; OraclePreparedStatement stmtDestinoMercadoAVistaLotePadrao = (OraclePreparedStatement) conDestino.prepareStatement(sqlMercadoAVistaLotePadrao); stmtDestinoMercadoAVistaLotePadrao.setExecuteBatch(COMANDOS_POR_LOTE); String sqlOutrosMercados = "INSERT INTO TMP_TB_COTACAO_OUTROS_MERCADOS(DATA_PREGAO, CODBDI, CODNEG, TPMERC, NOMRES, ESPECI, PRAZOT, MODREF, PREABE, PREMAX, PREMIN, PREMED, PREULT, PREOFC, PREOFV, TOTNEG, QUATOT, VOLTOT, PREEXE, INDOPC, DATVEN, FATCOT, PTOEXE, CODISI, DISMES) VALUES(:DATA_PREGAO, :CODBDI, :CODNEG, :TPMERC, :NOMRES, :ESPECI, :PRAZOT, :MODREF, :PREABE, :PREMAX, :PREMIN, :PREMED, :PREULT, :PREOFC, :PREOFV, :TOTNEG, :QUATOT, :VOLTOT, :PREEXE, :INDOPC, :DATVEN, :FATCOT, :PTOEXE, :CODISI, :DISMES)"; OraclePreparedStatement stmtDestinoOutrosMercados = (OraclePreparedStatement) conDestino.prepareStatement(sqlOutrosMercados); stmtDestinoOutrosMercados.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosImportadosDosArquivos = 0; Scanner in = null; int numeroDoRegistro = -1; try { for (File arquivoTXT : pArquivosTXT) { int quantidadeDeRegistrosImportadosDoArquivoAtual = 0; int vDATA_PREGAO; try { in = new Scanner(new FileInputStream(arquivoTXT), Constantes.CONJUNTO_DE_CARACTERES_DOS_ARQUIVOS_TEXTO_DA_BOVESPA.name()); String registro; numeroDoRegistro = 0; while (in.hasNextLine()) { ++numeroDoRegistro; registro = in.nextLine(); if (registro.length() != TAMANHO_DO_REGISTRO) throw new ProblemaNaImportacaoDeArquivo(); if (registro.startsWith("01")) { stmtDestinoMercadoAVistaLotePadrao.clearParameters(); stmtDestinoOutrosMercados.clearParameters(); vDATA_PREGAO = Integer.parseInt(registro.substring(2, 10).trim()); int vCODBDI = Integer.parseInt(registro.substring(10, 12).trim()); String vCODNEG = registro.substring(12, 24).trim(); int vTPMERC = Integer.parseInt(registro.substring(24, 27).trim()); String vNOMRES = registro.substring(27, 39).trim(); String vESPECI = registro.substring(39, 49).trim(); String vPRAZOT = registro.substring(49, 52).trim(); String vMODREF = registro.substring(52, 56).trim(); BigDecimal vPREABE = obterBigDecimal(registro.substring(56, 69).trim(), 13, 2); BigDecimal vPREMAX = obterBigDecimal(registro.substring(69, 82).trim(), 13, 2); BigDecimal vPREMIN = obterBigDecimal(registro.substring(82, 95).trim(), 13, 2); BigDecimal vPREMED = obterBigDecimal(registro.substring(95, 108).trim(), 13, 2); BigDecimal vPREULT = obterBigDecimal(registro.substring(108, 121).trim(), 13, 2); BigDecimal vPREOFC = obterBigDecimal(registro.substring(121, 134).trim(), 13, 2); BigDecimal vPREOFV = obterBigDecimal(registro.substring(134, 147).trim(), 13, 2); int vTOTNEG = Integer.parseInt(registro.substring(147, 152).trim()); BigDecimal vQUATOT = new BigDecimal(registro.substring(152, 170).trim()); BigDecimal vVOLTOT = obterBigDecimal(registro.substring(170, 188).trim(), 18, 2); BigDecimal vPREEXE = obterBigDecimal(registro.substring(188, 201).trim(), 13, 2); int vINDOPC = Integer.parseInt(registro.substring(201, 202).trim()); int vDATVEN = Integer.parseInt(registro.substring(202, 210).trim()); int vFATCOT = Integer.parseInt(registro.substring(210, 217).trim()); BigDecimal vPTOEXE = obterBigDecimal(registro.substring(217, 230).trim(), 13, 6); String vCODISI = registro.substring(230, 242).trim(); int vDISMES = Integer.parseInt(registro.substring(242, 245).trim()); boolean mercadoAVistaLotePadrao = (vTPMERC == 10 && vCODBDI == 2); OraclePreparedStatement stmtDestino; if (mercadoAVistaLotePadrao) { stmtDestino = stmtDestinoMercadoAVistaLotePadrao; } else { stmtDestino = stmtDestinoOutrosMercados; } stmtDestino.setIntAtName("DATA_PREGAO", vDATA_PREGAO); stmtDestino.setIntAtName("CODBDI", vCODBDI); stmtDestino.setStringAtName("CODNEG", vCODNEG); stmtDestino.setIntAtName("TPMERC", vTPMERC); stmtDestino.setStringAtName("NOMRES", vNOMRES); stmtDestino.setStringAtName("ESPECI", vESPECI); stmtDestino.setStringAtName("PRAZOT", vPRAZOT); stmtDestino.setStringAtName("MODREF", vMODREF); stmtDestino.setBigDecimalAtName("PREABE", vPREABE); stmtDestino.setBigDecimalAtName("PREMAX", vPREMAX); stmtDestino.setBigDecimalAtName("PREMIN", vPREMIN); stmtDestino.setBigDecimalAtName("PREMED", vPREMED); stmtDestino.setBigDecimalAtName("PREULT", vPREULT); stmtDestino.setBigDecimalAtName("PREOFC", vPREOFC); stmtDestino.setBigDecimalAtName("PREOFV", vPREOFV); stmtDestino.setIntAtName("TOTNEG", vTOTNEG); stmtDestino.setBigDecimalAtName("QUATOT", vQUATOT); stmtDestino.setBigDecimalAtName("VOLTOT", vVOLTOT); stmtDestino.setBigDecimalAtName("PREEXE", vPREEXE); stmtDestino.setIntAtName("INDOPC", vINDOPC); stmtDestino.setIntAtName("DATVEN", vDATVEN); stmtDestino.setIntAtName("FATCOT", vFATCOT); stmtDestino.setBigDecimalAtName("PTOEXE", vPTOEXE); stmtDestino.setStringAtName("CODISI", vCODISI); stmtDestino.setIntAtName("DISMES", vDISMES); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportadosDoArquivoAtual++; quantidadeDeRegistrosImportadosDosArquivos++; } else if (registro.startsWith("99")) { BigDecimal totalDeRegistros = obterBigDecimal(registro.substring(31, 42).trim(), 11, 0); assert (totalDeRegistros.intValue() - 2) == quantidadeDeRegistrosImportadosDoArquivoAtual : "Quantidade de registros divergente"; break; } double percentualCompleto = (double) quantidadeDeRegistrosImportadosDosArquivos / quantidadeEstimadaDeRegistros * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); ProblemaNaImportacaoDeArquivo problemaDetalhado = new ProblemaNaImportacaoDeArquivo(); problemaDetalhado.nomeDoArquivo = arquivoTXT.getName(); problemaDetalhado.linhaProblematicaDoArquivo = numeroDoRegistro; problemaDetalhado.detalhesSobreOProblema = ex; throw problemaDetalhado; } finally { in.close(); } } } finally { pAndamento.setPercentualCompleto(100); stmtDestinoMercadoAVistaLotePadrao.close(); stmtDestinoOutrosMercados.close(); } } Code Sample 2: public static String getSHA1Hash(String plainText) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(plainText.getBytes()); byte[] mdbytes = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < mdbytes.length; i++) { String hex = Integer.toHexString(0xFF & mdbytes[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString().toUpperCase(); }
00
Code Sample 1: private void writeStatsToDatabase(long transferJobAIPCount, long reprocessingJobAIPCount, long transferJobAIPVolume, long reprocessingJobAIPVolume, long overallBinaryAIPCount, Map<String, AIPStatistics> mimeTypeRegister) throws SQLException { int nextAIPStatsID; long nextMimetypeStatsID; Statement select = dbConnection.createStatement(); String aipStatsQuery = "select max(aip_statistics_id) from aip_statistics"; ResultSet result = select.executeQuery(aipStatsQuery); if (result.next()) { nextAIPStatsID = result.getInt(1) + 1; } else { throw new SQLException("Problem getting maximum AIP Statistics ID"); } String mimetypeStatsQuery = "select max(mimetype_aip_statistics_id) from mimetype_aip_statistics"; result = select.executeQuery(mimetypeStatsQuery); if (result.next()) { nextMimetypeStatsID = result.getLong(1) + 1; } else { throw new SQLException("Problem getting maximum MIME type AIP Statistics ID"); } String insertAIPStatsEntryQuery = "insert into aip_statistics " + "(aip_statistics_id, tj_aip_count, tj_aip_volume, rj_aip_count, rj_aip_volume, " + "collation_date, binary_aip_count) " + "values (?, ?, ?, ?, ?, ?, ?)"; PreparedStatement insert = dbConnection.prepareStatement(insertAIPStatsEntryQuery); insert.setInt(1, nextAIPStatsID); insert.setLong(2, transferJobAIPCount); insert.setLong(3, transferJobAIPVolume); insert.setLong(4, reprocessingJobAIPCount); insert.setLong(5, reprocessingJobAIPVolume); insert.setDate(6, new java.sql.Date(System.currentTimeMillis())); insert.setLong(7, overallBinaryAIPCount); int rowsAdded = insert.executeUpdate(); if (rowsAdded != 1) { dbConnection.rollback(); throw new SQLException("Could not insert row into AIP statistics table"); } String insertMimeTypeStatsQuery = "insert into mimetype_aip_statistics " + "(mimetype_aip_statistics_id, aip_statistics_id, mimetype_aip_count, mimetype_aip_volume, mimetype) " + "values (?, ?, ?, ?, ?)"; insert = dbConnection.prepareStatement(insertMimeTypeStatsQuery); insert.setInt(2, nextAIPStatsID); for (String mimeType : mimeTypeRegister.keySet()) { AIPStatistics mimeTypeStats = mimeTypeRegister.get(mimeType); insert.setLong(1, nextMimetypeStatsID); insert.setLong(3, mimeTypeStats.aipCount); insert.setLong(4, mimeTypeStats.aipVolume); insert.setString(5, mimeType); nextMimetypeStatsID++; rowsAdded = insert.executeUpdate(); if (rowsAdded != 1) { dbConnection.rollback(); throw new SQLException("Could not insert row into MIME Type AIP statistics table"); } } dbConnection.commit(); } Code Sample 2: private void initializeTree() { InputStreamReader reader = null; BufferedReader buffReader = null; try { for (int i = 0; i < ORDER.length; i++) { int index = ORDER[i]; String indexName = index < 10 ? "0" + index : (index > 20 ? "big" : "" + index); URL url = EmptyClass.class.getResource("engchar" + indexName + ".dic"); logger.info("... Loading: " + "engchar" + indexName + ".dic = {" + url + "}"); reader = new InputStreamReader(url.openStream()); buffReader = new BufferedReader(reader); String line = null; String word = null; do { line = buffReader.readLine(); if (line != null) { boolean plural = line.endsWith("/S"); boolean forbidden = line.endsWith("/X"); if (plural) { int stringIndex = line.indexOf("/S"); word = new String(line.substring(0, stringIndex)); } else if (forbidden) { int stringIndex = line.indexOf("/X"); word = new String(line.substring(0, stringIndex)); } else { word = line.toString(); } if (tree == null) { tree = new BKTree(); } tree.insertDictionaryWord(word, plural, forbidden); } } while (line != null); } logger.debug("Loading supplemental dictionary..."); List<String> listOfWords = KSupplementalDictionaryUtil.getWords(); for (String word : listOfWords) { tree.insertDictionaryWord(word, false, false); } initialized = true; } catch (Exception exception) { logger.error("Error", exception); } finally { if (reader != null) { try { reader.close(); } catch (Exception ex) { } } if (buffReader != null) { try { buffReader.close(); } catch (Exception ex) { } } } }
11
Code Sample 1: @Override public CasAssembly build() { try { prepareForBuild(); File casWorkingDirectory = casFile.getParentFile(); DefaultCasFileReadIndexToContigLookup read2contigMap = new DefaultCasFileReadIndexToContigLookup(); AbstractDefaultCasFileLookup readIdLookup = new DefaultReadCasFileLookup(casWorkingDirectory); CasParser.parseOnlyMetaData(casFile, MultipleWrapper.createMultipleWrapper(CasFileVisitor.class, read2contigMap, readIdLookup)); ReadWriteDirectoryFileServer consedOut = DirectoryFileServer.createReadWriteDirectoryFileServer(commandLine.getOptionValue("o")); long startTime = DateTimeUtils.currentTimeMillis(); int numberOfCasContigs = read2contigMap.getNumberOfContigs(); for (long i = 0; i < numberOfCasContigs; i++) { File outputDir = consedOut.createNewDir("" + i); Command aCommand = new Command(new File("fakeCommand")); aCommand.setOption("-casId", "" + i); aCommand.setOption("-cas", commandLine.getOptionValue("cas")); aCommand.setOption("-o", outputDir.getAbsolutePath()); aCommand.setOption("-tempDir", tempDir.getAbsolutePath()); aCommand.setOption("-prefix", "temp"); if (commandLine.hasOption("useIllumina")) { aCommand.addFlag("-useIllumina"); } if (commandLine.hasOption("useClosureTrimming")) { aCommand.addFlag("-useClosureTrimming"); } if (commandLine.hasOption("trim")) { aCommand.setOption("-trim", commandLine.getOptionValue("trim")); } if (commandLine.hasOption("trimMap")) { aCommand.setOption("-trimMap", commandLine.getOptionValue("trimMap")); } if (commandLine.hasOption("chromat_dir")) { aCommand.setOption("-chromat_dir", commandLine.getOptionValue("chromat_dir")); } submitSingleCasAssemblyConversion(aCommand); } waitForAllAssembliesToFinish(); int numContigs = 0; int numReads = 0; for (int i = 0; i < numberOfCasContigs; i++) { File countMap = consedOut.getFile(i + "/temp.counts"); Scanner scanner = new Scanner(countMap); if (!scanner.hasNextInt()) { throw new IllegalStateException("single assembly conversion # " + i + " did not complete"); } numContigs += scanner.nextInt(); numReads += scanner.nextInt(); scanner.close(); } System.out.println("num contigs =" + numContigs); System.out.println("num reads =" + numReads); consedOut.createNewDir("edit_dir"); consedOut.createNewDir("phd_dir"); String prefix = commandLine.hasOption("prefix") ? commandLine.getOptionValue("prefix") : DEFAULT_PREFIX; OutputStream masterAceOut = new FileOutputStream(consedOut.createNewFile("edit_dir/" + prefix + ".ace.1")); OutputStream masterPhdOut = new FileOutputStream(consedOut.createNewFile("phd_dir/" + prefix + ".phd.ball")); OutputStream masterConsensusOut = new FileOutputStream(consedOut.createNewFile(prefix + ".consensus.fasta")); OutputStream logOut = new FileOutputStream(consedOut.createNewFile(prefix + ".log")); try { masterAceOut.write(String.format("AS %d %d%n", numContigs, numReads).getBytes()); for (int i = 0; i < numberOfCasContigs; i++) { InputStream aceIn = consedOut.getFileAsStream(i + "/temp.ace"); IOUtils.copy(aceIn, masterAceOut); InputStream phdIn = consedOut.getFileAsStream(i + "/temp.phd"); IOUtils.copy(phdIn, masterPhdOut); InputStream consensusIn = consedOut.getFileAsStream(i + "/temp.consensus.fasta"); IOUtils.copy(consensusIn, masterConsensusOut); IOUtil.closeAndIgnoreErrors(aceIn, phdIn, consensusIn); File tempDir = consedOut.getFile(i + ""); IOUtil.recursiveDelete(tempDir); } consedOut.createNewSymLink("../phd_dir/" + prefix + ".phd.ball", "edit_dir/phd.ball"); if (commandLine.hasOption("chromat_dir")) { consedOut.createNewDir("chromat_dir"); File originalChromatDir = new File(commandLine.getOptionValue("chromat_dir")); for (File chromat : originalChromatDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".scf"); } })) { File newChromatFile = consedOut.createNewFile("chromat_dir/" + FilenameUtils.getBaseName(chromat.getName())); FileOutputStream newChromat = new FileOutputStream(newChromatFile); InputStream in = new FileInputStream(chromat); IOUtils.copy(in, newChromat); IOUtil.closeAndIgnoreErrors(in, newChromat); } } System.out.println("finished making casAssemblies"); for (File traceFile : readIdLookup.getFiles()) { final String name = traceFile.getName(); String extension = FilenameUtils.getExtension(name); if (name.contains("fastq")) { if (!consedOut.contains("solexa_dir")) { consedOut.createNewDir("solexa_dir"); } if (consedOut.contains("solexa_dir/" + name)) { IOUtil.delete(consedOut.getFile("solexa_dir/" + name)); } consedOut.createNewSymLink(traceFile.getAbsolutePath(), "solexa_dir/" + name); } else if ("sff".equals(extension)) { if (!consedOut.contains("sff_dir")) { consedOut.createNewDir("sff_dir"); } if (consedOut.contains("sff_dir/" + name)) { IOUtil.delete(consedOut.getFile("sff_dir/" + name)); } consedOut.createNewSymLink(traceFile.getAbsolutePath(), "sff_dir/" + name); } } long endTime = DateTimeUtils.currentTimeMillis(); logOut.write(String.format("took %s%n", new Period(endTime - startTime)).getBytes()); } finally { IOUtil.closeAndIgnoreErrors(masterAceOut, masterPhdOut, masterConsensusOut, logOut); } } catch (Exception e) { handleException(e); } finally { cleanup(); } return null; } Code Sample 2: @Override public void copierPhotos(FileInputStream fichierACopier, FileOutputStream fichierDestination) { FileChannel in = null; FileChannel out = null; try { in = fichierACopier.getChannel(); out = fichierDestination.getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
00
Code Sample 1: public String load(URL url) throws LoaderException { log.debug("loading content"); log.trace("opening connection: " + url); BufferedReader in = null; URLConnection conn = null; try { conn = url.openConnection(); in = null; if (encodedProxyLogin != null) { conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedProxyLogin); } } catch (IOException ioe) { log.warn("Error create connection"); throw new LoaderException("Error create connection", ioe); } log.trace("connection opened, reading ... "); StringBuilder buffer = new StringBuilder(); try { in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { buffer.append(inputLine); } } catch (IOException ioe) { log.warn("Error loading content"); throw new LoaderException("Error reading content. ", ioe); } finally { try { in.close(); } catch (Exception e) { } } log.debug("content loaded"); return buffer.toString(); } Code Sample 2: public static String genetateSHA256(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes("UTF-8")); byte[] passWd = md.digest(); String hex = toHex(passWd); return hex; }
11
Code Sample 1: public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception { String attachmentName = request.getParameter("attachment"); String virtualWiki = getVirtualWiki(request); File uploadPath = getEnvironment().uploadPath(virtualWiki, attachmentName); response.reset(); response.setHeader("Content-Disposition", getEnvironment().getStringSetting(Environment.PROPERTY_ATTACHMENT_TYPE) + ";filename=" + attachmentName + ";"); int dotIndex = attachmentName.indexOf('.'); if (dotIndex >= 0 && dotIndex < attachmentName.length() - 1) { String extension = attachmentName.substring(attachmentName.lastIndexOf('.') + 1); logger.fine("Extension: " + extension); String mimetype = (String) getMimeByExtension().get(extension.toLowerCase()); logger.fine("MIME: " + mimetype); if (mimetype != null) { logger.fine("Setting content type to: " + mimetype); response.setContentType(mimetype); } } FileInputStream in = null; ServletOutputStream out = null; try { in = new FileInputStream(uploadPath); out = response.getOutputStream(); IOUtils.copy(in, out); out.flush(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } Code Sample 2: public static void decompress(final File file, final File folder, final boolean deleteZipAfter) throws IOException { final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(file.getCanonicalFile()))); ZipEntry ze; try { while (null != (ze = zis.getNextEntry())) { final File f = new File(folder.getCanonicalPath(), ze.getName()); if (f.exists()) f.delete(); if (ze.isDirectory()) { f.mkdirs(); continue; } f.getParentFile().mkdirs(); final OutputStream fos = new BufferedOutputStream(new FileOutputStream(f)); try { try { final byte[] buf = new byte[8192]; int bytesRead; while (-1 != (bytesRead = zis.read(buf))) fos.write(buf, 0, bytesRead); } finally { fos.close(); } } catch (final IOException ioe) { f.delete(); throw ioe; } } } finally { zis.close(); } if (deleteZipAfter) file.delete(); }
00
Code Sample 1: public static void downloadFile(String htmlUrl, String dirUrl) { try { URL url = new URL(htmlUrl); System.out.println("Opening connection to " + htmlUrl + "..."); URLConnection urlC = url.openConnection(); InputStream is = url.openStream(); Date date = new Date(urlC.getLastModified()); System.out.println(", modified on: " + date.toLocaleString() + ")..."); System.out.flush(); FileOutputStream fos = null; String localFile = null; StringTokenizer st = new StringTokenizer(url.getFile(), "/"); while (st.hasMoreTokens()) localFile = st.nextToken(); fos = new FileOutputStream(dirUrl + "/" + localFile); int oneChar, count = 0; while ((oneChar = is.read()) != -1) { fos.write(oneChar); count++; } is.close(); fos.close(); System.out.println(count + " byte(s) copied"); } catch (MalformedURLException e) { System.err.println(e.toString()); } catch (IOException e) { System.err.println(e.toString()); } } Code Sample 2: private void postUrl() throws Exception { String authors = ""; for (String auth : plugin.getDescription().getAuthors()) { authors = authors + " " + auth; } authors = authors.trim(); String url = String.format("http://bukkitstats.randomappdev.com/ping.aspx?snam=%s&sprt=%s&shsh=%s&sver=%s&spcnt=%s&pnam=%s&pmcla=%s&paut=%s&pweb=%s&pver=%s", URLEncoder.encode(plugin.getServer().getName(), "UTF-8"), plugin.getServer().getPort(), hash, URLEncoder.encode(Bukkit.getVersion(), "UTF-8"), plugin.getServer().getOnlinePlayers().length, URLEncoder.encode(plugin.getDescription().getName(), "UTF-8"), URLEncoder.encode(plugin.getDescription().getMain(), "UTF-8"), URLEncoder.encode(authors, "UTF-8"), URLEncoder.encode(plugin.getDescription().getWebsite(), "UTF-8"), URLEncoder.encode(plugin.getDescription().getVersion(), "UTF-8")); new URL(url).openConnection().getInputStream(); }
11
Code Sample 1: private void loadMascotLibrary() { if (isMascotLibraryLoaded) return; try { boolean isLinux = false; boolean isAMD64 = false; String mascotLibraryFile; if (Configurator.getOSName().toLowerCase().contains("linux")) { isLinux = true; } if (Configurator.getOSArch().toLowerCase().contains("amd64")) { isAMD64 = true; } if (isLinux) { if (isAMD64) { mascotLibraryFile = "libmsparserj-64.so"; } else { mascotLibraryFile = "libmsparserj-32.so"; } } else { if (isAMD64) { mascotLibraryFile = "msparserj-64.dll"; } else { mascotLibraryFile = "msparserj-32.dll"; } } logger.warn("Using: " + mascotLibraryFile); URL mascot_lib = MascotDAO.class.getClassLoader().getResource(mascotLibraryFile); if (mascot_lib != null) { logger.debug("Mascot library URL: " + mascot_lib); tmpMascotLibraryFile = File.createTempFile("libmascot.so.", ".tmp", new File(System.getProperty("java.io.tmpdir"))); InputStream in = mascot_lib.openStream(); OutputStream out = new FileOutputStream(tmpMascotLibraryFile); IOUtils.copy(in, out); in.close(); out.close(); System.load(tmpMascotLibraryFile.getAbsolutePath()); isMascotLibraryLoaded = true; } else { throw new ConverterException("Could not load Mascot Library for system: " + Configurator.getOSName() + Configurator.getOSArch()); } } catch (IOException e) { throw new ConverterException("Error loading Mascot library: " + e.getMessage(), e); } } Code Sample 2: public static Object fetchCached(String address, int hours) throws MalformedURLException, IOException { String cacheName = md5(address); checkAndCreateDirectoryIfNeeded(); File r = new File(CACHELOCATION + cacheName); Date d = new Date(); long limit = d.getTime() - (1000 * 60 * 60 * hours); if (!r.exists() || (hours != -1 && r.lastModified() < limit)) { InputStream is = (InputStream) fetch(address); FileOutputStream fos = new FileOutputStream(CACHELOCATION + cacheName); int nextChar; while ((nextChar = is.read()) != -1) fos.write((char) nextChar); fos.flush(); } FileInputStream fis = new FileInputStream(CACHELOCATION + cacheName); return fis; }
00
Code Sample 1: public boolean check(Object credentials) { try { byte[] digest = null; if (credentials instanceof Password || credentials instanceof String) { synchronized (__md5Lock) { if (__md == null) __md = MessageDigest.getInstance("MD5"); __md.reset(); __md.update(credentials.toString().getBytes(StringUtil.__ISO_8859_1)); digest = __md.digest(); } if (digest == null || digest.length != _digest.length) return false; for (int i = 0; i < digest.length; i++) if (digest[i] != _digest[i]) return false; return true; } else if (credentials instanceof MD5) { MD5 md5 = (MD5) credentials; if (_digest.length != md5._digest.length) return false; for (int i = 0; i < _digest.length; i++) if (_digest[i] != md5._digest[i]) return false; return true; } else if (credentials instanceof Credential) { return ((Credential) credentials).check(this); } else { Log.warn("Can't check " + credentials.getClass() + " against MD5"); return false; } } catch (Exception e) { Log.warn(e); return false; } } Code Sample 2: static ConversionMap create(String file) { ConversionMap out = new ConversionMap(); URL url = ConversionMap.class.getResource("data/" + file); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); while (line != null) { if (line.length() > 0) { String[] arr = line.split("\t"); try { double value = Double.parseDouble(arr[1]); out.put(translate(lowercase(arr[0].getBytes())), value); out.defaultValue += value; out.length = arr[0].length(); } catch (NumberFormatException e) { throw new RuntimeException("Something is wrong with in conversion file: " + e); } } line = in.readLine(); } in.close(); out.defaultValue /= Math.pow(4, out.length); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Their was an error while reading the conversion map: " + e); } return out; }
11
Code Sample 1: public int subclass(int objectId, String description) throws FidoDatabaseException, ObjectNotFoundException { try { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { String sql = "insert into Objects (Description) " + "values ('" + description + "')"; conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); if (contains(stmt, objectId) == false) throw new ObjectNotFoundException(objectId); stmt.executeUpdate(sql); int id; sql = "select currval('objects_objectid_seq')"; rs = stmt.executeQuery(sql); if (rs.next() == false) throw new SQLException("No rows returned from select currval() query"); else id = rs.getInt(1); ObjectLinkTable objectLinkList = new ObjectLinkTable(); objectLinkList.linkObjects(stmt, id, "isa", objectId); conn.commit(); return id; } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: public static int deleteSysPosInsert() { Connection conn = null; PreparedStatement psmt = null; StringBuffer SQL = new StringBuffer(200); int deleted = 0; SQL.append(" DELETE FROM JHF_SYS_POSITION_INSERT "); try { conn = JdbcConnectionPool.mainConnection(); conn.setAutoCommit(false); conn.setReadOnly(false); psmt = conn.prepareStatement(SQL.toString()); deleted = psmt.executeUpdate(); conn.commit(); } catch (SQLException e) { if (null != conn) { try { conn.rollback(); } catch (SQLException e1) { System.out.println(" error when roll back !"); } } } finally { try { if (null != psmt) { psmt.close(); psmt = null; } if (null != conn) { conn.close(); conn = null; } } catch (SQLException e) { System.out.println(" error when psmt close or conn close ."); } } return deleted; }
11
Code Sample 1: public static void copy(File from_file, File to_file) throws IOException { if (!from_file.exists()) { throw new IOException("FileCopy: no such source file: " + from_file.getPath()); } if (!from_file.isFile()) { throw new IOException("FileCopy: can't copy directory: " + from_file.getPath()); } if (!from_file.canRead()) { throw new IOException("FileCopy: source file is unreadable: " + from_file.getPath()); } if (to_file.isDirectory()) { to_file = new File(to_file, from_file.getName()); } if (to_file.exists()) { if (!to_file.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + to_file.getPath()); } int choice = JOptionPane.showConfirmDialog(null, "Overwrite existing file " + to_file.getPath(), "File Exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (choice != JOptionPane.YES_OPTION) { throw new IOException("FileCopy: existing file was not overwritten."); } } else { String parent = to_file.getParent(); if (parent == null) { parent = Globals.getDefaultPath(); } File dir = new File(parent); if (!dir.exists()) { throw new IOException("FileCopy: destination directory doesn't exist: " + parent); } if (dir.isFile()) { throw new IOException("FileCopy: destination is not a directory: " + parent); } if (!dir.canWrite()) { throw new IOException("FileCopy: destination directory is unwriteable: " + parent); } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(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 copyTo(File src, File dest) throws IOException { if (src.equals(dest)) throw new IOException("copyTo src==dest file"); FileOutputStream fout = new FileOutputStream(dest); InputStream in = new FileInputStream(src); IOUtils.copyTo(in, fout); fout.flush(); fout.close(); in.close(); }
00
Code Sample 1: private void sort() { for (int i = 0; i < density.length; i++) { for (int j = density.length - 2; j >= i; j--) { if (density[j] > density[j + 1]) { KDNode n = nonEmptyNodesArray[j]; nonEmptyNodesArray[j] = nonEmptyNodesArray[j + 1]; nonEmptyNodesArray[j + 1] = n; double d = density[j]; density[j] = density[j + 1]; density[j + 1] = d; } } } } Code Sample 2: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
00
Code Sample 1: public void deleteUser(final List<Integer> userIds) { try { connection.setAutoCommit(false); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("user.delete")); Iterator<Integer> iter = userIds.iterator(); int userId; while (iter.hasNext()) { userId = iter.next(); psImpl.setInt(1, userId); psImpl.executeUpdate(); } } }); connection.commit(); cmDB.removeUsers(userIds); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; final StringBuilder sbValueBeforeMD5 = new StringBuilder(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.fatal("", e); return; } try { final long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(sId); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); final byte[] array = md5.digest(); final StringBuilder sb = new StringBuilder(); for (int j = 0; j < array.length; ++j) { final int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { logger.fatal("", e); } }
00
Code Sample 1: public void transform(String style, String spec, OutputStream out) throws IOException { URL url = new URL(rootURL, spec); InputStream in = new PatchXMLSymbolsStream(new StripDoctypeStream(url.openStream())); transform(style, in, out); in.close(); } Code Sample 2: public I18N(JApplet applet) { if (prop != null) { return; } String lang = "de"; try { Properties userProperties = new Properties(); if (applet != null) { URL url = new URL(applet.getCodeBase() + xConfigPath + "ElementDesigner.cfg"); userProperties.load(url.openStream()); } else { userProperties.load(new FileInputStream(xConfigPath + "ElementDesigner.cfg")); } if (userProperties.containsKey("language")) { lang = userProperties.getProperty("language"); } } catch (Exception ex) { ex.printStackTrace(); } prop = new Properties(); try { if (applet != null) { URL url = new URL(applet.getCodeBase() + xLanguagePath + lang + ".ini"); prop.load(url.openStream()); } else { prop.load(new FileInputStream(xLanguagePath + lang + ".ini")); } } catch (Exception ex) { ex.printStackTrace(); try { if (applet != null) { URL url = new URL(applet.getCodeBase() + xLanguagePath + "de.ini"); prop.load(url.openStream()); } else { prop.load(new FileInputStream(xLanguagePath + "de.ini")); } } catch (Exception ex2) { JOptionPane.showMessageDialog(null, "Language file languages/de.ini not found.\nPlease run the program from its directory."); System.exit(5); } } }
00
Code Sample 1: public void transform(String style, String spec, OutputStream out) throws IOException { URL url = new URL(rootURL, spec); InputStream in = new PatchXMLSymbolsStream(new StripDoctypeStream(url.openStream())); transform(style, in, out); in.close(); } Code Sample 2: private String getAuthUrlString(String account, String password) throws IOException, NoSuchAlgorithmException { Map<String, String> dict = retrieveLoginPage(); if (dict == null) { return null; } StringBuilder url = new StringBuilder("/config/login?login="); url.append(account); url.append("&passwd="); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); byte[] result = md5.digest(); for (int i = 0; i < 16; i++) { url.append(StringUtil.toHex2(result[i])); } String md5chal = dict.get(".challenge"); md5 = MessageDigest.getInstance("MD5"); md5.update(md5chal.getBytes(), 0, md5chal.length()); result = md5.digest(); for (int i = 0; i < 16; i++) { url.append(StringUtil.toHex2(result[i])); } Iterator<String> j = dict.keySet().iterator(); while (j.hasNext()) { String key = j.next(); String value = dict.get(key); if (!key.equals("passwd")) { if (key.equals(".save") || key.equals(".js")) { url.append("&" + key + "=1"); } else if (key.equals(".challenge")) { url.append("&" + key + "=" + value); } else { String u = URLEncoder.encode(value, "UTF-8"); url.append("&" + key + "=" + u); } } } url.append("&"); url.append(".hash=1"); url.append("&"); url.append(".md5=1"); return url.toString(); }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: 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(); } }
11
Code Sample 1: public void load(boolean isOrdered) throws ResourceInstantiationException { try { if (null == url) { throw new ResourceInstantiationException("URL not specified (null)."); } BufferedReader listReader; listReader = new BomStrippingInputStreamReader((url).openStream(), encoding); String line; int linenr = 0; while (null != (line = listReader.readLine())) { linenr++; GazetteerNode node = null; try { node = new GazetteerNode(line, separator, isOrdered); } catch (Exception ex) { throw new GateRuntimeException("Could not read gazetteer entry " + linenr + " from URL " + getURL() + ": " + ex.getMessage(), ex); } entries.add(new GazetteerNode(line, separator, isOrdered)); } listReader.close(); } catch (Exception x) { throw new ResourceInstantiationException(x.getClass() + ":" + x.getMessage()); } isModified = false; } Code Sample 2: public MapInfo loadLocalMapData(String fileName) { MapInfo info = mapCacheLocal.get(fileName); if (info != null && info.getContent() == null) { try { BufferedReader bufferedreader; URL fetchUrl = new URL(localMapContextUrl, fileName); URLConnection urlconnection = fetchUrl.openConnection(); if (urlconnection.getContentEncoding() != null) { bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), urlconnection.getContentEncoding())); } else { bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), "utf-8")); } String line; StringBuilder mapContent = new StringBuilder(); while ((line = bufferedreader.readLine()) != null) { mapContent.append(line); mapContent.append("\n"); } info.setContent(mapContent.toString()); GameMapImplementation gameMap = GameMapImplementation.createFromMapInfo(info); } catch (IOException _ex) { System.err.println("HexTD::readFile:: Can't read from " + fileName); } } else { System.err.println("HexTD::readFile:: file not in cache: " + fileName); } return info; }