label
class label
2 classes
source_code
stringlengths
398
72.9k
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 void makeLPKFile(String[] srcFilePath, String makeFilePath, LPKHeader header) { FileOutputStream os = null; DataOutputStream dos = null; try { LPKTable[] fileTable = new LPKTable[srcFilePath.length]; long fileOffset = outputOffset(header); for (int i = 0; i < srcFilePath.length; i++) { String sourceFileName = FileUtils.getFileName(srcFilePath[i]); long sourceFileSize = FileUtils.getFileSize(srcFilePath[i]); LPKTable ft = makeLPKTable(sourceFileName, sourceFileSize, fileOffset); fileOffset = outputNextOffset(sourceFileSize, fileOffset); fileTable[i] = ft; } File file = new File(makeFilePath); if (!file.exists()) { FileUtils.makedirs(file); } os = new FileOutputStream(file); dos = new DataOutputStream(os); dos.writeInt(header.getPAKIdentity()); writeByteArray(header.getPassword(), dos); dos.writeFloat(header.getVersion()); dos.writeLong(header.getTables()); for (int i = 0; i < fileTable.length; i++) { writeByteArray(fileTable[i].getFileName(), dos); dos.writeLong(fileTable[i].getFileSize()); dos.writeLong(fileTable[i].getOffSet()); } for (int i = 0; i < fileTable.length; i++) { File ftFile = new File(srcFilePath[i]); FileInputStream ftFis = new FileInputStream(ftFile); DataInputStream ftDis = new DataInputStream(ftFis); byte[] buff = new byte[256]; int readLength = 0; while ((readLength = ftDis.read(buff)) != -1) { makeBuffer(buff, readLength); dos.write(buff, 0, readLength); } ftDis.close(); ftFis.close(); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (dos != null) { try { dos.close(); dos = null; } catch (IOException e) { } } } }
00
Code Sample 1: public File createFileFromClasspathResource(String resourceUrl) throws IOException { File fichierTest = File.createTempFile("xmlFieldTestFile", ""); FileOutputStream fos = new FileOutputStream(fichierTest); InputStream is = XmlFieldDomSelectorTest.class.getResourceAsStream(resourceUrl); IOUtils.copy(is, fos); is.close(); fos.close(); return fichierTest; } Code Sample 2: public void unlock(String oid, String key) throws PersisterException { String lock = getLock(oid); if (lock == null) { throw new PersisterException("Object does not exist: OID = " + oid); } else if (!NULL.equals(lock) && (!lock.equals(key))) { throw new PersisterException("The object is currently locked with another key: OID = " + oid + ", LOCK = " + lock + ", KEY = " + key); } Connection conn = null; PreparedStatement ps = null; try { conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("update " + _table_name + " set " + _key_col + " = NULL, " + _ts_col + " = ? where " + _oid_col + " = ?"); ps.setLong(1, System.currentTimeMillis()); ps.setString(2, oid); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to unlock object: OID = " + oid + ", KEY = " + key, th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } }
11
Code Sample 1: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); } 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 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(); } } 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; }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public void generateHtmlPage(String real_filename, String url_filename) { String str_content = ""; URL m_url = null; URLConnection m_urlcon = null; try { m_url = new URL(url_filename); m_urlcon = m_url.openConnection(); InputStream in_stream = m_urlcon.getInputStream(); byte[] bytes = new byte[1]; Vector v_bytes = new Vector(); while (in_stream.read(bytes) != -1) { v_bytes.add(bytes); bytes = new byte[1]; } byte[] all_bytes = new byte[v_bytes.size()]; for (int i = 0; i < v_bytes.size(); i++) all_bytes[i] = ((byte[]) v_bytes.get(i))[0]; str_content = new String(all_bytes, "GBK"); } catch (Exception urle) { } try { oaFileOperation file_control = new oaFileOperation(); file_control.writeFile(str_content, real_filename, true); String strPath = url_filename.substring(0, url_filename.lastIndexOf("/") + 1); String strUrlFileName = url_filename.substring(url_filename.lastIndexOf("/") + 1); if (strUrlFileName.indexOf(".jsp") > 0) { strUrlFileName = strUrlFileName.substring(0, strUrlFileName.indexOf(".jsp")) + "_1.jsp"; m_url = new URL(strPath + strUrlFileName); m_url.openConnection(); } intWriteFileCount++; intWriteFileCount = (intWriteFileCount > 100000) ? 0 : intWriteFileCount; } catch (Exception e) { } m_urlcon = null; }
11
Code Sample 1: protected void migrateOnDemand() { try { if (fso.fileExists(prefix + ".fat") && !fso.fileExists(prefix + EXTENSIONS[UBM_FILE])) { RandomAccessFile ubm, meta, ctr, rbm; InputStream inputStream; OutputStream outputStream; fso.renameFile(prefix + ".fat", prefix + EXTENSIONS[UBM_FILE]); ubm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); meta = fso.openFile(prefix + EXTENSIONS[MTD_FILE], "rw"); ctr = fso.openFile(prefix + EXTENSIONS[CTR_FILE], "rw"); ubm.seek(ubm.length() - 16); meta.writeInt(blockSize = ubm.readInt()); meta.writeInt(size = ubm.readInt()); ctr.setLength(ubm.readLong() + blockSize); ctr.close(); meta.close(); ubm.setLength(ubm.length() - 16); ubm.seek(0); rbm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); inputStream = new BufferedInputStream(new RandomAccessFileInputStream(ubm)); outputStream = new BufferedOutputStream(new RandomAccessFileOutputStream(rbm)); for (int b; (b = inputStream.read()) != -1; ) outputStream.write(b); outputStream.close(); inputStream.close(); rbm.close(); ubm.close(); } } catch (IOException ie) { throw new WrappingRuntimeException(ie); } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: public HttpURLConnection getConnection(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = null; if (_proxy == null) { connection = (HttpURLConnection) url.openConnection(); } else { URLConnection con = url.openConnection(_proxy); String encodedUserPwd = new String(Base64.encodeBase64((_username + ":" + _password).getBytes())); con.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd); connection = (HttpURLConnection) con; } return connection; } Code Sample 2: @Test public void testGrantLicense() throws Exception { context.turnOffAuthorisationSystem(); Item item = Item.create(context); String defaultLicense = ConfigurationManager.getDefaultSubmissionLicense(); LicenseUtils.grantLicense(context, item, defaultLicense); StringWriter writer = new StringWriter(); IOUtils.copy(item.getBundles("LICENSE")[0].getBitstreams()[0].retrieve(), writer); String license = writer.toString(); assertThat("testGrantLicense 0", license, equalTo(defaultLicense)); context.restoreAuthSystemState(); }
00
Code Sample 1: @Override public ISource writeTo(ISource output) throws ResourceException { try { Document doc = getParent().getDocument(); Nodes places = doc.query(getPosition().getXpath()); if (places.size() == 0) { places = doc.query("//html"); } if (places.size() > 0 && places.get(0) instanceof Element) { Element target = (Element) places.get(0); List<URL> urls = getResourceURLs(); if (getType() == EType.TEXT) { Element tag = getHeaderTag(); ByteArrayOutputStream out = new ByteArrayOutputStream(); UtilIO.writeAllTo(urls, out); String content = out.toString(); out.close(); tag.appendChild(content); if (getPosition().getPlace() == EPlace.START) { target.insertChild(tag, 0); } else { target.appendChild(tag); } } else { for (URL url : urls) { String file = url.toString(); String name = file.substring(file.lastIndexOf("/") + 1) + "_res_" + (serialNumber++); Element tag = getHeaderTag(output, name); File resFile = getFile(output, name); if (!resFile.getParentFile().exists()) { if (!resFile.getParentFile().mkdirs()) { throw new ResourceException("Could not create resource directory '" + resFile.getParent() + "'."); } } UtilIO.writeToClose(url.openStream(), new FileOutputStream(resFile)); if (getPosition().getPlace() == EPlace.START) { target.insertChild(tag, 0); } else { target.appendChild(tag); } } } } else { throw new ResourceException("Head element not found."); } } catch (IOException e) { throw new ResourceException(e); } catch (SourceException e) { throw new ResourceException(e); } return output; } Code Sample 2: @Test(dependsOnMethods = { "getSize" }) public void download() throws IOException { FileObject typica = fsManager.resolveFile("s3://" + bucketName + "/jonny.zip"); File localCache = File.createTempFile("vfs.", ".s3-test"); FileOutputStream out = new FileOutputStream(localCache); IOUtils.copy(typica.getContent().getInputStream(), out); Assert.assertEquals(localCache.length(), typica.getContent().getSize()); localCache.delete(); }
11
Code Sample 1: static void copyFile(File file, File file1) throws IOException { byte abyte0[] = new byte[512]; FileInputStream fileinputstream = new FileInputStream(file); FileOutputStream fileoutputstream = new FileOutputStream(file1); int i; while ((i = fileinputstream.read(abyte0)) > 0) fileoutputstream.write(abyte0, 0, i); fileinputstream.close(); fileoutputstream.close(); } Code Sample 2: public void generateReport(AllTestsResult atr, AllConvsResult acr, File nwbConvGraph) { ConvResult[] convs = acr.getConvResults(); BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(nwbConvGraph)); writer = new BufferedWriter(new FileWriter(this.annotatedNWBGraph)); String line = null; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.startsWith("id*int")) { writer.write(line + " isTrusted*int chanceCorrect*float isConverter*int \r\n"); } else if (line.matches(NODE_LINE)) { String[] parts = line.split(" "); String rawConvName = parts[1]; String convName = rawConvName.replaceAll("\"", ""); boolean wroteAttributes = false; for (int ii = 0; ii < convs.length; ii++) { ConvResult cr = convs[ii]; if (cr.getShortName().equals(convName)) { int trusted; if (cr.isTrusted()) { trusted = 1; } else { trusted = 0; } writer.write(line + " " + trusted + " " + FormatUtil.formatToPercent(cr.getChanceCorrect()) + " 1 " + "\r\n"); wroteAttributes = true; break; } } if (!wroteAttributes) { writer.write(line + " 1 100.0 0" + "\r\n"); } } else { writer.write(line + "\r\n"); } } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to generate Graph Report.", e); try { if (reader != null) reader.close(); } catch (IOException e2) { this.log.log(LogService.LOG_ERROR, "Unable to close graph report stream", e); } } finally { try { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to close either graph report reader or " + "writer.", e); e.printStackTrace(); } } }
00
Code Sample 1: public void bspMain(BSP bsp, Serializable arg) throws AbortedException { if (!(arg instanceof String[])) { bsp.abort(new RuntimeException("String[] as arguments expected")); } String[] args = (String[]) arg; long t1 = 0L, t2; try { if (bsp != null) bsp.printStdOut(bsp.getHostname()); else System.out.println(InetAddress.getLocalHost().getCanonicalHostName()); } catch (Exception e) { if (bsp != null) bsp.printStdOut("exception: " + e); else System.out.println("exception: " + e); } Formula formula = null; if (bsp == null || bsp.getProcessId() == 0) { try { InputStream src; String input; if (args.length > 0) input = args[0]; else input = "sat/uuf175-03.cnf"; if (bsp != null) bsp.printStdOut("using formula definition: " + input); else System.out.println("using formula definition: " + input); if (bsp != null) { bsp.printStdOut("trying to read formula from class file server of the job owner's peer"); src = bsp.getResourceAsStream(input); } else { System.out.println("trying to read formula from http://www.upb.de/fachbereich/AG/agmadh/WWW/bono/" + input); URL url = new URL("http", "www.upb.de", -1, "/fachbereich/AG/agmadh/WWW/bono/" + input, null); src = url.openStream(); } formula = new Formula(src, bsp); } catch (Exception e) { if (bsp != null) { bsp.printStdOut("cannot load formula: " + e); bsp.abort(e); } else { System.out.println("cannot load formula: " + e); System.exit(1); } } formula.print(bsp); } if (bsp != null) { bsp.sync(); if (bsp.getProcessId() == 0) t1 = bsp.getTime(); Formula.parallelSolve(formula, bsp); bsp.sync(); if (bsp.getProcessId() == 0) { t2 = bsp.getTime(); bsp.printStdOut("consumed time: " + ((t2 - t1) / 1000) + "s"); } } else formula.solve(bsp); if (bsp == null || bsp.getProcessId() == 0) { if (formula.isSatisfiable()) { if (bsp != null) bsp.printStdOut("satisfiable"); else System.out.println("satisfiable"); } else { if (bsp != null) bsp.printStdOut("not satisfiable"); else System.out.println("not satisfiable"); } formula.printVariables(bsp); } } Code Sample 2: public boolean createUser(String username, String password, String name) throws Exception { boolean user_created = false; try { statement = connect.prepareStatement("SELECT COUNT(*) from toepen.users WHERE username = ? LIMIT 1"); statement.setString(1, username); resultSet = statement.executeQuery(); resultSet.next(); if (resultSet.getInt(1) == 0) { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); String password_hash = hash.toString(16); long ctime = System.currentTimeMillis() / 1000; statement = connect.prepareStatement("INSERT INTO toepen.users " + "(username, password, name, ctime) " + "VALUES (?, ?, ?, ?)"); statement.setString(1, username); statement.setString(2, password_hash); statement.setString(3, name); statement.setLong(4, ctime); if (statement.executeUpdate() > 0) { user_created = true; } } } catch (Exception ex) { System.out.println(ex); } finally { close(); return user_created; } }
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 BinaryDocument documentFor(String code, String type, int diagramIndex) { code = code.replaceAll("\n", "").replaceAll("\t", "").trim().replaceAll(" ", "%20"); StringBuilder builder = new StringBuilder("http://yuml.me/diagram/"); builder.append(type).append("/"); builder.append(code); URL url; try { url = new URL(builder.toString()); String name = "uml" + diagramIndex + ".png"; diagramIndex++; BinaryDocument pic = new BinaryDocument(name, "image/png"); IOUtils.copy(url.openStream(), pic.getContent().getOutputStream()); return pic; } catch (MalformedURLException e) { throw ManagedIOException.manage(e); } catch (IOException e) { throw ManagedIOException.manage(e); } }
11
Code Sample 1: public static String stringToHash(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Should not happened: SHA-1 algorithm is missing."); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Should not happened: Could not encode text bytes '" + text + "' to iso-8859-1."); } return new String(Base64.encodeBase64(md.digest())); } Code Sample 2: public static String getUserToken(String userName) { if (userName != null && userName.trim().length() > 0) try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update((userName + seed).getBytes("ISO-8859-1")); return BaseController.bytesToHex(md.digest()); } catch (NullPointerException npe) { } catch (NoSuchAlgorithmException e) { } catch (UnsupportedEncodingException e) { } return null; }
00
Code Sample 1: public static void main(String[] args) { FTPClient client = new FTPClient(); String sFTP = "ftp.servidor.com"; String sUser = "usuario"; String sPassword = "pasword"; try { System.out.println("Conectandose a " + sFTP); client.connect(sFTP); client.login(sUser, sPassword); System.out.println(client.printWorkingDirectory()); client.changeWorkingDirectory("\\httpdocs"); System.out.println(client.printWorkingDirectory()); System.out.println("Desconectando."); client.logout(); client.disconnect(); } catch (IOException ioe) { ioe.printStackTrace(); } } Code Sample 2: public String login() { String authSuccess = "false"; try { String errorMesg = ""; int error; if ((error = utils.stringIsNull(passwd)) != -1) { errorMesg += rb.getString("passwdField") + ": " + utils.errors[error] + " "; } else if ((error = utils.stringIsEmpty(passwd)) != -1) { errorMesg += rb.getString("passwdField") + ": " + utils.errors[error] + " "; } if ((error = utils.stringIsNull(login)) != -1) { errorMesg += rb.getString("loginField") + ": " + utils.errors[error] + " "; } else if ((error = utils.stringIsEmpty(login)) != -1) { errorMesg += rb.getString("loginField") + ": " + utils.errors[error] + " "; } String[] admins = conf.getProperty("admin").split("\\s"); boolean admin = false; for (int i = 0; i < admins.length; i++) { if (admins[i].equals(login)) { admin = true; } } if (!admin) { errorMesg += rb.getString("noAdmin"); session.invalidate(); } else { session.setAttribute("conf", conf); } if (errorMesg.length() > 0) { status = errorMesg; System.out.println(status); FacesContext context = FacesContext.getCurrentInstance(); context.renderResponse(); } else { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(passwd.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { String hex = Integer.toHexString(0xFF & result[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } authSuccess = (sqlManager.getPassword(login).equals(hexString.toString())) ? "true" : "false"; if (authSuccess.equals("false")) session.invalidate(); } } catch (NoSuchAlgorithmException nsae) { utils.catchExp(nsae); status = utils.getStatus(); if (stacktrace) { stackTrace = utils.getStackTrace(); } FacesContext.getCurrentInstance().renderResponse(); } catch (SQLException sqle) { utils.catchExp(sqle); status = utils.getStatus(); if (stacktrace) { stackTrace = utils.getStackTrace(); } FacesContext.getCurrentInstance().renderResponse(); } return authSuccess; }
00
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 int delete(BusinessObject o) throws DAOException { int delete = 0; Project project = (Project) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_PROJECT")); pst.setInt(1, project.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; }
00
Code Sample 1: private synchronized Document executeHttpMethod(final HttpUriRequest httpRequest) throws UnauthorizedException, ThrottledException, ApiException { if (!isNextRequestAllowed()) { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Wait " + WAITING_TIME + "ms for request."); } wait(WAITING_TIME); } catch (InterruptedException ie) { throw new ApiException("Waiting for request interrupted.", ie); } } try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Perform request."); } HttpResponse httpResponse = httpClient.execute(httpRequest); switch(httpResponse.getStatusLine().getStatusCode()) { case HTTP_OK: HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { InputStream responseStream = httpEntity.getContent(); if (responseStream == null) { throw new ApiException("TODO"); } else { String response = null; try { response = IOUtils.toString(responseStream, RESPONSE_ENCODING); } catch (IOException ioe) { throw new ApiException("Problem reading response", ioe); } catch (RuntimeException re) { httpRequest.abort(); throw new ApiException("Problem reading response", re); } finally { responseStream.close(); } StringReader responseReader = new StringReader(response); Document document = documentBuilder.parse(new InputSource(responseReader)); return document; } } case HTTP_UNAVAILABLE: throw new ThrottledException("TODO"); case HTTP_UNAUTHORIZED: throw new UnauthorizedException("TODO"); default: throw new ApiException("Unexpected HTTP status code: " + httpResponse.getStatusLine().getStatusCode()); } } catch (SAXException se) { throw new ApiException("TODO", se); } catch (IOException ioe) { throw new ApiException("TODO", ioe); } finally { updateLastRequestTimestamp(); } } Code Sample 2: public static void copyFile(File src, File dest) throws IOException { if (!src.exists()) throw new IOException("File not found '" + src.getAbsolutePath() + "'"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); }
00
Code Sample 1: @Override public void run(ProcedureRunner runner) throws Exception { if (url == null) { throw BuiltinExceptionFactory.createAttributeMissing(this, "url"); } if (inputPath == null) { throw BuiltinExceptionFactory.createAttributeMissing(this, "inputPath"); } CompositeMap context = runner.getContext(); Object inputObject = context.getObject(inputPath); if (inputObject == null) throw BuiltinExceptionFactory.createDataFromXPathIsNull(this, inputPath); if (!(inputObject instanceof CompositeMap)) throw BuiltinExceptionFactory.createInstanceTypeWrongException(inputPath, CompositeMap.class, inputObject.getClass()); URI uri = new URI(url); URL url = uri.toURL(); PrintWriter out = null; BufferedReader br = null; CompositeMap soapBody = createSOAPBody(); soapBody.addChild((CompositeMap) inputObject); String content = XMLOutputter.defaultInstance().toXML(soapBody.getRoot(), true); LoggingContext.getLogger(context, this.getClass().getCanonicalName()).config("request:\r\n" + content); HttpURLConnection httpUrlConnection = null; try { httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setDoInput(true); httpUrlConnection.setDoOutput(true); httpUrlConnection.setRequestMethod("POST"); httpUrlConnection.setRequestProperty("SOAPAction", "urn:anonOutInOp"); httpUrlConnection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); httpUrlConnection.connect(); OutputStream os = httpUrlConnection.getOutputStream(); out = new PrintWriter(os); out.println("<?xml version='1.0' encoding='UTF-8'?>"); out.println(new String(content.getBytes("UTF-8"))); out.flush(); out.close(); String soapResponse = null; CompositeMap soap = null; CompositeLoader cl = new CompositeLoader(); if (HttpURLConnection.HTTP_OK == httpUrlConnection.getResponseCode()) { soap = cl.loadFromStream(httpUrlConnection.getInputStream()); soapResponse = soap.toXML(); LoggingContext.getLogger(context, this.getClass().getCanonicalName()).config("correct response:" + soapResponse); } else { soap = cl.loadFromStream(httpUrlConnection.getErrorStream()); soapResponse = soap.toXML(); LoggingContext.getLogger(context, this.getClass().getCanonicalName()).config("error response:" + soapResponse); if (raiseExceptionOnError) { throw new ConfigurationFileException(WS_INVOKER_ERROR_CODE, new Object[] { url, soapResponse }, this); } } httpUrlConnection.disconnect(); CompositeMap result = (CompositeMap) soap.getChild(SOAPServiceInterpreter.BODY.getLocalName()).getChilds().get(0); if (returnPath != null) runner.getContext().putObject(returnPath, result, true); } catch (Exception e) { LoggingContext.getLogger(context, this.getClass().getCanonicalName()).log(Level.SEVERE, "", e); throw new RuntimeException(e); } finally { if (out != null) { out.close(); } if (br != null) { br.close(); } if (httpUrlConnection != null) { httpUrlConnection.disconnect(); } } } Code Sample 2: public static String SHA1(String text) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } StringBuffer hexString = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }
11
Code Sample 1: private File getTempFile(DigitalObject object, String pid) throws Exception { File directory = new File(tmpDir, object.getId()); File target = new File(directory, pid); if (!target.exists()) { target.getParentFile().mkdirs(); target.createNewFile(); } Payload payload = object.getPayload(pid); InputStream in = payload.open(); FileOutputStream out = null; try { out = new FileOutputStream(target); IOUtils.copyLarge(in, out); } catch (Exception ex) { close(out); target.delete(); payload.close(); throw ex; } close(out); payload.close(); return target; } Code Sample 2: @Override protected int run(CmdLineParser parser) { final List<String> args = parser.getRemainingArgs(); if (args.isEmpty()) { System.err.println("summarysort :: WORKDIR not given."); return 3; } if (args.size() == 1) { System.err.println("summarysort :: INPATH not given."); return 3; } final String outS = (String) parser.getOptionValue(outputDirOpt); final Path wrkDir = new Path(args.get(0)), in = new Path(args.get(1)), out = outS == null ? null : new Path(outS); final boolean verbose = parser.getBoolean(verboseOpt); final Configuration conf = getConf(); final Timer t = new Timer(); try { @SuppressWarnings("deprecation") final int maxReduceTasks = new JobClient(new JobConf(conf)).getClusterStatus().getMaxReduceTasks(); conf.setInt("mapred.reduce.tasks", Math.max(1, maxReduceTasks * 9 / 10)); final Job job = sortOne(conf, in, wrkDir, "summarysort", ""); System.out.printf("summarysort :: Waiting for job completion...\n"); t.start(); if (!job.waitForCompletion(verbose)) { System.err.println("summarysort :: Job failed."); return 4; } System.out.printf("summarysort :: Job complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("summarysort :: Hadoop error: %s\n", e); return 4; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } if (out != null) try { System.out.println("summarysort :: Merging output..."); t.start(); final FileSystem srcFS = wrkDir.getFileSystem(conf); final FileSystem dstFS = out.getFileSystem(conf); final OutputStream outs = dstFS.create(out); final FileStatus[] parts = srcFS.globStatus(new Path(wrkDir, in.getName() + "-[0-9][0-9][0-9][0-9][0-9][0-9]*")); { int i = 0; final Timer t2 = new Timer(); for (final FileStatus part : parts) { t2.start(); final InputStream ins = srcFS.open(part.getPath()); IOUtils.copyBytes(ins, outs, conf, false); ins.close(); System.out.printf("summarysort :: Merged part %d in %d.%03d s.\n", ++i, t2.stopS(), t2.fms()); } } for (final FileStatus part : parts) srcFS.delete(part.getPath(), false); outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); outs.close(); System.out.printf("summarysort :: Merging complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("summarysort :: Output merging failed: %s\n", e); return 5; } return 0; }
00
Code Sample 1: @Override public void run() { if (mMode == 0) { long currentVersion = Version.extractVersion(App.getVersion()); if (currentVersion == 0) { mMode = 2; RESULT = MSG_UP_TO_DATE; return; } long versionAvailable = currentVersion; mMode = 2; try { StringBuilder buffer = new StringBuilder(mCheckURL); try { NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()); if (!ni.isLoopback()) { if (ni.isUp()) { if (!ni.isVirtual()) { buffer.append('?'); byte[] macAddress = ni.getHardwareAddress(); for (byte one : macAddress) { buffer.append(Integer.toHexString(one >>> 4 & 0xF)); buffer.append(Integer.toHexString(one & 0xF)); } } } } } catch (Exception exception) { } URL url = new URL(buffer.toString()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); while (line != null) { StringTokenizer tokenizer = new StringTokenizer(line, "\t"); if (tokenizer.hasMoreTokens()) { try { if (tokenizer.nextToken().equalsIgnoreCase(mProductKey)) { String token = tokenizer.nextToken(); long version = Version.extractVersion(token); if (version > versionAvailable) { versionAvailable = version; } } } catch (Exception exception) { } } line = in.readLine(); } } catch (Exception exception) { } if (versionAvailable > currentVersion) { Preferences prefs = Preferences.getInstance(); String humanReadableVersion = Version.getHumanReadableVersion(versionAvailable); NEW_VERSION_AVAILABLE = true; RESULT = MessageFormat.format(MSG_OUT_OF_DATE, humanReadableVersion); if (versionAvailable > Version.extractVersion(prefs.getStringValue(MODULE, LAST_VERSION_KEY, App.getVersion()))) { prefs.setValue(MODULE, LAST_VERSION_KEY, humanReadableVersion); prefs.save(); mMode = 1; EventQueue.invokeLater(this); return; } } else { RESULT = MSG_UP_TO_DATE; } } else if (mMode == 1) { if (App.isNotificationAllowed()) { String result = getResult(); mMode = 2; if (WindowUtils.showConfirmDialog(null, result, MSG_UPDATE_TITLE, JOptionPane.OK_CANCEL_OPTION, new String[] { MSG_UPDATE_TITLE, MSG_IGNORE_TITLE }, MSG_UPDATE_TITLE) == JOptionPane.OK_OPTION) { goToUpdate(); } } else { DelayedTask.schedule(this, 250); } } } Code Sample 2: private void handleInterfaceDown(long eventID, long nodeID, String ipAddr, String eventTime) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (eventID == -1 || nodeID == -1 || ipAddr == null) { log.warn(EventConstants.INTERFACE_DOWN_EVENT_UEI + " ignored - info incomplete - eventid/nodeid/ip: " + eventID + "/" + nodeID + "/" + ipAddr); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement activeSvcsStmt = dbConn.prepareStatement(OutageConstants.DB_GET_ACTIVE_SERVICES_FOR_INTERFACE); PreparedStatement openStmt = dbConn.prepareStatement(OutageConstants.DB_OPEN_RECORD); PreparedStatement newOutageWriter = dbConn.prepareStatement(OutageConstants.DB_INS_NEW_OUTAGE); PreparedStatement getNextOutageIdStmt = dbConn.prepareStatement(OutageManagerConfigFactory.getInstance().getGetNextOutageID()); newOutageWriter = dbConn.prepareStatement(OutageConstants.DB_INS_NEW_OUTAGE); if (log.isDebugEnabled()) log.debug("handleInterfaceDown: creating new outage entries..."); activeSvcsStmt.setLong(1, nodeID); activeSvcsStmt.setString(2, ipAddr); ResultSet activeSvcsRS = activeSvcsStmt.executeQuery(); while (activeSvcsRS.next()) { long serviceID = activeSvcsRS.getLong(1); if (openOutageExists(dbConn, nodeID, ipAddr, serviceID)) { if (log.isDebugEnabled()) log.debug("handleInterfaceDown: " + nodeID + "/" + ipAddr + "/" + serviceID + " already down"); } else { long outageID = -1; ResultSet seqRS = getNextOutageIdStmt.executeQuery(); if (seqRS.next()) { outageID = seqRS.getLong(1); } seqRS.close(); newOutageWriter.setLong(1, outageID); newOutageWriter.setLong(2, eventID); newOutageWriter.setLong(3, nodeID); newOutageWriter.setString(4, ipAddr); newOutageWriter.setLong(5, serviceID); newOutageWriter.setTimestamp(6, convertEventTimeIntoTimestamp(eventTime)); newOutageWriter.executeUpdate(); if (log.isDebugEnabled()) log.debug("handleInterfaceDown: Recording new outage for " + nodeID + "/" + ipAddr + "/" + serviceID); } } activeSvcsRS.close(); try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("Outage recorded for all active services for " + nodeID + "/" + ipAddr); } catch (SQLException se) { log.warn("Rolling back transaction, interfaceDown could not be recorded for nodeid/ipAddr: " + nodeID + "/" + ipAddr, se); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } activeSvcsStmt.close(); openStmt.close(); newOutageWriter.close(); } catch (SQLException sqle) { log.warn("SQL exception while handling \'interfaceDown\'", sqle); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } }
11
Code Sample 1: public static void copyAFile(final String entree, final String sortie) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(entree).getChannel(); out = new FileOutputStream(sortie).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } Code Sample 2: public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + 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.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } }
11
Code Sample 1: public static void main(String[] argz) { int X, Y, Z; X = 256; Y = 256; Z = 256; try { String work_folder = "C:\\Documents and Settings\\Entheogen\\My Documents\\school\\jung\\vol_data\\CT_HEAD3"; FileOutputStream out_stream = new FileOutputStream(new File(work_folder + "\\converted.dat")); FileChannel out = out_stream.getChannel(); String f_name = "head256.raw"; File file = new File(work_folder + "\\" + f_name); FileChannel in = new FileInputStream(file).getChannel(); ByteBuffer buffa = BufferUtil.newByteBuffer((int) file.length()); in.read(buffa); in.close(); int N = 256; FloatBuffer output_data = BufferUtil.newFloatBuffer(N * N * N); float min = Float.MAX_VALUE; for (int i = 0, j = 0; i < buffa.capacity(); i++, j++) { byte c = buffa.get(i); min = Math.min(min, (float) (c)); output_data.put((float) (c)); } for (int i = 0; i < Y - X; ++i) { for (int j = 0; j < Y; ++j) { for (int k = 0; k < Z; ++k) { output_data.put(min); } } } output_data.rewind(); System.out.println("size of output_data = " + Integer.toString(output_data.capacity())); out.write(BufferUtil.copyFloatBufferAsByteBuffer(output_data)); ByteBuffer buffa2 = BufferUtil.newByteBuffer(2); buffa2.put((byte) '.'); out.close(); } catch (Exception exc) { exc.printStackTrace(); } } Code Sample 2: @Test public void testWriteAndReadFirstLevel() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile directory1 = new RFile("directory1"); RFile file = new RFile(directory1, "testreadwrite1st.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } }
11
Code Sample 1: private void execute(File file) throws IOException { if (file == null) throw new RuntimeException("undefined file"); if (!file.exists()) throw new RuntimeException("file not found :" + file); if (!file.isFile()) throw new RuntimeException("not a file :" + file); String login = cfg.getProperty(GC_USERNAME); String password = null; if (cfg.containsKey(GC_PASSWORD)) { password = cfg.getProperty(GC_PASSWORD); } else { password = new String(Base64.decode(cfg.getProperty(GC_PASSWORD64))); } PostMethod post = null; try { HttpClient client = new HttpClient(); post = new PostMethod("https://" + projectName + ".googlecode.com/files"); post.addRequestHeader("User-Agent", getClass().getName()); post.addRequestHeader("Authorization", "Basic " + Base64.encode(login + ":" + password)); List<Part> parts = new ArrayList<Part>(); String s = this.summary; if (StringUtils.isBlank(s)) { s = file.getName() + " (" + TimeUtils.toYYYYMMDD() + ")"; } parts.add(new StringPart("summary", s)); for (String lbl : this.labels) { if (StringUtils.isBlank(lbl)) continue; parts.add(new StringPart("label", lbl.trim())); } parts.add(new FilePart("filename", file)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()); post.setRequestEntity(requestEntity); int status = client.executeMethod(post); if (status != 201) { throw new IOException("http status !=201 : " + post.getResponseBodyAsString()); } else { IOUtils.copyTo(post.getResponseBodyAsStream(), new NullOutputStream()); } } finally { if (post != null) post.releaseConnection(); } } Code Sample 2: @Test public void testTrainingDefault() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); }
11
Code Sample 1: 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(); } Code Sample 2: public void handleEvent(Event event) { if (fileDialog == null) { fileDialog = new FileDialog(getShell(), SWT.OPEN); fileDialog.setText("Open device profile file..."); fileDialog.setFilterNames(new String[] { "Device profile (*.jar)" }); fileDialog.setFilterExtensions(new String[] { "*.jar" }); } fileDialog.open(); if (fileDialog.getFileName() != null) { File file; String manifestDeviceName = null; URL[] urls = new URL[1]; ArrayList descriptorEntries = new ArrayList(); try { file = new File(fileDialog.getFilterPath(), fileDialog.getFileName()); JarFile jar = new JarFile(file); Manifest manifest = jar.getManifest(); if (manifest != null) { Attributes attrs = manifest.getMainAttributes(); manifestDeviceName = attrs.getValue("Device-Name"); } for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorEntries.add(entry); } } jar.close(); urls[0] = file.toURL(); } catch (IOException ex) { Message.error("Error reading file: " + fileDialog.getFileName() + ", " + Message.getCauseMessage(ex), ex); return; } if (descriptorEntries.size() == 0) { Message.error("Cannot find any device profile in file: " + fileDialog.getFileName()); return; } if (descriptorEntries.size() > 1) { manifestDeviceName = null; } ClassLoader classLoader = Common.createExtensionsClassLoader(urls); HashMap devices = new HashMap(); for (Iterator it = descriptorEntries.iterator(); it.hasNext(); ) { JarEntry entry = (JarEntry) it.next(); try { devices.put(entry.getName(), DeviceImpl.create(emulatorContext, classLoader, entry.getName(), SwtDevice.class)); } catch (IOException ex) { Message.error("Error parsing device profile, " + Message.getCauseMessage(ex), ex); return; } } for (int i = 0; i < deviceModel.size(); i++) { DeviceEntry entry = (DeviceEntry) deviceModel.elementAt(i); if (devices.containsKey(entry.getDescriptorLocation())) { devices.remove(entry.getDescriptorLocation()); } } if (devices.size() == 0) { Message.info("Device profile already added"); return; } try { File deviceFile = new File(Config.getConfigPath(), file.getName()); if (deviceFile.exists()) { deviceFile = File.createTempFile("device", ".jar", Config.getConfigPath()); } IOUtils.copyFile(file, deviceFile); DeviceEntry entry = null; for (Iterator it = devices.keySet().iterator(); it.hasNext(); ) { String descriptorLocation = (String) it.next(); Device device = (Device) devices.get(descriptorLocation); if (manifestDeviceName != null) { entry = new DeviceEntry(manifestDeviceName, deviceFile.getName(), descriptorLocation, false); } else { entry = new DeviceEntry(device.getName(), deviceFile.getName(), descriptorLocation, false); } deviceModel.addElement(entry); for (int i = 0; i < deviceModel.size(); i++) { if (deviceModel.elementAt(i) == entry) { lsDevices.add(entry.getName()); lsDevices.select(i); } } Config.addDeviceEntry(entry); } lsDevicesListener.widgetSelected(null); } catch (IOException ex) { Message.error("Error adding device profile, " + Message.getCauseMessage(ex), ex); return; } } }
11
Code Sample 1: private void copyResources(File oggDecDir, String[] resources, String resPrefix) throws FileNotFoundException, IOException { for (int i = 0; i < resources.length; i++) { String res = resPrefix + resources[i]; InputStream is = this.getClass().getResourceAsStream(res); if (is == null) throw new IllegalArgumentException("cannot find resource '" + res + "'"); File file = new File(oggDecDir, resources[i]); if (!file.exists() || file.length() == 0) { FileOutputStream fos = new FileOutputStream(file); try { IOUtils.copyStreams(is, fos); } finally { fos.close(); } } } } Code Sample 2: private void processHelpFile() { InputStream in = null; if (line.hasOption("helpfile")) { OutputStream out = null; try { String filename = line.getOptionValue("helpfile"); in = new FileInputStream(filename); filename = filename.replace('\\', '/'); filename = filename.substring(filename.lastIndexOf('/') + 1); File outFile = new File(outputDir, filename); if (LOG.isInfoEnabled()) { LOG.info("Processing generated file " + outFile.getAbsolutePath()); } out = new FileOutputStream(outFile); baseProperties.setProperty("helpfile", filename); IOUtils.copy(in, out); } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } return; } Properties props = new Properties(baseProperties); ClassLoader cl = this.getClass().getClassLoader(); Document doc = null; try { in = cl.getResourceAsStream(RESOURCE_PKG + "/help-doc.xml"); doc = XmlUtils.parse(in); } catch (XmlException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } transformResource(doc, "help-doc.xsl", props, "help-doc.html"); baseProperties.setProperty("helpfile", "help-doc.html"); }
11
Code Sample 1: private void copy(FileInfo inputFile, FileInfo outputFile) { try { FileReader in = new FileReader(inputFile.file); FileWriter out = new FileWriter(outputFile.file); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); outputFile.file.setLastModified(inputFile.lastModified); } catch (IOException e) { } } Code Sample 2: public static boolean copyFile(final String src, final String dest) { if (fileExists(src)) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); return true; } catch (IOException e) { Logger.getAnonymousLogger().severe(e.getLocalizedMessage()); } } return false; }
11
Code Sample 1: public static void replaceEntry(File file, String entryName, InputStream stream) throws PersistenceException { try { File temporaryFile = File.createTempFile("pmMDA_zargo", ".zargo"); temporaryFile.deleteOnExit(); FileInputStream inputStream = new FileInputStream(file); ZipInputStream input = new ZipInputStream(inputStream); ZipOutputStream output = new ZipOutputStream(new FileOutputStream(temporaryFile)); ZipEntry entry = input.getNextEntry(); while (entry != null) { ZipEntry zipEntry = new ZipEntry(entry); zipEntry.setCompressedSize(-1); output.putNextEntry(zipEntry); if (!entry.getName().equals(entryName)) { IOUtils.copy(input, output); } else { IOUtils.copy(stream, output); } input.closeEntry(); output.closeEntry(); entry = input.getNextEntry(); } input.close(); inputStream.close(); output.close(); System.gc(); boolean isSuccess = file.delete(); if (!isSuccess) { throw new PersistenceException(); } isSuccess = temporaryFile.renameTo(file); if (!isSuccess) { throw new PersistenceException(); } } catch (IOException e) { throw new PersistenceException(e); } } Code Sample 2: void copyFile(String from, String to) throws IOException { File destFile = new File(to); if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(from).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
00
Code Sample 1: public void retrieveChallenges(int num) throws MalformedURLException, IOException, FBErrorException, FBConnectionException { if (num < 1 || num > 100) { error = true; FBErrorException fbee = new FBErrorException(); fbee.setErrorCode(-100); fbee.setErrorText("Invalid GetChallenges range"); throw fbee; } URL url = new URL(getHost() + getPath()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("X-FB-User", getUser()); conn.setRequestProperty("X-FB-Mode", "GetChallenges"); conn.setRequestProperty("X-FB-GetChallenges.Qty", new Integer(num).toString()); conn.connect(); Element fbresponse; try { fbresponse = readXML(conn); } catch (FBConnectionException fbce) { error = true; throw fbce; } catch (FBErrorException fbee) { error = true; throw fbee; } catch (Exception e) { error = true; FBConnectionException fbce = new FBConnectionException("XML parsing failed"); fbce.attachSubException(e); throw fbce; } NodeList nl = fbresponse.getElementsByTagName("GetChallengesResponse"); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i) instanceof Element && hasError((Element) nl.item(i))) { error = true; FBErrorException e = new FBErrorException(); e.setErrorCode(errorcode); e.setErrorText(errortext); throw e; } } NodeList challenge = fbresponse.getElementsByTagName("Challenge"); for (int i = 0; i < challenge.getLength(); i++) { NodeList children = challenge.item(i).getChildNodes(); for (int j = 0; j < children.getLength(); j++) { if (children.item(j) instanceof Text) { challenges.offer(children.item(j).getNodeValue()); } } } } Code Sample 2: @Test public void test01_ok_failed_500() throws Exception { DefaultHttpClient client = new DefaultHttpClient(); try { HttpPost post = new HttpPost(chartURL); HttpResponse response = client.execute(post); assertEquals("failed code for ", 500, response.getStatusLine().getStatusCode()); } finally { client.getConnectionManager().shutdown(); } }
11
Code Sample 1: public void saveDownloadFiles(List downloadFiles) throws SQLException { Connection conn = AppLayerDatabase.getInstance().getPooledConnection(); try { conn.setAutoCommit(false); Statement s = conn.createStatement(); s.executeUpdate("DELETE FROM DOWNLOADFILES"); s.close(); s = null; PreparedStatement ps = conn.prepareStatement("INSERT INTO DOWNLOADFILES " + "(name,targetpath,size,fnkey,enabled,state,downloadaddedtime,downloadstartedtime,downloadfinishedtime," + "retries,lastdownloadstoptime,gqid,filelistfilesha) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"); for (Iterator i = downloadFiles.iterator(); i.hasNext(); ) { FrostDownloadItem dlItem = (FrostDownloadItem) i.next(); int ix = 1; ps.setString(ix++, dlItem.getFilename()); ps.setString(ix++, dlItem.getTargetPath()); ps.setLong(ix++, (dlItem.getFileSize() == null ? 0 : dlItem.getFileSize().longValue())); ps.setString(ix++, dlItem.getKey()); ps.setBoolean(ix++, (dlItem.isEnabled() == null ? true : dlItem.isEnabled().booleanValue())); ps.setInt(ix++, dlItem.getState()); ps.setLong(ix++, dlItem.getDownloadAddedTime()); ps.setLong(ix++, dlItem.getDownloadStartedTime()); ps.setLong(ix++, dlItem.getDownloadFinishedTime()); ps.setInt(ix++, dlItem.getRetries()); ps.setLong(ix++, dlItem.getLastDownloadStopTime()); ps.setString(ix++, dlItem.getGqIdentifier()); ps.setString(ix++, dlItem.getFileListFileObject() == null ? null : dlItem.getFileListFileObject().getSha()); ps.executeUpdate(); } ps.close(); conn.commit(); conn.setAutoCommit(true); } catch (Throwable t) { logger.log(Level.SEVERE, "Exception during save", t); try { conn.rollback(); } catch (Throwable t1) { logger.log(Level.SEVERE, "Exception during rollback", t1); } try { conn.setAutoCommit(true); } catch (Throwable t1) { } } finally { AppLayerDatabase.getInstance().givePooledConnection(conn); } } Code Sample 2: public void deleteDomain(final List<Integer> domainIds) { try { connection.setAutoCommit(false); final int defaultDomainId = ((DomainDb) cmDB.getDefaultDomain()).getDomainId(); boolean defaultDomainDeleted = (Boolean) new ProcessEnvelope().executeObject(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public Object executeProcessReturnObject() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("domain.delete")); Iterator<Integer> iter = domainIds.iterator(); int domainId; boolean defaultDomainDeleted = false; while (iter.hasNext()) { domainId = iter.next(); if (!defaultDomainDeleted) defaultDomainDeleted = defaultDomainId == domainId; psImpl.setInt(1, domainId); psImpl.executeUpdate(); } return defaultDomainDeleted; } }); if (defaultDomainDeleted) { new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("domain.setDefaultDomainId")); psImpl.setInt(1, -1); psImpl.executeUpdate(); } }); } connection.commit(); cmDB.updateDomains(null, null); if (defaultDomainDeleted) { cm.updateDefaultDomain(); } } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } }
00
Code Sample 1: public static ObjectID[] sortDecending(ObjectID[] oids) { for (int i = 1; i < oids.length; i++) { ObjectID iId = oids[i]; for (int j = 0; j < oids.length - i; j++) { if (oids[j].getTypePrefix() > oids[j + 1].getTypePrefix()) { ObjectID temp = oids[j]; oids[j] = oids[j + 1]; oids[j + 1] = temp; } } } return oids; } Code Sample 2: private void installBinaryFile(File source, File destination) { byte[] buffer = new byte[8192]; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); int read; while ((read = fis.read(buffer)) != -1) { fos.write(buffer, 0, read); } } catch (FileNotFoundException e) { } catch (IOException e) { new ProjectCreateException(e, "Failed to read binary file: %1$s", source.getAbsolutePath()); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { } } if (fos != null) { try { fos.close(); } catch (IOException e) { } } } }
11
Code Sample 1: public static void registerProviders(ResteasyProviderFactory factory) throws Exception { Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources("META-INF/services/" + Providers.class.getName()); LinkedHashSet<String> set = new LinkedHashSet<String>(); while (en.hasMoreElements()) { URL url = en.nextElement(); InputStream is = url.openStream(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.equals("")) continue; set.add(line); } } finally { is.close(); } } for (String line : set) { try { Class clazz = Thread.currentThread().getContextClassLoader().loadClass(line); factory.registerProvider(clazz, true); } catch (NoClassDefFoundError e) { logger.warn("NoClassDefFoundError: Unable to load builtin provider: " + line); } catch (ClassNotFoundException e) { logger.warn("ClassNotFoundException: Unable to load builtin provider: " + line); } } } Code Sample 2: private static String appletLoad(String file, Output OUT) { if (!urlpath.endsWith("/")) { urlpath += '/'; } if (!urlpath.startsWith("http://")) { urlpath = "http://" + urlpath; } String url = ""; if (file.equals("languages.txt")) { url = urlpath + file; } else { url = urlpath + "users/" + file; } try { StringBuffer sb = new StringBuffer(2000); BufferedReader br = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String a; while ((a = br.readLine()) != null) { sb.append(a).append('\n'); } return sb.toString(); } catch (Exception e) { OUT.println("load failed for file->" + file); } return ""; }
00
Code Sample 1: @Override protected String doInBackground(String... params) { HttpURLConnection conn = null; String localFilePath = params[0]; if (localFilePath == null) { return null; } try { URL url = new URL(ConnectionHandler.getServerURL() + ":" + ConnectionHandler.getServerPort() + "/"); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); DataInputStream fileReader = new DataInputStream(new FileInputStream(localFilePath)); dos.write(toByte(twoHyphens + boundary + lineEnd)); dos.write(toByte("Content-Disposition: form-data; name=\"uploadfile\"; filename=\"redpinfile\"" + lineEnd)); dos.write(toByte("Content-Type: application/octet-stream" + lineEnd)); dos.write(toByte("Content-Length: " + fileReader.available() + lineEnd)); dos.write(toByte(lineEnd)); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fileReader.read(buffer)) != -1) { dos.write(buffer, 0, bytesRead); } dos.write(toByte(lineEnd)); dos.write(toByte(twoHyphens + boundary + twoHyphens + lineEnd)); dos.flush(); dos.close(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = conn.getInputStream(); int ch; StringBuffer b = new StringBuffer(); while ((ch = is.read()) != -1) { b.append((char) ch); } return b.toString(); } } catch (MalformedURLException ex) { Log.w(TAG, "error: " + ex.getMessage(), ex); } catch (IOException ioe) { Log.w(TAG, "error: " + ioe.getMessage(), ioe); } finally { if (conn != null) { conn.disconnect(); } } return null; } Code Sample 2: public TVRageShowInfo(String xmlShowName) { String[] tmp, tmp2; String line = ""; this.usrShowName = xmlShowName; try { URL url = new URL("http://www.tvrage.com/quickinfo.php?show=" + xmlShowName.replaceAll(" ", "%20")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { tmp = line.split("@"); if (tmp[0].equals("Show Name")) showName = tmp[1]; if (tmp[0].equals("Show URL")) showURL = tmp[1]; if (tmp[0].equals("Latest Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); latestSeasonNum = tmp2[0]; latestEpisodeNum = tmp2[1]; if (latestSeasonNum.charAt(0) == '0') latestSeasonNum = latestSeasonNum.substring(1); } else if (i == 1) latestTitle = st.nextToken().replaceAll("&", "and"); else latestAirDate = st.nextToken(); } } if (tmp[0].equals("Next Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); nextSeasonNum = tmp2[0]; nextEpisodeNum = tmp2[1]; if (nextSeasonNum.charAt(0) == '0') nextSeasonNum = nextSeasonNum.substring(1); } else if (i == 1) nextTitle = st.nextToken().replaceAll("&", "and"); else nextAirDate = st.nextToken(); } } if (tmp[0].equals("Status")) status = tmp[1]; if (tmp[0].equals("Airtime")) airTime = tmp[1]; } if (airTime.length() != 0) { tmp = airTime.split(","); airTimeHour = tmp[1]; } in.close(); url = new URL(showURL); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { if (line.indexOf("<b>Latest Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[2].indexOf(':') > -1) { tmp = tmp[2].split(":"); latestSeriesNum = tmp[0]; } } else if (line.indexOf("<b>Next Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[2].indexOf(':') > -1) { tmp = tmp[2].split(":"); nextSeriesNum = tmp[0]; } } } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
00
Code Sample 1: private boolean verifyAppId(String appid) { try { String urlstr = "http://" + appid + ".appspot.com"; URL url = new URL(urlstr); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { buf.append(line); } reader.close(); return buf.toString().contains("hyk-proxy"); } catch (Exception e) { } return false; } Code Sample 2: void startzm() { URL myzzurl; InputStream myzstream; byte zmemimage[]; boolean joined; zmemimage = null; try { System.err.println(zcodefile); myzzurl = new URL(zcodefile); myzstream = myzzurl.openStream(); zmemimage = suckstream(myzstream); } catch (MalformedURLException booga) { try { myzstream = new FileInputStream(zcodefile); zmemimage = suckstream(myzstream); } catch (IOException booga2) { add("North", new Label("Malformed URL")); failed = true; } } catch (IOException booga) { add("North", new Label("I/O Error")); } if (zmemimage != null) { switch(zmemimage[0]) { case 3: zm = new ZMachine3(screen, status_line, zmemimage); break; case 5: remove(status_line); zm = new ZMachine5(screen, zmemimage); break; case 8: remove(status_line); zm = new ZMachine8(screen, zmemimage); break; default: add("North", new Label("Not a valid V3,V5, or V8 story file")); } if (zm != null) zm.start(); } joined = false; if (zmemimage != null) { while (!joined) { try { zm.join(); joined = true; } catch (InterruptedException booga) { } } } System.exit(0); }
00
Code Sample 1: private static URL getURL(String name) throws EfreetException { URL url = ClassLoader.getSystemResource(name + ".xml"); try { if (url == null) { try { Context initContext = new InitialContext(); Context envContext = (Context) initContext.lookup("java:/comp/env"); String xmlFileDir = (String) envContext.lookup("xml/efreet"); url = new URL("file:" + xmlFileDir + "/" + name + ".xml"); } catch (NameNotFoundException nnfe) { logger.warn("Name not found on context "); } catch (NamingException e) { logger.error("Error retrieving Context : ", e); } } try { if (url != null) { url.openConnection(); } } catch (FileNotFoundException fnfe) { url = null; } if (url == null) { url = Thread.currentThread().getContextClassLoader().getResource(name + ".xml"); } } catch (IOException ioe) { logger.error("Error reading XML file", ioe); throw new EfreetException(ioe.getMessage()); } return url; } Code Sample 2: public static void copy(final File src, File dst, final boolean overwrite) throws IOException, IllegalArgumentException { if (!src.isFile() || !src.exists()) { throw new IllegalArgumentException("Source file '" + src.getAbsolutePath() + "' not found!"); } if (dst.exists()) { if (dst.isDirectory()) { dst = new File(dst, src.getName()); } else if (dst.isFile()) { if (!overwrite) { throw new IllegalArgumentException("Destination file '" + dst.getAbsolutePath() + "' already exists!"); } } else { throw new IllegalArgumentException("Invalid destination object '" + dst.getAbsolutePath() + "'!"); } } final File dstParent = dst.getParentFile(); if (!dstParent.exists()) { if (!dstParent.mkdirs()) { throw new IOException("Failed to create directory " + dstParent.getAbsolutePath()); } } long fileSize = src.length(); if (fileSize > 20971520l) { final FileInputStream in = new FileInputStream(src); final FileOutputStream out = new FileOutputStream(dst); try { int doneCnt = -1; final int bufSize = 32768; final byte buf[] = new byte[bufSize]; while ((doneCnt = in.read(buf, 0, bufSize)) >= 0) { if (doneCnt == 0) { Thread.yield(); } else { out.write(buf, 0, doneCnt); } } out.flush(); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } } } else { final FileInputStream fis = new FileInputStream(src); final FileOutputStream fos = new FileOutputStream(dst); final FileChannel in = fis.getChannel(), out = fos.getChannel(); try { long offs = 0, doneCnt = 0; final long copyCnt = Math.min(65536, fileSize); do { doneCnt = in.transferTo(offs, copyCnt, out); offs += doneCnt; fileSize -= doneCnt; } while (fileSize > 0); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } try { fis.close(); } catch (final IOException e) { } try { fos.close(); } catch (final IOException e) { } } } }
00
Code Sample 1: private String getRenderedBody(String spec) throws Exception { log.entering(Rss2MailTask.class.getName(), "getRenderedBody"); final URL url = new URL(spec); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); final InputStream inputStream = connection.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; final StringBuffer bf = new StringBuffer(); while (line != null) { line = reader.readLine(); if (line != null) { bf.append(line); } } log.exiting(Rss2MailTask.class.getName(), "getRenderedBody"); return bf.toString(); } Code Sample 2: @Override public String decryptString(String passphrase, String crypted) throws Exception { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes("UTF-8")); byte digest[] = md.digest(); String digestString = base64encode(digest); System.out.println(digestString); SecureRandom sr = new SecureRandom(digestString.getBytes()); KeyGenerator kGen = KeyGenerator.getInstance("AES"); kGen.init(128, sr); Key key = kGen.generateKey(); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key); byte[] cryptString = base64decode(crypted); byte[] bOut = cipher.doFinal(cryptString); String outString = new String(bOut, "UTF-8"); return outString; }
11
Code Sample 1: public static String crypt(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("String to encript cannot be null or zero length"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { throw new ForumException("" + e); } return hexString.toString(); } Code Sample 2: public static String hash(String plaintext) { if (plaintext == null) { return ""; } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); md.update(plaintext.getBytes("UTF-8")); } catch (Exception e) { } return new String(Base64.encodeBase64(md.digest())); }
00
Code Sample 1: public static String rename_tag(String sessionid, String originalTag, String newTagName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_tag"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "rename_tag")); nameValuePairs.add(new BasicNameValuePair("new_tag_name", newTagName)); nameValuePairs.add(new BasicNameValuePair("absolute_tag", originalTag)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; } Code Sample 2: public void initForEncryption() throws CryptographyException, IOException { String ownerPassword = pdDocument.getOwnerPasswordForEncryption(); String userPassword = pdDocument.getUserPasswordForEncryption(); if (ownerPassword == null) { ownerPassword = ""; } if (userPassword == null) { userPassword = ""; } PDStandardEncryption encParameters = (PDStandardEncryption) pdDocument.getEncryptionDictionary(); int permissionInt = encParameters.getPermissions(); int revision = encParameters.getRevision(); int length = encParameters.getLength() / 8; COSArray idArray = document.getDocumentID(); if (idArray == null || idArray.size() < 2) { idArray = new COSArray(); try { MessageDigest md = MessageDigest.getInstance("MD5"); BigInteger time = BigInteger.valueOf(System.currentTimeMillis()); md.update(time.toByteArray()); md.update(ownerPassword.getBytes()); md.update(userPassword.getBytes()); md.update(document.toString().getBytes()); byte[] id = md.digest(this.toString().getBytes()); COSString idString = new COSString(); idString.append(id); idArray.add(idString); idArray.add(idString); document.setDocumentID(idArray); } catch (NoSuchAlgorithmException e) { throw new CryptographyException(e); } } COSString id = (COSString) idArray.getObject(0); encryption = new PDFEncryption(); byte[] o = encryption.computeOwnerPassword(ownerPassword.getBytes("ISO-8859-1"), userPassword.getBytes("ISO-8859-1"), revision, length); byte[] u = encryption.computeUserPassword(userPassword.getBytes("ISO-8859-1"), o, permissionInt, id.getBytes(), revision, length); encryptionKey = encryption.computeEncryptedKey(userPassword.getBytes("ISO-8859-1"), o, permissionInt, id.getBytes(), revision, length); encParameters.setOwnerKey(o); encParameters.setUserKey(u); document.setEncryptionDictionary(encParameters.getCOSDictionary()); }
00
Code Sample 1: private void SaveToArchive(Layer layer, String layerFileName) throws Exception { Object archiveObj = layer.getBlackboard().get("ArchiveFileName"); Object entryObj = layer.getBlackboard().get("ArchiveEntryPrefix"); if ((archiveObj == null) || (entryObj == null)) return; String archiveName = archiveObj.toString(); String entryPrefix = entryObj.toString(); if ((archiveName == "") || (entryPrefix == "")) return; File tempZip = File.createTempFile("tmp", ".zip"); InputStream in = new BufferedInputStream(new FileInputStream(archiveName)); OutputStream out = new BufferedOutputStream(new FileOutputStream(tempZip)); copy(in, out); in.close(); out.close(); ZipFile zipFile = new ZipFile(tempZip); ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(archiveName))); ZipInputStream zin = new ZipInputStream(new FileInputStream(tempZip)); ZipEntry entry = zin.getNextEntry(); while (entry != null) { String entryName = entry.getName(); String en = GUIUtil.nameWithoutExtension(new File(entryName)); if (en.equalsIgnoreCase(entryPrefix)) { if (entryName.endsWith(".jmp")) { String layerTaskPath = CreateArchivePlugIn.createLayerTask(layer, archiveName, entryPrefix); CreateArchivePlugIn.WriteZipEntry(layerTaskPath, entryPrefix, zout); } else if ((!entryName.endsWith(".shx")) && (!entryName.endsWith(".dbf")) && (!entryName.endsWith(".shp.xml")) && (!entryName.endsWith(".prj"))) { CreateArchivePlugIn.WriteZipEntry(layerFileName, entryPrefix, zout); } } else { zout.putNextEntry(entry); copy(zin, zout); } entry = zin.getNextEntry(); } zin.close(); zout.close(); zipFile.close(); tempZip.delete(); } Code Sample 2: protected File downloadUpdate(String resource) throws AgentException { RESTCall call = makeRESTCall(resource); call.invoke(); File tmpFile; try { tmpFile = File.createTempFile("controller-update-", ".war", new File(tmpPath)); } catch (IOException e) { throw new AgentException("Failed to create temporary file", e); } InputStream is; try { is = call.getInputStream(); } catch (IOException e) { throw new AgentException("Failed to open input stream", e); } try { FileOutputStream os; try { os = new FileOutputStream(tmpFile); } catch (FileNotFoundException e) { throw new AgentException("Failed to open temporary file for writing", e); } boolean success = false; try { IOUtils.copy(is, os); success = true; } catch (IOException e) { throw new AgentException("Failed to download update", e); } finally { try { os.flush(); os.close(); } catch (IOException e) { if (!success) throw new AgentException("Failed to flush to disk", e); } } } finally { try { is.close(); } catch (IOException e) { log.error("Failed to close input stream", e); } call.disconnect(); } return tmpFile; }
11
Code Sample 1: public static String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; } Code Sample 2: public String digestPassword(String password) { StringBuffer hexString = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes()); byte[] messageDigest = algorithm.digest(); for (byte b : messageDigest) { hexString.append(Integer.toHexString(0xFF & b)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hexString.toString(); }
11
Code Sample 1: @Override protected ActionForward executeAction(ActionMapping mapping, ActionForm form, User user, HttpServletRequest request, HttpServletResponse response) throws Exception { long resourceId = ServletRequestUtils.getLongParameter(request, "resourceId", 0L); String attributeIdentifier = request.getParameter("identifier"); if (resourceId != 0L && StringUtils.hasText(attributeIdentifier)) { try { BinaryAttribute binaryAttribute = resourceManager.readAttribute(resourceId, attributeIdentifier, user); response.addHeader("Content-Disposition", "attachment; filename=\"" + binaryAttribute.getName() + '"'); String contentType = binaryAttribute.getContentType(); if (contentType != null) { if ("application/x-zip-compressed".equalsIgnoreCase(contentType)) { response.setContentType("application/octet-stream"); } else { response.setContentType(contentType); } } else { response.setContentType("application/octet-stream"); } IOUtils.copy(binaryAttribute.getInputStream(), response.getOutputStream()); return null; } catch (DataRetrievalFailureException e) { addGlobalError(request, "errors.notFound"); } catch (Exception e) { addGlobalError(request, e); } } return mapping.getInputForward(); } Code Sample 2: private static void copyFile(File f) { try { String baseName = baseDir.getCanonicalPath(); String fullPath = f.getCanonicalPath(); String nameSufix = fullPath.substring(baseName.length() + 1); File destFile = new File(FileDestDir, nameSufix); destFile.getParentFile().mkdirs(); destFile.createNewFile(); FileChannel fromChannel = new FileInputStream(f).getChannel(); FileChannel toChannel = new FileOutputStream(destFile).getChannel(); fromChannel.transferTo(0, fromChannel.size(), toChannel); fromChannel.close(); toChannel.close(); destFile.setLastModified(f.lastModified()); } catch (Exception e) { System.err.println(e.getMessage()); } }
11
Code Sample 1: private String copyAndHash(InputStream input, File into) throws IOException { MessageDigest digest = createMessageDigest(); DigestInputStream dis = new DigestInputStream(input, digest); IOException ex; FileOutputStream fos = null; try { fos = new FileOutputStream(into); IOUtils.copyLarge(dis, fos); byte[] hash = digest.digest(); Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } return formatter.toString(); } catch (IOException e) { ex = e; } finally { IOUtils.closeQuietly(dis); IOUtils.closeQuietly(fos); } if (logger.isWarnEnabled()) logger.warn("Couldn't retrieve data from input!", ex); deleteTempFile(into); throw ex; } Code Sample 2: public static final void copy(String source, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(source)); to = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " copying file"); } try { to.close(); from.close(); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " closing files"); } }
11
Code Sample 1: public void testAddFiles() throws Exception { File original = ZipPlugin.getFileInPlugin(new Path("testresources/test.zip")); File copy = new File(original.getParentFile(), "1test.zip"); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(original); out = new FileOutputStream(copy); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } ArchiveFile archive = new ArchiveFile(ZipPlugin.createArchive(copy.getPath())); archive.addFiles(new String[] { ZipPlugin.getFileInPlugin(new Path("testresources/add.txt")).getPath() }, new NullProgressMonitor()); IArchive[] children = archive.getChildren(); boolean found = false; for (IArchive child : children) { if (child.getLabel(IArchive.NAME).equals("add.txt")) found = true; } assertTrue(found); copy.delete(); } Code Sample 2: public static long writePropertiesInOpenXMLDocument(String ext, InputStream in, OutputStreamProvider outProvider, Map<String, String> properties) { in = new BufferedInputStream(in); try { File tempPptx = null; POIXMLDocument doc; if (ext.toLowerCase().equals("docx")) { doc = new XWPFDocument(in); } else if (ext.toLowerCase().equals("xlsx")) { doc = new XSSFWorkbook(in); } else if (ext.toLowerCase().equals("pptx")) { tempPptx = File.createTempFile("temp", "pptx"); OutputStream tempPptxOut = new FileOutputStream(tempPptx); tempPptxOut = new BufferedOutputStream(tempPptxOut); IOUtils.copy(in, tempPptxOut); tempPptxOut.close(); doc = new XSLFSlideShow(tempPptx.getAbsolutePath()); } else { throw new IllegalArgumentException("Writing properties for a " + ext + " file is not supported"); } for (Map.Entry<String, String> property : properties.entrySet()) { CoreProperties coreProperties = doc.getProperties().getCoreProperties(); if (property.getKey().equals(Metadata.TITLE)) { coreProperties.setTitle(property.getValue()); } else if (property.getKey().equals(Metadata.AUTHOR)) { coreProperties.setCreator(property.getValue()); } else if (property.getKey().equals(Metadata.KEYWORDS)) { coreProperties.getUnderlyingProperties().setKeywordsProperty(property.getValue()); } else if (property.getKey().equals(Metadata.COMMENTS)) { coreProperties.setDescription(property.getValue()); } else if (property.getKey().equals(Metadata.SUBJECT)) { coreProperties.setSubjectProperty(property.getValue()); } else if (property.getKey().equals(Metadata.COMPANY)) { doc.getProperties().getExtendedProperties().getUnderlyingProperties().setCompany(property.getValue()); } else { org.apache.poi.POIXMLProperties.CustomProperties customProperties = doc.getProperties().getCustomProperties(); if (customProperties.contains(property.getKey())) { int index = 0; for (CTProperty prop : customProperties.getUnderlyingProperties().getPropertyArray()) { if (prop.getName().equals(property.getKey())) { customProperties.getUnderlyingProperties().removeProperty(index); break; } index++; } } customProperties.addProperty(property.getKey(), property.getValue()); } } in.close(); File tempOpenXMLDocumentFile = File.createTempFile("temp", "tmp"); OutputStream tempOpenXMLDocumentOut = new FileOutputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentOut = new BufferedOutputStream(tempOpenXMLDocumentOut); doc.write(tempOpenXMLDocumentOut); tempOpenXMLDocumentOut.close(); long length = tempOpenXMLDocumentFile.length(); InputStream tempOpenXMLDocumentIn = new FileInputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentIn = new BufferedInputStream(tempOpenXMLDocumentIn); OutputStream out = null; try { out = outProvider.getOutputStream(); out = new BufferedOutputStream(out); IOUtils.copy(tempOpenXMLDocumentIn, out); out.flush(); } finally { IOUtils.closeQuietly(out); } if (!FileUtils.deleteQuietly(tempOpenXMLDocumentFile)) { tempOpenXMLDocumentFile.deleteOnExit(); } if (tempPptx != null && !FileUtils.deleteQuietly(tempPptx)) { tempPptx.deleteOnExit(); } return length; } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidFormatException e) { throw new RuntimeException(e); } catch (OpenXML4JException e) { throw new RuntimeException(e); } catch (XmlException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(in); } }
11
Code Sample 1: private static void setEnvEntry(File fromEAR, File toEAR, String ejbJarName, String envEntryName, String envEntryValue) throws Exception { ZipInputStream earFile = new ZipInputStream(new FileInputStream(fromEAR)); FileOutputStream fos = new FileOutputStream(toEAR); ZipOutputStream tempZip = new ZipOutputStream(fos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals(ejbJarName)) { content = editEJBJAR(next, content, envEntryName, envEntryValue); next = new ZipEntry(ejbJarName); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); fos.close(); } Code Sample 2: public static void copyFile(File source, File dest) throws Exception { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { throw new Exception("Cannot copy file " + source.getAbsolutePath() + " to " + dest.getAbsolutePath(), e); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (Exception e) { throw new Exception("Cannot close streams.", e); } } }
11
Code Sample 1: public static String digest(String text, String algorithm, String charsetName) { try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(text.getBytes(charsetName), 0, text.length()); return convertToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("unexpected exception: " + e, e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("unexpected exception: " + e, e); } } 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 void run() { if (data.length() > 0) { String method = getMethod(); String action = getAction(); URL url; try { URL actionURL; URL baseURL = hdoc.getBase(); if (action == null) { String file = baseURL.getFile(); actionURL = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(), file); } else actionURL = new URL(baseURL, action); URLConnection connection; if ("post".equalsIgnoreCase(method)) { url = actionURL; connection = url.openConnection(); ((HttpURLConnection) connection).setFollowRedirects(false); XRendererSupport.setCookies(url, connection); connection.setRequestProperty("Accept-Language", "en-us"); connection.setRequestProperty("User-Agent", XRendererSupport.getContext().getUserAgent()); postData(connection, data); XRendererSupport.getContext().getLogger().message(this, "Posted data: {" + data + "}"); } else { url = new URL(actionURL + "?" + data); connection = url.openConnection(); XRendererSupport.setCookies(url, connection); } connection.connect(); in = connection.getInputStream(); URL base = connection.getURL(); XRendererSupport.getCookies(base, connection); XRendererSupport.getContext().getLogger().message(this, "Stream got ok."); JEditorPane c = (JEditorPane) getContainer(); HTMLEditorKit kit = (HTMLEditorKit) c.getEditorKit(); newDoc = (HTMLDocument) kit.createDefaultDocument(); newDoc.putProperty(Document.StreamDescriptionProperty, base); SwingUtilities.invokeLater(new Runnable() { public void run() { XRendererSupport.getContext().getLogger().message(this, "loading..."); loadDocument(); XRendererSupport.getContext().getLogger().message(this, "document loaded..."); } }); } catch (MalformedURLException m) { } catch (IOException e) { } } } Code Sample 2: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
11
Code Sample 1: public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) return; FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: protected void copy(File src, File dest) throws IOException { if (src.isDirectory() && dest.isFile()) throw new IOException("Cannot copy a directory to a file"); if (src.isDirectory()) { File newDir = new File(dest, src.getName()); if (!newDir.mkdirs()) throw new IOException("Cannot create a new Directory"); File[] entries = src.listFiles(); for (int i = 0; i < entries.length; ++i) copy(entries[i], newDir); return; } if (dest.isDirectory()) { File newFile = new File(dest, src.getName()); newFile.createNewFile(); copy(src, newFile); return; } try { if (src.length() == 0) { dest.createNewFile(); return; } FileChannel fc = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); long transfered = 0; long totalLength = src.length(); while (transfered < totalLength) { long num = fc.transferTo(transfered, totalLength - transfered, dstChannel); if (num == 0) throw new IOException("Error while copying"); transfered += num; } dstChannel.close(); fc.close(); } catch (IOException e) { if (os.equals("Unix")) { _logger.fine("Trying to use cp to copy file..."); File cp = new File("/usr/bin/cp"); if (!cp.exists()) cp = new File("/bin/cp"); if (!cp.exists()) cp = new File("/usr/local/bin/cp"); if (!cp.exists()) cp = new File("/sbin/cp"); if (!cp.exists()) cp = new File("/usr/sbin/cp"); if (!cp.exists()) cp = new File("/usr/local/sbin/cp"); if (cp.exists()) { Process cpProcess = Runtime.getRuntime().exec(cp.getAbsolutePath() + " '" + src.getAbsolutePath() + "' '" + dest.getAbsolutePath() + "'"); int errCode; try { errCode = cpProcess.waitFor(); } catch (java.lang.InterruptedException ie) { throw e; } return; } } throw e; } }
11
Code Sample 1: public static final boolean copy(File source, File target, boolean overwrite) { if (!overwrite && target.exists()) { LOGGER.error("Target file exist and it not permitted to overwrite it !"); return false; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } catch (IOException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } finally { try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } } return true; } 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: public String sendSMS(String destinationNumber, String txt, String id) throws IOException { String out = ""; String smsdata = ""; smsdata += URLEncoder.encode("id", enc) + "=" + URLEncoder.encode(id, enc); smsdata += "&" + URLEncoder.encode("phoneNumber", enc) + "=" + URLEncoder.encode(destinationNumber, enc); smsdata += "&" + URLEncoder.encode("conversationId", enc) + "=" + URLEncoder.encode(id, enc); smsdata += "&" + URLEncoder.encode("text", enc) + "=" + URLEncoder.encode(txt, enc); smsdata += "&" + URLEncoder.encode("_rnr_se", enc) + "=" + URLEncoder.encode(rnrSEE, enc); System.out.println("smsdata: " + smsdata); URL smsurl = new URL("https://www.google.com/voice/b/0/sms/send/"); URLConnection smsconn = smsurl.openConnection(); smsconn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken); smsconn.setRequestProperty("User-agent", USER_AGENT); smsconn.setDoOutput(true); OutputStreamWriter callwr = new OutputStreamWriter(smsconn.getOutputStream()); callwr.write(smsdata); callwr.flush(); BufferedReader callrd = new BufferedReader(new InputStreamReader(smsconn.getInputStream())); String line; while ((line = callrd.readLine()) != null) { out += line + "\n\r"; } callwr.close(); callrd.close(); if (out.equals("")) { throw new IOException("No Response Data Received."); } return out; } Code Sample 2: public URL grabCover(String artist, String title) { if (idf.jCheckBox3.isSelected()) { println("Searching cover for: " + artist); artist = artist.trim(); URL url = null; int searchnumber = 0; try { URL yahoo = new URL("http://www.gracenote.com/search/?query=" + artist.toLowerCase().replaceAll(" ", "+") + "&search_type=artist"); BufferedReader in = new BufferedReader(new InputStreamReader(yahoo.openStream())); println("" + yahoo); String inputLine; String line = ""; while ((inputLine = in.readLine()) != null) line += inputLine; boolean notfound = true; String cut = line; while (notfound) { String search = "<div class=\"album-name large\"><strong>Album:</strong> <a href=\""; if (line.indexOf(search) <= 0) { println("Artist was not found!"); in.close(); return null; } cut = cut.substring(cut.indexOf(search) + search.length()); String test = cut.substring(0, cut.indexOf("\"")); URL secondurl = new URL("http://www.gracenote.com" + test); println("" + secondurl); BufferedReader secin = new BufferedReader(new InputStreamReader(secondurl.openStream())); String secinputLine; String secline = ""; while ((secinputLine = secin.readLine()) != null) secline += secinputLine; if (!(secline.toUpperCase().indexOf(title.toUpperCase()) < 0 && idf.jCheckBox2.isSelected())) { String secsearch = "<div class=\"album-image\"><img src=\""; String seccut = secline.substring(secline.indexOf(secsearch) + secsearch.length()); seccut = seccut.substring(0, seccut.indexOf("\"")); url = new URL("http://www.gracenote.com" + seccut); if (url.toString().indexOf("covers/default") <= 0 && url.toString().indexOf("covers/") > 0) { notfound = false; } } secin.close(); } in.close(); println(url.toString()); } catch (Exception e) { println("error " + e + "\n"); e.printStackTrace(); } return url; } else { return null; } }
00
Code Sample 1: public boolean finish() { IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName.getText()); try { project.create(null); project.open(null); IProjectDescription desc = project.getDescription(); desc.setNatureIds(new String[] { JavaCore.NATURE_ID }); project.setDescription(desc, null); IJavaProject javaProject = JavaCore.create(project); IPath fitLib = project.getFullPath().append(FIT_LIBRARY); javaProject.setRawClasspath(createClassPathEntries(project, fitLib), null); copyLibrary(project); javaProject.setOutputLocation(createOutputFolder(project, DEFAULT_OUTPUT_FOLDER).getFullPath(), null); createOutputFolder(project, fitTests.getText()); createOutputFolder(project, fitResults.getText()); if (!DEFAULT_OUTPUT_FOLDER.equals(fitResults.getText())) { DefaultFolderProperties.setDefinedOutputLocation(project, fitResults.getText()); } if (!DEFAULT_SOURCE_FOLDER.equals(fitFixtures.getText())) { DefaultFolderProperties.setDefinedSourceLocation(project, fitFixtures.getText()); } if (includeExamplesCheck.getSelection()) { copySamples(project); } } catch (CoreException e) { handleError(getContainer().getShell(), project, "Could not create project:" + e.getMessage()); return false; } catch (IOException e) { handleError(getContainer().getShell(), project, "Could not create project:" + e.getMessage()); return false; } return true; } Code Sample 2: public static void copyFile(String fromPath, String toPath) { try { File inputFile = new File(fromPath); String dirImg = (new File(toPath)).getParent(); File tmp = new File(dirImg); if (!tmp.exists()) { tmp.mkdir(); } File outputFile = new File(toPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); } }
11
Code Sample 1: protected String getOldHash(String text) { String hash = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte[] digestedBytes = md.digest(); hash = HexUtils.convert(digestedBytes); } catch (NoSuchAlgorithmException e) { log.log(Level.SEVERE, "Error creating SHA password hash:" + e.getMessage()); hash = text; } catch (UnsupportedEncodingException e) { log.log(Level.SEVERE, "UTF-8 not supported!?!"); } return hash; } Code Sample 2: public static String md5(String senha) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Ocorreu NoSuchAlgorithmException"); } md.update(senha.getBytes()); byte[] xx = md.digest(); String n2 = null; StringBuffer resposta = new StringBuffer(); for (int i = 0; i < xx.length; i++) { n2 = Integer.toHexString(0XFF & ((int) (xx[i]))); if (n2.length() < 2) { n2 = "0" + n2; } resposta.append(n2); } return resposta.toString(); }
00
Code Sample 1: private void openConnection() throws IOException { connection = (HttpURLConnection) url.openConnection(Global.getProxy()); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml; charset=" + XmlRpcMessages.getString("XmlRpcClient.Encoding")); if (requestProperties != null) { for (Iterator propertyNames = requestProperties.keySet().iterator(); propertyNames.hasNext(); ) { String propertyName = (String) propertyNames.next(); connection.setRequestProperty(propertyName, (String) requestProperties.get(propertyName)); } } } Code Sample 2: public boolean crear() { int result = 0; String sql = "insert into ronda" + "(divisionxTorneo_idDivisionxTorneo, fechaRonda, nRonda, estado ) " + "values (?, ?, ?, ?)"; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement(unaRonda); result = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (result > 0); }
11
Code Sample 1: 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: public void run() { try { Socket socket = getSocket(); System.out.println("opening socket to " + address + " on " + port); InputStream in = socket.getInputStream(); for (; ; ) { FileTransferHeader header = FileTransferHeader.readHeader(in); if (header == null) break; System.out.println("header: " + header); String[] parts = header.getFilename().getSegments(); String filename; if (parts.length > 0) filename = "dl-" + parts[parts.length - 1]; else filename = "dl-" + session.getScreenname(); System.out.println("writing to file " + filename); long sum = 0; if (new File(filename).exists()) { FileInputStream fis = new FileInputStream(filename); byte[] block = new byte[10]; for (int i = 0; i < block.length; ) { int count = fis.read(block); if (count == -1) break; i += count; } FileTransferChecksum summer = new FileTransferChecksum(); summer.update(block, 0, 10); sum = summer.getValue(); } FileChannel fileChannel = new FileOutputStream(filename).getChannel(); FileTransferHeader outHeader = new FileTransferHeader(header); outHeader.setHeaderType(FileTransferHeader.HEADERTYPE_ACK); outHeader.setIcbmMessageId(cookie); outHeader.setBytesReceived(0); outHeader.setReceivedChecksum(sum); OutputStream socketOut = socket.getOutputStream(); System.out.println("sending header: " + outHeader); outHeader.write(socketOut); for (int i = 0; i < header.getFileSize(); ) { long transferred = fileChannel.transferFrom(Channels.newChannel(in), 0, header.getFileSize() - i); System.out.println("transferred " + transferred); if (transferred == -1) return; i += transferred; } System.out.println("finished transfer!"); fileChannel.close(); FileTransferHeader doneHeader = new FileTransferHeader(header); doneHeader.setHeaderType(FileTransferHeader.HEADERTYPE_RECEIVED); doneHeader.setFlags(doneHeader.getFlags() | FileTransferHeader.FLAG_DONE); doneHeader.setBytesReceived(doneHeader.getBytesReceived() + 1); doneHeader.setIcbmMessageId(cookie); doneHeader.setFilesLeft(doneHeader.getFilesLeft() - 1); doneHeader.write(socketOut); if (doneHeader.getFilesLeft() - 1 <= 0) { socket.close(); break; } } } catch (IOException e) { e.printStackTrace(); return; } }
11
Code Sample 1: public void render(final HttpServletRequest request, final HttpServletResponse response, InputStream inputStream, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } IOUtils.copy(inputStream, response.getOutputStream()); } Code Sample 2: void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static boolean cpy(File a, File b) { try { FileInputStream astream = null; FileOutputStream bstream = null; try { astream = new FileInputStream(a); bstream = new FileOutputStream(b); long flength = a.length(); int bufsize = (int) Math.min(flength, 1024); byte buf[] = new byte[bufsize]; long n = 0; while (n < flength) { int naread = astream.read(buf); bstream.write(buf, 0, naread); n += naread; } } finally { if (astream != null) astream.close(); if (bstream != null) bstream.close(); } } catch (IOException e) { e.printStackTrace(); return false; } return true; }
11
Code Sample 1: private void copyFromStdin(Path dst, FileSystem dstFs) throws IOException { if (dstFs.isDirectory(dst)) { throw new IOException("When source is stdin, destination must be a file."); } if (dstFs.exists(dst)) { throw new IOException("Target " + dst.toString() + " already exists."); } FSDataOutputStream out = dstFs.create(dst); try { IOUtils.copyBytes(System.in, out, getConf(), false); } finally { out.close(); } } Code Sample 2: @Test public void testCopy_inputStreamToWriter_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); try { IOUtils.copy((InputStream) null, writer); fail(); } catch (NullPointerException ex) { } }
00
Code Sample 1: public static void main(String args[]) { Connection con; if (args.length != 2) { System.out.println("Usage: Shutdown <host> <password>"); System.exit(0); } try { con = new Connection(args[0]); con.tStart(); Message message = new Message(MessageTypes.SHUTDOWN_SERVER); java.security.MessageDigest hash = java.security.MessageDigest.getInstance("SHA-1"); hash.update(args[1].getBytes("UTF-8")); message.put("pwhash", hash.digest()); con.send(message); con.join(); } catch (java.io.UnsupportedEncodingException e) { System.err.println("Password character encoding not supported."); } catch (java.io.IOException e) { System.out.println(e.toString()); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("Password hash algorithm SHA-1 not supported by runtime."); } catch (InterruptedException e) { } System.exit(0); } Code Sample 2: public static BufferedReader getReader(int license) { URL url = getResource(license); if (url == null) return null; InputStream inStream; try { inStream = url.openStream(); } catch (IOException e) { return null; } return new BufferedReader(new InputStreamReader(inStream)); }
00
Code Sample 1: public static void main(String[] args) { try { Transaction transaction = session.beginTransaction(); URL url1 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/keren.jpg"); HttpURLConnection conn1 = (HttpURLConnection) url1.openConnection(); conn1.connect(); Users keren = new Users("kerenhaas@gmail.com", "123456", "keren", null, "sokolov 14 Raanana", Hibernate.createBlob(conn1.getInputStream(), conn1.getContentLength()), "about keren", "admin", false); session.save(keren); session.flush(); session.refresh(keren); URL url2 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/alex.jpg"); HttpURLConnection conn2 = (HttpURLConnection) url2.openConnection(); Users alex = new Users("alex.uretsky@mail.huji.ac.il", "123456", "alex", null, null, Hibernate.createBlob(conn2.getInputStream(), conn2.getContentLength()), null, "admin", false); session.save(alex); session.flush(); session.refresh(alex); URL url3 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/julia.jpg"); HttpURLConnection conn3 = (HttpURLConnection) url3.openConnection(); conn3.connect(); Users julia = new Users("juliasht@gmail.com", "123456", "julia", null, null, Hibernate.createBlob(conn3.getInputStream(), conn3.getContentLength()), null, "admin", false); session.save(julia); session.flush(); session.refresh(julia); URL url4 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/meir.jpg"); HttpURLConnection conn4 = (HttpURLConnection) url4.openConnection(); conn4.connect(); Users meir = new Users("meir.spielrein@mail.huji.ac.il", "123456", "meir", null, null, Hibernate.createBlob(conn4.getInputStream(), conn4.getContentLength()), null, "admin", false); session.save(meir); session.flush(); session.refresh(meir); URL url5 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/miki.jpg"); HttpURLConnection conn5 = (HttpURLConnection) url5.openConnection(); conn5.connect(); Users miki = new Users("miki.shifman@mail.huji.ac.il", "123456", "miki", null, null, Hibernate.createBlob(conn5.getInputStream(), conn5.getContentLength()), null, "admin", false); session.save(miki); session.flush(); session.refresh(miki); URL url6 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/tamar.jpg"); HttpURLConnection conn6 = (HttpURLConnection) url6.openConnection(); conn6.connect(); Users tami = new Users("taamar@gmail.com", "123456", "tami", null, null, Hibernate.createBlob(conn6.getInputStream(), conn6.getContentLength()), null, "admin", false); session.save(tami); session.flush(); session.refresh(tami); Lists basicComplexity = new Lists("Complexity", "Basic"); session.save(basicComplexity); Lists mediumComplexity = new Lists("Complexity", "Medium"); session.save(mediumComplexity); Lists highComplexity = new Lists("Complexity", "High"); session.save(highComplexity); Lists chefComplexity = new Lists("Complexity", "Chef"); session.save(chefComplexity); Lists appetizers = new Lists("DishType", "Appetizers"); session.save(appetizers); Lists firstCourse = new Lists("DishType", "First Course"); session.save(firstCourse); Lists mainCourse = new Lists("DishType", "Main Course"); session.save(mainCourse); Lists dessert = new Lists("DishType", "Dessert"); session.save(dessert); Lists cocktails = new Lists("DishType", "Cocktails"); session.save(cocktails); System.out.println("2 : " + session.isOpen()); Lists italian = new Lists("Cuisine", "Italian"); session.save(italian); Lists chinese = new Lists("Cuisine", "Chinese"); session.save(chinese); Lists indian = new Lists("Cuisine", "Indian"); session.save(indian); Lists french = new Lists("Cuisine", "French"); session.save(french); Lists thai = new Lists("Cuisine", "Thai"); session.save(thai); Lists arabic = new Lists("Cuisine", "Arabic"); session.save(arabic); Lists israeli = new Lists("Cuisine", "Israeli"); session.save(israeli); Lists other = new Lists("Cuisine", "Other"); session.save(other); Ingredients flour = new Ingredients("flour"); session.save(flour); Ingredients sugar = new Ingredients("white sugar"); session.save(sugar); Ingredients bakingPower = new Ingredients("baking powder"); session.save(bakingPower); Ingredients groundNutmeg = new Ingredients("ground nutmeg"); session.save(groundNutmeg); Ingredients salt = new Ingredients("salt"); session.save(salt); Ingredients pepper = new Ingredients("pepper"); session.save(pepper); Ingredients egg = new Ingredients("egg"); session.save(egg); Ingredients milk = new Ingredients("milk"); session.save(milk); Ingredients butter = new Ingredients("butter"); session.save(butter); Ingredients groundCinnamon = new Ingredients("ground cinnamon"); session.save(groundCinnamon); Ingredients strawberries = new Ingredients("strawberries"); session.save(strawberries); Ingredients bisquick = new Ingredients("bisquick"); session.save(bisquick); Ingredients whippedCream = new Ingredients("Whipped Cream"); session.save(whippedCream); Ingredients potato = new Ingredients("potato"); session.save(potato); Ingredients carrot = new Ingredients("carrot"); session.save(carrot); Ingredients onion = new Ingredients("onion"); session.save(onion); Ingredients ketchup = new Ingredients("ketchup"); session.save(ketchup); Ingredients mustard = new Ingredients("mustard"); session.save(mustard); Ingredients cookingCream = new Ingredients("Cooking Cream"); session.save(cookingCream); Ingredients bread = new Ingredients("bread"); session.save(bread); Ingredients caviar = new Ingredients("caviar"); session.save(caviar); Ingredients foigra = new Ingredients("foigra"); session.save(foigra); Ingredients vodka = new Ingredients("vodka"); session.save(vodka); Ingredients orangeJuice = new Ingredients("orangeJuice"); session.save(orangeJuice); Ingredients ribs = new Ingredients("ribs"); session.save(ribs); Ingredients tomato = new Ingredients("tomato"); session.save(tomato); Ingredients cucumber = new Ingredients("cucumber"); session.save(cucumber); Ingredients oliveoil = new Ingredients("olive oil"); session.save(oliveoil); Ingredients chickenBreast = new Ingredients("chicken Breast"); session.save(chickenBreast); Ingredients apple = new Ingredients("apple"); session.save(apple); Ingredients vanilla = new Ingredients("vanilla"); session.save(vanilla); String description; description = "These muffins are delicious! The cinnamon sugar topping flavors them perfectly. This is my 10 year old brother's favorite recipe"; Recipes rec1 = addRecipe(basicComplexity, description, "French Breakfast Muffins", keren, 10, 25, 12, dessert, "http://www.cs.huji.ac.il/~keren_ha/J2EE/muffins.jpg", Arrays.asList("Preheat oven to 350 degrees F (175 degrees C). Grease muffin cups or line with paper muffin liners.", "In a medium mixing bowl, stir together flour, 1/2 cup sugar, baking powder, nutmeg and salt. Make a well in the center of the mixture. Stir together egg, milk and 1/3 cup melted butter. Add egg mixture to flour mixture; stir until just moistened (batter may be lumpy). Spoon batter into prepared muffin cups.", "Bake in preheated oven for 20 to 25 minutes. Meanwhile, combine 1/4 cup sugar, cinnamon When muffins are finished baking, dip tops of muffins in the melted butter, and then in the cinnamon sugar mixture. Serve warm.")); createRecipeIngredients(rec1, flour, 1.5, "cups"); createRecipeIngredients(rec1, sugar, 0.5, "cups"); createRecipeIngredients(rec1, bakingPower, 1.5, "teaspoons"); createRecipeIngredients(rec1, groundNutmeg, 0.25, "teaspoons"); createRecipeIngredients(rec1, salt, 0.125, "teaspoons"); createRecipeIngredients(rec1, egg, 1, "lightly beaten"); createRecipeIngredients(rec1, milk, 0.5, "cups"); createRecipeIngredients(rec1, butter, 0.33, "cups"); createRecipeIngredients(rec1, groundCinnamon, 0.25, "cups"); createRecipeIngredients(rec1, groundCinnamon, 0.5, "teaspoon"); createRecipeIngredients(rec1, sugar, 0.33, "cups"); session.flush(); session.refresh(rec1); description = "This dish leaves even the biggest pasta lover satisfied. Fresh vegetables make this dish wonderful and it's easy to add meat to if you wish."; Recipes rec2 = addRecipe(mediumComplexity, description, "Veggie Pasta Minus the Pasta", alex, 30, 40, 6, mainCourse, "http://2.bp.blogspot.com/_wAVccjOeYzc/R4KYRa5MkLI/AAAAAAAAGz8/WeosqyuyjoQ/s400/vegetarian-tofu-curry-recipe+(13).JPG", Arrays.asList("Preheat an oven to 350 degrees F (175 degrees C). Arrange the tomatoes on a baking sheet with the cut sides facing up. ", "Roast the tomatoes in the preheated oven until cooked through and slightly browned on the underside, about 15 minutes. ", "Place squash halves face down in glass baking dish with the water; cover with plastic wrap. Microwave on High for 8 minutes. Leave covered and set aside. Once the squash is cool enough to handle, scrape in strands into a large bowl with a fork; season with salt and pepper and toss with 1 tablespoon olive oil. ", "Heat the remaining 2 tablespoons olive oil in a large skillet over medium-low heat; cook and stir the garlic, basil, and Italian seasoning in the oil until the garlic is softened, about 10 minutes. Add the onion, green bell pepper, eggplant, and carrot to the garlic; increase heat to medium. Continue cooking and stirring until the vegetables are nearly tender, 10 to 15 minutes. Mix the tomatoes and white wine into the vegetable mixture; cook another 2 to 3 minutes. Transfer the vegetables to the bowl with the spaghetti squash; gently toss together.")); createRecipeIngredients(rec2, flour, 1.5, "cups"); createRecipeIngredients(rec2, sugar, 0.5, "cups"); createRecipeIngredients(rec2, bakingPower, 1.5, "teaspoons"); createRecipeIngredients(rec2, groundNutmeg, 0.25, "teaspoons"); createRecipeIngredients(rec2, salt, 0.125, "teaspoons"); createRecipeIngredients(rec2, egg, 1, "lightly beaten"); createRecipeIngredients(rec2, milk, 0.5, "cups"); createRecipeIngredients(rec2, butter, 0.33, "cups"); createRecipeIngredients(rec2, groundCinnamon, 0.25, "cups"); createRecipeIngredients(rec2, groundCinnamon, 0.5, "teaspoon"); createRecipeIngredients(rec2, sugar, 0.33, "cups"); createComment(rec2, 1, julia, "This dish was extremely disappointing. I was very optimistic looking at the ingredient list, but after putting it all together, there was a profound lack of flavor. We eat a good deal of vegetable dishes, but this is not one we will be repeating."); createComment(rec2, 4, alex, "Very good, I also think to use less butter."); session.flush(); session.refresh(rec2); description = "A finger licking good strawberry cake!"; Recipes rec3 = addRecipe(basicComplexity, description, "Strawberry short cake", alex, 60, 70, 12, dessert, "http://static.open.salon.com/files/coconut_strawberry_cake1226877577.jpg", Arrays.asList("Sprinkle strawberries with 2/3 cups sugar. Let stand 1 hour ", "Heat over to 425 degrees.", "Mix all ingredients and place in the over", "Slice it and eat up!")); createRecipeIngredients(rec3, strawberries, 1.5, "cups"); createRecipeIngredients(rec3, sugar, 0.66, "cups"); createRecipeIngredients(rec3, bisquick, 2, "boxese"); createRecipeIngredients(rec3, sugar, 3, "tablespoons"); createRecipeIngredients(rec3, milk, 0.5, "cups"); createRecipeIngredients(rec3, whippedCream, 0.75, "cups"); createComment(rec3, 5, julia, "Best cake I ever had!!! Kudos!!"); session.flush(); session.refresh(rec3); description = "My secret Barbecue Beef Short Ribs recipe revealed!"; Recipes rec4 = addRecipe(highComplexity, description, "Short Ribs", meir, 70, 500, 6, mainCourse, "http://farm2.static.flickr.com/1310/1237575824_9068241a81.jpg", Arrays.asList("Put the potatoes and carrots in a large slow cooker", "Top with the onion wedges then the beef", "Combine the ketchup, , mustrard and salt", "Put ofver the beef", "Cook on LOW for 8 to 10 hours")); createRecipeIngredients(rec4, potato, 10, "pieces"); createRecipeIngredients(rec4, carrot, 1, "cups"); createRecipeIngredients(rec4, onion, 2, "units"); createRecipeIngredients(rec4, ribs, 3.5, "pounds"); createRecipeIngredients(rec4, ketchup, 1, "cups"); createRecipeIngredients(rec4, mustard, 0.5, "teaspoon"); createComment(rec4, 4, keren, "My whole family loved it!"); createComment(rec4, 5, alex, "This was outstanding, will definitely use this recipe often. I used chicken legs as that was what I had and it worked great. thanks!!!!"); session.flush(); session.refresh(rec4); description = "a simple, yet yasty, Salad"; Recipes rec5 = addRecipe(basicComplexity, description, "Garden Salad", alex, 10, 15, 6, firstCourse, "http://ww-recipes.net/wp-content/uploads/2008/09/weight-watchers-arabic-salad-recipe.jpg", Arrays.asList("Slice the tomatoes to cubes", "Slice the cucumbers to julian strips", "add a pinch salt and pepper", "top with olive oil")); createRecipeIngredients(rec5, tomato, 3, "pieces"); createRecipeIngredients(rec5, cucumber, 3, "pieces"); createRecipeIngredients(rec5, oliveoil, 2, "tablespoons"); createRecipeIngredients(rec5, salt, 1, "pinch"); createRecipeIngredients(rec5, pepper, 1, "pinch"); createComment(rec5, 5, julia, "Delicious and so easy to make!"); session.flush(); session.refresh(rec5); description = "Creme Brule - the full recipe! no shortcuts ;) "; Recipes rec7 = addRecipe(highComplexity, description, "Creme brule", miki, 30, 200, 6, dessert, "http://www.cookingforengineers.com/hello/259/958/640/IMG_3335_sharp.jpg", Arrays.asList("bring the cooking cream to boiling temperature", "insert vanilla stick", "whisk eggs with sugar", "add cream to eggs CAREFULLY", "put in over for 30 minutes, then to the fridge for 4 hours")); createRecipeIngredients(rec7, cookingCream, 2, "cartons"); createRecipeIngredients(rec7, egg, 3, "yolks"); createRecipeIngredients(rec7, sugar, 2, "tablespoons"); createRecipeIngredients(rec7, vanilla, 1, "stick"); createComment(rec7, 4, julia, "Delicious and so easy to make!"); session.flush(); session.refresh(rec7); description = "some toasts with foigra to get the meal started"; Recipes rec8 = addRecipe(basicComplexity, description, "foigra on toast", alex, 15, 15, 6, appetizers, "http://www.italiq-expos.com/news/images/Gastronomie/Foie-gras/assiette-foie-gras.jpg", Arrays.asList("cut bread into oval slices", "place in toaster until a golden brown color in formed", "speard some foigra pate on the toasts", "optional - add some baluga caviar on top")); createRecipeIngredients(rec8, bread, 6, "slices"); createRecipeIngredients(rec8, foigra, 1, "can"); createRecipeIngredients(rec8, caviar, 1, "minijar"); createComment(rec8, 5, julia, "Delicious and so easy to make!"); session.flush(); session.refresh(rec8); description = "delicious diatetic chicken steak"; Recipes rec9 = addRecipe(mediumComplexity, description, "chicken steak", meir, 15, 20, 2, mainCourse, "http://4.bp.blogspot.com/_jhlSdMizhlU/RdOVtm-0QAI/AAAAAAAAABg/81W-JvXOACI/s400/Chicken_Steak.jpg", Arrays.asList("Heat a frying pan with some (preferably olive) oil", "when the oil is hot, place the chicken and onions in the middle", "fry on both sides on medium flame until it starts to turn golden", "season with salt and pepper")); createRecipeIngredients(rec9, chickenBreast, 2, "pieces"); createRecipeIngredients(rec9, onion, 1, "piece"); createRecipeIngredients(rec9, salt, 1, "pinch"); createRecipeIngredients(rec9, pepper, 1, "pinch"); createComment(rec9, 5, julia, "Delicious and so easy to make!"); session.flush(); session.refresh(rec9); Favorites fav1 = new Favorites(keren, rec1, null); session.save(fav1); Favorites fav2 = new Favorites(keren, rec2, null); session.save(fav2); Favorites fav3 = new Favorites(keren, rec3, null); session.save(fav3); Favorites fav4 = new Favorites(keren, rec4, null); session.save(fav4); Favorites fav5 = new Favorites(alex, rec4, null); session.save(fav5); Favorites fav6 = new Favorites(alex, rec2, null); session.save(fav6); RecentlyViewed recViewed1 = new RecentlyViewed(keren, rec1, new Date()); session.save(recViewed1); RecentlyViewed recViewed2 = new RecentlyViewed(keren, rec2, new Date()); session.save(recViewed2); Friends friend1 = new Friends(keren, alex, true); session.save(friend1); Friends friend2 = new Friends(alex, keren, true); session.save(friend2); Friends friend3 = new Friends(keren, julia, false); session.save(friend3); Friends friend4 = new Friends(keren, meir, true); session.save(friend4); Friends friend5 = new Friends(meir, keren, true); session.save(friend5); Friends friend6 = new Friends(tami, keren, false); session.save(friend6); transaction.commit(); } catch (Exception e) { e.printStackTrace(); } finally { session.flush(); session.close(); } } Code Sample 2: public void load() throws ResourceInstantiationException { if (null == url) { throw new ResourceInstantiationException("URL not set (null)."); } try { BufferedReader defReader = new BomStrippingInputStreamReader((url).openStream(), ENCODING); String line; LinearNode node; while (null != (line = defReader.readLine())) { node = new LinearNode(line); try { this.add(node); } catch (GateRuntimeException ex) { throw new ResourceInstantiationException(ex); } } defReader.close(); isModified = false; } catch (Exception x) { throw new ResourceInstantiationException(x); } }
00
Code Sample 1: public String getMD5String(String par1Str) { try { String s = (new StringBuilder()).append(field_27370_a).append(par1Str).toString(); MessageDigest messagedigest = MessageDigest.getInstance("MD5"); messagedigest.update(s.getBytes(), 0, s.length()); return (new BigInteger(1, messagedigest.digest())).toString(16); } catch (NoSuchAlgorithmException nosuchalgorithmexception) { throw new RuntimeException(nosuchalgorithmexception); } } Code Sample 2: public static void copyFile(String f_in, String f_out, boolean remove) throws FileNotFoundException, IOException { if (remove) { PogoString readcode = new PogoString(PogoUtil.readFile(f_in)); readcode = PogoUtil.removeLogMessages(readcode); PogoUtil.writeFile(f_out, readcode.str); } else { FileInputStream fid = new FileInputStream(f_in); FileOutputStream fidout = new FileOutputStream(f_out); int nb = fid.available(); byte[] inStr = new byte[nb]; if (fid.read(inStr) > 0) fidout.write(inStr); fid.close(); fidout.close(); } }
11
Code Sample 1: private void createScript(File scriptsLocation, String relativePath, String scriptContent) { Writer fileWriter = null; try { File scriptFile = new File(scriptsLocation.getAbsolutePath() + "/" + relativePath); scriptFile.getParentFile().mkdirs(); fileWriter = new FileWriter(scriptFile); IOUtils.copy(new StringReader(scriptContent), fileWriter); } catch (IOException e) { throw new UnitilsException(e); } finally { IOUtils.closeQuietly(fileWriter); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } } Code Sample 2: public void createZip(String baseDir, String objFileName) throws Exception { logger.info("createZip: [ " + baseDir + "] [" + objFileName + "]"); baseDir = baseDir + "/" + timesmpt; File folderObject = new File(baseDir); if (folderObject.exists()) { List<?> fileList = getSubFiles(new File(baseDir)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFileName)); ZipEntry ze = null; byte[] buf = new byte[1024]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { File f = (File) fileList.get(i); ze = new ZipEntry(getAbsFileName(baseDir, f)); ze.setSize(f.length()); ze.setTime(f.lastModified()); zos.putNextEntry(ze); InputStream is = new BufferedInputStream(new FileInputStream(f)); while ((readLen = is.read(buf, 0, 1024)) != -1) { zos.write(buf, 0, readLen); } is.close(); } zos.close(); } else { throw new Exception("this folder isnot exist!"); } }
00
Code Sample 1: public static String sendGetRequest(String endpoint, String requestParameters) { if (endpoint == null) return null; String result = null; if (endpoint.startsWith("http://")) { try { StringBuffer data = new StringBuffer(); String urlStr = endpoint; if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } URL url = new URL(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); result = sb.toString(); } catch (Exception e) { Logger.getLogger(HTTPClient.class.getClass().getName()).log(Level.FINE, "Could not connect to URL, is the service online?"); } } return result; } Code Sample 2: public static byte[] downloadHttpFile(String url) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); int responseCode = conn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) throw new IOException("Invalid HTTP response: " + responseCode + " for url " + conn.getURL()); InputStream in = conn.getInputStream(); try { return Utilities.getInputBytes(in); } finally { in.close(); } }
00
Code Sample 1: public static void main(String[] args) { if (args.length != 2) throw new IllegalArgumentException("Expected arguments: fileName log"); String fileName = args[0]; String logFile = args[1]; LineNumberReader reader = null; PrintWriter writer = null; try { Reader reader0 = new FileReader(fileName); reader = new LineNumberReader(reader0); Writer writer0 = new FileWriter(logFile); BufferedWriter writer1 = new BufferedWriter(writer0); writer = new PrintWriter(writer1); String line = reader.readLine(); while (line != null) { line = line.trim(); if (line.length() >= 81) { writer.println("Analyzing Sudoku #" + reader.getLineNumber()); System.out.println("Analyzing Sudoku #" + reader.getLineNumber()); Grid grid = new Grid(); for (int i = 0; i < 81; i++) { char ch = line.charAt(i); if (ch >= '1' && ch <= '9') { int value = (ch - '0'); grid.setCellValue(i % 9, i / 9, value); } } Solver solver = new Solver(grid); solver.rebuildPotentialValues(); try { Map<Rule, Integer> rules = solver.solve(null); Map<String, Integer> ruleNames = solver.toNamedList(rules); double difficulty = 0; String hardestRule = ""; for (Rule rule : rules.keySet()) { if (rule.getDifficulty() > difficulty) { difficulty = rule.getDifficulty(); hardestRule = rule.getName(); } } for (String rule : ruleNames.keySet()) { int count = ruleNames.get(rule); writer.println(Integer.toString(count) + " " + rule); System.out.println(Integer.toString(count) + " " + rule); } writer.println("Hardest technique: " + hardestRule); System.out.println("Hardest technique: " + hardestRule); writer.println("Difficulty: " + difficulty); System.out.println("Difficulty: " + difficulty); } catch (UnsupportedOperationException ex) { writer.println("Failed !"); System.out.println("Failed !"); } writer.println(); System.out.println(); writer.flush(); } else System.out.println("Skipping incomplete line: " + line); line = reader.readLine(); } writer.close(); reader.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException ex) { ex.printStackTrace(); } } System.out.print("Finished."); } Code Sample 2: public String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
00
Code Sample 1: public ResponseStatus submit(Collection<SubmissionData> data) throws IOException { if (sessionId == null) throw new IllegalStateException("Perform successful handshake first."); if (data.size() > 50) throw new IllegalArgumentException("Max 50 submissions at once"); StringBuilder builder = new StringBuilder(data.size() * 100); int index = 0; for (SubmissionData submissionData : data) { builder.append(submissionData.toString(sessionId, index)); builder.append('\n'); index++; } String body = builder.toString(); if (Caller.getInstance().isDebugMode()) System.out.println("submit: " + body); HttpURLConnection urlConnection = Caller.getInstance().openConnection(submissionUrl); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); OutputStream outputStream = urlConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream)); writer.write(body); writer.close(); InputStream is = urlConnection.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); String status = r.readLine(); r.close(); int statusCode = ResponseStatus.codeForStatus(status); if (statusCode == ResponseStatus.FAILED) { return new ResponseStatus(statusCode, status.substring(status.indexOf(' ') + 1)); } return new ResponseStatus(statusCode); } Code Sample 2: public static String md5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: @Override public void handle(HttpExchange http) throws IOException { Headers reqHeaders = http.getRequestHeaders(); Headers respHeader = http.getResponseHeaders(); respHeader.add("Content-Type", "text/plain"); http.sendResponseHeaders(200, 0); PrintWriter console = new PrintWriter(System.err); PrintWriter web = new PrintWriter(http.getResponseBody()); PrintWriter out = new PrintWriter(new YWriter(web, console)); out.println("### " + new Date() + " ###"); out.println("Method: " + http.getRequestMethod()); out.println("Protocol: " + http.getProtocol()); out.println("RemoteAddress.HostName: " + http.getRemoteAddress().getHostName()); for (String key : reqHeaders.keySet()) { out.println("* \"" + key + "\""); for (String v : reqHeaders.get(key)) { out.println("\t" + v); } } InputStream in = http.getRequestBody(); if (in != null) { out.println(); IOUtils.copyTo(new InputStreamReader(in), out); in.close(); } out.flush(); out.close(); } Code Sample 2: public int batchTransactionUpdate(List<String> queryStrLisyt, Connection con) throws Exception { int ret = 0; Statement stmt; if (con != null) { con.setAutoCommit(false); stmt = con.createStatement(); try { stmt.executeUpdate("START TRANSACTION;"); for (int i = 0; i < queryStrLisyt.size(); i++) { stmt.addBatch(queryStrLisyt.get(i)); } int[] updateCounts = stmt.executeBatch(); for (int i = 0; i < updateCounts.length; i++) { FileLogger.debug("batch update result:" + updateCounts[i] + ", Statement.SUCCESS_NO_INFO" + Statement.SUCCESS_NO_INFO); if (updateCounts[i] == Statement.SUCCESS_NO_INFO || updateCounts[i] > 0) { ret++; } else if (updateCounts[i] == Statement.EXECUTE_FAILED) ; { throw new Exception("query failed, while process batch update"); } } con.commit(); } catch (Exception e) { ret = 0; FileLogger.debug(e.getMessage()); con.rollback(); } finally { con.setAutoCommit(true); stmt.close(); } } return ret; }
11
Code Sample 1: public static void copyToFileAndCloseStreams(InputStream istr, File destFile) throws IOException { OutputStream ostr = null; try { ostr = new FileOutputStream(destFile); IOUtils.copy(istr, ostr); } finally { if (ostr != null) ostr.close(); if (istr != null) istr.close(); } } Code Sample 2: public void execute() throws BuildException { Project proj = getProject(); if (templateFile == null) throw new BuildException("Template file not set"); if (targetFile == null) throw new BuildException("Target file not set"); try { File template = new File(templateFile); File target = new File(targetFile); if (!template.exists()) throw new BuildException("Template file does not exist " + template.toString()); if (!template.canRead()) throw new BuildException("Cannot read template file: " + template.toString()); if (((!append) && (!overwrite)) && (!target.exists())) throw new BuildException("Target file already exists and append and overwrite are false " + target.toString()); if (VERBOSE) { System.out.println("ProcessTemplate: tmpl in " + template.toString()); System.out.println("ProcessTemplate: file out " + target.toString()); } BufferedReader reader = new BufferedReader(new FileReader(template)); BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile, append)); parse(reader, writer); writer.flush(); writer.close(); } catch (Exception e) { if (VERBOSE) e.printStackTrace(); throw new BuildException(e); } }
00
Code Sample 1: public static void BubbleSortByte2(byte[] num) { int last_exchange; int right_border = num.length - 1; do { last_exchange = 0; for (int j = 0; j < num.length - 1; j++) { if (num[j] > num[j + 1]) { byte temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; last_exchange = j; } } right_border = last_exchange; } while (right_border > 0); } Code Sample 2: private void createWar() throws IOException, XMLStreamException { String appName = this.fileout.getName(); int i = appName.indexOf("."); if (i != -1) appName = appName.substring(0, i); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(this.fileout)); { ZipEntry entry = new ZipEntry("WEB-INF/web.xml"); zout.putNextEntry(entry); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter w = factory.createXMLStreamWriter(zout, "ASCII"); w.writeStartDocument("ASCII", "1.0"); w.writeStartElement("web-app"); w.writeAttribute("xsi", XSI, "schemaLocation", "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml /ns/javaee/web-app_2_5.xsd"); w.writeAttribute("version", "2.5"); w.writeAttribute("xmlns", J2EE); w.writeAttribute("xmlns:xsi", XSI); w.writeStartElement("description"); w.writeCharacters("Site maintenance for " + appName); w.writeEndElement(); w.writeStartElement("display-name"); w.writeCharacters(appName); w.writeEndElement(); w.writeStartElement("servlet"); w.writeStartElement("servlet-name"); w.writeCharacters("down"); w.writeEndElement(); w.writeStartElement("jsp-file"); w.writeCharacters("/WEB-INF/jsp/down.jsp"); w.writeEndElement(); w.writeEndElement(); w.writeStartElement("servlet-mapping"); w.writeStartElement("servlet-name"); w.writeCharacters("down"); w.writeEndElement(); w.writeStartElement("url-pattern"); w.writeCharacters("/*"); w.writeEndElement(); w.writeEndElement(); w.writeEndElement(); w.writeEndDocument(); w.flush(); zout.closeEntry(); } { ZipEntry entry = new ZipEntry("WEB-INF/jsp/down.jsp"); zout.putNextEntry(entry); PrintWriter w = new PrintWriter(zout); if (this.messageFile != null) { IOUtils.copyTo(new FileReader(this.messageFile), w); } else if (this.messageString != null) { w.print("<html><body>" + this.messageString + "</body></html>"); } else { w.print("<html><body><div style='text-align:center;font-size:500%;'>Oh No !<br/><b>" + appName + "</b><br/>is down for maintenance!</div></body></html>"); } w.flush(); zout.closeEntry(); } zout.finish(); zout.flush(); zout.close(); }
11
Code Sample 1: @Override public void save(String arxivId, InputStream inputStream, String encoding) { String filename = StringUtil.arxivid2filename(arxivId, "tex"); try { Writer writer = new OutputStreamWriter(new FileOutputStream(String.format("%s/%s", LATEX_DOCUMENT_DIR, filename)), encoding); IOUtils.copy(inputStream, writer, encoding); writer.flush(); writer.close(); inputStream.close(); } catch (IOException e) { logger.error("Failed to save the Latex source with id='{}'", arxivId, e); throw new RuntimeException(e); } } Code Sample 2: @Test public void testCopy_inputStreamToWriter_Encoding_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); try { IOUtils.copy((InputStream) null, writer, "UTF8"); fail(); } catch (NullPointerException ex) { } }
11
Code Sample 1: public static void writeFullImageToStream(Image scaledImage, String javaFormat, OutputStream os) throws IOException { BufferedImage bufImage = new BufferedImage(scaledImage.getWidth(null), scaledImage.getHeight(null), BufferedImage.TYPE_BYTE_BINARY); Graphics gr = bufImage.getGraphics(); gr.drawImage(scaledImage, 0, 0, null); gr.dispose(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(bufImage, javaFormat, bos); IOUtils.copyStreams(new ByteArrayInputStream(bos.toByteArray()), os); } Code Sample 2: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uuid = req.getParameterValues(Constants.PARAM_UUID)[0]; String datastream = null; if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version.foxml\""); } else { datastream = req.getParameterValues(Constants.PARAM_DATASTREAM)[0]; resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version_" + datastream + ".xml\""); } ServletOutputStream os = resp.getOutputStream(); if (uuid != null && !"".equals(uuid)) { try { StringBuffer sb = new StringBuffer(); if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/objectXML"); } else if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/").append(datastream).append("/content"); } InputStream is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), false); if (is == null) { return; } try { if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { os.write(Constants.XML_HEADER_WITH_BACKSLASHES.getBytes()); } IOUtils.copyStreams(is, os); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { is = null; } } } } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); } } }
00
Code Sample 1: public DoSearch(String searchType, String searchString) { String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerDoSearch"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "search.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + key + "&search=" + URLEncoder.encode(searchString, "UTF-8") + "&searchtype=" + URLEncoder.encode(searchType, "UTF-8") + "&filename=" + URLEncoder.encode(username, "UTF-8") + "search.xml"; ; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("entry"); int num = nodelist.getLength(); searchDocs = new String[num][3]; searchDocImageName = new String[num]; searchDocsToolTip = new String[num]; for (int i = 0; i < num; i++) { searchDocs[i][0] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "filename"); searchDocs[i][1] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "project"); searchDocs[i][2] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "documentid"); searchDocImageName[i] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "imagename"); searchDocsToolTip[i] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "description"); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (Exception ex) { System.out.println(ex); } System.out.println(rvalue); if (rvalue.equalsIgnoreCase("yes")) { } } Code Sample 2: public static String cryptoSHA(String _strSrc) { try { BASE64Encoder encoder = new BASE64Encoder(); MessageDigest sha = MessageDigest.getInstance("SHA"); sha.update(_strSrc.getBytes()); byte[] buffer = sha.digest(); return encoder.encode(buffer); } catch (Exception err) { System.out.println(err); } return ""; }
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 String GetSHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return LoginHttpPostProcessor.ConvertToHex(sha1hash); }
00
Code Sample 1: protected InputStream transform(URL url) throws IOException { TransformerFactory tf = TransformerFactory.newInstance(); InputStream xsl_is = null; InputStream url_is = null; ByteArrayOutputStream os = null; byte[] output; try { xsl_is = Classes.getThreadClassLoader().getResourceAsStream(getStylesheet()); url_is = new BufferedInputStream(url.openStream()); os = new ByteArrayOutputStream(); Transformer tr = tf.newTransformer(new StreamSource(xsl_is)); tr.transform(new StreamSource(url_is), new StreamResult(os)); output = os.toByteArray(); } catch (TransformerConfigurationException tce) { throw new IOException(tce.getLocalizedMessage()); } catch (TransformerException te) { throw new IOException(te.getLocalizedMessage()); } finally { try { if (os != null) os.close(); } catch (Throwable t) { } try { if (url_is != null) url_is.close(); } catch (Throwable t) { } try { if (xsl_is != null) xsl_is.close(); } catch (Throwable t) { } } if (logService.isEnabledFor(LogLevel.TRACE)) logService.log(LogLevel.TRACE, new String(output)); return new ByteArrayInputStream(output); } Code Sample 2: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); HttpGet request = new HttpGet(SERVICE_URI + "/json/getroutes/1"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); DefaultHttpClient httpClient = new DefaultHttpClient(); String theString = new String(""); try { HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); Vector<String> vectorOfStrings = new Vector<String>(); String tempString = new String(); String tempStringAgent = new String(); String tempStringClient = new String(); String tempStringRoute = new String(); String tempStringZone = new String(); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } stream.close(); theString = builder.toString(); JSONObject json = new JSONObject(theString); Log.i("_GetClient_", "<jsonobject>\n" + json.toString() + "\n</jsonobject>"); this.dm = new DataManipulator(this); JSONArray nameArray = json.getJSONArray("GetRoutesByAgentResult"); for (int i = 0; i < nameArray.length(); i++) { tempStringAgent = nameArray.getJSONObject(i).getString("Agent"); tempStringClient = nameArray.getJSONObject(i).getString("Client"); tempStringRoute = nameArray.getJSONObject(i).getString("Route"); tempStringZone = nameArray.getJSONObject(i).getString("Zone"); Log.i("_GetClient_", "<Agent" + i + ">" + tempStringAgent + "</Agent" + i + ">\n"); Log.i("_GetClient_", "<Client" + i + ">" + tempStringClient + "</Client" + i + ">\n"); Log.i("_GetClient_", "<Route" + i + ">" + tempStringRoute + "</Route" + i + ">\n"); Log.i("_GetClient_", "<Zone" + i + ">" + tempStringZone + "</Zone" + i + ">\n"); tempString = nameArray.getJSONObject(i).getString("Client") + "\n" + nameArray.getJSONObject(i).getString("Route") + "\n" + nameArray.getJSONObject(i).getString("Zone"); vectorOfStrings.add(new String(tempString)); } int orderCount = vectorOfStrings.size(); String[] orderTimeStamps = new String[orderCount]; vectorOfStrings.copyInto(orderTimeStamps); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, orderTimeStamps)); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: private static void generateTIFF(Connection con, String category, String area_code, String topic_code, String timeseries, String diff_timeseries, Calendar time, String area_label, String raster_label, String image_label, String note, Rectangle2D bounds, Rectangle2D raster_bounds, String source_filename, String diff_filename, String legend_filename, String output_filename, int output_maximum_size) throws SQLException, IOException { Debug.println("ImageCropper.generateTIFF begin"); MapContext map_context = new MapContext("test", new Configuration()); try { Map map = new Map(map_context, area_label, new Configuration()); map.setCoordSys(ProjectionCategories.default_coordinate_system); map.setPatternOutline(new XPatternOutline(new XPatternPaint(Color.white))); String type = null; RasterLayer rlayer = getRasterLayer(map, raster_label, getLinuxPathEquivalent(source_filename), getLinuxPathEquivalent(diff_filename), type, getLinuxPathEquivalent(legend_filename)); map.addLayer(rlayer, true); map.setBounds2DImage(bounds, true); Dimension image_dim = null; image_dim = new Dimension((int) rlayer.raster.getDeviceBounds().getWidth() + 1, (int) rlayer.raster.getDeviceBounds().getHeight() + 1); if (output_maximum_size > 0) { double width_factor = image_dim.getWidth() / output_maximum_size; double height_factor = image_dim.getHeight() / output_maximum_size; double factor = Math.max(width_factor, height_factor); if (factor > 1.0) { image_dim.setSize(image_dim.getWidth() / factor, image_dim.getHeight() / factor); } } map.setImageDimension(image_dim); map.scale(); image_dim = new Dimension((int) map.getBounds2DImage().getWidth(), (int) map.getBounds2DImage().getHeight()); Image image = null; Graphics gr = null; image = ImageCreator.getImage(image_dim); gr = image.getGraphics(); try { map.paint(gr); } catch (Exception e) { Debug.println("map.paint error: " + e.getMessage()); } String tiff_filename = ""; try { tiff_filename = formatPath(category, timeseries, output_filename); new File(new_filename).mkdirs(); Debug.println("tiff_filename: " + tiff_filename); BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_BYTE_INDEXED); bi.createGraphics().drawImage(image, 0, 0, null); File f = new File(tiff_filename); FileOutputStream out = new FileOutputStream(f); TIFFEncodeParam param = new TIFFEncodeParam(); param.setCompression(TIFFEncodeParam.COMPRESSION_PACKBITS); TIFFImageEncoder encoder = (TIFFImageEncoder) TIFFCodec.createImageEncoder("tiff", out, param); encoder.encode(bi); out.close(); } catch (IOException e) { Debug.println("ImageCropper.generateTIFF TIFFCodec e: " + e.getMessage()); throw new IOException("GenerateTIFF.IOException: " + e); } PreparedStatement pstmt = null; try { String query = "select Proj_ID, AccessType_Code from project " + "where Proj_Code= '" + area_code.trim() + "'"; Statement stmt = null; ResultSet rs = null; int proj_id = -1; int access_code = -1; stmt = con.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { proj_id = rs.getInt(1); access_code = rs.getInt(2); } rs.close(); stmt.close(); String delete_raster = "delete from rasterlayer where " + "Raster_Name='" + tiff_name.trim() + "' and Group_Code='" + category.trim() + "' and Proj_ID =" + proj_id; Debug.println("***** delete_raster: " + delete_raster); pstmt = con.prepareStatement(delete_raster); boolean del = pstmt.execute(); pstmt.close(); String insert_raster = "insert into rasterlayer(Raster_Name, " + "Group_Code, Proj_ID, Raster_TimeCode, Raster_Xmin, " + "Raster_Ymin, Raster_Area_Xmin, Raster_Area_Ymin, " + "Raster_Visibility, Raster_Order, Raster_Path, " + "AccessType_Code, Raster_TimePeriod) values(?,?,?,?, " + "?,?,?,?,?,?,?,?,?)"; pstmt = con.prepareStatement(insert_raster); pstmt.setString(1, tiff_name); pstmt.setString(2, category); pstmt.setInt(3, proj_id); pstmt.setString(4, timeseries); pstmt.setDouble(5, raster_bounds.getX()); pstmt.setDouble(6, raster_bounds.getY()); pstmt.setDouble(7, raster_bounds.getWidth()); pstmt.setDouble(8, raster_bounds.getHeight()); pstmt.setString(9, "false"); int sequence = 0; if (tiff_name.endsWith("DP")) { sequence = 1; } else if (tiff_name.endsWith("DY")) { sequence = 2; } else if (tiff_name.endsWith("DA")) { sequence = 3; } pstmt.setInt(10, sequence); pstmt.setString(11, tiff_filename); pstmt.setInt(12, access_code); if (time == null) { pstmt.setNull(13, java.sql.Types.DATE); } else { pstmt.setDate(13, new java.sql.Date(time.getTimeInMillis())); } pstmt.executeUpdate(); } catch (SQLException e) { Debug.println("SQLException occurred e: " + e.getMessage()); con.rollback(); throw new SQLException("GenerateTIFF.SQLException: " + e); } finally { pstmt.close(); } } catch (Exception e) { Debug.println("ImageCropper.generateTIFF e: " + e.getMessage()); } Debug.println("ImageCropper.generateTIFF end"); } Code Sample 2: public void insertProfile() throws ClassNotFoundException, SQLException { Connection connection = null; PreparedStatement ps1 = null; PreparedStatement ps2 = null; PreparedStatement ps3 = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(this.url); connection.setAutoCommit(false); String query1 = "INSERT INTO customers(name,password) VALUES(?,?)"; ps1 = connection.prepareStatement(query1); ps1.setString(1, this.name); ps1.setString(2, this.password); String query2 = "INSERT INTO customer_roles(name,role_name) VALUES(?,?)"; ps2 = connection.prepareStatement(query2); ps2.setString(1, this.name); ps2.setString(2, "user"); String query3 = "INSERT INTO customers_profile(name,first_name,middle_name,last_name,address1,address2,city,post_box,email,country)" + "VALUES(?,?,?,?,?,?,?,?,?,?)"; ps3 = connection.prepareStatement(query3); ps3.setString(1, this.name); ps3.setString(2, this.firstName); ps3.setString(3, this.middleName); ps3.setString(4, this.lastName); ps3.setString(5, this.address1); ps3.setString(6, this.address2); ps3.setString(7, this.city); ps3.setString(8, this.postBox); ps3.setString(9, this.email); ps3.setString(10, this.country); ps1.executeUpdate(); ps2.executeUpdate(); ps3.executeUpdate(); connection.commit(); } catch (Exception ex) { connection.rollback(); } finally { try { this.connection.close(); } catch (Exception ex) { } try { ps1.close(); } catch (Exception ex) { } try { ps2.close(); } catch (Exception ex) { } try { ps3.close(); } catch (Exception ex) { } } }
00
Code Sample 1: public static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); InputStream is = CheckAvailability.class.getResourceAsStream("/isbns.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String isbn = null; HttpGet get = null; while ((isbn = br.readLine().split(" ")[0]) != null) { System.out.println("Target url: \n\t" + String.format(isbnSearchUrl, isbn)); get = new HttpGet(String.format(isbnSearchUrl, isbn)); HttpResponse resp = httpclient.execute(get); Scanner s = new Scanner(resp.getEntity().getContent()); String pattern = s.findWithinHorizon("((\\d*) hold[s]? on first copy returned of (\\d*) )?[cC]opies", 0); if (pattern != null) { MatchResult match = s.match(); if (match.groupCount() == 3) { if (match.group(2) == null) { System.out.println(isbn + ": copies available"); } else { System.out.println(isbn + ": " + match.group(2) + " holds on " + match.group(3) + " copies"); } } } else { System.out.println(isbn + ": no match"); } get.abort(); } } Code Sample 2: public static String encodePassword(String password) { try { MessageDigest messageDiegest = MessageDigest.getInstance("SHA-1"); messageDiegest.update(password.getBytes("UTF-8")); return Base64.encodeToString(messageDiegest.digest(), false); } catch (NoSuchAlgorithmException e) { log.error("Exception while encoding password"); throw new Error(e); } catch (UnsupportedEncodingException e) { log.error("Exception while encoding password"); throw new Error(e); } }
11
Code Sample 1: public List<SuspectFileProcessingStatus> retrieve() throws Exception { BufferedOutputStream bos = null; try { String listFilePath = GeneralUtils.generateAbsolutePath(getDownloadDirectoryPath(), getListName(), "/"); listFilePath = listFilePath.concat(".xml"); if (!new File(getDownloadDirectoryPath()).exists()) { FileUtils.forceMkdir(new File(getDownloadDirectoryPath())); } FileOutputStream listFileOutputStream = new FileOutputStream(listFilePath); bos = new BufferedOutputStream(listFileOutputStream); InputStream is = null; if (getUseProxy()) { is = URLUtils.getResponse(getUrl(), getUserName(), getPassword(), URLUtils.HTTP_GET_METHOD, getProxyHost(), getProxyPort()); IOUtils.copyLarge(is, bos); } else { URLUtils.getResponse(getUrl(), getUserName(), getPassword(), bos, null); } bos.flush(); bos.close(); File listFile = new File(listFilePath); if (!listFile.exists()) { throw new IllegalStateException("The list file did not get created"); } if (isLoggingInfo()) { logInfo("Downloaded list file : " + listFile); } List<SuspectFileProcessingStatus> sfpsList = new ArrayList<SuspectFileProcessingStatus>(); String loadType = GeneralConstants.LOAD_TYPE_FULL; String feedType = GeneralConstants.EMPTY_TOKEN; String listName = getListName(); String errorCode = ""; String description = ""; SuspectFileProcessingStatus sfps = getSuspectsLoaderService().storeFileIntoListIncomingDir(listFile, loadType, feedType, listName, errorCode, description); sfpsList.add(sfps); if (isLoggingInfo()) { logInfo("Retrieved list file with SuspectFileProcessingStatus: " + sfps); } return sfpsList; } finally { if (null != bos) { bos.close(); } } } Code Sample 2: protected final void loadLogFile(String filename) throws IOException { cleanUp(true, false); InputStream is = null; OutputStream os = null; File f = File.createTempFile("log", null); try { is = getClass().getResourceAsStream(filename); Assert.isTrue(is != null, "File not found: " + filename); os = new FileOutputStream(f); IOUtils.copy(is, os); setLogFile(f); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
00
Code Sample 1: public Document getKmlStream(String streetname, String number, String neighbourhood, String city, String state) throws RotaException { StringBuffer urlsb = new StringBuffer(resourceBundle.getString(Constants.URL_SEARCH)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); InputStream in = null; HttpURLConnection httpConnection = null; Document doc = null; dbf.setValidating(false); String proxy = resourceBundle.getString(Constants.PROXY_HOST); String port = resourceBundle.getString(Constants.PROXY_PORT); try { String address = String.format("%s+%s+%s+%s+%s", URLEncoder.encode(streetname.trim(), Constants.URL_ENCODING), URLEncoder.encode(number.trim(), Constants.URL_ENCODING), URLEncoder.encode(neighbourhood.trim(), Constants.URL_ENCODING), URLEncoder.encode(city.trim(), Constants.URL_ENCODING), URLEncoder.encode(state.trim(), Constants.URL_ENCODING)); DocumentBuilder df = dbf.newDocumentBuilder(); urlsb.append(address); urlsb.append(resourceBundle.getString(Constants.GOOGLE_TYPE_OUTPUT)); urlsb.append(resourceBundle.getString(Constants.SENSOR)); urlsb.append(resourceBundle.getString(Constants.GOOGLE_KEY)); urlsb.append(resourceBundle.getString(Constants.GOOGLE_KEY_VALUE)); String addressUTF8 = urlsb.toString(); URL url = new URL(addressUTF8); Properties systemproperties = System.getProperties(); if (proxy != null && !proxy.equals("")) { systemproperties.setProperty("http.proxyHost", proxy); systemproperties.setProperty("http.proxyPort", port); } httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.connect(); in = httpConnection.getInputStream(); doc = df.parse(in); in.close(); httpConnection.disconnect(); if (doc == null || !verificaStatusRequisicao(doc)) { throw new RotaException("N�o foi poss�vel realizar a geodecodifica��o com o endere�o informado!"); } return doc; } catch (UnsupportedEncodingException ue) { logger.error(ue); throw new RotaException("Encoding n�o suportado : " + ue.getMessage()); } catch (MalformedURLException ma) { logger.error(ma); throw new RotaException("Erro na URL : " + ma.getMessage()); } catch (ParserConfigurationException pe) { logger.error(pe); throw new RotaException("Erro ao realizar o parser da configura��o : " + pe.getMessage()); } catch (SAXException sa) { logger.error(sa); throw new RotaException("Erro de SAX : " + sa.getMessage()); } catch (ConnectException co) { logger.error(co); throw new RotaException("N�o foi poss�vel estabelecer a conex�o http : " + co.getMessage()); } catch (IOException io) { logger.error(io); throw new RotaException("Erro de io : ", io); } catch (Exception ex) { throw new RotaException("N�o foi poss�vel gerar a rota : " + ex.getMessage()); } finally { if (in != null) { try { in.close(); } catch (Exception ex) { throw new RotaException("N�o foi poss�vel fechar o stream de dados ! : " + ex.getMessage()); } } if (httpConnection != null) { httpConnection.disconnect(); } } } Code Sample 2: void readData(URL url) throws IOException { int i = 0, j = 0, k = 0; double xvalue, yvalue; double xindex, yindex; InputStream is = url.openStream(); is.mark(0); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); int columnsize = 0; double temp_prev = 0; double temp_new = 0; int first = 0; s = br.readLine(); StringTokenizer st = new StringTokenizer(s); columnsize = Integer.parseInt(st.nextToken()); data = new double[columnsize][100][100]; isize = 0; jsize = 0; while ((s = br.readLine()) != null) { st = new StringTokenizer(s); for (k = 0; k < columnsize; k++) { temp_new = Double.parseDouble(st.nextToken()); if (first == 0) { temp_prev = temp_new; first = 1; } if (k == 0) { if (temp_new != temp_prev) { temp_prev = temp_new; i++; j = 0; } } data[k][i][j] = temp_new; } j++; } isize = i + 1; jsize = j; }
11
Code Sample 1: public void copyFile(final File sourceFile, final File destinationFile) throws FileIOException { final FileChannel sourceChannel; try { sourceChannel = new FileInputStream(sourceFile).getChannel(); } catch (FileNotFoundException exception) { final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile; LOGGER.fatal(message); throw fileIOException(message, sourceFile, exception); } final FileChannel destinationChannel; try { destinationChannel = new FileOutputStream(destinationFile).getChannel(); } catch (FileNotFoundException exception) { final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile; LOGGER.fatal(message); throw fileIOException(message, destinationFile, exception); } try { destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (Exception exception) { final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile; LOGGER.fatal(message); throw fileIOException(message, null, exception); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException exception) { LOGGER.error("closing source", exception); } } if (destinationChannel != null) { try { destinationChannel.close(); } catch (IOException exception) { LOGGER.error("closing destination", exception); } } } } Code Sample 2: public void writeToStream(OutputStream out) throws IOException { InputStream result = null; if (tempFile != null) { InputStream input = new BufferedInputStream(new FileInputStream(tempFile)); IOUtils.copy(input, out); IOUtils.closeQuietly(input); } else if (tempBuffer != null) { out.write(tempBuffer); } }
00
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: public static int UsePassword(String username, String password, String new_password) { try { URL url = new URL("http://eiffel.itba.edu.ar/hci/service/Security.groovy?method=ChangePassword&username=" + username + "&password=" + password + "&new_password=" + new_password); URLConnection urlc = url.openConnection(); urlc.setDoOutput(false); urlc.setAllowUserInteraction(false); BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); String response = sb.toString(); if (response == null) { return -1; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document dom = db.parse(is); NodeList nl = dom.getElementsByTagName("response"); String status = ((Element) nl.item(0)).getAttributes().item(0).getTextContent(); if (status.toString().equals("fail")) { return -1; } return 0; } catch (Exception e) { e.printStackTrace(); } return -1; }
11
Code Sample 1: public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); } Code Sample 2: public static String CreateHash(String s) { String str = s.toString(); if (str == null || str.length() == 0) { throw new IllegalArgumentException("String cannot be null or empty"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return (hexString.toString()); }
11
Code Sample 1: public synchronized String encrypt(String plaintext) throws ServiceRuntimeException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new ServiceRuntimeException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new ServiceRuntimeException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: static String getMD5Hash(String str) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] b = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < b.length; i++) { int v = (int) b[i]; v = v < 0 ? 0x100 + v : v; String cc = Integer.toHexString(v); if (cc.length() == 1) sb.append('0'); sb.append(cc); } return sb.toString(); }
00
Code Sample 1: @Override public void run() { try { long pos = begin; byte[] buf = new byte[1024]; URLConnection cn = url.openConnection(); Utils.setHeader(cn); cn.setRequestProperty("Range", "bytes=" + begin + "-" + end); BufferedInputStream bis = new BufferedInputStream(cn.getInputStream()); int len; while ((len = bis.read(buf)) > 0) { synchronized (file) { file.seek(pos); file.write(buf, 0, len); } pos += len; Statics.getInstance().addComleted(len); } } catch (Exception e) { e.printStackTrace(); } latch.countDown(); } Code Sample 2: public String loadURLString(java.net.URL url) { try { BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String s = ""; while (br.ready() && s != null) { s = br.readLine(); if (s != null) { buf.append(s); buf.append("\n"); } } return buf.toString(); } catch (IOException ex) { return ""; } catch (NullPointerException npe) { return ""; } }
00
Code Sample 1: public static ObjectID[] sortDecending(ObjectID[] oids) { for (int i = 1; i < oids.length; i++) { ObjectID iId = oids[i]; for (int j = 0; j < oids.length - i; j++) { if (oids[j].getTypePrefix() > oids[j + 1].getTypePrefix()) { ObjectID temp = oids[j]; oids[j] = oids[j + 1]; oids[j + 1] = temp; } } } return oids; } Code Sample 2: public static String hashClientPassword(String algorithm, String password, String salt) throws IllegalArgumentException, DruidSafeRuntimeException { if (algorithm == null) { throw new IllegalArgumentException("THE ALGORITHM MUST NOT BE NULL"); } if (password == null) { throw new IllegalArgumentException("THE PASSWORD MUST NOT BE NULL"); } if (salt == null) { salt = ""; } String result = null; try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(password.getBytes()); md.update(salt.getBytes()); result = SecurityHelper.byteArrayToHexString(md.digest()); } catch (NoSuchAlgorithmException e) { throw new DruidSafeRuntimeException(e); } return result; }
00
Code Sample 1: public static boolean copy(FileSystem srcFS, Path src, FileSystem dstFS, Path dst, boolean deleteSource, boolean overwrite, Configuration conf) throws IOException { LOG.debug("[sgkim] copy - start"); dst = checkDest(src.getName(), dstFS, dst, overwrite); if (srcFS.getFileStatus(src).isDir()) { checkDependencies(srcFS, src, dstFS, dst); if (!dstFS.mkdirs(dst)) { return false; } FileStatus contents[] = srcFS.listStatus(src); for (int i = 0; i < contents.length; i++) { copy(srcFS, contents[i].getPath(), dstFS, new Path(dst, contents[i].getPath().getName()), deleteSource, overwrite, conf); } } else if (srcFS.isFile(src)) { InputStream in = null; OutputStream out = null; try { LOG.debug("[sgkim] srcFS: " + srcFS + ", src: " + src); in = srcFS.open(src); LOG.debug("[sgkim] dstFS: " + dstFS + ", dst: " + dst); out = dstFS.create(dst, overwrite); LOG.debug("[sgkim] copyBytes - start"); IOUtils.copyBytes(in, out, conf, true); LOG.debug("[sgkim] copyBytes - end"); } catch (IOException e) { IOUtils.closeStream(out); IOUtils.closeStream(in); throw e; } } else { throw new IOException(src.toString() + ": No such file or directory"); } LOG.debug("[sgkim] copy - end"); if (deleteSource) { return srcFS.delete(src, true); } else { return true; } } Code Sample 2: private void runUpdate(String sql, boolean transactional) { log().info("Vacuumd executing statement: " + sql); Connection dbConn = null; boolean commitRequired = false; boolean autoCommitFlag = !transactional; try { dbConn = getDataSourceFactory().getConnection(); dbConn.setAutoCommit(autoCommitFlag); PreparedStatement stmt = dbConn.prepareStatement(sql); int count = stmt.executeUpdate(); stmt.close(); if (log().isDebugEnabled()) { log().debug("Vacuumd: Ran update " + sql + ": this affected " + count + " rows"); } commitRequired = transactional; } catch (SQLException ex) { log().error("Vacuumd: Database error execuating statement " + sql, ex); } finally { if (dbConn != null) { try { if (commitRequired) { dbConn.commit(); } else if (transactional) { dbConn.rollback(); } } catch (SQLException ex) { } finally { if (dbConn != null) { try { dbConn.close(); } catch (Exception e) { } } } } } }
11
Code Sample 1: public String getClass(EmeraldjbBean eb) throws EmeraldjbException { Entity entity = (Entity) eb; StringBuffer sb = new StringBuffer(); String myPackage = getPackageName(eb); sb.append("package " + myPackage + ";\n"); sb.append("\n"); DaoValuesGenerator valgen = new DaoValuesGenerator(); String values_class_name = valgen.getClassName(entity); sb.append("\n"); List importList = new Vector(); importList.add("java.io.*;"); importList.add("java.sql.Date;"); importList.add("com.emeraldjb.runtime.patternXmlObj.*;"); importList.add("javax.xml.parsers.*;"); importList.add("java.text.ParseException;"); importList.add("org.xml.sax.*;"); importList.add("org.xml.sax.helpers.*;"); importList.add(valgen.getPackageName(eb) + "." + values_class_name + ";"); Iterator it = importList.iterator(); while (it.hasNext()) { String importName = (String) it.next(); sb.append("import " + importName + "\n"); } sb.append("\n"); String proto_version = entity.getPatternValue(GeneratorConst.PATTERN_STREAM_PROTO_VERSION, "1"); boolean short_version = entity.getPatternBooleanValue(GeneratorConst.PATTERN_STREAM_XML_SHORT, false); StringBuffer preface = new StringBuffer(); StringBuffer consts = new StringBuffer(); StringBuffer f_writer = new StringBuffer(); StringBuffer f_writer_short = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); StringBuffer end_elems = new StringBuffer(); boolean end_elem_needs_catch = false; consts.append("\n public static final String EL_CLASS_TAG=\"" + values_class_name + "\";"); preface.append("\n xos.print(\"<!-- This format is optimised for space, below are the column mappings\");"); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); int col_num = 0; while (it.hasNext()) { col_num++; Member member = (Member) it.next(); String nm = member.getName(); preface.append("\n xos.print(\"c" + col_num + " = " + nm + "\");"); String elem_name = nm; String elem_name_short = "c" + col_num; String el_name = nm.toUpperCase(); if (member.getColLen() > 0 || !member.isNullAllowed()) { end_elem_needs_catch = true; } String element_const = "EL_" + el_name; String element_const_short = "EL_" + el_name + "_SHORT"; consts.append("\n public static final String " + element_const + "=\"" + elem_name + "\";" + "\n public static final String " + element_const_short + "=\"" + elem_name_short + "\";"); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "values_." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToXmlCode(pad, element_const, getter + "()")); f_writer_short.append(gen_type.getToXmlCode(pad, element_const_short, getter + "()")); end_elems.append(gen_type.getFromXmlCode(pad, element_const, setter)); end_elems.append("\n //and also the short version"); end_elems.append(gen_type.getFromXmlCode(pad, element_const_short, setter)); } preface.append("\n xos.print(\"-->\");"); String body_part = f_writer.toString(); String body_part_short = preface.toString() + f_writer_short.toString(); String reader_vars = ""; String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + " extends DefaultHandler implements TSParser\n"); sb.append("{" + consts + "\n public static final int PROTO_VERSION=" + proto_version + ";" + "\n private transient StringBuffer cdata_=new StringBuffer();" + "\n private transient String endElement_;" + "\n private transient TSParser parentParser_;" + "\n private transient XMLReader theReader_;\n" + "\n private " + values_class_name + " values_;"); sb.append("\n\n"); sb.append("\n /**" + "\n * This is really only here as an example. It is very rare to write a single" + "\n * object to a file - far more likely to have a collection or object graph. " + "\n * in which case you can write something similar - maybe using the writeXmlShort" + "\n * version instread." + "\n */" + "\n public static void writeToFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileOutputStream fos = new FileOutputStream(file_nm);" + "\n XmlOutputFilter xos = new XmlOutputFilter(fos);" + "\n xos.openElement(\"FILE_\"+EL_CLASS_TAG);" + "\n writeXml(xos, obj);" + "\n xos.closeElement();" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException, SAXException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileInputStream fis = new FileInputStream(file_nm);" + "\n DataInputStream dis = new DataInputStream(fis);" + "\n marshalFromXml(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeXml(XmlOutputFilter xos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n xos.openElement(EL_CLASS_TAG);" + body_part + "\n xos.closeElement();" + "\n } // end of writeXml" + "\n" + "\n public static void writeXmlShort(XmlOutputFilter xos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n xos.openElement(EL_CLASS_TAG);" + body_part_short + "\n xos.closeElement();" + "\n } // end of writeXml" + "\n" + "\n public " + streamer_class_name + "(" + values_class_name + " obj) {" + "\n values_ = obj;" + "\n } // end of ctor" + "\n"); String xml_bit = addXmlFunctions(streamer_class_name, values_class_name, end_elem_needs_catch, end_elems, f_reader); String close = "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"; return sb.toString() + xml_bit + close; } Code Sample 2: public void concatFiles() throws IOException { Writer writer = null; try { final File targetFile = new File(getTargetDirectory(), getTargetFile()); targetFile.getParentFile().mkdirs(); if (null != getEncoding()) { getLog().info("Writing aggregated file with encoding '" + getEncoding() + "'"); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), getEncoding())); } else { getLog().info("WARNING: writing aggregated file with system encoding"); writer = new FileWriter(targetFile); } for (File file : getFiles()) { Reader reader = null; try { if (null != getEncoding()) { getLog().info("Reading file " + file.getCanonicalPath() + " with encoding '" + getEncoding() + "'"); reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), getEncoding())); } else { getLog().info("WARNING: Reading file " + file.getCanonicalPath() + " with system encoding"); reader = new FileReader(file); } IOUtils.copy(reader, writer); final String delimiter = getDelimiter(); if (delimiter != null) { writer.write(delimiter.toCharArray()); } } finally { IOUtils.closeQuietly(reader); } } } finally { IOUtils.closeQuietly(writer); } }
11
Code Sample 1: @Test public void testCopy_readerToOutputStream_Encoding_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null, "UTF16"); fail(); } catch (NullPointerException ex) { } } Code Sample 2: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
00
Code Sample 1: public static void main(String[] args) throws IOException { File fileIn = new File("D:\\zz_c\\study2\\src\\study\\io\\A.java"); InputStream fin = new FileInputStream(fileIn); PipedInputStream pin = new PipedInputStream(); PipedOutputStream pout = new PipedOutputStream(); pout.connect(pin); IoRead i = new IoRead(); i.setIn(pin); File fileOU1 = new File("D:\\zz_c\\study2\\src\\study\\io\\A1.java"); File fileOU2 = new File("D:\\zz_c\\study2\\src\\study\\io\\A2.java"); File fileOU3 = new File("D:\\zz_c\\study2\\src\\study\\io\\A3.java"); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU1))); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU2))); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU3))); PipedInputStream pin2 = new PipedInputStream(); PipedOutputStream pout2 = new PipedOutputStream(); i.addOut(pout2); pout2.connect(pin2); i.start(); int read; try { read = fin.read(); while (read != -1) { pout.write(read); read = fin.read(); } fin.close(); pout.close(); } catch (IOException e) { e.printStackTrace(); } int c = pin2.read(); while (c != -1) { System.out.print((char) c); c = pin2.read(); } pin2.close(); } Code Sample 2: private void alterarCategoria(Categoria cat) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "UPDATE categoria SET nome_categoria = ? where id_categoria = ?"; ps = conn.prepareStatement(sql); ps.setString(1, cat.getNome()); ps.setInt(2, cat.getCodigo()); ps.executeUpdate(); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } }
00
Code Sample 1: @Override public boolean connect(String host, String userName, String password) throws IOException, UnknownHostException { try { if (ftpClient != null) if (ftpClient.isConnected()) ftpClient.disconnect(); ftpClient = new FTPSClient("SSL", false); boolean success = false; ftpClient.connect(host); int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) success = ftpClient.login(userName, password); if (!success) ftpClient.disconnect(); return success; } catch (Exception ex) { throw new IOException(ex.getMessage()); } } Code Sample 2: private void readArchives(final VideoArchiveSet vas) throws IOException { final BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; try { while ((line = in.readLine()) != null) { if (line.startsWith("ARCHIVE")) { final StringTokenizer s = new StringTokenizer(line); s.nextToken(); final Integer tapeNumber = Integer.valueOf(s.nextToken()); final Timecode timeCode = new Timecode(s.nextToken()); final VideoArchive va = new VideoArchive(); va.setTimeCode(timeCode); va.setTapeNumber(tapeNumber); vas.addVideoArchive(va); archives.put(tapeNumber, va); } } } catch (IOException e) { throw e; } finally { in.close(); } if (archives.size() == 0) { log.warn("No lines with ARCHIVE were found in the current vif file, will try to look at another vif with same yearday, " + "ship and platform and try to get archives from there:"); String urlBase = url.getPath().toString().substring(0, url.getPath().toString().lastIndexOf("/")); File vifDir = new File(urlBase); File[] allYeardayFiles = vifDir.listFiles(); for (int i = 0; i < allYeardayFiles.length; i++) { if (allYeardayFiles[i].toString().endsWith(".vif")) { String filename = allYeardayFiles[i].toString().substring(allYeardayFiles[i].toString().lastIndexOf("/")); String fileLC = filename.toLowerCase(); String toLookFor = new String(new Character(vifMetadata.shipCode).toString() + new Character(vifMetadata.platformCode).toString()); String toLookForLC = toLookFor.toLowerCase(); if (fileLC.indexOf(toLookForLC) >= 0) { log.warn("Will try to read archives from file " + allYeardayFiles[i]); final BufferedReader tempIn = new BufferedReader(new FileReader(allYeardayFiles[i])); String tempLine = null; try { while ((tempLine = tempIn.readLine()) != null) { if (tempLine.startsWith("ARCHIVE")) { final StringTokenizer s = new StringTokenizer(tempLine); s.nextToken(); final Integer tapeNumber = Integer.valueOf(s.nextToken()); final Timecode timeCode = new Timecode(s.nextToken()); final VideoArchive va = new VideoArchive(); va.setTimeCode(timeCode); va.setTapeNumber(tapeNumber); vas.addVideoArchive(va); archives.put(tapeNumber, va); } } } catch (IOException e) { throw e; } finally { tempIn.close(); } } } if (archives.size() > 0) { log.warn("Found " + archives.size() + " archives in that vif so will use that"); break; } } if (archives.size() == 0) { log.warn("Still no archives were found in the file. Unable to process it."); } } }
00
Code Sample 1: public static void main(String[] args) { try { URL url = new URL("http://localhost:6557"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); int responseCode = conn.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String decodedString; while ((decodedString = in.readLine()) != null) { System.out.println(decodedString); } in.close(); conn.disconnect(); } catch (Exception ex) { Logger.getLogger(TestSSLConnection.class.getName()).log(Level.SEVERE, null, ex); } } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
11
Code Sample 1: public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESENC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.encrypt(reader, writer, key, mode); } Code Sample 2: public static File copyFile(String path) { File src = new File(path); File dest = new File(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; }
11
Code Sample 1: private void copyFile(File in, File out) { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException ex) { ex.printStackTrace(); } } Code Sample 2: public String getClass(EmeraldjbBean eb) throws EmeraldjbException { Entity entity = (Entity) eb; StringBuffer sb = new StringBuffer(); String myPackage = getPackageName(eb); sb.append("package " + myPackage + ";\n"); sb.append("\n"); DaoValuesGenerator valgen = new DaoValuesGenerator(); String values_class_name = valgen.getClassName(entity); sb.append("\n"); List importList = new Vector(); importList.add("java.io.FileOutputStream;"); importList.add("java.io.FileInputStream;"); importList.add("java.io.DataInputStream;"); importList.add("java.io.DataOutputStream;"); importList.add("java.io.IOException;"); importList.add("java.sql.Date;"); importList.add(valgen.getPackageName(eb) + "." + values_class_name + ";"); Iterator it = importList.iterator(); while (it.hasNext()) { String importName = (String) it.next(); sb.append("import " + importName + "\n"); } sb.append("\n"); String proto_version = entity.getPatternValue(GeneratorConst.PATTERN_STREAM_PROTO_VERSION, "1"); String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + "\n"); sb.append("{" + "\n public static final int PROTO_VERSION=" + proto_version + ";"); sb.append("\n\n"); StringBuffer f_writer = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); while (it.hasNext()) { Member member = (Member) it.next(); String nm = member.getName(); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToBinaryCode(pad, "dos", getter + "()")); f_reader.append(gen_type.getFromBinaryCode(pad, "din", setter)); } String reader_vars = ""; sb.append("\n public static void writeToFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileOutputStream fos = new FileOutputStream(file_nm);" + "\n DataOutputStream dos = new DataOutputStream(fos);" + "\n writeStream(dos, obj);" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileInputStream fis = new FileInputStream(file_nm);" + "\n DataInputStream dis = new DataInputStream(fis);" + "\n readStream(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeStream(DataOutputStream dos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n dos.writeByte(PROTO_VERSION);" + "\n " + f_writer + "\n } // end of writeStream" + "\n" + "\n public static void readStream(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + "\n int proto_version = din.readByte();" + "\n if (proto_version==" + proto_version + ") readStreamV1(din,obj);" + "\n } // end of readStream" + "\n" + "\n public static void readStreamV1(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + reader_vars + f_reader + "\n } // end of readStreamV1" + "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"); return sb.toString(); }
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: 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 getSHADigest(String input) { if (input == null) return null; MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (java.security.NoSuchAlgorithmException nsae) { throw new RuntimeException(nsae); } if (sha == null) throw new RuntimeException("No message digest"); sha.update(input.getBytes()); byte[] data = sha.digest(); StringBuffer buf = new StringBuffer(data.length * 2); for (int i = 0; i < data.length; i++) { int value = data[i] & 0xff; buf.append(hexDigit(value >> 4)); buf.append(hexDigit(value)); } return buf.toString(); } Code Sample 2: protected byte[] computeHash() { try { final MessageDigest inputHash = MessageDigest.getInstance("SHA"); inputHash.update(bufferFileData().getBytes()); return inputHash.digest(); } catch (final NoSuchAlgorithmException nsae) { lastException = nsae; return new byte[0]; } catch (final IOException ioe) { lastException = ioe; return new byte[0]; } }
11
Code Sample 1: public synchronized String encrypt(final String pPassword) throws NoSuchAlgorithmException, UnsupportedEncodingException { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(pPassword.getBytes("UTF-8")); final byte raw[] = md.digest(); return BASE64Encoder.encodeBuffer(raw); } Code Sample 2: public static String digest(String text, String algorithm, String charsetName) { try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(text.getBytes(charsetName), 0, text.length()); return convertToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("unexpected exception: " + e, e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("unexpected exception: " + e, e); } }
00
Code Sample 1: public void _testConvertIntoOneFile() { File csvFile = new File("C:/DE311/solution_workspace/WorkbookTaglib/WorkbookTagDemoWebapp/src/main/resources/csv/google.csv"); try { Charset guessedCharset = com.glaforge.i18n.io.CharsetToolkit.guessEncoding(csvFile, 4096); CSVReader reader = new CSVReader(new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), guessedCharset))); Writer writer = new FileWriter("/temp/test.html"); int nbLines = CsvConverterUtils.countLines(new BufferedReader(new FileReader(csvFile))); HtmlConverter conv = new HtmlConverter(); conv.convert(reader, writer, nbLines); } catch (Exception e) { fail(e.getMessage()); } } Code Sample 2: public static String generateGuid(boolean secure) { MessageDigest md5 = null; String valueBeforeMD5 = null; String valueAfterMD5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0L; if (secure) rand = mySecureRand.nextLong(); else rand = myRand.nextLong(); sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte array[] = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; j++) { int b = array[j] & 0xff; if (b < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); }
11
Code Sample 1: public void deletePortletName(PortletName portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (portletNameBean.getPortletId() == null) throw new IllegalArgumentException("portletNameId is null"); String sql = "delete from WM_PORTAL_PORTLET_NAME " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, portletNameBean.getPortletId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } Code Sample 2: public boolean addSiteScore(ArrayList<InitScoreTable> siteScores, InitScoreTable scoreTable, String filePath, String strTime) { boolean bResult = false; String strSql = ""; Connection conn = null; Statement stm = null; try { conn = db.getConnection(); conn.setAutoCommit(false); stm = conn.createStatement(); strSql = "delete from t_siteScore where strTaskId = '" + scoreTable.getStrSiteScoreTaskId() + "'"; stm.executeUpdate(strSql); for (int i = 0; i < siteScores.size(); i++) { InitScoreTable temp = siteScores.get(i); String tempSql = "select * from t_tagConf where strTagName='" + temp.getStrSiteScoreTagName() + "' and strTagYear='" + temp.getStrSiteScoreYear() + "' "; System.out.println(tempSql); ResultSet rst = stm.executeQuery(tempSql); if (rst.next()) { temp.setStrSiteScoreTagId(rst.getString("strId")); temp.setStrSiteinfoScoreParentId(rst.getString("strParentId")); } rst = null; } Iterator<InitScoreTable> it = siteScores.iterator(); String strCreatedTime = com.siteeval.common.Format.getDateTime(); String taskId = ""; while (it.hasNext()) { InitScoreTable thebean = it.next(); taskId = thebean.getStrSiteScoreTaskId(); String strId = UID.getID(); strSql = "INSERT INTO " + strTableName3 + "(strId,strTaskId,strTagId," + "strTagType,strTagName,strParentId,flaTagScore,strYear,datCreatedTime,strCreator) " + "VALUES('" + strId + "','" + taskId + "','" + thebean.getStrSiteScoreTagId() + "','" + thebean.getStrSiteScoreTagType() + "','" + thebean.getStrSiteScoreTagName() + "','" + thebean.getStrSiteinfoScoreParentId() + "','" + thebean.getFlaSiteScoreTagScore() + "','" + thebean.getStrSiteScoreYear() + "','" + strCreatedTime + "','" + thebean.getStrSiteScoreCreator() + "')"; stm.executeUpdate(strSql); } strSql = "update t_siteTotalScore set strSiteState=1,flaSiteScore='" + scoreTable.getFlaSiteScore() + "',flaInfoDisclosureScore='" + scoreTable.getFlaInfoDisclosureScore() + "',flaOnlineServicesScore='" + scoreTable.getFlaOnlineServicesScore() + "',flaPublicParticipationSore='" + scoreTable.getFlaPublicParticipationSore() + "',flaWebDesignScore='" + scoreTable.getFlaWebDesignScore() + "',strSiteFeature='" + scoreTable.getStrTotalScoreSiteFeature() + "',strSiteAdvantage='" + scoreTable.getStrTotalScoreSiteAdvantage() + "',strSiteFailure='" + scoreTable.getStrTotalScoreSiteFailure() + "' where strTaskId='" + scoreTable.getStrSiteScoreTaskId() + "'"; stm.executeUpdate(strSql); strSql = "update " + strTableName1 + " set templateUrl='" + filePath + "',dTaskBeginTime='" + strTime + "',dTaskEndTime='" + strTime + "' where strid = '" + scoreTable.getStrSiteScoreTaskId() + "'"; stm.executeUpdate(strSql); conn.commit(); bResult = true; } catch (Exception e) { try { conn.rollback(); } catch (Exception eee) { } System.out.println("������վ���ֱ���Ϣʱ���?"); } finally { try { conn.setAutoCommit(true); if (stm != null) { stm.close(); } if (conn != null) { conn.close(); } } catch (Exception ee) { } } return bResult; }
00
Code Sample 1: @Override public boolean accept(File file) { if (file.getName().equals(".svn")) { return false; } final long modify = file.lastModified(); final long time = DateUtils.toDate("2012-03-21 17:43", "yyyy-MM-dd HH:mm").getTime(); if (modify >= time) { if (file.isFile()) { File f = new File(StringsUtils.replace(file.getAbsolutePath(), filePath2, filePath1)); f.getParentFile().mkdirs(); try { IOUtils.copyFile(file, f); } catch (IOException e) { e.printStackTrace(); } System.out.println(f.getName()); } } return true; } Code Sample 2: public Long createSite(Site site, List<String> hosts) { if (log.isDebugEnabled()) { log.debug("site: " + site); if (site != null) { log.debug(" language: " + site.getDefLanguage()); log.debug(" country: " + site.getDefCountry()); log.debug(" variant: " + site.getDefVariant()); log.debug(" companyId: " + site.getCompanyId()); } } PreparedStatement ps = null; DatabaseAdapter dbDyn = null; try { dbDyn = DatabaseAdapter.getInstance(); CustomSequenceType seq = new CustomSequenceType(); seq.setSequenceName("seq_WM_PORTAL_LIST_SITE"); seq.setTableName("WM_PORTAL_LIST_SITE"); seq.setColumnName("ID_SITE"); Long siteId = dbDyn.getSequenceNextValue(seq); ps = dbDyn.prepareStatement("insert into WM_PORTAL_LIST_SITE (" + "ID_SITE, ID_FIRM, DEF_LANGUAGE, DEF_COUNTRY, DEF_VARIANT, " + "NAME_SITE, ADMIN_EMAIL, IS_CSS_DYNAMIC, CSS_FILE, " + "IS_REGISTER_ALLOWED " + ")values " + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ? " + (dbDyn.getIsNeedUpdateBracket() ? ")" : "")); int num = 1; RsetTools.setLong(ps, num++, siteId); RsetTools.setLong(ps, num++, site.getCompanyId()); ps.setString(num++, site.getDefLanguage()); ps.setString(num++, site.getDefCountry()); ps.setString(num++, site.getDefVariant()); ps.setString(num++, site.getSiteName()); ps.setString(num++, site.getAdminEmail()); ps.setInt(num++, site.getCssDynamic() ? 1 : 0); ps.setString(num++, site.getCssFile()); ps.setInt(num++, site.getRegisterAllowed() ? 1 : 0); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of inserted records - " + i1); if (hosts != null) { for (String s : hosts) { VirtualHost host = new VirtualHostBean(null, siteId, s); InternalDaoFactory.getInternalVirtualHostDao().createVirtualHost(dbDyn, host); } } dbDyn.commit(); return siteId; } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error add new site"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
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: 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."); }
00
Code Sample 1: public ASDGrammarReader(String fileName, boolean includeCoords) throws IOException, MalformedURLException { includePixelCoords = includeCoords; fileName = fileName.trim(); urlConnection = null; urlStream = null; if (fileName.substring(0, 5).equalsIgnoreCase("http:")) { URL fileURL = new URL(fileName); urlConnection = (HttpURLConnection) fileURL.openConnection(); urlStream = urlConnection.getInputStream(); reader = new ASDTokenReader(new BufferedReader(new InputStreamReader(urlStream))); } else reader = new ASDTokenReader(new FileReader(fileName)); } Code Sample 2: public byte[] loadClassFirst(final String className) { if (className.equals("com.sun.sgs.impl.kernel.KernelContext")) { final URL url = Thread.currentThread().getContextClassLoader().getResource("com/sun/sgs/impl/kernel/KernelContext.0.9.6.class.bin"); if (url != null) { try { return StreamUtil.read(url.openStream()); } catch (IOException e) { } } throw new IllegalStateException("Unable to load KernelContext.0.9.6.class.bin"); } return null; }
11
Code Sample 1: public static void decompressFile(File f) throws IOException { File target = new File(f.toString().substring(0, f.toString().length() - 3)); System.out.print("Decompressing: " + f.getName() + ".. "); long initialSize = f.length(); GZIPInputStream in = new GZIPInputStream(new FileInputStream(f)); FileOutputStream fos = new FileOutputStream(target); byte[] buf = new byte[1024]; int read; while ((read = in.read(buf)) != -1) { fos.write(buf, 0, read); } System.out.println("Done."); fos.close(); in.close(); long endSize = target.length(); System.out.println("Initial size: " + initialSize + "; Decompressed size: " + endSize); } Code Sample 2: @Override public void actionPerformed(ActionEvent e) { if (copiedFiles_ != null) { File[] tmpFiles = new File[copiedFiles_.length]; File tmpDir = new File(Settings.getPropertyString(ConstantKeys.project_dir), "tmp/"); tmpDir.mkdirs(); for (int i = copiedFiles_.length - 1; i >= 0; i--) { Frame f = FrameManager.getInstance().getFrameAtIndex(i); try { File in = f.getFile(); File out = new File(tmpDir, f.getFile().getName()); FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); tmpFiles[i] = out; } catch (IOException e1) { e1.printStackTrace(); } } try { FrameManager.getInstance().insertFrames(getTable().getSelectedRow(), FrameManager.INSERT_TYPE.MOVE, tmpFiles); } catch (IOException e1) { e1.printStackTrace(); } } }
00
Code Sample 1: public void delete(DeleteInterceptorChain chain, DistinguishedName dn, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue(); PreparedStatement ps = con.prepareStatement(this.deleteSQL); ps.setString(1, uid); ps.executeUpdate(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } } Code Sample 2: public TextureData newTextureData(URL url, int internalFormat, int pixelFormat, boolean mipmap, String fileSuffix) throws IOException { InputStream stream = new BufferedInputStream(url.openStream()); try { return newTextureData(stream, internalFormat, pixelFormat, mipmap, fileSuffix); } finally { stream.close(); } }
11
Code Sample 1: public static String get(String u, String usr, String pwd) { String response = ""; logger.debug("Attempting to call: " + u); logger.debug("Creating Authenticator: usr=" + usr + ", pwd=" + pwd); Authenticator.setDefault(new CustomAuthenticator(usr, pwd)); try { URL url = new URL(u); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer sb = new StringBuffer(0); String str; while ((str = in.readLine()) != null) { sb.append(str); } in.close(); logger.debug("Response: " + sb.toString()); response = sb.toString(); } catch (MalformedURLException e) { logger.error(e); logger.trace(e, e); } catch (IOException e) { logger.error(e); logger.trace(e, e); } return response; } Code Sample 2: public static String readURL(String urlStr, boolean debug) { if (debug) System.out.print(" trying: " + urlStr + "\n"); URL url = null; try { url = new URL(urlStr); } catch (java.net.MalformedURLException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } HttpURLConnection huc = null; try { huc = (HttpURLConnection) url.openConnection(); } catch (IOException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentType = huc.getContentType(); if (contentType == null || contentType.indexOf("text/xml") < 0) { System.out.print("*** Warning *** Content-Type not set to text/xml"); System.out.print('\n'); System.out.print(" Content-type: "); System.out.print(contentType); System.out.print('\n'); } InputStream urlStream = null; try { urlStream = huc.getInputStream(); } catch (java.io.IOException e) { System.out.print("test failed: opening URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(urlStream)); boolean xml = true; String href = null, inputLine = null; StringBuffer content = new StringBuffer(), stylesheet = null; Transformer transformer = null; try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading first line of response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } if (inputLine == null) { System.out.print("test failed: No input read from URL"); System.out.print('\n'); return null; } if (!inputLine.startsWith("<?xml ")) { xml = false; content.append(inputLine); } if (xml) { int offset = inputLine.indexOf('>'); if (offset + 2 < inputLine.length()) { inputLine = inputLine.substring(offset + 1); offset = inputLine.indexOf('<'); if (offset > 0) inputLine = inputLine.substring(offset); } else try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } content.append(inputLine); } try { while ((inputLine = in.readLine()) != null) content.append(inputLine); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentStr = content.toString(); if (transformer != null) { StreamSource streamXMLRecord = new StreamSource(new StringReader(contentStr)); StringWriter xmlRecordWriter = new StringWriter(); try { transformer.transform(streamXMLRecord, new StreamResult(xmlRecordWriter)); System.out.print(" successfully applied stylesheet '"); System.out.print(href); System.out.print("'"); System.out.print('\n'); } catch (javax.xml.transform.TransformerException e) { System.out.print("unable to apply stylesheet '"); System.out.print(href); System.out.print("'to response: "); System.out.print(e.getMessage()); System.out.print('\n'); e.printStackTrace(); } } return contentStr; }
11
Code Sample 1: public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); } Code Sample 2: @Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { expected = new StringBuilder(); System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + (queryString = httpServletRequest.getQueryString())); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + (body = baos.toString())); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); expected.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); expected.append(value); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); }
00
Code Sample 1: protected Source resolveRepositoryURI(String path) throws TransformerException { Source resolvedSource = null; try { if (path != null) { URL url = new URL(path); InputStream in = url.openStream(); if (in != null) { resolvedSource = new StreamSource(in); } } else { throw new TransformerException("Resource does not exist. \"" + path + "\" is not accessible."); } } catch (MalformedURLException mfue) { throw new TransformerException("Error accessing resource using servlet context: " + path, mfue); } catch (IOException ioe) { throw new TransformerException("Unable to access resource at: " + path, ioe); } return resolvedSource; } Code Sample 2: private File download(String filename, URL url) { int size = -1; int received = 0; try { fireDownloadStarted(filename); File file = createFile(filename); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); System.out.println("下载资源:" + filename + ", url=" + url); // BufferedInputStream bis = new // BufferedInputStream(url.openStream()); InputStream bis = url.openStream(); byte[] buf = new byte[1024]; int count = 0; long lastUpdate = 0; size = bis.available(); while ((count = bis.read(buf)) != -1) { bos.write(buf, 0, count); received += count; long now = System.currentTimeMillis(); if (now - lastUpdate > 500) { fireDownloadUpdate(filename, size, received); lastUpdate = now; } } bos.close(); System.out.println("资源下载完毕:" + filename); fireDownloadCompleted(filename); return file; } catch (IOException e) { System.out.println("下载资源失败:" + filename + ", error=" + e.getMessage()); fireDownloadInterrupted(filename); if (!(e instanceof FileNotFoundException)) { e.printStackTrace(); } } return null; }