label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public static void copyFile4(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copy(in, out); in.close(); out.close(); } Code Sample 2: public static void main(String[] args) throws IOException { String uri = "hdfs://localhost:8020/user/leeing/maxtemp/sample.txt"; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); FSDataInputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 8192, false); System.out.println("\n"); in.seek(0); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); } }
00
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private void auth() throws IOException { authorized = false; seqNumber = 0; DatagramSocket ds = new DatagramSocket(); ds.setSoTimeout(UDPHID_DEFAULT_TIMEOUT); ds.connect(addr, port); DatagramPacket p = new DatagramPacket(buffer.array(), buffer.capacity()); for (int i = 0; i < UDPHID_DEFAULT_ATTEMPTS; i++) { buffer.clear(); buffer.put((byte) REQ_CHALLENGE); buffer.put(htons((short) UDPHID_PROTO)); buffer.put(name.getBytes()); ds.send(new DatagramPacket(buffer.array(), buffer.position())); buffer.clear(); try { ds.receive(p); } catch (SocketTimeoutException e) { continue; } switch(buffer.get()) { case ANS_CHALLENGE: break; case ANS_FAILURE: throw new IOException("REQ_FAILURE"); default: throw new IOException("invalid packet"); } byte challenge_id = buffer.get(); int challenge_len = (int) buffer.get(); byte[] challenge = new byte[challenge_len]; buffer.get(challenge, 0, p.getLength() - buffer.position()); byte[] response; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(challenge_id); md.update(password.getBytes(), 0, password.length()); md.update(challenge, 0, challenge.length); response = md.digest(); } catch (NoSuchAlgorithmException e) { throw new IOException("NoSuchAlgorithmException: " + e.toString()); } buffer.clear(); buffer.put((byte) REQ_RESPONSE); buffer.put(challenge_id); buffer.put((byte) response.length); buffer.put(response); buffer.put(login.getBytes()); ds.send(new DatagramPacket(buffer.array(), buffer.position())); buffer.clear(); try { ds.receive(p); } catch (SocketTimeoutException e) { continue; } switch(buffer.get()) { case ANS_SUCCESS: int sidLength = buffer.get(); sid = new byte[sidLength]; buffer.get(sid, 0, sidLength); authorized = true; return; case ANS_FAILURE: throw new IOException("access deny"); default: throw new IOException("invalid packet"); } } throw new IOException("operation time out"); }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { String name = metadata.get(Metadata.RESOURCE_NAME_KEY); if (name != null && wanted.containsKey(name)) { FileOutputStream out = new FileOutputStream(wanted.get(name)); IOUtils.copy(stream, out); out.close(); } else { if (downstreamParser != null) { downstreamParser.parse(stream, handler, metadata, context); } } }
00
Code Sample 1: public static void executeUpdate(Database db, String... statements) throws SQLException { Connection con = null; Statement stmt = null; try { con = getConnection(db); con.setAutoCommit(false); stmt = con.createStatement(); for (String statement : statements) { stmt.executeUpdate(statement); } con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { } throw e; } finally { closeStatement(stmt); closeConnection(con); } } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
11
Code Sample 1: public static String encryptPassword(String originalPassword) { if (!StringUtils.hasText(originalPassword)) { originalPassword = randomPassword(); } try { MessageDigest md5 = MessageDigest.getInstance(PASSWORD_ENCRYPTION_TYPE); md5.update(originalPassword.getBytes()); byte[] bytes = md5.digest(); int value; StringBuilder buf = new StringBuilder(); for (byte aByte : bytes) { value = aByte; if (value < 0) { value += 256; } if (value < 16) { buf.append("0"); } buf.append(Integer.toHexString(value)); } return buf.toString(); } catch (NoSuchAlgorithmException e) { log.debug("Do not encrypt password,use original password", e); return originalPassword; } } Code Sample 2: static String getMD5Sum(String source) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(source.getBytes()); byte[] md5sum = digest.digest(); BigInteger bigInt = new BigInteger(1, md5sum); return bigInt.toString(16); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("MD5 algorithm seems to not be supported. This is a requirement!"); } }
11
Code Sample 1: protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } } Code Sample 2: 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(); } }
11
Code Sample 1: private void writeResponse(final Collection<? extends Resource> resources, final HttpServletResponse response) throws IOException { for (final Resource resource : resources) { InputStream in = null; try { in = resource.getInputStream(); final OutputStream out = response.getOutputStream(); final long bytesCopied = IOUtils.copyLarge(in, out); if (bytesCopied < 0L) throw new StreamCorruptedException("Bad number of copied bytes (" + bytesCopied + ") for resource=" + resource.getFilename()); if (logger.isDebugEnabled()) logger.debug("writeResponse(" + resource.getFile() + ") copied " + bytesCopied + " bytes"); } finally { if (in != null) in.close(); } } } Code Sample 2: protected String encrypt(final String data, final String key) throws CryptographicFailureException { Validate.notNull(data, "Provided data cannot be null."); Validate.notNull(key, "Provided key name cannot be null."); final PublicKey pk = getPublicKey(key); if (pk == null) { throw new CryptographicFailureException("PublicKeyNotFound", String.format("Cannot find public key '%s'", key)); } try { final Cipher cipher = Cipher.getInstance(pk.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, pk); final ByteArrayInputStream bin = new ByteArrayInputStream(data.getBytes()); final CipherInputStream cin = new CipherInputStream(bin, cipher); final ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(cin, bout); return new String(Base64.encodeBase64(bout.toByteArray())); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(String.format("Cannot find instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (NoSuchPaddingException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (InvalidKeyException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (IOException e) { throw new IllegalStateException("Cannot build in-memory cipher copy", e); } }
00
Code Sample 1: Object execute(String method, Vector params) throws XmlRpcException, IOException { fault = false; long now = 0; if (XmlRpc.debug) { System.err.println("Client calling procedure '" + method + "' with parameters " + params); now = System.currentTimeMillis(); } try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); if (buffer == null) { buffer = new ByteArrayOutputStream(); } else { buffer.reset(); } XmlWriter writer = new XmlWriter(buffer); writeRequest(writer, method, params); writer.flush(); byte[] request = buffer.toByteArray(); URLConnection con = url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setAllowUserInteraction(false); con.setRequestProperty("Content-Length", Integer.toString(request.length)); con.setRequestProperty("Content-Type", "text/xml"); if (auth != null) { con.setRequestProperty("Authorization", "Basic " + auth); } OutputStream out = con.getOutputStream(); out.write(request); out.flush(); out.close(); InputStream in = con.getInputStream(); parse(in); } catch (Exception x) { if (XmlRpc.debug) { x.printStackTrace(); } throw new IOException(x.getMessage()); } if (fault) { XmlRpcException exception = null; try { Hashtable f = (Hashtable) result; String faultString = (String) f.get("faultString"); int faultCode = Integer.parseInt(f.get("faultCode").toString()); exception = new XmlRpcException(faultCode, faultString.trim()); } catch (Exception x) { throw new XmlRpcException(0, "Invalid fault response"); } throw exception; } if (XmlRpc.debug) { System.err.println("Spent " + (System.currentTimeMillis() - now) + " in request"); } return result; } Code Sample 2: private void sendFile(File file, HttpServletResponse response) throws IOException { response.setContentLength((int) file.length()); InputStream inputStream = null; try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, response.getOutputStream()); } finally { IOUtils.closeQuietly(inputStream); } }
11
Code Sample 1: public String excute(String targetUrl, String params, String type) { URL url; HttpURLConnection connection = null; try { url = new URL(targetUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(type); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length)); connection.setRequestProperty("Content-Language", CHAR_SET); connection.setRequestProperty("Connection", "close"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); if (params != null) { if (params.length() > 0) { DataOutputStream wr; wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(params); wr.flush(); wr.close(); } } InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, CHAR_SET)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append("\r\n"); } rd.close(); return response.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } Code Sample 2: public static ArrayList<Quote> fetchAllQuotes(String symbol, Date from, Date to) { try { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(from); String monthFrom = (new Integer(calendar.get(GregorianCalendar.MONTH))).toString(); String dayFrom = (new Integer(calendar.get(GregorianCalendar.DAY_OF_MONTH))).toString(); String yearFrom = (new Integer(calendar.get(GregorianCalendar.YEAR))).toString(); calendar.setTime(to); String monthTo = (new Integer(calendar.get(GregorianCalendar.MONTH))).toString(); String dayTo = (new Integer(calendar.get(GregorianCalendar.DAY_OF_MONTH))).toString(); String yearTo = (new Integer(calendar.get(GregorianCalendar.YEAR))).toString(); URL url = new URL("http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=" + monthFrom + "&b=" + dayFrom + "&c=" + yearFrom + "&d=" + monthTo + "&e=" + dayTo + "&f=" + yearTo + "&g=d&ignore=.csv"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; ArrayList<Quote> result = new ArrayList<Quote>(); reader.readLine(); while ((line = reader.readLine()) != null) { String[] values = line.split(","); String date = values[0]; Date dateQuote = new SimpleDateFormat("yyyy-MM-dd").parse(date); double open = Double.valueOf(values[1]); double high = Double.valueOf(values[2]); double low = Double.valueOf(values[3]); double close = Double.valueOf(values[4]); long volume = Long.valueOf(values[5]); double adjClose = Double.valueOf(values[6]); Quote q = new Quote(dateQuote, open, high, low, close, volume, adjClose); result.add(q); } reader.close(); Collections.reverse(result); return result; } catch (MalformedURLException e) { System.out.println("URL malformee"); } catch (IOException e) { System.out.println("Donnees illisibles"); } catch (ParseException e) { e.printStackTrace(); } return null; }
00
Code Sample 1: private boolean copyAvecProgressNIO(File sRC2, File dEST2, JProgressBar progressEnCours) throws IOException { boolean resultat = false; FileInputStream fis = new FileInputStream(sRC2); FileOutputStream fos = new FileOutputStream(dEST2); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); progressEnCours.setValue(0); progressEnCours.setString(sRC2 + " : 0 %"); channelSrc.transferTo(0, channelSrc.size(), channelDest); progressEnCours.setValue(100); progressEnCours.setString(sRC2 + " : 100 %"); if (channelSrc.size() == channelDest.size()) { resultat = true; } else { resultat = false; } fis.close(); fos.close(); return (resultat); } Code Sample 2: public static String getEncryptedPassword(String clearTextPassword) { if (StringUtil.isEmpty(clearTextPassword)) return ""; try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(clearTextPassword.getBytes()); return new sun.misc.BASE64Encoder().encode(md.digest()); } catch (NoSuchAlgorithmException e) { _log.error("Failed to encrypt password.", e); } return ""; }
11
Code Sample 1: public static HashCash mintCash(String resource, Map<String, List<String>> extensions, Calendar date, int value, int version) throws NoSuchAlgorithmException { if (version < 0 || version > 1) throw new IllegalArgumentException("Only supported versions are 0 and 1"); if (value < 0 || value > hashLength) throw new IllegalArgumentException("Value must be between 0 and " + hashLength); if (resource.contains(":")) throw new IllegalArgumentException("Resource must not contain ':'"); HashCash result = new HashCash(); MessageDigest md = MessageDigest.getInstance("SHA1"); result.myResource = resource; result.myExtensions = (null == extensions ? new HashMap<String, List<String>>() : extensions); result.myDate = date; result.myVersion = version; String prefix; SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString); switch(version) { case 0: prefix = version + ":" + dateFormat.format(date.getTime()) + ":" + resource + ":" + serializeExtensions(extensions) + ":"; result.myToken = generateCash(prefix, value, md); md.reset(); md.update(result.myToken.getBytes()); result.myValue = numberOfLeadingZeros(md.digest()); break; case 1: result.myValue = value; prefix = version + ":" + value + ":" + dateFormat.format(date.getTime()) + ":" + resource + ":" + serializeExtensions(extensions) + ":"; result.myToken = generateCash(prefix, value, md); break; default: throw new IllegalArgumentException("Only supported versions are 0 and 1"); } return result; } Code Sample 2: private String getHash(String string) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md5.reset(); md5.update(string.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString(0xFF & result[i])); } String str = hexString.toString(); return str; }
00
Code Sample 1: public static String toMD5(String seed) { MessageDigest md5 = null; StringBuffer temp_sb = null; try { md5 = MessageDigest.getInstance("MD5"); md5.update(seed.getBytes()); byte[] array = md5.digest(); temp_sb = new StringBuffer(); for (int i = 0; i < array.length; i++) { int b = array[i] & 0xFF; if (b < 0x10) temp_sb.append('0'); temp_sb.append(Integer.toHexString(b)); } } catch (NoSuchAlgorithmException err) { err.printStackTrace(); } return temp_sb.toString(); } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: public void copy(final File source, final File dest) throws IOException { final FileInputStream in = new FileInputStream(source); try { final FileOutputStream out = new FileOutputStream(dest); try { final FileChannel inChannel = in.getChannel(); final FileChannel outChannel = out.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { out.close(); } } finally { in.close(); } } Code Sample 2: private String getResourceAsString(final String name) throws IOException { final InputStream is = JiBXTestCase.class.getResourceAsStream(name); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyAndClose(is, baos); return baos.toString(); }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(imageFile.separator) + 1, path.length())); File imageFile = new File(path); directoryPath = "Images" + imageFile.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + imageFile.separator + "Images" + imageFile.separator + imageName.substring(0, 1).toUpperCase() + imageFile.separator + imageName; File newFile = new File(imagePath); int i = 1; while (newFile.exists()) { imagePath = "." + imageFile.separator + "Images" + imageFile.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); newFile = new File(imagePath); i++; } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); dataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { try { int thumbWidth = PREVIEW_WIDTH; int thumbHeight = PREVIEW_HEIGHT; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getIconWidth(); int imageHeight = image.getIconHeight(); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image.getImage(), 0, 0, thumbWidth, thumbHeight, null); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imagePathThumb)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = 100; quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float) quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } } } }
00
Code Sample 1: public static final void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://www.apache.org/"); System.out.println("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); HttpEntity entity = response.getEntity(); if (entity != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); try { System.out.println(reader.readLine()); } catch (IOException ex) { throw ex; } catch (RuntimeException ex) { httpget.abort(); throw ex; } finally { reader.close(); } } } Code Sample 2: public static boolean checkEncryptedPassword(String md5key, String passwordAccount, String encryptedPassword, int passwdenc) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance(Constants.ALGORITHM); switch(passwdenc) { case 1: md.update((md5key + encryptedPassword).getBytes("8859_1")); return md.digest().equals(passwordAccount.getBytes("8859_1")); case 2: md.update((encryptedPassword + md5key).getBytes("8859_1")); return md.digest().equals(passwordAccount.getBytes("8859_1")); default: return false; } }
11
Code Sample 1: public static String md5(String str) { if (str == null) { System.err.println("Stringx.md5 (String) : null string."); return ""; } String rt = ""; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes("gb2312")); byte[] bt = md5.digest(); String s = null; int l = 0; for (int i = 0; i < bt.length; i++) { s = Integer.toHexString(bt[i]); l = s.length(); if (l > 2) s = s.substring(l - 2, l); else if (l == 1) s = "0" + s; rt += s; } } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return rt; } Code Sample 2: public static String hashString(String password) { String hashword = null; try { MessageDigest sha = MessageDigest.getInstance("SHA"); sha.update(password.getBytes("UTF-8")); BigInteger hash = new BigInteger(1, sha.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { log.error(nsae); } catch (UnsupportedEncodingException e) { log.error(e); } return pad(hashword, 32, '0'); }
00
Code Sample 1: public static 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: private void copyFile(File sourcefile, File targetfile) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(sourcefile)); out = new BufferedOutputStream(new FileOutputStream(targetfile)); byte[] buffer = new byte[4096]; int bytesread = 0; while ((bytesread = in.read(buffer)) >= 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } }
00
Code Sample 1: public boolean parseResults(URL url, String analysis_type, CurationI curation, Date analysis_date, String regexp) throws OutputMalFormatException { boolean parsed = false; try { InputStream data_stream = url.openStream(); parsed = parseResults(data_stream, analysis_type, curation, analysis_date, regexp); } catch (OutputMalFormatException ex) { throw new OutputMalFormatException(ex.getMessage(), ex); } catch (Exception ex) { System.out.println(ex.getMessage()); } return parsed; } Code Sample 2: private boolean doesURLExists(String programURIStr) throws Exception { boolean retVal = true; TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); URL url = new URL(programURIStr); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setConnectTimeout(30000); urlConn.connect(); log.debug("HTTP Status code: " + urlConn.getResponseCode() + " for URL: " + programURIStr); if (HttpURLConnection.HTTP_OK != urlConn.getResponseCode()) { urlConn.disconnect(); throw new Exception("HTTP status code " + urlConn.getResponseCode() + " for " + programURIStr); } urlConn.disconnect(); return retVal; }
11
Code Sample 1: public static String hashSHA1(String value) { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(value.getBytes()); BigInteger hash = new BigInteger(1, digest.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException e) { } return null; } Code Sample 2: 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(); }
00
Code Sample 1: public static String encode(String arg) { if (arg == null) { arg = ""; } MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.update(arg.getBytes(JavaCenterHome.JCH_CHARSET)); } catch (Exception e) { e.printStackTrace(); } return toHex(md5.digest()); } Code Sample 2: public static String CreateZip(String[] filesToZip, String zipFileName) { byte[] buffer = new byte[18024]; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); out.setLevel(Deflater.BEST_COMPRESSION); for (int i = 0; i < filesToZip.length; i++) { FileInputStream in = new FileInputStream(filesToZip[i]); String fileName = null; for (int X = filesToZip[i].length() - 1; X >= 0; X--) { if (filesToZip[i].charAt(X) == '\\' || filesToZip[i].charAt(X) == '/') { fileName = filesToZip[i].substring(X + 1); break; } else if (X == 0) fileName = filesToZip[i]; } out.putNextEntry(new ZipEntry(fileName)); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); } out.close(); } catch (IllegalArgumentException e) { return "Failed to create zip: " + e.toString(); } catch (FileNotFoundException e) { return "Failed to create zip: " + e.toString(); } catch (IOException e) { return "Failed to create zip: " + e.toString(); } return "Success"; }
00
Code Sample 1: public static void copyFileByNIO(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: protected int doExecuteUpdate(PreparedStatement statement) throws SQLException { connection.setAutoCommit(isAutoCommit()); int rs = -1; try { lastError = null; rs = statement.executeUpdate(); if (!isAutoCommit()) connection.commit(); } catch (Exception ex) { if (!isAutoCommit()) { lastError = ex; connection.rollback(); LogUtils.log(Level.SEVERE, "Transaction is being rollback. Error: " + ex.toString()); } } finally { if (statement != null) statement.close(); } return rs; }
00
Code Sample 1: private void writeData(IBaseType dataType, Writer writer) throws XMLStreamException { InputStream isData; DataType data = (DataType) baseType; if (data.isSetInputStream()) { isData = data.getInputStream(); try { IOUtils.copy(isData, writer); } catch (IOException e) { throw new XMLStreamException("DataType fail writing streaming data ", e); } } else if (data.isSetOutputStream()) { throw new XMLStreamException("DataType only can write streaming input, its an output stream (only for reading) "); } else { new CharactersEventImpl(startElement.getLocation(), String.valueOf(baseType.asData()), false).writeAsEncodedUnicode(writer); } } Code Sample 2: public String post(Map<String, String> headersMap, String monitoringRequest) { HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter("http.useragent", "sla@soi OCCI Client v0.2"); HttpPost httpPost = new HttpPost("http://" + hostname + ":" + port + resource); List<Header> headersList = this.convert2Headers(headersMap); for (Iterator<Header> iterator = headersList.iterator(); iterator.hasNext(); ) { httpPost.addHeader(iterator.next()); } if (monitoringRequest == null) { logger.info("Monitoring Request has not been specified - "); monitoringRequest = Terms.MONITORING_NOT_CONFIGURED; logger.info("Monitoring Request has not been specified - " + monitoringRequest); } else { logger.info("Monitoring Request is - " + monitoringRequest); } logger.info(httpPost.getRequestLine()); logger.info(httpPost.getAllHeaders()); Header[] headersArray = httpPost.getAllHeaders(); String[] fields = { Response.Location }; HashMap<String, String> occiHeaders = new HashMap<String, String>(); for (int H = 0; H < headersArray.length; H++) { Header header = headersArray[H]; logger.info("header - request -" + header.toString()); logger.info(" headerName - " + header.getName()); logger.info(" headerValue - " + header.getValue()); } String statusLine = null; try { HttpResponse httpResponse = httpClient.execute(httpPost); statusLine = httpResponse.getStatusLine().toString(); int statusCode = httpResponse.getStatusLine().getStatusCode(); logger.info("----------------------------------------"); logger.info("StatusLine - (full) - " + httpResponse.getStatusLine()); logger.info(" StatusCode - " + statusCode); logger.info(" Reason - " + httpResponse.getStatusLine().getReasonPhrase()); logger.info(" Protocol - " + httpResponse.getStatusLine().getProtocolVersion().toString()); logger.info("----------------------------------------"); if (StatusCode.validate(statusCode)) { logger.info("Response Validated"); } else { logger.error("Response NOT Validated"); } Header[] headers = httpResponse.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Header header = headers[i]; logger.info("header - response - " + header.toString()); logger.info(" headerName - " + header.getName()); logger.info(" headerValue - " + header.getValue()); for (int h = 0; h < fields.length; h++) { logger.info(" Looking for - " + fields[h]); if (fields[h].equals(header.getName().toString())) { logger.info(" Found an OCCI Header - " + header.getName()); occiHeaders.put(header.getName(), header.getValue()); } } } } catch (org.apache.http.conn.HttpHostConnectException e) { e.printStackTrace(); logger.error(e); return null; } catch (ClientProtocolException e) { e.printStackTrace(); logger.error(e); return null; } catch (IOException e) { e.printStackTrace(); logger.error(e); return null; } finally { httpClient.getConnectionManager().shutdown(); } logger.info("occiHeaders - " + occiHeaders); if (occiHeaders.containsKey(Response.Location)) { logger.info("Valid Provision"); return occiHeaders.get(Response.Location).toString().replaceAll(Response.jobs, ""); } logger.info("NOT a Valid Provision" + statusLine); return null; }
00
Code Sample 1: public static void copy(final File src, final File dest) throws IOException { OutputStream stream = new FileOutputStream(dest); FileInputStream fis = new FileInputStream(src); byte[] buffer = new byte[16384]; while (fis.available() != 0) { int read = fis.read(buffer); stream.write(buffer, 0, read); } stream.flush(); } Code Sample 2: public void getFile(String url, String filepath) throws BggException { System.out.println(url); int retry = retryCount + 1; lastURL = url; for (retriedCount = 0; retriedCount < retry; retriedCount++) { int responseCode = -1; try { HttpURLConnection con = null; BufferedInputStream bis = null; OutputStream osw = null; try { con = (HttpURLConnection) new URL(url).openConnection(); con.setDoInput(true); setHeaders(con); con.setRequestMethod("GET"); responseCode = con.getResponseCode(); bis = new BufferedInputStream(con.getInputStream()); int data; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filepath)); while ((data = bis.read()) != -1) bos.write(data); bos.flush(); bos.close(); break; } finally { try { bis.close(); } catch (Exception ignore) { } try { osw.close(); } catch (Exception ignore) { } try { con.disconnect(); } catch (Exception ignore) { } } } catch (IOException ioe) { if (responseCode == UNAUTHORIZED || responseCode == FORBIDDEN) { throw new BggException(ioe.getMessage(), responseCode); } if (retriedCount == retryCount) { throw new BggException(ioe.getMessage(), responseCode); } } try { Thread.sleep(retryIntervalMillis); } catch (InterruptedException ignore) { } } }
11
Code Sample 1: public static void main(String[] args) throws Exception { URL url = new URL("http://www.yahoo.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = ""; String page = ""; while ((line = br.readLine()) != null) { page += line; } System.out.println(page); } Code Sample 2: private static ArrayList<String> BingSearch(String query) { ArrayList<String> bingSearchResults = new ArrayList<String>(); try { String request = "http://api.bing.net/xml.aspx?AppId=731DD1E61BE6DE4601A3008DC7A0EB379149EC29" + "&Version=2.2&Market=en-US&Query=" + URLEncoder.encode("Java example for " + query, "UTF-8") + "&Sources=web+spell&Web.Count=30"; URL url = new URL(request); System.out.println("Host : " + url.getHost()); url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; String finalContents = ""; while ((inputLine = reader.readLine()) != null) { finalContents += "\n" + inputLine; } Document doc = Jsoup.parse(finalContents); Elements eles = doc.getElementsByTag("web:Url"); for (Element ele : eles) { String urlText = ele.text(); if (!urlText.endsWith(".pdf") && !urlText.endsWith(".doc") && !urlText.endsWith(".ppt") && !urlText.endsWith(".PDF") && !urlText.endsWith(".DOC") && !urlText.endsWith(".PPT")) bingSearchResults.add(ele.text()); System.out.println("BingResult: " + ele.text()); } } catch (Exception e) { e.printStackTrace(); } return bingSearchResults; }
00
Code Sample 1: private void bokActionPerformed(java.awt.event.ActionEvent evt) { if (this.seriesstatementpanel.getEnteredvalues().get(0).toString().trim().equals("")) { this.showWarningMessage("Enter Series Title"); } else { String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds(); String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveSeriesName("2", seriesstatementpanel.getEnteredvalues(), patlib); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SeriesNameServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); if (rootelement.getChild("Error") == null) { this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase")); } else { this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor")); } } catch (Exception e) { System.out.println(e); } } } Code Sample 2: public void run() { String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_BACKUP; URL url; InputStream stream = null; try { url = new URL(masterUrl); stream = url.openStream(); stream.close(); } catch (Exception e) { fail = e.getMessage(); } finally { IOUtils.closeQuietly(stream); } }
00
Code Sample 1: private void streamBinaryData(String urlstr, String format, ServletOutputStream outstr, HttpServletResponse resp) { String ErrorStr = null; try { resp.setContentType(getMimeType(format)); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { URL url = new URL(urlstr); URLConnection urlc = url.openConnection(); int length = urlc.getContentLength(); resp.setContentLength(length); InputStream in = urlc.getInputStream(); bis = new BufferedInputStream(in); bos = new BufferedOutputStream(outstr); byte[] buff = new byte[length]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { e.printStackTrace(); ErrorStr = "Error Streaming the Data"; outstr.print(ErrorStr); } finally { if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } if (outstr != null) { outstr.flush(); outstr.close(); } } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static String md5hash(String text) { java.security.MessageDigest md; try { md = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } md.update(text.getBytes()); byte[] md5bytes = md.digest(); return new String(org.apache.commons.codec.binary.Hex.encodeHex(md5bytes)); }
00
Code Sample 1: void bsort(int a[], int lo, int hi) throws Exception { for (int j = hi; j > lo; j--) { for (int i = lo; i < j; i++) { if (a[i] > a[i + 1]) { int T = a[i]; a[i] = a[i + 1]; a[i + 1] = T; pause(); } } } } Code Sample 2: @Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ASiCUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ASiCUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
00
Code Sample 1: public MapInfo getMap(double latitude, double longitude, double wanted_mapblast_scale, int image_width, int image_height, String file_path_wo_extension, ProgressListener progress_listener) throws IOException { try { double mapserver_scale = getDownloadScale(wanted_mapblast_scale); URL url = new URL(getUrl(latitude, longitude, mapserver_scale, image_width, image_height)); if (Debug.DEBUG) Debug.println("map_download", "loading map from url: " + url); URLConnection connection = url.openConnection(); if (resources_.getBoolean(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_USE)) { String proxy_userid = resources_.getString(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_USERNAME); String proxy_password = resources_.getString(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_PASSWORD); String auth_string = proxy_userid + ":" + proxy_password; auth_string = "Basic " + new sun.misc.BASE64Encoder().encode(auth_string.getBytes()); connection.setRequestProperty("Proxy-Authorization", auth_string); } connection = setRequestProperties(connection); connection.connect(); String mime_type = connection.getContentType().toLowerCase(); if (!mime_type.startsWith("image")) { if (mime_type.startsWith("text")) { HTMLViewerFrame viewer = new HTMLViewerFrame(url); viewer.setSize(640, 480); viewer.setTitle("ERROR on loading url: " + url); viewer.setVisible(true); throw new IOException("Invalid mime type (expected 'image/*'): received " + mime_type + "\nPage is displayed in HTML frame."); } throw new IOException("Invalid mime type (expected 'image/*'): received " + mime_type); } int content_length = connection.getContentLength(); if (content_length < 0) progress_listener.actionStart(PROGRESS_LISTENER_ID, 0, Integer.MIN_VALUE); else progress_listener.actionStart(PROGRESS_LISTENER_ID, 0, content_length); String extension = mime_type.substring(mime_type.indexOf('/') + 1); String filename = file_path_wo_extension + extension; MapInfo map_info = new MapInfo(); map_info.setLatitude(latitude); map_info.setLongitude(longitude); map_info.setScale((float) getCorrectedMapblastScale(wanted_mapblast_scale)); map_info.setWidth(image_width); map_info.setHeight(image_height); map_info.setFilename(filename); FileOutputStream out = new FileOutputStream(filename); byte[] buffer = new byte[BUFFER_SIZE]; BufferedInputStream in = new BufferedInputStream(connection.getInputStream(), BUFFER_SIZE); int sum_bytes = 0; int num_bytes = 0; while ((num_bytes = in.read(buffer)) != -1) { out.write(buffer, 0, num_bytes); sum_bytes += num_bytes; progress_listener.actionProgress(PROGRESS_LISTENER_ID, sum_bytes); } progress_listener.actionEnd(PROGRESS_LISTENER_ID); in.close(); out.close(); return (map_info); } catch (NoRouteToHostException nrhe) { nrhe.printStackTrace(); progress_listener.actionEnd(PROGRESS_LISTENER_ID); String message = nrhe.getMessage() + ":\n" + resources_.getString(DownloadMouseModeLayer.KEY_LOCALIZE_MESSAGE_DOWNLOAD_ERROR_NO_ROUTE_TO_HOST_MESSAGE); throw new IOException(message); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); progress_listener.actionEnd(PROGRESS_LISTENER_ID); String message = fnfe.getMessage() + ":\n" + resources_.getString(DownloadMouseModeLayer.KEY_LOCALIZE_MESSAGE_DOWNLOAD_ERROR_FILE_NOT_FOUND_MESSAGE); throw new IOException(message); } catch (Exception e) { progress_listener.actionEnd(PROGRESS_LISTENER_ID); e.printStackTrace(); String message = e.getMessage(); if (message == null) { Throwable cause = e.getCause(); if (cause != null) message = cause.getMessage(); } throw new IOException(message); } } Code Sample 2: public static final String getContent(String address) { String content = ""; OutputStream out = null; URLConnection conn = null; InputStream in = null; try { URL url = new URL(address); out = new ByteArrayOutputStream(); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); } content = out.toString(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } } return content; }
00
Code Sample 1: public boolean exists(String filename) { String localFileName = (java.io.File.separatorChar != '/') ? filename.replace('/', java.io.File.separatorChar) : filename; for (int i = 0; i < dirs.length; i++) { if (zipEntries[i] != null) { if (zipEntries[i].get(filename) != null) return true; String dir = ""; String name = filename; int index = filename.lastIndexOf('/'); if (index >= 0) { dir = filename.substring(0, index); name = filename.substring(index + 1); } Vector directory = (Vector) zipEntries[i].get(dir); if (directory != null && directory.contains(name)) return true; continue; } if (bases[i] != null) { try { URL url = new URL(bases[i], filename); URLConnection conn = url.openConnection(); conn.connect(); conn.getInputStream().close(); return true; } catch (IOException ex) { } continue; } if (dirs[i] == null) continue; if (zips[i] != null) { String fullname = zipDirs[i] != null ? zipDirs[i] + filename : filename; ZipEntry ze = zips[i].getEntry(fullname); if (ze != null) return true; } else { try { File f = new File(dirs[i], localFileName); if (f.exists()) return true; } catch (SecurityException ex) { } } } return false; } Code Sample 2: private void copy(final File src, final File dstDir) { dstDir.mkdirs(); final File dst = new File(dstDir, src.getName()); BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(src), "ISO-8859-1")); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst), "ISO-8859-1")); String read; while ((read = reader.readLine()) != null) { Line line = new Line(read); if (line.isComment()) continue; writer.write(read); writer.newLine(); } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { } if (writer != null) { try { writer.flush(); } catch (IOException e) { } try { writer.close(); } catch (IOException e) { } } } }
11
Code Sample 1: public static void copyFile(File sourceFile, File targetFile) throws FileCopyingException { try { FileInputStream inputStream = new FileInputStream(sourceFile); FileOutputStream outputStream = new FileOutputStream(targetFile); FileChannel readableChannel = inputStream.getChannel(); FileChannel writableChannel = outputStream.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); inputStream.close(); outputStream.close(); } catch (IOException ioException) { String exceptionMessage = "An error occurred when copying from the file \"" + sourceFile.getAbsolutePath() + "\" to the file \"" + targetFile.getAbsolutePath() + "\"."; throw new FileCopyingException(exceptionMessage, ioException); } } Code Sample 2: public 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) { } } } }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public ServiceInfo[] findServices(String name) { Vector results = new Vector(); String service_file = ServiceDiscovery.SERVICE_HOME + name; for (int loader_count = 0; loader_count < class_loaders_.size(); loader_count++) { ClassLoader loader = (ClassLoader) class_loaders_.elementAt(loader_count); Enumeration enumeration = null; try { enumeration = loader.getResources(service_file); } catch (IOException ex) { ex.printStackTrace(); } if (enumeration == null) continue; while (enumeration.hasMoreElements()) { try { URL url = (URL) enumeration.nextElement(); InputStream is = url.openStream(); if (is != null) { try { BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(is, "UTF-8")); } catch (java.io.UnsupportedEncodingException e) { rd = new BufferedReader(new InputStreamReader(is)); } try { String service_class_name; while ((service_class_name = rd.readLine()) != null) { service_class_name.trim(); if ("".equals(service_class_name)) continue; if (service_class_name.startsWith("#")) continue; ServiceInfo sinfo = new ServiceInfo(); sinfo.setClassName(service_class_name); sinfo.setLoader(loader); sinfo.setURL(url); results.add(sinfo); } } finally { rd.close(); } } finally { is.close(); } } } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ioe) { ; } } } ServiceInfo result_array[] = new ServiceInfo[results.size()]; results.copyInto(result_array); return (result_array); }
11
Code Sample 1: private File Gzip(File f) throws IOException { if (f == null || !f.exists()) return null; File dest_dir = f.getParentFile(); String dest_filename = f.getName() + ".gz"; File zipfile = new File(dest_dir, dest_filename); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(zipfile)); FileInputStream in = new FileInputStream(f); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.finish(); try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } try { f.delete(); } catch (Exception e) { } return zipfile; } Code Sample 2: public void run() { try { File inf = new File(dest); if (!inf.exists()) { inf.getParentFile().mkdirs(); } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); out.transferFrom(in, 0, in.size()); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); System.err.println("Error copying file \n" + src + "\n" + dest); } }
00
Code Sample 1: public String elementsSearch() { int index = 0; for (int i1 = 0; i1 < 6; i1++) { for (int i2 = 0; i2 < 5; i2++) { if (index < 5) { if (initialMatrix[i1][i2] > 0) { finalMatrix[index] = initialMatrix[i1][i2]; index++; } } else break; } } int temp; for (int i = 0; i < finalMatrix.length; i++) { for (int j = 0; j < finalMatrix.length - 1; j++) { if (finalMatrix[j] < finalMatrix[j + 1]) { temp = finalMatrix[j]; finalMatrix[j] = finalMatrix[j + 1]; finalMatrix[j + 1] = temp; } } } String result = ""; for (int k : finalMatrix) result += k + " "; return result; } Code Sample 2: public static void concatFiles(List<File> sourceFiles, File destFile) throws IOException { FileOutputStream outFile = new FileOutputStream(destFile); FileChannel outChannel = outFile.getChannel(); for (File f : sourceFiles) { FileInputStream fis = new FileInputStream(f); FileChannel channel = fis.getChannel(); channel.transferTo(0, channel.size(), outChannel); channel.close(); fis.close(); } outChannel.close(); }
11
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public static String encrypt32(String plainText) { String str = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } str = buf.toString(); System.out.println("result: " + buf.toString()); System.out.println("result: " + buf.toString().substring(8, 24)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return str; } return str; }
11
Code Sample 1: public static void main(String[] args) throws Exception { PatternLayout pl = new PatternLayout("%d{ISO8601} %-5p %c: %m\n"); ConsoleAppender ca = new ConsoleAppender(pl); Logger.getRoot().addAppender(ca); Logger.getRoot().setLevel(Level.INFO); Options options = new Options(); options.addOption("p", "put", false, "put a file in the DHT overlay"); options.addOption("g", "get", false, "get a file from the DHT"); options.addOption("r", "remove", false, "remove a file from the DHT"); options.addOption("u", "update", false, "updates the lease"); options.addOption("j", "join", false, "join the DHT overlay"); options.addOption("c", "config", true, "the configuration file"); options.addOption("k", "key", true, "the key to read a file from"); options.addOption("f", "file", true, "the file to read or write"); options.addOption("a", "app", true, "the application ID"); options.addOption("s", "secret", true, "the secret used to hide data"); options.addOption("t", "ttl", true, "how long in seconds data should persist"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); String configFile = null; String mode = null; String secretStr = null; int ttl = 9999; String keyStr = null; String file = null; int appId = 0; if (cmd.hasOption("j")) { mode = "join"; } if (cmd.hasOption("p")) { mode = "put"; } if (cmd.hasOption("g")) { mode = "get"; } if (cmd.hasOption("r")) { mode = "remove"; } if (cmd.hasOption("u")) { mode = "update"; } if (cmd.hasOption("c")) { configFile = cmd.getOptionValue("c"); } if (cmd.hasOption("k")) { keyStr = cmd.getOptionValue("k"); } if (cmd.hasOption("f")) { file = cmd.getOptionValue("f"); } if (cmd.hasOption("s")) { secretStr = cmd.getOptionValue("s"); } if (cmd.hasOption("t")) { ttl = Integer.parseInt(cmd.getOptionValue("t")); } if (cmd.hasOption("a")) { appId = Integer.parseInt(cmd.getOptionValue("a")); } if (mode == null) { System.err.println("ERROR: --put or --get or --remove or --join or --update is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (configFile == null) { System.err.println("ERROR: --config is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } Properties conf = new Properties(); conf.load(new FileInputStream(configFile)); DHT dht = new DHT(conf); if (mode.equals("join")) { dht.join(); } else if (mode.equals("put")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("putting file " + file); FileInputStream in = new FileInputStream(file); byte[] tmp = new byte[1000000]; int num = in.read(tmp); byte[] value = new byte[num]; System.arraycopy(tmp, 0, value, 0, num); in.close(); if (dht.put((short) appId, keyStr.getBytes(), value, ttl, secretStr.getBytes()) < 0) { logger.info("There was an error while putting a key-value."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("get")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("getting file " + file); ArrayList<byte[]> values = new ArrayList<byte[]>(); if (dht.get((short) appId, keyStr.getBytes(), Integer.MAX_VALUE, values) < 0) { logger.info("There was an error while getting a value."); System.exit(0); } if (values.size() == 0 || values == null) { System.out.println("No values returned."); System.exit(0); } FileOutputStream out = new FileOutputStream(file); System.out.println("Found " + values.size() + " values -- saving the first one only."); out.write(values.get(0)); out.close(); System.out.println("Ok!"); } else if (mode.equals("remove")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("removing <key,value> for key=" + keyStr); if (dht.remove((short) appId, keyStr.getBytes(), secretStr.getBytes()) < 0) { logger.info("There was an error while removing a key."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("update")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("updating <key,value> for key=" + keyStr); if (dht.updateLease((short) appId, keyStr.getBytes(), ttl) < 0) { logger.info("There was an error while updating data lease."); System.exit(0); } System.out.println("Ok!"); } DHT.getInstance().stop(); } Code Sample 2: public void copyFile(File source, File destination) { try { FileInputStream sourceStream = new FileInputStream(source); try { FileOutputStream destinationStream = new FileOutputStream(destination); try { FileChannel sourceChannel = sourceStream.getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationStream.getChannel()); } finally { try { destinationStream.close(); } catch (Exception e) { throw new RuntimeIoException(e, IoMode.CLOSE); } } } finally { try { sourceStream.close(); } catch (Exception e) { throw new RuntimeIoException(e, IoMode.CLOSE); } } } catch (IOException e) { throw new RuntimeIoException(e, IoMode.COPY); } }
11
Code Sample 1: public static boolean copyFile(File source, File dest) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(source).getChannel(); dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (IOException e) { return false; } finally { try { if (srcChannel != null) { srcChannel.close(); } } catch (IOException e) { } try { if (dstChannel != null) { dstChannel.close(); } } catch (IOException e) { } } return true; } Code Sample 2: public static void concatFiles(List<File> sourceFiles, File destFile) throws IOException { FileOutputStream outFile = new FileOutputStream(destFile); FileChannel outChannel = outFile.getChannel(); for (File f : sourceFiles) { FileInputStream fis = new FileInputStream(f); FileChannel channel = fis.getChannel(); channel.transferTo(0, channel.size(), outChannel); channel.close(); fis.close(); } outChannel.close(); }
00
Code Sample 1: protected boolean registerFromFile(URI providerList) { boolean registeredSomething = false; InputStream urlStream = null; try { urlStream = providerList.toURL().openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlStream, "UTF-8")); String provider; while ((provider = reader.readLine()) != null) { int comment = provider.indexOf('#'); if (comment != -1) { provider = provider.substring(0, comment); } provider = provider.trim(); if (provider.length() > 0) { try { registeredSomething |= registerAssoc(provider); } catch (Exception allElse) { if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { LOG.log(Level.WARNING, "Failed to register \'" + provider + "\'", allElse); } } } } } catch (IOException ex) { LOG.log(Level.WARNING, "Failed to read provider list " + providerList, ex); return false; } finally { if (null != urlStream) { try { urlStream.close(); } catch (IOException ignored) { } } } return registeredSomething; } Code Sample 2: public void testReleaseOnEntityWriteTo() throws Exception { HttpParams params = defaultParams.copy(); ConnManagerParams.setMaxTotalConnections(params, 1); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1)); ThreadSafeClientConnManager mgr = createTSCCM(params, null); assertEquals(0, mgr.getConnectionsInPool()); DefaultHttpClient client = new DefaultHttpClient(mgr, params); HttpGet httpget = new HttpGet("/random/20000"); HttpHost target = getServerHttp(); HttpResponse response = client.execute(target, httpget); ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null); try { connreq.getConnection(250, TimeUnit.MILLISECONDS); fail("ConnectionPoolTimeoutException should have been thrown"); } catch (ConnectionPoolTimeoutException expected) { } HttpEntity e = response.getEntity(); assertNotNull(e); ByteArrayOutputStream outsteam = new ByteArrayOutputStream(); e.writeTo(outsteam); assertEquals(1, mgr.getConnectionsInPool()); connreq = mgr.requestConnection(new HttpRoute(target), null); ManagedClientConnection conn = connreq.getConnection(250, TimeUnit.MILLISECONDS); mgr.releaseConnection(conn, -1, null); mgr.shutdown(); }
00
Code Sample 1: public void openAndClose(ZKEntry zke, LinkedList toOpen, LinkedList toRemove) throws SQLException { conn.setAutoCommit(false); try { Statement stm = conn.createStatement(); ResultSet rset = stm.executeQuery("SELECT now();"); rset.next(); Timestamp now = rset.getTimestamp("now()"); for (int i = 0; i < toRemove.size(); i++) { Workitem wi = (Workitem) toRemove.get(i); rset = stm.executeQuery("SELECT intime, part FROM stampzk WHERE stampzkid = '" + wi.getStampZkId() + "';"); rset.next(); long diff = now.getTime() - rset.getLong("intime"); float diffp = diff * rset.getFloat("part"); stm.executeUpdate("UPDATE stampzk SET outtime='" + now.getTime() + "', diff='" + diff + "', diffp='" + diffp + "' WHERE stampzkid='" + wi.getStampZkId() + "';"); } rset = stm.executeQuery("SELECT COUNT(*) FROM stampzk WHERE personalid='" + zke.getWorker().getPersonalId() + "' AND outtime='0';"); rset.next(); int count = rset.getInt("COUNT(*)") + toOpen.size(); rset = stm.executeQuery("SELECT * FROM stampzk WHERE personalid='" + zke.getWorker().getPersonalId() + "' AND outtime='0';"); while (rset.next()) { long diff = now.getTime() - rset.getLong("intime"); float diffp = diff * rset.getFloat("part"); int firstId = rset.getInt("firstid"); if (firstId == 0) firstId = rset.getInt("stampzkid"); Statement ust = conn.createStatement(); ust.executeUpdate("UPDATE stampzk SET outtime='" + now.getTime() + "', diff='" + diff + "', diffp='" + diffp + "' WHERE stampzkid='" + rset.getInt("stampzkid") + "';"); ust.executeUpdate("INSERT INTO stampzk SET zeitkid='" + rset.getInt("zeitkid") + "', personalid='" + zke.getWorker().getPersonalId() + "', funcsid='" + rset.getInt("funcsid") + "', part='" + (float) 1f / count + "', intime='" + now.getTime() + "', firstid='" + firstId + "';"); } for (int i = 0; i < toOpen.size(); i++) { stm.executeUpdate("INSERT INTO stampzk SET zeitkid='" + zke.getZeitKId() + "', personalid='" + zke.getWorker().getPersonalId() + "', intime='" + now.getTime() + "', funcsid='" + ((Workitem) toOpen.get(i)).getWorkType() + "', part='" + (float) 1f / count + "';"); } } catch (SQLException sqle) { conn.rollback(); conn.setAutoCommit(true); throw sqle; } conn.commit(); conn.setAutoCommit(true); } Code Sample 2: public Void doInBackground() { Transferable clipData = clipboard.getContents(this); File file = new File("Videos/" + (mp3.getArtist() + " - " + mp3.getTitle() + ".jpg").replace("/", "").replace("\\", "")); try { String test = (String) (clipData.getTransferData(DataFlavor.stringFlavor)); String testje = test.toLowerCase(); if (testje.indexOf(".flv") > 0 || testje.indexOf(".wmv") > 0 || testje.indexOf(".mpg") > 0 || testje.indexOf(".mpeg") > 0 || testje.indexOf(".avi") > 0 || testje.indexOf(".avi") > 0 || testje.indexOf(".divx") > 0 || testje.indexOf(".avi") > 0) { URL url = new URL(test); (new File("Videos/")).mkdirs(); System.out.println("Saving video to " + file); try { URLConnection urlC = url.openConnection(); InputStream is = url.openStream(); System.out.flush(); FileOutputStream fos = null; fos = new FileOutputStream(file); byte[] buf = new byte[32768]; int len; while ((len = is.read(buf)) > 0) { fos.write(buf, 0, len); } is.close(); fos.close(); } catch (Exception e) { System.out.println("Error saving video from url: " + url); mp3.setVideo(file.getAbsolutePath()); } } } catch (Exception ex) { System.out.println("not a valid video file"); ex.printStackTrace(); } return null; }
00
Code Sample 1: public EFaxResult sendFax(ototype.SendFaxWrapper parameters) { EFaxResult efr = new EFaxResult(); if (!validFaxUser(parameters.getUserID(), parameters.getPassWord())) { efr.setResultCode(211); return efr; } Connection conn = null; String faxKey = getSegquence("t_fax_send") + ""; String sql = "insert into t_fax_send(faxKey,userID,appcode,sendername," + "sendernumber,sendercompany,sendtime,accountId, userId2, PID, moduleId, CDRType) values(?,?,?,?,?,?,?,?,?,?,?,?)"; Fax fax = parameters.getFax(); FaxContactor sender = fax.getSender(); FaxContactor[] receiver = fax.getReceiver(); try { conn = this.getJdbcTemplate().getDataSource().getConnection(); conn.setAutoCommit(false); PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, faxKey); pstmt.setString(2, parameters.getUserID()); pstmt.setString(3, parameters.getAppCode()); pstmt.setString(4, sender.getContactor()); pstmt.setString(5, sender.getFaxNumber()); pstmt.setString(6, sender.getCompany()); pstmt.setString(7, fax.getSendTime()); pstmt.setString(8, parameters.getAccountId()); pstmt.setString(9, parameters.getUserId()); pstmt.setString(10, parameters.getPID()); pstmt.setInt(11, parameters.getModuleId()); pstmt.setInt(12, parameters.getCDRType()); pstmt.executeUpdate(); sql = "insert into t_fax_contactor(faxKey,contactorID,contactor,faxnumber,company) values(?,?,?,?,?)"; pstmt = conn.prepareStatement(sql); for (int k = 0; k < receiver.length; k++) { pstmt.setString(1, faxKey); pstmt.setString(2, receiver[k].getContactorID()); pstmt.setString(3, receiver[k].getContactor()); pstmt.setString(4, receiver[k].getFaxNumber()); pstmt.setString(5, receiver[k].getCompany()); pstmt.addBatch(); } pstmt.executeBatch(); sql = "insert into t_fax_file(faxKey,fileID,filename,filetype,fileurl,faxpages) values(?,?,?,?,?,?)"; pstmt = conn.prepareStatement(sql); FaxFile[] files = fax.getFiles(); for (int h = 0; h < files.length; h++) { String fileID = getSegquence("t_Fax_file") + ""; pstmt.setString(1, faxKey); pstmt.setString(2, fileID); pstmt.setString(3, files[h].getFileName()); pstmt.setString(4, files[h].getFileType()); pstmt.setString(5, files[h].getFileURL()); pstmt.setInt(6, files[h].getFaxPages()); Service.writeByteFile(files[h].getFile(), fileID); pstmt.addBatch(); } pstmt.executeBatch(); conn.commit(); efr.setResultCode(100); efr.setResultInfo(faxKey); } catch (SQLException e) { efr.setResultCode(200); try { conn.rollback(); } catch (Exception e1) { logger.error("Error validFaxUser", e1); } logger.error("Error validFaxUser", e); } catch (IOException e) { efr.setResultCode(200); logger.error("Error write file on sendfax", e); } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { logger.error("Error sendFax on close conn", e); } } } return efr; } Code Sample 2: public static void copyFile(File source, String target) throws FileNotFoundException, IOException { File fout = new File(target); fout.mkdirs(); fout.delete(); fout = new File(target); FileChannel in = new FileInputStream(source).getChannel(); FileChannel out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); }
00
Code Sample 1: public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { Git git = Git.getCurrent(req.getSession()); GitComponentReader gitReader = git.getComponentReader("warpinjector"); String id = req.getParameter("id"); GitElement element = gitReader.getElement(id); String path = (String) element.getAttribute("targetdir"); File folder = new File(path); PrintWriter out = helper.getPrintWriter(resp); MessageBundle messageBundle = new MessageBundle("net.sf.warpcore.cms/servlets/InjectorServletMessages"); Locale locale = req.getLocale(); helper.header(out, messageBundle, locale); if (git.getUser() == null) { helper.notLoggedIn(out, messageBundle, locale); } else { try { MultiPartRequest request = new MultiPartRequest(req); FileInfo info = request.getFileInfo("userfile"); File file = info.getFile(); out.println("tempfile found: " + file.getPath() + "<br>"); String fileName = info.getFileName(); File target = new File(folder, fileName); out.println("copying tempfile to: " + target.getPath() + "<br>"); FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(target); byte buf[] = new byte[1024]; int n; while ((n = fis.read(buf)) > 0) fos.write(buf, 0, n); fis.close(); fos.close(); out.println("copy successful - deleting old tempfile<br>"); out.println("deletion result. " + file.delete() + "<p>"); out.println(messageBundle.getMessage("Done. The file {0} has been uploaded", new String[] { "'" + fileName + "'" }, locale)); out.println("<p><a href=\"" + req.getRequestURI() + "?id=" + req.getParameter("id") + "\">" + messageBundle.getMessage("Click here to import another file.", locale) + "</a>"); } catch (Exception ex) { out.println(messageBundle.getMessage("An error occured: {0}", new String[] { ex.getMessage() }, locale)); } } helper.footer(out); } Code Sample 2: @Test public void test20_badSmtp() throws Exception { Db db = DbConnection.defaultCieDbRW(); try { db.begin(); oldSmtp = Config.getProperty(db, "com.entelience.mail.MailHelper.hostName", "localhost"); oldSupport = Config.getProperty(db, "com.entelience.esis.feature.SupportNotifier", false); Config.setProperty(db, "com.entelience.mail.MailHelper.hostName", "127.0.10.1", 1); Config.setProperty(db, "com.entelience.esis.feature.SupportNotifier", "true", 1); PreparedStatement pst = db.prepareStatement("DELETE FROM t_client_errors"); db.executeUpdate(pst); db.commit(); } catch (Exception e) { db.rollback(); } finally { db.safeClose(); } }
00
Code Sample 1: protected Document fetchResource(String method, String parameter, Locale locale, final FloodLimit limit) throws IOException, SAXException { return getDocument(new CachedPage(getResourceLocation(method, parameter, locale)) { @Override protected Reader openConnection(URL url) throws IOException { try { if (limit != null) { limit.acquirePermit(); } return super.openConnection(url); } catch (InterruptedException e) { throw new IOException(e); } } ; }.get()); } Code Sample 2: private void scanURL(String packagePath, Collection<String> componentClassNames, URL url) throws IOException { URLConnection connection = url.openConnection(); JarFile jarFile; if (connection instanceof JarURLConnection) { jarFile = ((JarURLConnection) connection).getJarFile(); } else { jarFile = getAlternativeJarFile(url); } if (jarFile != null) { scanJarFile(packagePath, componentClassNames, jarFile); } else if (supportsDirStream(url)) { Stack<Queued> queue = new Stack<Queued>(); queue.push(new Queued(url, packagePath)); while (!queue.isEmpty()) { Queued queued = queue.pop(); scanDirStream(queued.packagePath, queued.packageURL, componentClassNames, queue); } } else { String packageName = packagePath.replace("/", "."); if (packageName.endsWith(".")) { packageName = packageName.substring(0, packageName.length() - 1); } scanDir(packageName, new File(url.getFile()), componentClassNames); } }
11
Code Sample 1: public static String digest(String str) { StringBuffer sb = new StringBuffer(); try { MessageDigest md5 = MessageDigest.getInstance("md5"); md5.update(str.getBytes("ISO8859-1")); byte[] array = md5.digest(); for (int x = 0; x < 16; x++) { if ((array[x] & 0xff) < 0x10) sb.append("0"); sb.append(Long.toString(array[x] & 0xff, 16)); } } catch (Exception e) { System.out.println(e); } return sb.toString(); } Code Sample 2: @Override public String getMD5(String host) { String res = ""; Double randNumber = Math.random() + System.currentTimeMillis(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(randNumber.toString().getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (Exception ex) { } return res; }
00
Code Sample 1: public APIResponse update(Transaction transaction) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/transaction/update").openConnection(); connection.setDoOutput(true); connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setUseCaches(false); connection.setConnectTimeout(TIMEOUT); connection.connect(); marshaller.marshal(transaction, new MappedXMLStreamWriter(new MappedNamespaceConvention(new Configuration()), new OutputStreamWriter(connection.getOutputStream(), "utf-8"))); connection.getOutputStream().flush(); connection.getOutputStream().close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { JSONObject obj = new JSONObject(new String(new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")).readLine())); response.setDone(true); response.setMessage(unmarshaller.unmarshal(new MappedXMLStreamReader(obj, new MappedNamespaceConvention(new Configuration())))); connection.getInputStream().close(); } else { response.setDone(false); response.setMessage("Update Transaction Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; } Code Sample 2: public void run() { try { File inf = new File(dest); if (!inf.exists()) { inf.getParentFile().mkdirs(); } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); out.transferFrom(in, 0, in.size()); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); System.err.println("Error copying file \n" + src + "\n" + dest); } }
11
Code Sample 1: private static String getDigest(String srcStr, String alg) { Assert.notNull(srcStr); Assert.notNull(alg); try { MessageDigest alga = MessageDigest.getInstance(alg); alga.update(srcStr.getBytes()); byte[] digesta = alga.digest(); return byte2hex(digesta); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
11
Code Sample 1: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } Code Sample 2: public static void copyFile(File sourceFile, File destinationFile) throws IOException { if (!destinationFile.exists()) { destinationFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
11
Code Sample 1: public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String act = request.getParameter("act"); if (null == act) { } else if ("down".equalsIgnoreCase(act)) { String vest = request.getParameter("vest"); String id = request.getParameter("id"); if (null == vest) { t_attach_Form attach = null; t_attach_QueryMap query = new t_attach_QueryMap(); attach = query.getByID(id); if (null != attach) { String filename = attach.getAttach_name(); String fullname = attach.getAttach_fullname(); response.addHeader("Content-Disposition", "attachment;filename=" + filename + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); } } } else if ("review".equalsIgnoreCase(vest)) { t_infor_review_QueryMap reviewQuery = new t_infor_review_QueryMap(); t_infor_review_Form review = reviewQuery.getByID(id); String seq = request.getParameter("seq"); String name = null, fullname = null; if ("1".equals(seq)) { name = review.getAttachname1(); fullname = review.getAttachfullname1(); } else if ("2".equals(seq)) { name = review.getAttachname2(); fullname = review.getAttachfullname2(); } else if ("3".equals(seq)) { name = review.getAttachname3(); fullname = review.getAttachfullname3(); } String downTypeStr = DownType.getInst().getDownTypeByFileName(name); logger.debug("filename=" + name + " downtype=" + downTypeStr); response.setContentType(downTypeStr); response.addHeader("Content-Disposition", "attachment;filename=" + name + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); in.close(); } } } else if ("upload".equalsIgnoreCase(act)) { String infoId = request.getParameter("inforId"); logger.debug("infoId=" + infoId); } } catch (Exception e) { } } Code Sample 2: 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 src, File dest) throws IOException { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; fIn = new FileInputStream(src); fOut = new FileOutputStream(dest); fIChan = fIn.getChannel(); fOChan = fOut.getChannel(); fSize = fIChan.size(); mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); fOChan.write(mBuf); fIChan.close(); fIn.close(); fOChan.close(); fOut.close(); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static String getSHA1Hash(String plainText) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(plainText.getBytes()); byte[] mdbytes = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < mdbytes.length; i++) { String hex = Integer.toHexString(0xFF & mdbytes[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString().toUpperCase(); } Code Sample 2: public static synchronized String encrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); return new Base64(-1).encodeToString(raw); }
11
Code Sample 1: public boolean copyFile(File source, File dest) { try { FileReader in = new FileReader(source); FileWriter out = new FileWriter(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return true; } catch (Exception e) { return false; } } Code Sample 2: public void compressFile(String filePath) { String outPut = filePath + ".zip"; try { FileInputStream in = new FileInputStream(filePath); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outPut)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); } catch (Exception c) { c.printStackTrace(); } }
11
Code Sample 1: public void end() throws Exception { handle.waitFor(); Calendar endTime = Calendar.getInstance(); File resultsDir = new File(runDir, "results"); if (!resultsDir.isDirectory()) throw new Exception("The results directory not found!"); String resHtml = null; String resTxt = null; String[] resultFiles = resultsDir.list(); for (String resultFile : resultFiles) { if (resultFile.indexOf("html") >= 0) resHtml = resultFile; else if (resultFile.indexOf("txt") >= 0) resTxt = resultFile; } if (resHtml == null) throw new IOException("SPECweb2005 output (html) file not found"); if (resTxt == null) throw new IOException("SPECweb2005 output (txt) file not found"); File resultHtml = new File(resultsDir, resHtml); copyFile(resultHtml.getAbsolutePath(), runDir + "SPECWeb-result.html", false); BufferedReader reader = new BufferedReader(new FileReader(new File(resultsDir, resTxt))); logger.fine("Text file: " + resultsDir + resTxt); Writer writer = new FileWriter(runDir + "summary.xml"); SummaryParser parser = new SummaryParser(getRunId(), startTime, endTime, logger); parser.convert(reader, writer); writer.close(); reader.close(); } Code Sample 2: public static void moveOutputAsmFile(File inputLocation, File outputLocation) throws Exception { FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(inputLocation); outputStream = new FileOutputStream(outputLocation); byte buffer[] = new byte[1024]; while (inputStream.available() > 0) { int read = inputStream.read(buffer); outputStream.write(buffer, 0, read); } inputLocation.delete(); } finally { IOUtil.closeAndIgnoreErrors(inputStream); IOUtil.closeAndIgnoreErrors(outputStream); } }
11
Code Sample 1: public static void copyFile(File in, File out, boolean append) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out, append).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: private void initLogging() { File logging = new File(App.getHome(), "logging.properties"); if (!logging.exists()) { InputStream input = getClass().getResourceAsStream("logging.properties-setup"); OutputStream output = null; try { output = new FileOutputStream(logging); IOUtils.copy(input, output); } catch (Exception ex) { } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } FileInputStream input = null; try { input = new FileInputStream(logging); LogManager.getLogManager().readConfiguration(input); } catch (Exception ex) { } finally { IOUtils.closeQuietly(input); } }
00
Code Sample 1: public URL rawGetURLfromWebID(String id) { try { System.out.println("Resolving id" + id); String resolve = "/webid/ResolverServlet?wpid=MeetingMachine&method=form&uri=" + id + "&href=_[text/url]"; String resolver = "http://webid.hpl.hp.com:5190"; URL url = new URL(resolve + resolver); URLConnection c = url.openConnection(); c.setDoOutput(true); c.setDoInput(true); c.setUseCaches(false); } catch (Exception e) { if (PropertyEventHeap.debug) { PropertyEventHeap.log("rawGetURLfromWebID " + e); } } return null; } Code Sample 2: public void run() { if (currentNode == null || currentNode.equals("")) { JOptionPane.showMessageDialog(null, "Please select a genome to download first", "Error", JOptionPane.ERROR_MESSAGE); return; } String localFile = parameter.getTemporaryFilesPath() + currentNode; String remotePath = NCBI_FTP_PATH + currentPath; String remoteFile = remotePath + "/" + currentNode; try { ftp.connect(NCBI_FTP_HOST); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); JOptionPane.showMessageDialog(null, "FTP server refused connection", "Error", JOptionPane.ERROR_MESSAGE); } ftp.login("anonymous", "anonymous@big.ac.cn"); inProgress = true; ftp.setFileType(FTPClient.BINARY_FILE_TYPE); long size = getFileSize(remotePath, currentNode); if (size == -1) throw new FileNotFoundException(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(localFile)); BufferedInputStream in = new BufferedInputStream(ftp.retrieveFileStream(remoteFile), ftp.getBufferSize()); byte[] b = new byte[1024]; long bytesTransferred = 0; int tick = 0; int oldTick = 0; int len; while ((len = in.read(b)) != -1) { out.write(b, 0, len); bytesTransferred += 1024; if ((tick = new Long(bytesTransferred * 100 / size).intValue()) > oldTick) { progressBar.setValue(tick < 100 ? tick : 99); oldTick = tick; } } in.close(); out.close(); ftp.completePendingCommand(); progressBar.setValue(100); fileDownloaded = localFile; JOptionPane.showMessageDialog(null, "File successfully downloaded", "Congratulation!", JOptionPane.INFORMATION_MESSAGE); ftp.logout(); } catch (SocketException ex) { JOptionPane.showMessageDialog(null, "Error occurs while trying to connect server", "Error", JOptionPane.ERROR_MESSAGE); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, "This file is not found on the server", "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Error occurs while fetching data", "Error", JOptionPane.ERROR_MESSAGE); } finally { inProgress = false; if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } }
00
Code Sample 1: public Result search(Object object) { if (object == null || !(object instanceof String)) { return null; } String query = (String) object; Result hitResult = new Result(); Set<Hit> hits = new HashSet<Hit>(8); try { query = URLEncoder.encode(query, "UTF-8"); URL url = new URL("http://ajax.googleapis.com/ajax/services/search/web?start=0&rsz=large&v=1.0&q=" + query); URLConnection connection = url.openConnection(); connection.addRequestProperty("Referer", HTTP_REFERER); String line; StringBuilder builder = new StringBuilder(); InputStream input = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); while ((line = reader.readLine()) != null) { builder.append(line); } input.close(); String response = builder.toString(); JSONObject json = new JSONObject(response); LOGGER.debug(json.getString("responseData")); int count = json.getJSONObject("responseData").getJSONObject("cursor").getInt("estimatedResultCount"); hitResult.setEstimatedCount(count); JSONArray ja = json.getJSONObject("responseData").getJSONArray("results"); for (int i = 0; i < ja.length(); i++) { JSONObject j = ja.getJSONObject(i); Hit hit = new Hit(); String result = j.getString("titleNoFormatting"); hit.setTitle(result == null || result.equals("") ? "${EMPTY}" : result); result = j.getString("url"); hit.setUrl(new URL(result)); hits.add(hit); } } catch (Exception e) { e.printStackTrace(); LOGGER.error("Something went wrong..." + e.getMessage()); } hitResult.setHits(hits); return hitResult; } Code Sample 2: public RTUser getUserInfo(final String username) { getSession(); Map<String, String> attributes = Collections.emptyMap(); final HttpGet get = new HttpGet(m_baseURL + "/REST/1.0/user/" + username); try { final HttpResponse response = getClient().execute(get); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != HttpStatus.SC_OK) { throw new RequestTrackerException("Received a non-200 response code from the server: " + responseCode); } else { if (response.getEntity() != null) { attributes = parseResponseStream(response.getEntity().getContent()); } } } catch (final Exception e) { LogUtils.errorf(this, e, "An exception occurred while getting user info for " + username); return null; } final String id = attributes.get("id"); final String realname = attributes.get("realname"); final String email = attributes.get("emailaddress"); if (id == null || "".equals(id)) { LogUtils.errorf(this, "Unable to retrieve ID from user info."); return null; } return new RTUser(Long.parseLong(id.replace("user/", "")), username, realname, email); }
11
Code Sample 1: private static String md5(String pwd) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(pwd.getBytes(), 0, pwd.length()); return new BigInteger(1, md5.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new Error(); } } Code Sample 2: private static String doHash(String frase, String algorithm) { try { String ret; MessageDigest md = MessageDigest.getInstance(algorithm); md.update(frase.getBytes()); BigInteger bigInt = new BigInteger(1, md.digest()); ret = bigInt.toString(16); return ret; } catch (NoSuchAlgorithmException e) { return null; } }
00
Code Sample 1: public boolean actualizarIdPartida(int idJugadorDiv, int idRonda, int idPartida) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPartida = " + idPartida + " WHERE jugadorxDivision_idJugadorxDivision = " + idJugadorDiv + " AND ronda_numeroRonda = " + idRonda; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); intResult = 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 (intResult > 0); } Code Sample 2: public static synchronized String getMD5_Base64(final String input) { if (isInited == false) { isInited = true; try { digest = MessageDigest.getInstance("MD5"); } catch (Exception ex) { logger.error("Cannot get MessageDigest. Application may fail to run correctly.", ex); } } if (digest == null) { return input; } try { digest.update(input.getBytes("UTF-8")); } catch (java.io.UnsupportedEncodingException ex) { logger.error("Assertion: This should never occur."); } byte[] rawData = digest.digest(); byte[] encoded = Base64.encode(rawData); String retValue = new String(encoded); return retValue; }
00
Code Sample 1: public static final String getUniqueKey() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; ; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { println("Warn: getUniqueKey(), Error trying to get localhost" + e.getMessage()); } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { println("Warn: getUniqueKey() " + e); } return digest; } Code Sample 2: public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { System.out.println("复制文件失败,源文件" + srcFileName + "不存在!"); return false; } else if (!srcFile.isFile()) { System.out.println("复制文件失败," + srcFileName + "不是一个文件!"); return false; } File descFile = new File(descFileName); if (descFile.exists()) { if (coverlay) { System.out.println("目标文件已存在,准备删除!"); if (!FileOperateUtils.delFile(descFileName)) { System.out.println("删除目标文件" + descFileName + "失败!"); return false; } } else { System.out.println("复制文件失败,目标文件" + descFileName + "已存在!"); return false; } } else { if (!descFile.getParentFile().exists()) { System.out.println("目标文件所在的目录不存在,创建目录!"); if (!descFile.getParentFile().mkdirs()) { System.out.println("创建目标文件所在的目录失败!"); return false; } } } int readByte = 0; InputStream ins = null; OutputStream outs = null; try { ins = new FileInputStream(srcFile); outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; while ((readByte = ins.read(buf)) != -1) { outs.write(buf, 0, readByte); } System.out.println("复制单个文件" + srcFileName + "到" + descFileName + "成功!"); return true; } catch (Exception e) { System.out.println("复制文件失败:" + e.getMessage()); return false; } finally { if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public static void readShaderSource(ClassLoader context, String path, URL url, StringBuffer result) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = reader.readLine()) != null) { if (line.startsWith("#include ")) { String includeFile = line.substring(9).trim(); String next = Locator.getRelativeOf(path, includeFile); URL nextURL = Locator.getResource(next, context); if (nextURL == null) { next = includeFile; nextURL = Locator.getResource(next, context); } if (nextURL == null) { throw new FileNotFoundException("Can't find include file " + includeFile); } readShaderSource(context, next, nextURL, result); } else { result.append(line + "\n"); } } } catch (IOException e) { throw new RuntimeException(e); } }
11
Code Sample 1: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.close(output); } } finally { IOUtils.close(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } Code Sample 2: public static String getEncryptedPassword(String password) throws PasswordException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); } catch (Exception e) { throw new PasswordException(e); } return convertToString(md.digest()); }
11
Code Sample 1: public static boolean copyFile(File from, File tu) { final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(tu); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { return false; } return true; } Code Sample 2: private void unzipResource(final String resourceName, final File targetDirectory) throws IOException { final URL resource = this.getClass().getResource(resourceName); assertNotNull("Expected '" + resourceName + "' not found.", resource); assertTrue(targetDirectory.isAbsolute()); FileUtils.deleteDirectory(targetDirectory); assertTrue(targetDirectory.mkdirs()); ZipInputStream in = null; boolean suppressExceptionOnClose = true; try { in = new ZipInputStream(resource.openStream()); ZipEntry e; while ((e = in.getNextEntry()) != null) { if (e.isDirectory()) { continue; } final File dest = new File(targetDirectory, e.getName()); assertTrue(dest.isAbsolute()); OutputStream out = null; try { out = FileUtils.openOutputStream(dest); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } suppressExceptionOnClose = true; } catch (final IOException ex) { if (!suppressExceptionOnClose) { throw ex; } } } in.closeEntry(); } suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } }
00
Code Sample 1: public static boolean copyFile(File from, File tu) { final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(tu); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { return false; } return true; } 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: public String hmacSHA256(String message, byte[] key) { MessageDigest sha256 = null; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new java.lang.AssertionError(this.getClass().getName() + ".hmacSHA256(): SHA-256 algorithm not found!"); } if (key.length > 64) { sha256.update(key); key = sha256.digest(); sha256.reset(); } byte block[] = new byte[64]; for (int i = 0; i < key.length; ++i) block[i] = key[i]; for (int i = key.length; i < block.length; ++i) block[i] = 0; for (int i = 0; i < 64; ++i) block[i] ^= 0x36; sha256.update(block); try { sha256.update(message.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new java.lang.AssertionError("ITunesU.hmacSH256(): UTF-8 encoding not supported!"); } byte[] hash = sha256.digest(); sha256.reset(); for (int i = 0; i < 64; ++i) block[i] ^= (0x36 ^ 0x5c); sha256.update(block); sha256.update(hash); hash = sha256.digest(); char[] hexadecimals = new char[hash.length * 2]; for (int i = 0; i < hash.length; ++i) { for (int j = 0; j < 2; ++j) { int value = (hash[i] >> (4 - 4 * j)) & 0xf; char base = (value < 10) ? ('0') : ('a' - 10); hexadecimals[i * 2 + j] = (char) (base + value); } } return new String(hexadecimals); } Code Sample 2: public String preProcessHTML(String uri) { final StringBuffer buf = new StringBuffer(); try { HTMLDocument doc = new HTMLDocument() { public HTMLEditorKit.ParserCallback getReader(int pos) { return new HTMLEditorKit.ParserCallback() { public void handleText(char[] data, int pos) { buf.append(data); buf.append('\n'); } }; } }; URL url = new URI(uri).toURL(); URLConnection conn = url.openConnection(); Reader rd = new InputStreamReader(conn.getInputStream()); new ParserDelegator().parse(rd, doc.getReader(0), Boolean.TRUE); } catch (MalformedURLException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (URISyntaxException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } return buf.toString(); }
00
Code Sample 1: public void saveSharedFiles(List<FrostSharedFileItem> sfFiles) throws SQLException { Connection conn = AppLayerDatabase.getInstance().getPooledConnection(); try { conn.setAutoCommit(false); Statement s = conn.createStatement(); s.executeUpdate("DELETE FROM SHAREDFILES"); s.close(); s = null; PreparedStatement ps = conn.prepareStatement("INSERT INTO SHAREDFILES (" + "path,size,fnkey,sha,owner,comment,rating,keywords," + "lastuploaded,uploadcount,reflastsent,requestlastreceived,requestsreceivedcount,lastmodified) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); for (Iterator<FrostSharedFileItem> i = sfFiles.iterator(); i.hasNext(); ) { FrostSharedFileItem sfItem = i.next(); int ix = 1; ps.setString(ix++, sfItem.getFile().getPath()); ps.setLong(ix++, sfItem.getFileSize()); ps.setString(ix++, sfItem.getChkKey()); ps.setString(ix++, sfItem.getSha()); ps.setString(ix++, sfItem.getOwner()); ps.setString(ix++, sfItem.getComment()); ps.setInt(ix++, sfItem.getRating()); ps.setString(ix++, sfItem.getKeywords()); ps.setLong(ix++, sfItem.getLastUploaded()); ps.setInt(ix++, sfItem.getUploadCount()); ps.setLong(ix++, sfItem.getRefLastSent()); ps.setLong(ix++, sfItem.getRequestLastReceived()); ps.setInt(ix++, sfItem.getRequestsReceived()); ps.setLong(ix++, sfItem.getLastModified()); 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 static Vector getVectorForm(String u, String usr, String pwd) { Vector response = new Vector(); 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())); String str; while ((str = in.readLine()) != null) { response.add(str); } in.close(); logger.debug("Response: " + response.toString()); } catch (MalformedURLException e) { logger.error(e); logger.trace(e, e); } catch (IOException e) { logger.error(e); logger.trace(e, e); } return response; }
11
Code Sample 1: private void addIngredients(Recipe recipe, int id) throws Exception { PreparedStatement pst = null; try { conn = getConnection(); pst = conn.prepareStatement("INSERT INTO ingredients (recipe_id, name, amount, measure_id, shop_flag) VALUES (?,?,?,?,?)"); IngredientContainer ings = recipe.getIngredients(); Ingredient ingBean = null; Iterator it; for (it = ings.getIngredients().iterator(); it.hasNext(); ) { ingBean = (Ingredient) it.next(); pst.setInt(1, id); pst.setString(2, ingBean.getName()); pst.setDouble(3, ingBean.getAmount()); pst.setInt(4, ingBean.getType()); pst.setInt(5, ingBean.getShopFlag()); pst.executeUpdate(); } conn.commit(); } catch (Exception e) { conn.rollback(); MainFrame.appendStatusText("Can't add ingredient, the exception was " + e.getMessage()); } finally { try { if (pst != null) pst.close(); pst = null; } catch (Exception ex) { MainFrame.appendStatusText("Can't close database connection."); } } } Code Sample 2: public static boolean copyDataToNewTable(EboContext p_eboctx, String srcTableName, String destTableName, String where, boolean log, int mode) throws boRuntimeException { srcTableName = srcTableName.toUpperCase(); destTableName = destTableName.toUpperCase(); Connection cn = null; Connection cndef = null; boolean ret = false; try { boolean srcexists = false; boolean destexists = false; final InitialContext ic = new InitialContext(); cn = p_eboctx.getConnectionData(); cndef = p_eboctx.getConnectionDef(); PreparedStatement pstm = cn.prepareStatement("SELECT TABLE_NAME FROM USER_TABLES WHERE TABLE_NAME=?"); pstm.setString(1, srcTableName); ResultSet rslt = pstm.executeQuery(); if (rslt.next()) { srcexists = true; } rslt.close(); pstm.setString(1, destTableName); rslt = pstm.executeQuery(); if (rslt.next()) { destexists = true; } if (!destexists) { rslt.close(); pstm.close(); pstm = cn.prepareStatement("SELECT VIEW_NAME FROM USER_VIEWS WHERE VIEW_NAME=?"); pstm.setString(1, destTableName); rslt = pstm.executeQuery(); if (rslt.next()) { CallableStatement cstm = cn.prepareCall("DROP VIEW " + destTableName); cstm.execute(); cstm.close(); } } rslt.close(); pstm.close(); if (srcexists && !destexists) { if (log) { logger.finest(LoggerMessageLocalizer.getMessage("CREATING_AND_COPY_DATA_FROM") + " [" + srcTableName + "] " + LoggerMessageLocalizer.getMessage("TO") + " [" + destTableName + "]"); } CallableStatement cstm = cn.prepareCall("CREATE TABLE " + destTableName + " AS SELECT * FROM " + srcTableName + " " + (((where != null) && (where.length() > 0)) ? (" WHERE " + where) : "")); cstm.execute(); cstm.close(); if (log) { logger.finest(LoggerMessageLocalizer.getMessage("UPDATING_NGTDIC")); } cn.commit(); ret = true; } else if (srcexists && destexists) { if (log) { logger.finest(LoggerMessageLocalizer.getMessage("COPY_DATA_FROM") + " [" + srcTableName + "] " + LoggerMessageLocalizer.getMessage("TO") + " [" + destTableName + "]"); } PreparedStatement pstm2 = cn.prepareStatement("SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = ? "); pstm2.setString(1, destTableName); ResultSet rslt2 = pstm2.executeQuery(); StringBuffer fields = new StringBuffer(); PreparedStatement pstm3 = cn.prepareStatement("SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = ? and COLUMN_NAME=?"); while (rslt2.next()) { pstm3.setString(1, srcTableName); pstm3.setString(2, rslt2.getString(1)); ResultSet rslt3 = pstm3.executeQuery(); if (rslt3.next()) { if (fields.length() > 0) { fields.append(','); } fields.append('"').append(rslt2.getString(1)).append('"'); } rslt3.close(); } pstm3.close(); rslt2.close(); pstm2.close(); CallableStatement cstm; int recs = 0; if ((mode == 0) || (mode == 1)) { cstm = cn.prepareCall("INSERT INTO " + destTableName + "( " + fields.toString() + " ) ( SELECT " + fields.toString() + " FROM " + srcTableName + " " + (((where != null) && (where.length() > 0)) ? (" WHERE " + where) : "") + ")"); recs = cstm.executeUpdate(); cstm.close(); if (log) { logger.finest(LoggerMessageLocalizer.getMessage("DONE") + " [" + recs + "] " + LoggerMessageLocalizer.getMessage("RECORDS_COPIED")); } } cn.commit(); ret = true; } } catch (Exception e) { try { cn.rollback(); } catch (Exception z) { throw new boRuntimeException("boBuildDB.moveTable", "BO-1304", z); } throw new boRuntimeException("boBuildDB.moveTable", "BO-1304", e); } finally { try { cn.close(); } catch (Exception e) { } try { cndef.close(); } catch (Exception e) { } } return ret; }
11
Code Sample 1: public static void copyFile(String source, String destination, boolean overwrite) { File sourceFile = new File(source); try { File destinationFile = new File(destination); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destinationFile)); int temp = 0; while ((temp = bis.read()) != -1) bos.write(temp); bis.close(); bos.close(); } catch (Exception e) { } return; } Code Sample 2: private final void copyTargetFileToSourceFile(File sourceFile, File targetFile) throws MJProcessorException { if (!targetFile.exists()) { targetFile.getParentFile().mkdirs(); try { if (!targetFile.exists()) { targetFile.createNewFile(); } } catch (IOException e) { throw new MJProcessorException(e.getMessage(), e); } } FileChannel in = null, out = null; try { in = new FileInputStream(sourceFile).getChannel(); out = new FileOutputStream(targetFile).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (IOException e) { log.error(e); } finally { if (in != null) try { in.close(); } catch (IOException e) { log.error(e); } if (out != null) try { out.close(); } catch (IOException e) { log.error(e); } } }
00
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void main(String[] args) throws Exception { HttpGet get = new HttpGet("https://localhost/docs/index.html"); DefaultHttpClient client = new DefaultHttpClient(); ServerConfig config = new ServerConfig(new Properties()); config.setParam("https.keyStoreFile", "test.keystore"); config.setParam("https.keyPassword", "nopassword"); config.setParam("https.keyStoreType", "JKS"); config.setParam("https.protocol", "SSLv3"); SSLContextCreator ssl = new SSLContextCreator(config); SSLContext ctx = ssl.getSSLContext(); SSLSocketFactory socketFactory = new SSLSocketFactory(ctx); Scheme sch = new Scheme("https", 443, socketFactory); client.getConnectionManager().getSchemeRegistry().register(sch); HttpResponse response = client.execute(get); System.out.println(response.getStatusLine().getStatusCode()); }
00
Code Sample 1: public static void writeDataResourceText(GenericValue dataResource, String mimeTypeId, Locale locale, Map templateContext, CmsOFBizRemoteClient remoteClient, Writer out, boolean cache) throws IOException, GeneralException { Map context = (Map) templateContext.get("context"); if (context == null) { context = FastMap.newInstance(); } String webSiteId = (String) templateContext.get("webSiteId"); if (UtilValidate.isEmpty(webSiteId)) { if (context != null) webSiteId = (String) context.get("webSiteId"); } String https = (String) templateContext.get("https"); if (UtilValidate.isEmpty(https)) { if (context != null) https = (String) context.get("https"); } Map fields = dataResource.getAllFields(); String dataResourceId = (String) fields.get("dataResourceId"); String dataResourceTypeId = (String) fields.get("dataResourceTypeId"); if (UtilValidate.isEmpty(dataResourceTypeId)) { dataResourceTypeId = "SHORT_TEXT"; } if ("SHORT_TEXT".equals(dataResourceTypeId) || "LINK".equals(dataResourceTypeId)) { String text = (String) fields.get("objectInfo"); writeText(remoteClient, dataResource, text, templateContext, mimeTypeId, locale, out); } else if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)) { GenericValue electronicText; if (cache) { electronicText = remoteClient.findByPrimaryKeyCache("ElectronicText", UtilMisc.toMap("dataResourceId", dataResourceId)); } else { electronicText = remoteClient.findByPrimaryKey("ElectronicText", UtilMisc.toMap("dataResourceId", dataResourceId)); } fields = electronicText.getAllFields(); String text = (String) fields.get("textData"); writeText(remoteClient, dataResource, text, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.endsWith("_OBJECT")) { String text = (String) fields.get("dataResourceId"); writeText(remoteClient, dataResource, text, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.equals("URL_RESOURCE")) { String text = null; URL url = new URL((String) fields.get("objectInfo")); if (url.getHost() != null) { InputStream in = url.openStream(); int c; StringWriter sw = new StringWriter(); while ((c = in.read()) != -1) { sw.write(c); } sw.close(); text = sw.toString(); } else { String prefix = DataResourceWorker.buildRequestPrefix(remoteClient, locale, webSiteId, https); String sep = ""; if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) { sep = "/"; } String fixedUrlStr = prefix + sep + url.toString(); URL fixedUrl = new URL(fixedUrlStr); text = (String) fixedUrl.getContent(); } out.write(text); } else if (dataResourceTypeId.endsWith("_FILE_BIN")) { writeText(remoteClient, dataResource, dataResourceId, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.endsWith("_FILE")) { String dataResourceMimeTypeId = (String) fields.get("mimeTypeId"); String objectInfo = (String) fields.get("objectInfo"); String rootDir = (String) context.get("rootDir"); if (dataResourceMimeTypeId == null || dataResourceMimeTypeId.startsWith("text")) { renderFile(dataResourceTypeId, objectInfo, rootDir, out); } else { writeText(remoteClient, dataResource, dataResourceId, templateContext, mimeTypeId, locale, out); } } else { throw new GeneralException("The dataResourceTypeId [" + dataResourceTypeId + "] is not supported in renderDataResourceAsText"); } } Code Sample 2: public static String calculatesMD5(String plainText) throws NoSuchAlgorithmException { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(plainText.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { plainText = Integer.toHexString(0xFF & digest[i]); if (plainText.length() < 2) { plainText = "0" + plainText; } hexString.append(plainText); } return hexString.toString(); }
00
Code Sample 1: public MusicBrainzXMLParser(URL url) throws DocumentException, IOException { URLConnection urlConnection = url.openConnection(); InputStream httpStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1")); SAXReader reader = new SAXReader(); doc = reader.read(br); br.close(); } Code Sample 2: public static void copyFile(File file, String pathExport) throws IOException { File out = new File(pathExport); FileChannel sourceChannel = new FileInputStream(file).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: protected static byte[] downloadAndSendBinary(String u, boolean saveOnDisk, File f) throws IOException { URL url = new URL(u); Authenticator.setDefault(new HTTPResourceAuthenticator()); HTTPResourceAuthenticator.addURL(url); logger.debug("Retrieving " + url.toString()); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); URLConnection conn = url.openConnection(); conn.setRequestProperty("User-agent", "PS3 Media Server " + PMS.getVersion()); InputStream in = conn.getInputStream(); FileOutputStream fOUT = null; if (saveOnDisk && f != null) { fOUT = new FileOutputStream(f); } byte buf[] = new byte[4096]; int n = -1; while ((n = in.read(buf)) > -1) { bytes.write(buf, 0, n); if (fOUT != null) { fOUT.write(buf, 0, n); } } in.close(); if (fOUT != null) { fOUT.close(); } return bytes.toByteArray(); } Code Sample 2: private void jbInit() throws Exception { getContentPane().setLayout(borderLayout1); this.setTitle("�ϥλ���"); jTextPane1.setEditable(false); this.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); jScrollPane1.getViewport().add(jTextPane1); this.setSize(400, 600); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); URL url = ReadmeFrame.class.getResource("readme.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuilder strBuilder = new StringBuilder(); while (reader.ready()) { strBuilder.append(reader.readLine()); strBuilder.append('\n'); } reader.close(); jTextPane1.setText(strBuilder.toString()); }
00
Code Sample 1: public void run() { BufferedReader inp = null; try { String urlString = "http://www.hubtracker.com/query.php?action=add&username=" + user + "&password=" + pass + "&email=" + e_mail + "&address=" + Vars.Hub_Host; URL url = new URL(urlString); URLConnection conn; if (!Vars.Proxy_Host.equals("")) conn = url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(Vars.Proxy_Host, Vars.Proxy_Port))); else conn = url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.connect(); inp = new BufferedReader(new InputStreamReader(conn.getInputStream())); String xx; while ((xx = inp.readLine()) != null) PluginMain.result += "\n" + xx; if (curCmd != null) this.curCmd.cur_client.sendFromBot("[hubtracker:] " + PluginMain.result); else PluginMain.curFrame.showMsg(); inp.close(); inp = null; } catch (MalformedURLException ue) { PluginMain.result = ue.toString(); } catch (Exception e) { PluginMain.result = e.toString(); } done = true; } Code Sample 2: public MsgRecvInfo[] recvMsg(MsgRecvReq msgRecvReq) throws SQLException { String updateSQL = " update dyhikemomessages set receive_id = ?, receive_Time = ? where mo_to =? and receive_id =0 limit 20"; String selectSQL = " select MOMSG_ID,mo_from,mo_to,create_time,mo_content from dyhikemomessages where receive_id =? "; String insertSQL = " insert into t_receive_history select * from dyhikemomessages where receive_id =? "; String deleteSQL = " delete from dyhikemomessages where receive_id =? "; Logger logger = Logger.getLogger(this.getClass()); ArrayList msgInfoList = new ArrayList(); String mo_to = msgRecvReq.getAuthInfo().getUserName(); MsgRecvInfo[] msgInfoArray = new ototype.MsgRecvInfo[0]; String receiveTime = Const.DF.format(new Date()); logger.debug("recvMsgNew1"); Connection conn = null; try { int receiveID = this.getSegquence("receiveID"); conn = this.getJdbcTemplate().getDataSource().getConnection(); conn.setAutoCommit(false); PreparedStatement pstmt = conn.prepareStatement(updateSQL); pstmt.setInt(1, receiveID); pstmt.setString(2, receiveTime); pstmt.setString(3, mo_to); int recordCount = pstmt.executeUpdate(); logger.info(recordCount + " record(s) got"); if (recordCount > 0) { pstmt = conn.prepareStatement(selectSQL); pstmt.setInt(1, receiveID); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { MsgRecvInfo msg = new MsgRecvInfo(); msg.setDestMobile(rs.getString("mo_to")); msg.setRecvAddi(rs.getString("mo_to")); msg.setSendAddi(rs.getString("MO_FROM")); msg.setContent(rs.getString("mo_content")); msg.setRecvDate(rs.getString("create_time")); msgInfoList.add(msg); } msgInfoArray = (MsgRecvInfo[]) msgInfoList.toArray(new MsgRecvInfo[msgInfoList.size()]); pstmt = conn.prepareStatement(insertSQL); pstmt.setInt(1, receiveID); pstmt.execute(); pstmt = conn.prepareStatement(deleteSQL); pstmt.setInt(1, receiveID); pstmt.execute(); conn.commit(); } logger.debug("recvMsgNew2"); return msgInfoArray; } catch (SQLException e) { conn.rollback(); throw e; } finally { if (conn != null) { conn.setAutoCommit(true); conn.close(); } } }
11
Code Sample 1: protected static String fileName2md5(String input) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(input.getBytes("iso-8859-1")); byte[] byteHash = md.digest(); md.reset(); StringBuffer resultString = new StringBuffer(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); } catch (Exception ex) { Logger.error(ex.getClass() + " " + ex.getMessage()); for (int i = 0; i < ex.getStackTrace().length; i++) Logger.error(" " + ex.getStackTrace()[i].toString()); ex.printStackTrace(); } return String.valueOf(Math.random() * Long.MAX_VALUE); } Code Sample 2: public static String generateToken(ClientInfo clientInfo) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); Random rand = new Random(); String random = clientInfo.getIpAddress() + ":" + clientInfo.getPort() + ":" + rand.nextInt(); md5.update(random.getBytes()); String token = toHexString(md5.digest((new Date()).toString().getBytes())); clientInfo.setToken(token); return token; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
00
Code Sample 1: public static void copyFile(File in, File out) throws Exception { Permissions before = getFilePermissons(in); FileChannel inFile = new FileInputStream(in).getChannel(); FileChannel outFile = new FileOutputStream(out).getChannel(); inFile.transferTo(0, inFile.size(), outFile); inFile.close(); outFile.close(); setFilePermissions(out, before); } Code Sample 2: public void delUser(User user) throws SQLException, IOException, ClassNotFoundException { String dbUserID; String stockSymbol; Statement stmt = con.createStatement(); try { con.setAutoCommit(false); dbUserID = user.getUserID(); if (getUser(dbUserID) != null) { ResultSet rs1 = stmt.executeQuery("SELECT userID, symbol " + "FROM UserStocks WHERE userID = '" + dbUserID + "'"); while (rs1.next()) { try { stockSymbol = rs1.getString("symbol"); delUserStocks(dbUserID, stockSymbol); } catch (SQLException ex) { throw new SQLException("Deletion of user stock holding failed: " + ex.getMessage()); } } try { stmt.executeUpdate("DELETE FROM Users WHERE " + "userID = '" + dbUserID + "'"); } catch (SQLException ex) { throw new SQLException("User deletion failed: " + ex.getMessage()); } } else throw new IOException("User not found in database - cannot delete."); try { con.commit(); } catch (SQLException ex) { throw new SQLException("Transaction commit failed: " + ex.getMessage()); } } catch (SQLException ex) { try { con.rollback(); } catch (SQLException sqx) { throw new SQLException("Transaction failed then rollback failed: " + sqx.getMessage()); } throw new SQLException("Transaction failed; was rolled back: " + ex.getMessage()); } stmt.close(); }
00
Code Sample 1: private Concept fetchDataNeeded(String conceptUri) { if (cache.size() > MAX_CACHE) cache.clear(); if (cache.containsKey(conceptUri)) return this.cache.get(conceptUri); try { URL url = new URL(conceptUri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Accept", "application/rdf+xml"); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK && connection.getContentType().contains("application/rdf+xml")) { InputStream is = connection.getInputStream(); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("uri", conceptUri); Transformer tf = this.templates.getDAOTransformer(keyTemplates, parameters); DOMResult outputTarget = new DOMResult(); tf.transform(new StreamSource(is), outputTarget); Concept concept = ConceptXMLBind.getInstance().restoreConcept(outputTarget.getNode()); this.cache.put(conceptUri, concept); return concept; } else { logger.error("Unable to get a representation of the resource: " + connection.getResponseCode() + " => " + connection.getContentType()); throw new RuntimeException("Unable to get a representation of the resource"); } } catch (Exception e) { logger.error("Unable to fetch data for concept " + conceptUri, e); throw new RuntimeException(e); } } Code Sample 2: private HttpURLConnection sendData(URL url, String user, String password) throws IOException, IllegalArgumentException { String tmpAuthUserName = ""; if (user != null) { tmpAuthUserName = user; } final String anAuthUserName = tmpAuthUserName; String tmpAuthPasswd = ""; if (password != null) { tmpAuthPasswd = password; } final String anAuthPasswd = tmpAuthPasswd; Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(anAuthUserName, anAuthPasswd.toCharArray()); } }); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(1000); conn.connect(); return conn; }
00
Code Sample 1: public static boolean insert(final CelulaFinanceira objCelulaFinanceira) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into celula_financeira " + "(descricao, id_orgao, id_gestao, " + "id_natureza_despesa, id_programa_trabalho, " + "id_unidade_orcamentaria, id_fonte_recursos, " + "valor_provisionado, gasto_previsto, gasto_real, " + "saldo_previsto, saldo_real)" + " values (?, ?, ?, ?, ?, ?, ?, TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2))"; pst = c.prepareStatement(sql); pst.setString(1, objCelulaFinanceira.getDescricao()); pst.setLong(2, (objCelulaFinanceira.getOrgao()).getCodigo()); pst.setString(3, (objCelulaFinanceira.getGestao()).getCodigo()); pst.setString(4, (objCelulaFinanceira.getNaturezaDespesa()).getCodigo()); pst.setString(5, (objCelulaFinanceira.getProgramaTrabalho()).getCodigo()); pst.setString(6, (objCelulaFinanceira.getUnidadeOrcamentaria()).getCodigo()); pst.setString(7, (objCelulaFinanceira.getFonteRecursos()).getCodigo()); pst.setDouble(8, objCelulaFinanceira.getValorProvisionado()); pst.setDouble(9, objCelulaFinanceira.getGastoPrevisto()); pst.setDouble(10, objCelulaFinanceira.getGastoReal()); pst.setDouble(11, objCelulaFinanceira.getSaldoPrevisto()); pst.setDouble(12, objCelulaFinanceira.getSaldoReal()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { System.out.println("[CelulaFinanceiraDAO.insert] Erro ao inserir -> " + e1.getMessage()); } System.out.println("[CelulaFinanceiraDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } } Code Sample 2: private static void copy(File source, File target, byte[] buffer) throws FileNotFoundException, IOException { InputStream in = new FileInputStream(source); File parent = target.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } if (target.isDirectory()) { target = new File(target, source.getName()); } OutputStream out = new FileOutputStream(target); int read; try { while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } catch (IOException e) { throw e; } finally { in.close(); out.close(); } }
11
Code Sample 1: public static void zip(ZipOutputStream out, File f, String base) throws Exception { if (f.isDirectory()) { File[] fl = f.listFiles(); base = base.length() == 0 ? "" : base + File.separator; for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + fl[i].getName()); } } else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); FileInputStream in = new FileInputStream(f); IOUtils.copyStream(in, out); in.close(); } Thread.sleep(10); } Code Sample 2: public static final boolean zipUpdate(String zipfile, String name, String oldname, byte[] contents, boolean delete) { try { File temp = File.createTempFile("atf", ".zip"); InputStream in = new BufferedInputStream(new FileInputStream(zipfile)); OutputStream os = new BufferedOutputStream(new FileOutputStream(temp)); ZipInputStream zin = new ZipInputStream(in); ZipOutputStream zout = new ZipOutputStream(os); ZipEntry e; ZipEntry e2; byte buffer[] = new byte[TEMP_FILE_BUFFER_SIZE]; int bytesRead; boolean found = false; boolean rename = false; String oname = name; if (oldname != null) { name = oldname; rename = true; } while ((e = zin.getNextEntry()) != null) { if (!e.isDirectory()) { String ename = e.getName(); if (delete && ename.equals(name)) continue; e2 = new ZipEntry(rename ? oname : ename); zout.putNextEntry(e2); if (ename.equals(name)) { found = true; zout.write(contents); } else { while ((bytesRead = zin.read(buffer)) != -1) zout.write(buffer, 0, bytesRead); } zout.closeEntry(); } } if (!found && !delete) { e = new ZipEntry(name); zout.putNextEntry(e); zout.write(contents); zout.closeEntry(); } zin.close(); zout.close(); File fp = new File(zipfile); fp.delete(); MLUtil.copyFile(temp, fp); temp.delete(); return (true); } catch (FileNotFoundException e) { MLUtil.runtimeError(e, "updateZip " + zipfile + " " + name); } catch (IOException e) { MLUtil.runtimeError(e, "updateZip " + zipfile + " " + name); } return (false); }
11
Code Sample 1: static JSONObject executeMethod(HttpClient httpClient, HttpMethod method, int timeout) throws HttpRequestFailureException, HttpException, IOException, HttpRequestTimeoutException { try { method.getParams().setSoTimeout(timeout * 1000); int status = -1; JSONObject result = null; for (int i = 0; i < RETRY; i++) { System.out.println("Execute method[" + method.getURI() + "](try " + (i + 1) + ")"); status = httpClient.executeMethod(method); if (status == HttpStatus.SC_OK) { InputStream inputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(inputStream, baos); String response = new String(baos.toByteArray(), "UTF-8"); System.out.println(response); result = JSONObject.fromString(response); if (result.has("status")) { String lingrStatus = result.getString("status"); if ("ok".equals(lingrStatus)) { break; } else { try { Thread.sleep(1000); } catch (InterruptedException e) { } } } } else { throw new HttpRequestFailureException(status); } } return result; } catch (SocketTimeoutException e) { throw new HttpRequestTimeoutException(e); } finally { method.releaseConnection(); } } Code Sample 2: private boolean performModuleInstallation(Model m) { String seldir = directoryHandler.getSelectedDirectory(); if (seldir == null) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A target directory must be selected."); box.open(); return false; } String sjar = pathText.getText(); File fjar = new File(sjar); if (!fjar.exists()) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A non-existing jar file has been selected."); box.open(); return false; } int count = 0; try { URLClassLoader loader = new URLClassLoader(new URL[] { fjar.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(fjar)); JarEntry entry = jis.getNextJarEntry(); while (entry != null) { String name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); Class<?> cls = loader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && (cls.getModifiers() & Modifier.ABSTRACT) == 0) { if (!testAlgorithm(cls, m)) return false; count++; } } entry = jis.getNextJarEntry(); } } catch (Exception e1) { Application.logexcept("Could not load classes from jar file.", e1); return false; } if (count == 0) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("There don't seem to be any algorithms in the specified module."); box.open(); return false; } try { FileChannel ic = new FileInputStream(sjar).getChannel(); FileChannel oc = new FileOutputStream(seldir + File.separator + fjar.getName()).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (Exception e) { Application.logexcept("Could not install module", e); return false; } result = new Object(); return true; }
00
Code Sample 1: public int down(String downLoadUrl, String saveUrl) { int status = 1; long fileSize = 0; int len = 0; byte[] bt = new byte[1024]; RandomAccessFile raFile = null; long totalSize = 0; URL url = null; HttpURLConnection httpConn = null; BufferedInputStream bis = null; try { url = new URL(downLoadUrl); httpConn = (HttpURLConnection) url.openConnection(); if (httpConn.getHeaderField("Content-Length") == null) { status = 500; } else { totalSize = Long.parseLong(httpConn.getHeaderField("Content-Length")); System.out.println("文件大小:" + totalSize / 1000000 + " M"); httpConn.disconnect(); httpConn = (HttpURLConnection) url.openConnection(); fileSize = loadFileSize(saveUrl + BACK_SUFFIX); System.out.println("已下载:" + fileSize / 1000000 + " M"); httpConn.setRequestProperty("RANGE", "bytes=" + fileSize + "-"); httpConn.setRequestProperty("Accept", "image/gif,image/x-xbitmap,application/msword,*/*"); raFile = new RandomAccessFile(saveUrl + BACK_SUFFIX, "rw"); raFile.seek(fileSize); bis = new BufferedInputStream(httpConn.getInputStream()); while ((len = bis.read(bt)) > 0) { raFile.write(bt, 0, len); float progress = 0.f; float downSize = raFile.length(); progress = downSize / totalSize; System.out.println(progress * 100 + "%" + "\t\t" + downSize / 1000000 + "M"); } } } catch (FileNotFoundException e) { status = 404; } catch (Exception e) { e.printStackTrace(); } finally { try { if (bis != null) bis.close(); if (raFile != null) raFile.close(); } catch (IOException e) { e.printStackTrace(); } } if (loadFileSize(saveUrl + BACK_SUFFIX) == totalSize) { fileRename(saveUrl + BACK_SUFFIX, saveUrl); } return status; } Code Sample 2: public synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new Exception(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
00
Code Sample 1: public static boolean update(Orgao orgao) { int result = 0; Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); String sql = "update orgao set nome = (?) where id_orgao= ?"; pst = c.prepareStatement(sql); pst.setString(1, orgao.getNome()); pst.setInt(2, orgao.getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (SQLException e) { try { c.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } System.out.println("[OrgaoDAO.update] Erro ao atualizar -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } } Code Sample 2: private void process(String zipFileName, String directory, String db) throws SQLException { InputStream in = null; try { if (!FileUtils.exists(zipFileName)) { throw new IOException("File not found: " + zipFileName); } String originalDbName = null; int originalDbLen = 0; if (db != null) { originalDbName = getOriginalDbName(zipFileName, db); if (originalDbName == null) { throw new IOException("No database named " + db + " found"); } if (originalDbName.startsWith(File.separator)) { originalDbName = originalDbName.substring(1); } originalDbLen = originalDbName.length(); } in = FileUtils.openFileInputStream(zipFileName); ZipInputStream zipIn = new ZipInputStream(in); while (true) { ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { break; } String fileName = entry.getName(); fileName = fileName.replace('\\', File.separatorChar); fileName = fileName.replace('/', File.separatorChar); if (fileName.startsWith(File.separator)) { fileName = fileName.substring(1); } boolean copy = false; if (db == null) { copy = true; } else if (fileName.startsWith(originalDbName + ".")) { fileName = db + fileName.substring(originalDbLen); copy = true; } if (copy) { OutputStream out = null; try { out = FileUtils.openFileOutputStream(directory + File.separator + fileName, false); IOUtils.copy(zipIn, out); out.close(); } finally { IOUtils.closeSilently(out); } } zipIn.closeEntry(); } zipIn.closeEntry(); zipIn.close(); } catch (IOException e) { throw Message.convertIOException(e, zipFileName); } finally { IOUtils.closeSilently(in); } }
11
Code Sample 1: public static void copyFile(File dst, File src, boolean append) throws FileNotFoundException, IOException { dst.createNewFile(); FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dst).getChannel(); long startAt = 0; if (append) startAt = out.size(); in.transferTo(startAt, in.size(), out); out.close(); in.close(); } Code Sample 2: private String unJar(String jarPath, String jarEntry) { String path; if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/")); String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/")); try { new File(path + "/" + relPath).mkdirs(); JarFile jar = new JarFile(jarPath); ZipEntry ze = jar.getEntry(jarEntry); File bin = new File(path + "/" + jarEntry); IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin)); } catch (Exception e) { e.printStackTrace(); } return path + "/" + jarEntry; }
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: private String choosePivotVertex() throws ProcessorExecutionException { String result = null; Graph src; Graph dest; Path tmpDir; System.out.println("##########>" + _dirMgr.getSeqNum() + " Choose the pivot vertex"); src = new Graph(Graph.defaultGraph()); src.setPath(_curr_path); dest = new Graph(Graph.defaultGraph()); try { tmpDir = _dirMgr.getTempDir(); } catch (IOException e) { throw new ProcessorExecutionException(e); } dest.setPath(tmpDir); GraphAlgorithm choose_pivot = new PivotChoose(); choose_pivot.setConf(context); choose_pivot.setSource(src); choose_pivot.setDestination(dest); choose_pivot.setMapperNum(getMapperNum()); choose_pivot.setReducerNum(getReducerNum()); choose_pivot.execute(); try { Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); result = the_line.substring(PivotChoose.KEY_PIVOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("##########> Chosen pivot id = " + result); } catch (IOException e) { throw new ProcessorExecutionException(e); } return result; }
00
Code Sample 1: public static byte[] getHashedID(String ID) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(ID.getBytes()); byte[] digest = md5.digest(); byte[] bytes = new byte[WLDB_ID_SIZE]; for (int i = 0; i < bytes.length; i++) { bytes[i] = digest[i]; } return bytes; } catch (NoSuchAlgorithmException exception) { System.err.println("Java VM is not compatible"); return null; } } Code Sample 2: public void login(LoginData loginData) throws ConnectionEstablishException, AccessDeniedException { try { int reply; this.ftpClient.connect(loginData.getFtpServer()); reply = this.ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { this.ftpClient.disconnect(); throw (new ConnectionEstablishException("FTP server refused connection.")); } } catch (IOException e) { if (this.ftpClient.isConnected()) { try { this.ftpClient.disconnect(); } catch (IOException f) { } } e.printStackTrace(); throw (new ConnectionEstablishException("Could not connect to server.", e)); } try { if (!this.ftpClient.login(loginData.getFtpBenutzer(), loginData.getFtpPasswort())) { this.logout(); throw (new AccessDeniedException("Could not login into server.")); } } catch (IOException ioe) { ioe.printStackTrace(); throw (new AccessDeniedException("Could not login into server.", ioe)); } }
11
Code Sample 1: public boolean copyFile(File destinationFolder, File fromFile) { boolean result = false; String toFileName = destinationFolder.getAbsolutePath() + "/" + fromFile.getName(); File toFile = new File(toFileName); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (from != null) { try { from.close(); } catch (IOException e2) { e2.printStackTrace(); } if (to != null) { try { to.close(); result = true; } catch (IOException e3) { e3.printStackTrace(); } } } } return result; } Code Sample 2: private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); String response = new String(baos.toByteArray(), "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + response); return response; }
11
Code Sample 1: public static String getHash(String input) { MessageDigest m; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } m.update(input.getBytes(), 0, input.length()); return new BigInteger(1, m.digest()).toString(16); } Code Sample 2: public static boolean isMatchingAsPassword(final String password, final String amd5Password) { boolean response = false; try { final MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes()); final byte[] md5Byte = algorithm.digest(); final StringBuffer buffer = new StringBuffer(); for (final byte b : md5Byte) { if ((b <= 15) && (b >= 0)) { buffer.append("0"); } buffer.append(Integer.toHexString(0xFF & b)); } response = (amd5Password != null) && amd5Password.equals(buffer.toString()); } catch (final NoSuchAlgorithmException e) { ProjektUtil.LOG.error("No digester MD5 found in classpath!", e); } return response; }
11
Code Sample 1: public static void copy(File src, File dest) throws IOException { OutputStream stream = new FileOutputStream(dest); FileInputStream fis = new FileInputStream(src); byte[] buffer = new byte[16384]; while (fis.available() != 0) { int read = fis.read(buffer); stream.write(buffer, 0, read); } stream.flush(); } Code Sample 2: protected File downloadUpdate(String resource) throws AgentException { RESTCall call = makeRESTCall(resource); call.invoke(); File tmpFile; try { tmpFile = File.createTempFile("controller-update-", ".war", new File(tmpPath)); } catch (IOException e) { throw new AgentException("Failed to create temporary file", e); } InputStream is; try { is = call.getInputStream(); } catch (IOException e) { throw new AgentException("Failed to open input stream", e); } try { FileOutputStream os; try { os = new FileOutputStream(tmpFile); } catch (FileNotFoundException e) { throw new AgentException("Failed to open temporary file for writing", e); } boolean success = false; try { IOUtils.copy(is, os); success = true; } catch (IOException e) { throw new AgentException("Failed to download update", e); } finally { try { os.flush(); os.close(); } catch (IOException e) { if (!success) throw new AgentException("Failed to flush to disk", e); } } } finally { try { is.close(); } catch (IOException e) { log.error("Failed to close input stream", e); } call.disconnect(); } return tmpFile; }
00
Code Sample 1: public static boolean copyFile(String fileIn, String fileOut) { FileChannel in = null; FileChannel out = null; boolean retour = false; try { in = new FileInputStream(fileIn).getChannel(); out = new FileOutputStream(fileOut).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); retour = true; } catch (IOException e) { System.err.println("File : " + fileIn); e.printStackTrace(); } return retour; } Code Sample 2: private Document getOpenLinkResponse(String queryDoc) throws IOException, UnvalidResponseException { URL url = new URL(WS_URI); URLConnection conn = url.openConnection(); logger.debug(".conn open"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "text/xml"); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(queryDoc); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); logger.debug(".resp obtained"); StringBuffer responseBuffer = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { responseBuffer.append(line); responseBuffer.append(NEWLINE); } wr.close(); rd.close(); logger.debug(".done"); try { return documentParser.parse(responseBuffer.toString()); } catch (SAXException e) { throw new UnvalidResponseException("Response is not a valid XML file", e); } }
11
Code Sample 1: private void _resetLanguages(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception { List list = (List) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST); for (int i = 0; i < list.size(); i++) { long langId = ((Language) list.get(i)).getId(); try { String filePath = getGlobalVariablesPath() + "cms_language_" + langId + ".properties"; File from = new java.io.File(filePath); from.createNewFile(); String tmpFilePath = getTemporyDirPath() + "cms_language_" + langId + "_properties.tmp"; File to = new java.io.File(tmpFilePath); to.createNewFile(); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { Logger.debug(this, "Property File copy Failed " + e, e); } } } Code Sample 2: @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(); }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public void download(String contentUuid, File path) throws WebServiceClientException { try { URL url = new URL(getPath("/download/" + contentUuid)); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); OutputStream output = new FileOutputStream(path); IoUtils.copyBytes(inputStream, output); IoUtils.close(inputStream); IoUtils.close(output); } catch (IOException ioex) { throw new WebServiceClientException("Could not download or saving content to path [" + path.getAbsolutePath() + "]", ioex); } catch (Exception ex) { throw new WebServiceClientException("Could not download content from web service.", ex); } }
00
Code Sample 1: private static byte[] calcMd5(String pass) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(pass.getBytes(), 0, pass.length()); byte[] hash = digest.digest(); return hash; } catch (NoSuchAlgorithmException e) { System.err.println("No MD5 algorithm found"); System.exit(1); } return null; } Code Sample 2: public boolean login(URL strUrl, String loginName, String loginPwd, String sessionID) throws Exception { String starter = "-----------------------------"; String returnChar = "\r\n"; String lineEnd = "--"; URL urlString = strUrl; String input = null; List txtList = new ArrayList(); List fileList = new ArrayList(); String targetFile = null; String actionStatus = null; StringBuffer returnMessage = new StringBuffer(); List head = new ArrayList(); final String boundary = String.valueOf(System.currentTimeMillis()); URL url = null; URLConnection conn = null; BufferedReader br = null; DataOutputStream dos = null; boolean isLogin = false; txtList.add(new HtmlFormText("loginName", loginName)); txtList.add(new HtmlFormText("loginPwd", loginPwd)); txtList.add(new HtmlFormText("navMode", "I")); txtList.add(new HtmlFormText("action", "login")); try { url = new URL(urlString, "/" + projectName + "/Login.do"); conn = url.openConnection(); ((HttpURLConnection) conn).setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "multipart/form-data, boundary=" + "---------------------------" + boundary); if (input != null) { String auth = "Basic " + new sun.misc.BASE64Encoder().encode(input.getBytes()); conn.setRequestProperty("Authorization", auth); } dos = new DataOutputStream(conn.getOutputStream()); dos.write((starter + boundary + returnChar).getBytes()); for (int i = 0; i < txtList.size(); i++) { HtmlFormText htmltext = (HtmlFormText) txtList.get(i); dos.write(htmltext.getTranslated()); if (i + 1 < txtList.size()) { dos.write((starter + boundary + returnChar).getBytes()); } else if (fileList.size() > 0) { dos.write((starter + boundary + returnChar).getBytes()); } } dos.write((starter + boundary + "--" + returnChar).getBytes()); dos.flush(); br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String key; String header; int i = 1; key = conn.getHeaderFieldKey(i); header = conn.getHeaderField(i); System.out.println(header); if (Utility.isEmpty(header) || header.indexOf("JSESSIONID") < 0) { header = "JSESSIONID=" + sessionID + "; Path=/" + projectName; } while (key != null) { head.add(header); i++; key = conn.getHeaderFieldKey(i); header = conn.getHeaderField(i); } String tempstr; int line = 0; while (null != ((tempstr = br.readLine()))) { if (!tempstr.equals("")) { if ("window.location.replace(\"/eip/Home.do\");".indexOf(returnMessage.append(formatLine(tempstr)).toString()) != -1) { isLogin = true; break; } line++; } } txtList.clear(); fileList.clear(); } catch (Exception e) { e.printStackTrace(); } finally { try { dos.close(); } catch (Exception e) { } try { br.close(); } catch (Exception e) { } } this.setHeadList(head); return isLogin; }
00
Code Sample 1: static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: public void covertFile(File file) throws IOException { if (!file.isFile()) { return; } Reader reader = null; OutputStream os = null; File newfile = null; String filename = file.getName(); boolean succeed = false; try { newfile = new File(file.getParentFile(), filename + ".bak"); reader = new InputStreamReader(new FileInputStream(file), fromEncoding); os = new FileOutputStream(newfile); IOUtils.copy(reader, os, toEncoding); } catch (Exception e) { e.printStackTrace(); throw new IOException("Encoding error for file [" + file.getAbsolutePath() + "]"); } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (Exception e) { e.printStackTrace(); } } } try { file.delete(); succeed = newfile.renameTo(file); } catch (Exception e) { throw new IOException("Clear bak error for file [" + file.getAbsolutePath() + "]"); } if (succeed) { System.out.println("Changed encoding for file [" + file.getAbsolutePath() + "]"); } } Code Sample 2: private void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
00
Code Sample 1: public int down(String downLoadUrl, String saveUrl) { int status = 1; long fileSize = 0; int len = 0; byte[] bt = new byte[1024]; RandomAccessFile raFile = null; long totalSize = 0; URL url = null; HttpURLConnection httpConn = null; BufferedInputStream bis = null; try { url = new URL(downLoadUrl); httpConn = (HttpURLConnection) url.openConnection(); if (httpConn.getHeaderField("Content-Length") == null) { status = 500; } else { totalSize = Long.parseLong(httpConn.getHeaderField("Content-Length")); System.out.println("文件大小:" + totalSize / 1000000 + " M"); httpConn.disconnect(); httpConn = (HttpURLConnection) url.openConnection(); fileSize = loadFileSize(saveUrl + BACK_SUFFIX); System.out.println("已下载:" + fileSize / 1000000 + " M"); httpConn.setRequestProperty("RANGE", "bytes=" + fileSize + "-"); httpConn.setRequestProperty("Accept", "image/gif,image/x-xbitmap,application/msword,*/*"); raFile = new RandomAccessFile(saveUrl + BACK_SUFFIX, "rw"); raFile.seek(fileSize); bis = new BufferedInputStream(httpConn.getInputStream()); while ((len = bis.read(bt)) > 0) { raFile.write(bt, 0, len); float progress = 0.f; float downSize = raFile.length(); progress = downSize / totalSize; System.out.println(progress * 100 + "%" + "\t\t" + downSize / 1000000 + "M"); } } } catch (FileNotFoundException e) { status = 404; } catch (Exception e) { e.printStackTrace(); } finally { try { if (bis != null) bis.close(); if (raFile != null) raFile.close(); } catch (IOException e) { e.printStackTrace(); } } if (loadFileSize(saveUrl + BACK_SUFFIX) == totalSize) { fileRename(saveUrl + BACK_SUFFIX, saveUrl); } return status; } Code Sample 2: protected InputStream getInputStream() throws IOException { if (source instanceof URL) { URL url = (URL) source; location = url.toString(); return url.openStream(); } else if (source instanceof File) { location = ((File) source).getAbsolutePath(); return new FileInputStream((File) source); } else if (source instanceof String) { location = (String) source; return new FileInputStream((String) source); } else if (source instanceof InputStream) { return (InputStream) source; } return null; }
11
Code Sample 1: public static void main(String[] args) throws IOException { MSPack pack = new MSPack(new FileInputStream(args[0])); String[] files = pack.getFileNames(); for (int i = 0; i < files.length; i++) System.out.println(i + ": " + files[i] + ": " + pack.getLengths()[i]); System.out.println("Writing " + files[files.length - 1]); InputStream is = pack.getInputStream(files.length - 1); OutputStream os = new FileOutputStream(files[files.length - 1]); int n; byte[] buf = new byte[4096]; while ((n = is.read(buf)) != -1) os.write(buf, 0, n); os.close(); is.close(); } Code Sample 2: public static void copyFromOffset(long offset, File exe, File cab) throws IOException { DataInputStream in = new DataInputStream(new FileInputStream(exe)); FileOutputStream out = new FileOutputStream(cab); byte[] buffer = new byte[4096]; int bytes_read; in.skipBytes((int) offset); while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); in = null; out = null; }
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 static void extractZipPackage(String fileName, String destinationFolder) throws Exception { if (NullStatus.isNull(destinationFolder)) { destinationFolder = ""; } new File(destinationFolder).mkdirs(); File inputFile = new File(fileName); ZipFile zipFile = new ZipFile(inputFile); Enumeration<? extends ZipEntry> oEnum = zipFile.entries(); while (oEnum.hasMoreElements()) { ZipEntry zipEntry = oEnum.nextElement(); File file = new File(destinationFolder + "/" + zipEntry.getName()); if (zipEntry.isDirectory()) { file.mkdirs(); } else { String destinationFolderName = destinationFolder + "/" + zipEntry.getName(); destinationFolderName = destinationFolderName.substring(0, destinationFolderName.lastIndexOf("/")); new File(destinationFolderName).mkdirs(); FileOutputStream fos = new FileOutputStream(file); IOUtils.copy(zipFile.getInputStream(zipEntry), fos); fos.close(); } } }
00
Code Sample 1: public static Image getPluginImage(final Object plugin, final String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; } Code Sample 2: @Test public void testConfigurartion() { try { Enumeration<URL> assemblersToRegister = this.getClass().getClassLoader().getResources("META-INF/PrintAssemblerFactory.properties"); log.debug("PrintAssemblerFactory " + SimplePrintJobTest.class.getClassLoader().getResource("META-INF/PrintAssemblerFactory.properties")); log.debug("ehcache " + SimplePrintJobTest.class.getClassLoader().getResource("ehcache.xml")); log.debug("log4j " + this.getClass().getClassLoader().getResource("/log4j.xml")); if (log.isDebugEnabled()) { while (assemblersToRegister.hasMoreElements()) { URL url = (URL) assemblersToRegister.nextElement(); InputStream in = url.openStream(); BufferedReader buff = new BufferedReader(new InputStreamReader(in)); String line = buff.readLine(); while (line != null) { log.debug(line); line = buff.readLine(); } buff.close(); in.close(); } } } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: @Override public void run() { String src = null; try { src = File.readText(srcFile); if (Char.isValidate(src)) { java.net.URL url = new java.net.URL(ConsEnv.HOMEPAGE + "code/code0001.ashx"); java.util.HashMap<String, String> params = new java.util.HashMap<String, String>(); String ext = File.getExtension(srcFile.getName()); if (Char.isValidate(ext) && ext.charAt(0) == '.') { ext = ext.substring(1); } params.put("l", ext); params.put("i", "1"); params.put("n", ck_LineNbr.isSelected() ? "1" : "0"); params.put("u", ck_LinkUri.isSelected() ? "1" : "0"); params.put("t", cb_TagStyle.getSelectedItem() + ""); String tab = tf_TabCount.getText().trim(); if (java.util.regex.Pattern.matches("^\\d+$", tab)) { tab = "4"; } params.put("s", tab); params.put("o", "html"); params.put("c", src); java.net.HttpURLConnection con = (java.net.HttpURLConnection) url.openConnection(); java.io.InputStream stream = Http.post(con, params); ep_CodeView.setContentType(con.getContentType()); src = File.readText(stream); stream.close(); con.disconnect(); java.io.File tmpFile = java.io.File.createTempFile("src_", ".html"); tmpFile.deleteOnExit(); File.saveText(tmpFile, src); ep_CodeView.setPage(tmpFile.toURI().toURL()); ep_CodeView.setFont(ep_CodeView.getFont().deriveFont(20f)); } } catch (Exception exp) { Logs.exception(exp); } } Code Sample 2: private void publishPage(URL url, String path, File outputFile) throws IOException { if (debug) { System.out.println(" publishing page: " + path); System.out.println(" url == " + url); System.out.println(" file == " + outputFile); } StringBuffer sb = new StringBuffer(); try { InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); boolean firstLine = true; String line; do { line = br.readLine(); if (line != null) { if (!firstLine) sb.append("\n"); else firstLine = false; sb.append(line); } } while (line != null); br.close(); } catch (IOException e) { String mess = outputFile.toString() + ": " + e.getMessage(); errors.add(mess); } FileOutputStream fos = new FileOutputStream(outputFile); OutputStreamWriter sw = new OutputStreamWriter(fos); sw.write(sb.toString()); sw.close(); if (prepareArchive) archiveFiles.add(new ArchiveFile(path, outputFile)); }
11
Code Sample 1: private synchronized boolean createOrganization(String organizationName, HttpServletRequest req) { if ((organizationName == null) || (organizationName.equals(""))) { message = "invalid new_organization_name."; return false; } String tmpxml = TextUtil.xmlEscape(organizationName); String tmpdb = DBAccess.SQLEscape(organizationName); if ((!organizationName.equals(tmpxml)) || (!organizationName.equals(tmpdb)) || (!TextUtil.isValidFilename(organizationName))) { message = "invalid new_organization_name."; return false; } if ((organizationName.indexOf('-') > -1) || (organizationName.indexOf(' ') > -1)) { message = "invalid new_organization_name."; return false; } String[] orgnames = ServerConsoleServlet.getOrganizationNames(); for (int i = 0; i < orgnames.length; i++) { if (orgnames.equals(organizationName)) { message = "already exists."; return false; } } message = "create new organization: " + organizationName; File newOrganizationDirectory = new File(ServerConsoleServlet.RepositoryLocalDirectory.getAbsolutePath() + File.separator + organizationName); if (!newOrganizationDirectory.mkdir()) { message = "cannot create directory."; return false; } File cacheDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("CacheDirName")); cacheDir.mkdir(); File confDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("ConfDirName")); confDir.mkdir(); File rdfDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("RDFDirName")); rdfDir.mkdir(); File resourceDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("ResourceDirName")); resourceDir.mkdir(); File obsoleteDir = new File(resourceDir.getAbsolutePath() + File.separator + "obsolete"); obsoleteDir.mkdir(); File schemaDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("SchemaDirName")); schemaDir.mkdir(); String organization_temp_dir = ServerConsoleServlet.convertToAbsolutePath(ServerConsoleServlet.getConfigByTagName("OrganizationTemplate")); File templ = new File(organization_temp_dir); File[] confFiles = templ.listFiles(); for (int i = 0; i < confFiles.length; i++) { try { FileReader fr = new FileReader(confFiles[i]); FileWriter fw = new FileWriter(confDir.getAbsolutePath() + File.separator + confFiles[i].getName()); int c = -1; while ((c = fr.read()) != -1) fw.write(c); fw.flush(); fw.close(); fr.close(); } catch (IOException e) { } } SchemaModelHolder.reloadSchemaModel(organizationName); ResourceModelHolder.reloadResourceModel(organizationName); UserLogServlet.initializeUserLogDB(organizationName); MetaEditServlet.createNewProject(organizationName, "standard", MetaEditServlet.convertProjectIdToProjectUri(organizationName, "standard", req), this.username); ResourceModelHolder.reloadResourceModel(organizationName); message = organizationName + " is created. Restart Tomcat to activate this organization."; return true; } Code Sample 2: private static String fetchImageViaHttp(URL imgUrl) throws IOException { String sURL = imgUrl.toString(); String imgFile = imgUrl.getPath(); HttpURLConnection cnx = (HttpURLConnection) imgUrl.openConnection(); String uri = null; try { cnx.setAllowUserInteraction(false); cnx.setDoOutput(true); cnx.addRequestProperty("Cache-Control", "no-cache"); RequestContext ctx = RequestContext.get(); if (ctx != null) cnx.addRequestProperty("User-Agent", ctx.header("user-agent")); else cnx.addRequestProperty("User-Agent", user_agent); cnx.addRequestProperty("Referer", sURL.substring(0, sURL.indexOf('/', sURL.indexOf('.')) + 1)); cnx.connect(); if (cnx.getResponseCode() != HttpURLConnection.HTTP_OK) return null; InputStream imgData = cnx.getInputStream(); String ext = FilenameUtils.getExtension(imgFile).toLowerCase(); if (!Multimedia.isImageFile("aa." + ext)) ext = "jpg"; uri = FMT_FN.format(new Date()) + RandomStringUtils.randomAlphanumeric(4) + '.' + ext; File fileDest = new File(img_path + uri); if (!fileDest.getParentFile().exists()) fileDest.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(fileDest); try { IOUtils.copy(imgData, fos); } finally { IOUtils.closeQuietly(imgData); IOUtils.closeQuietly(fos); } } finally { cnx.disconnect(); } return RequestContext.get().contextPath() + "/uploads/img/" + uri; }
00
Code Sample 1: private static void findDictionary() { java.net.URL url = Translator.class.getResource("Translator.class"); String location = url.getFile(); String dictionaryName = (String) Settings.getDefault().getSetting("dictionary"); InputStream inputStream; try { if (location.indexOf(".jar!") == -1) inputStream = new FileInputStream(location.substring(0, location.indexOf("Translator.class")) + dictionaryName); else { JarFile jarFile; if (location.indexOf("rachota.sourceforge.net") != -1) { String fileName = location.substring(0, location.indexOf("!/") + 2); url = new URL("jar:http://rachota.sourceforge.net/rachota_22.jar!/"); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); jarFile = jarConnection.getJarFile(); } else { String fileName = System.getProperty("os.name").indexOf("Windows") == -1 ? "/" : ""; fileName = fileName + location.substring(6, location.indexOf(".jar") + 4); fileName = Tools.replaceAll(fileName, "%20", " "); jarFile = new JarFile(fileName); } ZipEntry entry = jarFile.getEntry("org/cesilko/rachota/core/" + dictionaryName); if (entry == null) { entry = jarFile.getEntry("org/cesilko/rachota/core/Dictionary_en_US.properties"); Settings.getDefault().setSetting("dictionary", "Dictionary_en_US.properties"); } inputStream = jarFile.getInputStream(entry); } dictionary = new PropertyResourceBundle(inputStream); } catch (Exception e) { System.out.println("Error: Reading from " + dictionaryName + " dictionary failed."); e.printStackTrace(); } } Code Sample 2: private SpequlosResponse executeGet(String targetURL, String urlParameters) { URL url; HttpURLConnection connection = null; boolean succ = false; try { url = new URL(targetURL + "?" + urlParameters); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer log = new StringBuffer(); ArrayList<String> response = new ArrayList<String>(); while ((line = rd.readLine()) != null) { if (line.startsWith("<div class=\"qos\">")) { System.out.println("here is the line : " + line); String resp = line.split(">")[1].split("<")[0]; System.out.println("here is the splitted line : " + resp); if (!resp.startsWith("None")) { succ = true; String[] values = resp.split(" "); ArrayList<String> realvalues = new ArrayList<String>(); for (String s : values) { realvalues.add(s); } if (realvalues.size() == 5) { realvalues.add(2, realvalues.get(2) + " " + realvalues.get(3)); realvalues.remove(3); realvalues.remove(3); } for (String n : realvalues) { response.add(n); } } } else { log.append(line); log.append('\r'); } } rd.close(); SpequlosResponse speqresp = new SpequlosResponse(response, log.toString(), succ); return speqresp; } catch (Exception e) { e.printStackTrace(); String log = "Please check the availability of Spequlos server!<br />" + "URL:" + targetURL + "<br />" + "PARAMETERS:" + urlParameters + "<br />"; return new SpequlosResponse(null, log, succ); } finally { if (connection != null) connection.disconnect(); } }
00
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 Void doInBackground() { setProgress(0); for (int i = 0; i < uploadFiles.size(); i++) { String filePath = uploadFiles.elementAt(i).getFilePath(); String fileName = uploadFiles.elementAt(i).getFileName(); String fileMsg = "Uploading file " + (i + 1) + "/" + uploadFiles.size() + "\n"; this.publish(fileMsg); try { File inFile = new File(filePath); FileInputStream in = new FileInputStream(inFile); byte[] inBytes = new byte[(int) chunkSize]; int count = 1; int maxCount = (int) (inFile.length() / chunkSize); if (inFile.length() % chunkSize > 0) { maxCount++; } int readCount = 0; readCount = in.read(inBytes); while (readCount > 0) { File splitFile = File.createTempFile("upl", null, null); String splitName = splitFile.getPath(); FileOutputStream out = new FileOutputStream(splitFile); out.write(inBytes, 0, readCount); out.close(); boolean chunkFinal = (count == maxCount); fileMsg = " - Sending chunk " + count + "/" + maxCount + ": "; this.publish(fileMsg); boolean uploadSuccess = false; int uploadTries = 0; while (!uploadSuccess && uploadTries <= 5) { uploadTries++; boolean uploadStatus = upload(splitName, fileName, count, chunkFinal); if (uploadStatus) { fileMsg = "OK\n"; this.publish(fileMsg); uploadSuccess = true; } else { fileMsg = "ERROR\n"; this.publish(fileMsg); uploadSuccess = false; } } if (!uploadSuccess) { fileMsg = "There was an error uploading your files. Please let the pipeline administrator know about this problem. Cut and paste the messages in this box, and supply them.\n"; this.publish(fileMsg); errorFlag = true; return null; } float thisProgress = (count * 100) / (maxCount); float completeProgress = (i * (100 / uploadFiles.size())); float totalProgress = completeProgress + (thisProgress / uploadFiles.size()); setProgress((int) totalProgress); splitFile.delete(); readCount = in.read(inBytes); count++; } } catch (Exception e) { this.publish(e.toString()); } } return null; }
00
Code Sample 1: private void sendToURL(String URL, String file) throws Exception { URL url = new URL(URL); InputStream is = new BufferedInputStream(new FileInputStream(file)); OutputStream os = url.openConnection().getOutputStream(); copyDocument(is, os); is.close(); os.close(); } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
00
Code Sample 1: private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(inputStream, outputStream); } finally { outputStream.close(); inputStream.close(); } } Code Sample 2: public final void conectar() throws IOException, FTPException { ftp = null; ftp = new FTPClient(); ftp.setRemoteHost(cfg.getFTPHost()); ftp.connect(); ftp.login(cfg.getFTPUser(), cfg.getFTPPass()); ftp.setProgressMonitor(pMonitor); ftp.setConnectMode(FTPConnectMode.PASV); ftp.setType(FTPTransferType.BINARY); }