label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public static void copyFile(File in, File out, long maxCount) throws IOException { final FileChannel sourceChannel = new FileInputStream(in).getChannel(); final FileChannel destinationChannel = new FileOutputStream(out).getChannel(); if (maxCount == 0) maxCount = sourceChannel.size(); try { final long size = sourceChannel.size(); long position = 0; while (position < size) { position += sourceChannel.transferTo(position, maxCount, destinationChannel); } } finally { sourceChannel.close(); destinationChannel.close(); } } Code Sample 2: private void show(String fileName, HttpServletResponse response) throws IOException { TelnetInputStream ftpIn = ftpClient_sun.get(fileName); OutputStream out = null; try { out = response.getOutputStream(); IOUtils.copy(ftpIn, out); } finally { if (ftpIn != null) { ftpIn.close(); } } }
11
Code Sample 1: @SuppressWarnings("unchecked") public ArrayList<GmailContact> getAllContacts() throws GmailException { String query = properties.getString("export_page"); query = query.replace("[RANDOM_INT]", "" + random.nextInt()); int statusCode = -1; GetMethod get = new GetMethod(query); if (log.isInfoEnabled()) log.info("getting all contacts ..."); try { statusCode = client.executeMethod(get); if (statusCode != 200) throw new GmailException("In contacts export page: Status code expected: 200 -> Status code returned: " + statusCode); } catch (HttpException e) { throw new GmailException("HttpException in contacts export page:" + e.getMessage()); } catch (IOException e) { throw new GmailException("IOException in contacts export page:" + e.getMessage()); } finally { get.releaseConnection(); } if (log.isTraceEnabled()) log.trace("accessing contacts export page successful..."); String query_post = properties.getString("outlook_export_page"); PostMethod post = new PostMethod(query_post); post.addRequestHeader("Accept-Encoding", "gzip,deflate"); post.addRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.8"); NameValuePair[] data = { new NameValuePair("at", getCookie("GMAIL_AT")), new NameValuePair("ecf", "o"), new NameValuePair("ac", "Export Contacts") }; post.setRequestBody(data); if (log.isTraceEnabled()) log.trace("getting contacts csv file..."); try { statusCode = client.executeMethod(post); if (statusCode != 200) throw new GmailException("In csv file post: Status code expected: 200 -> Status code returned: " + statusCode); if (log.isTraceEnabled()) log.trace("Gmail: csv charset: " + post.getResponseCharSet()); GMAIL_OUTPUT_CHARSET = post.getResponseCharSet(); InputStreamReader isr = new InputStreamReader(new GZIPInputStream(post.getResponseBodyAsStream()), post.getResponseCharSet()); CSVReader reader = new CSVReader(isr); List csvEntries = reader.readAll(); reader.close(); ArrayList<GmailContact> contacts = new ArrayList<GmailContact>(); MessageDigest m = MessageDigest.getInstance("MD5"); if (log.isTraceEnabled()) log.trace("creating Gmail contacts..."); for (int i = 1; i < csvEntries.size(); i++) { GmailContact contact = new GmailContact(); String[] value = (String[]) csvEntries.get(i); for (int j = 0; j < value.length; j++) { switch(j) { case 0: contact.setName(value[j]); break; case 1: contact.setEmail(value[j]); if (contact.getName() == null) contact.setIdName(value[j]); else contact.setIdName(contact.getName() + value[j]); break; case 2: contact.setNotes(value[j]); break; case 3: contact.setEmail2(value[j]); break; case 4: contact.setEmail3(value[j]); break; case 5: contact.setMobilePhone(value[j]); break; case 6: contact.setPager(value[j]); break; case 7: contact.setCompany(value[j]); break; case 8: contact.setJobTitle(value[j]); break; case 9: contact.setHomePhone(value[j]); break; case 10: contact.setHomePhone2(value[j]); break; case 11: contact.setHomeFax(value[j]); break; case 12: contact.setHomeAddress(value[j]); break; case 13: contact.setBusinessPhone(value[j]); break; case 14: contact.setBusinessPhone2(value[j]); break; case 15: contact.setBusinessFax(value[j]); break; case 16: contact.setBusinessAddress(value[j]); break; case 17: contact.setOtherPhone(value[j]); break; case 18: contact.setOtherFax(value[j]); break; case 19: contact.setOtherAddress(value[j]); break; } } m.update(contact.toString().getBytes()); if (log.isTraceEnabled()) log.trace("setting Md5 Hash..."); contact.setMd5Hash(new BigInteger(m.digest()).toString()); contacts.add(contact); } if (log.isTraceEnabled()) log.trace("Mapping contacts uid..."); Collections.sort(contacts); ArrayList<GmailContact> idList = getAllContactsID(); for (int i = 0; i < idList.size(); i++) { contacts.get(i).setId(idList.get(i).getId()); } if (log.isInfoEnabled()) log.info("getting all contacts info successful..."); return contacts; } catch (HttpException e) { throw new GmailException("HttpException in csv file post:" + e.getMessage()); } catch (IOException e) { throw new GmailException("IOException in csv file post:" + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new GmailException("No such md5 algorithm " + e.getMessage()); } finally { post.releaseConnection(); } } Code Sample 2: protected boolean check(String username, String password, String realm, String nonce, String nc, String cnonce, String qop, String uri, String response, HttpServletRequest request) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(username.getBytes()); md.update((byte) ':'); md.update(realm.getBytes()); md.update((byte) ':'); md.update(password.getBytes()); byte[] ha1 = md.digest(); md.reset(); md.update(request.getMethod().getBytes()); md.update((byte) ':'); md.update(uri.getBytes()); byte[] ha2 = md.digest(); md.update(TypeUtil.toString(ha1, 16).getBytes()); md.update((byte) ':'); md.update(nonce.getBytes()); md.update((byte) ':'); md.update(nc.getBytes()); md.update((byte) ':'); md.update(cnonce.getBytes()); md.update((byte) ':'); md.update(qop.getBytes()); md.update((byte) ':'); md.update(TypeUtil.toString(ha2, 16).getBytes()); byte[] digest = md.digest(); return response.equals(encode(digest)); } catch (Exception e) { e.printStackTrace(); return false; } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: private void insertContent(ImageData imageData, Element element) { URL url = getClass().getResource(imageData.getURL()); try { File imageFileRead = new File(url.toURI()); FileInputStream inputStream = new FileInputStream(imageFileRead); String imageFileWritePath = "htmlReportFiles" + "/" + imageData.getURL(); File imageFileWrite = new File(imageFileWritePath); String[] filePathTokens = imageFileWritePath.split("/"); String directoryPathCreate = filePathTokens[0]; int i = 1; while (i < filePathTokens.length - 1) { directoryPathCreate = directoryPathCreate + "/" + filePathTokens[i]; i++; } File fileDirectoryPathCreate = new File(directoryPathCreate); if (!fileDirectoryPathCreate.exists()) { boolean successfulFileCreation = fileDirectoryPathCreate.mkdirs(); if (successfulFileCreation == false) { throw new ExplanationException("Unable to create folders in path " + directoryPathCreate); } } FileOutputStream fileOutputStream = new FileOutputStream(imageFileWrite); byte[] data = new byte[1024]; int readDataNumberOfBytes = 0; while (readDataNumberOfBytes != -1) { readDataNumberOfBytes = inputStream.read(data, 0, data.length); if (readDataNumberOfBytes != -1) { fileOutputStream.write(data, 0, readDataNumberOfBytes); } } inputStream.close(); fileOutputStream.close(); } catch (Exception ex) { throw new ExplanationException(ex.getMessage()); } String caption = imageData.getCaption(); Element imageElement = element.addElement("img"); if (imageData.getURL().charAt(0) != '/') imageElement.addAttribute("src", "htmlReportFiles" + "/" + imageData.getURL()); else imageElement.addAttribute("src", "htmlReportFiles" + imageData.getURL()); imageElement.addAttribute("alt", "image not available"); if (caption != null) { element.addElement("br"); element.addText(caption); } }
00
Code Sample 1: public void run() { try { URL url = new URL("http://pokedev.org/time.php"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringTokenizer s = new StringTokenizer(in.readLine()); m_day = Integer.parseInt(s.nextToken()); m_hour = Integer.parseInt(s.nextToken()); m_minutes = Integer.parseInt(s.nextToken()); in.close(); } catch (Exception e) { System.out.println("ERROR: Cannot reach time server, reverting to local time"); Calendar cal = Calendar.getInstance(); m_hour = cal.get(Calendar.HOUR_OF_DAY); m_minutes = 0; m_day = 0; } while (m_isRunning) { m_minutes = m_minutes == 59 ? 0 : m_minutes + 1; if (m_minutes == 0) { if (m_hour == 23) { incrementDay(); m_hour = 0; } else { m_hour += 1; } } m_hour = m_hour == 23 ? 0 : m_hour + 1; if (System.currentTimeMillis() - m_lastWeatherUpdate >= 3600000) { generateWeather(); m_lastWeatherUpdate = System.currentTimeMillis(); } try { Thread.sleep(60000); } catch (Exception e) { } } System.out.println("INFO: Time Service stopped"); } Code Sample 2: @Override public RServiceResponse execute(final NexusServiceRequest inData) throws NexusServiceException { final RServiceRequest data = (RServiceRequest) inData; final RServiceResponse retval = new RServiceResponse(); final StringBuilder result = new StringBuilder("R service call results:\n"); RSession session; RConnection connection = null; try { result.append("Session Attachment: \n"); final byte[] sessionBytes = data.getSession(); if (sessionBytes != null && sessionBytes.length > 0) { session = RUtils.getInstance().bytesToSession(sessionBytes); result.append(" attaching to " + session + "\n"); connection = session.attach(); } else { result.append(" creating new session\n"); connection = new RConnection(data.getServerAddress()); } result.append("Input Parameters: \n"); for (String attributeName : data.getInputVariables().keySet()) { final Object parameter = data.getInputVariables().get(attributeName); if (parameter instanceof URI) { final FileObject file = VFS.getManager().resolveFile(((URI) parameter).toString()); final RFileOutputStream ros = connection.createFile(file.getName().getBaseName()); IOUtils.copy(file.getContent().getInputStream(), ros); connection.assign(attributeName, file.getName().getBaseName()); } else { connection.assign(attributeName, RUtils.getInstance().convertToREXP(parameter)); } result.append(" " + parameter.getClass().getSimpleName() + " " + attributeName + "=" + parameter + "\n"); } final REXP rExpression = connection.eval(RUtils.getInstance().wrapCode(data.getCode().replace('\r', '\n'))); result.append("Execution results:\n" + rExpression.asString() + "\n"); if (rExpression.isNull() || rExpression.asString().startsWith("Error")) { retval.setErr(rExpression.asString()); throw new NexusServiceException("R error: " + rExpression.asString()); } result.append("Output Parameters:\n"); final String[] rVariables = connection.eval("ls();").asStrings(); for (String varname : rVariables) { final String[] rVariable = connection.eval("class(" + varname + ")").asStrings(); if (rVariable.length == 2 && "file".equals(rVariable[0]) && "connection".equals(rVariable[1])) { final String rFileName = connection.eval("showConnections(TRUE)[" + varname + "]").asString(); result.append(" R File ").append(varname).append('=').append(rFileName).append('\n'); final RFileInputStream rInputStream = connection.openFile(rFileName); final File file = File.createTempFile("nexus-" + data.getRequestId(), ".dat"); IOUtils.copy(rInputStream, new FileOutputStream(file)); retval.getOutputVariables().put(varname, file.getCanonicalFile().toURI()); } else { final Object varvalue = RUtils.getInstance().convertREXP(connection.eval(varname)); retval.getOutputVariables().put(varname, varvalue); final String printValue = varvalue == null ? "null" : varvalue.getClass().isArray() ? Arrays.asList(varvalue).toString() : varvalue.toString(); result.append(" ").append(varvalue == null ? "" : varvalue.getClass().getSimpleName()).append(' ').append(varname).append('=').append(printValue).append('\n'); } } } catch (ClassNotFoundException cnfe) { retval.setErr(cnfe.getMessage()); LOGGER.error("Rserve Exception", cnfe); } catch (RserveException rse) { retval.setErr(rse.getMessage()); LOGGER.error("Rserve Exception", rse); } catch (REXPMismatchException rme) { retval.setErr(rme.getMessage()); LOGGER.error("REXP Mismatch Exception", rme); } catch (IOException rme) { retval.setErr(rme.getMessage()); LOGGER.error("IO Exception copying file ", rme); } finally { result.append("Session Detachment:\n"); if (connection != null) { RSession outSession; if (retval.isKeepSession()) { try { outSession = connection.detach(); } catch (RserveException e) { LOGGER.debug("Error detaching R session", e); outSession = null; } } else { outSession = null; } final boolean close = outSession == null; if (!close) { retval.setSession(RUtils.getInstance().sessionToBytes(outSession)); result.append(" suspended session for later use\n"); } connection.close(); retval.setSession(null); result.append(" session closed.\n"); } } retval.setOut(result.toString()); return retval; }
11
Code Sample 1: public void backup(File source) throws BackupException { try { int index = source.getAbsolutePath().lastIndexOf("."); if (index == -1) return; File dest = new File(source.getAbsolutePath().substring(0, index) + ".bak"); FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception ex) { throw new BackupException(ex.getMessage(), ex, source); } } Code Sample 2: @Override public void setDocumentSpace(DocumentSpace space) { for (Document doc : space) { File result = new File(parent, doc.getName()); if (doc instanceof XMLDOMDocument) { new PlainXMLDocumentWriter(result).writeDocument(doc); } else if (doc instanceof BinaryDocument) { BinaryDocument bin = (BinaryDocument) doc; try { IOUtils.copy(bin.getContent().getInputStream(), new FileOutputStream(result)); } catch (IOException e) { throw ManagedIOException.manage(e); } } else { System.err.println("Unkown Document type"); } } }
11
Code Sample 1: public void shouldAllowClosingInputStreamTwice() throws IOException { OutputStream outputStream = fileSystem.createOutputStream(_("hello"), OutputMode.OVERWRITE); outputStream.write(new byte[] { 1, 2, 3 }); outputStream.close(); InputStream inputStream = fileSystem.createInputStream(_("hello")); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copy(inputStream, buffer); inputStream.close(); inputStream.close(); } Code Sample 2: private String copyAndHash(InputStream input, File into) throws IOException { MessageDigest digest = createMessageDigest(); DigestInputStream dis = new DigestInputStream(input, digest); IOException ex; FileOutputStream fos = null; try { fos = new FileOutputStream(into); IOUtils.copyLarge(dis, fos); byte[] hash = digest.digest(); Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } return formatter.toString(); } catch (IOException e) { ex = e; } finally { IOUtils.closeQuietly(dis); IOUtils.closeQuietly(fos); } if (logger.isWarnEnabled()) logger.warn("Couldn't retrieve data from input!", ex); deleteTempFile(into); throw ex; }
00
Code Sample 1: public static boolean writeFileByChars(Reader pReader, File pFile, boolean pAppend) { boolean flag = false; try { FileWriter fw = new FileWriter(pFile, pAppend); IOUtils.copy(pReader, fw); fw.flush(); fw.close(); pReader.close(); flag = true; } catch (Exception e) { LOG.error("将字符流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; } Code Sample 2: public static String getDigest(String input) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(input.getBytes()); byte[] outDigest = md5.digest(); StringBuffer outBuf = new StringBuffer(33); for (int i = 0; i < outDigest.length; i++) { byte b = outDigest[i]; int hi = (b >> 4) & 0x0f; outBuf.append(MD5Digest.hexTab[hi]); int lo = b & 0x0f; outBuf.append(MD5Digest.hexTab[lo]); } return outBuf.toString(); }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (destFile.getParentFile() != null && !destFile.getParentFile().mkdirs()) { LOG.error("GeneralHelper.copyFile(): Cannot create parent directories from " + destFile); } FileInputStream fIn = null; FileOutputStream fOut = null; FileChannel source = null; FileChannel destination = null; try { fIn = new FileInputStream(sourceFile); source = fIn.getChannel(); fOut = new FileOutputStream(destFile); destination = fOut.getChannel(); long transfered = 0; final long bytes = source.size(); while (transfered < bytes) { transfered += destination.transferFrom(source, 0, source.size()); destination.position(transfered); } } finally { if (source != null) { source.close(); } else if (fIn != null) { fIn.close(); } if (destination != null) { destination.close(); } else if (fOut != null) { fOut.close(); } } } Code Sample 2: public static String calculateHash(String data, String algorithm) { if (data == null) { return null; } algorithm = (algorithm == null ? INTERNAL : algorithm.toUpperCase()); if (algorithm.equals(PLAIN)) { return data; } if (algorithm.startsWith("{RSA}")) { return encode(data, algorithm.substring(5), "RSA"); } try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(data.getBytes("UTF-8")); return getHashString(md.digest()); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); return null; } catch (NoSuchAlgorithmException nsae) { logger.error(nsae.getMessage()); return null; } }
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 static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public void 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 String connect(String host, int port, String init) { HttpURLConnection c = null; String ret = ""; int response; URL url = null; try { url = new URL("http://" + gwhost + ":" + gwport + "/connect?host=" + Utils.URLEncode(host.getBytes()) + "&port=" + Utils.URLEncode(("" + port).getBytes()) + "&passwd=" + Utils.URLEncode(gwpasswd.getBytes()) + "&data=" + Utils.URLEncode(stringToByteArray(init, encoding, utf8output))); } catch (MalformedURLException me) { ret += "Exception: " + me.getMessage(); } try { c = (HttpURLConnection) url.openConnection(); response = c.getResponseCode(); identifier = c.getHeaderField("X-Identifier"); if (c != null) c.disconnect(); } catch (Exception e) { ret += "Error trying to connect to HTTP proxy server, aborting... "; ret += "Exception: " + e.getMessage(); return ret; } if (response != HttpStatus.SC_OK) { ret += "Error trying to connect to IRC server, reason: "; switch(response) { case HttpStatus.SC_FORBIDDEN: ret += "Wrong password"; break; case HttpStatus.SC_BAD_GATEWAY: ret += "Bad gateway"; break; case HttpStatus.SC_NOT_FOUND: ret += "IRC connection not found"; break; default: ret += "HTTP response code: " + response; break; } return ret; } else { connected = true; return null; } }
11
Code Sample 1: private JButton getButtonImagen() { if (buttonImagen == null) { buttonImagen = new JButton(); buttonImagen.setText(Messages.getString("gui.AdministracionResorces.6")); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetree.png"))); buttonImagen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } } }); } return buttonImagen; } Code Sample 2: @Override @RemoteMethod public boolean encrypt(int idAnexo) { try { Anexo anexo = anexoService.selectById(idAnexo); aes.init(Cipher.ENCRYPT_MODE, aeskeySpec); FileInputStream fis = new FileInputStream(config.baseDir + "/arquivos_upload_direto/" + anexo.getAnexoCaminho()); CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(config.baseDir + "/arquivos_upload_direto/encrypt/" + anexo.getAnexoCaminho()), aes); IOUtils.copy(fis, cos); cos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
11
Code Sample 1: public String SHA1(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convToHex(sha1hash); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(CMessageDigestFile.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(CMessageDigestFile.class.getName()).log(Level.SEVERE, null, ex); } return ""; } Code Sample 2: public static String encryptPass2(String pass) throws UnsupportedEncodingException { String passEncrypt; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { } md5.update(pass.getBytes()); String dis = new String(md5.digest(), 10); passEncrypt = dis.toString(); return passEncrypt; }
11
Code Sample 1: public static void main(String[] args) throws Exception { if (args.length < 3) { usage(System.out); System.exit(1); } final File tmpFile = File.createTempFile("sej", null); tmpFile.deleteOnExit(); final FileOutputStream destination = new FileOutputStream(tmpFile); final String mainClass = args[1]; final Collection jars = new LinkedList(); for (int i = 2; i < args.length; i++) { String arg = args[i]; jars.add(arg); } JarInterpretted interpretted = new JarInterpretted(destination); JarCat rowr = new JarCat(destination, createManifest(mainClass), jars); interpretted.write(); rowr.write(); destination.close(); final File finalDestinationFile = new File(args[0]); final FileOutputStream finalDestination = new FileOutputStream(finalDestinationFile); IOUtils.copy(new FileInputStream(tmpFile), finalDestination); finalDestination.close(); Chmod chmod = new Chmod("a+rx", new File[] { finalDestinationFile }); chmod.invoke(); } Code Sample 2: public static void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
11
Code Sample 1: private String fetchContent() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String str; while ((str = reader.readLine()) != null) { buf.append(str); } return buf.toString(); } Code Sample 2: public void readData() throws IOException { i = 0; j = 0; URL url = getClass().getResource("resources/Chrom_623_620.dat"); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); s = br.readLine(); StringTokenizer st = new StringTokenizer(s); s = br.readLine(); st = new StringTokenizer(s); chrom_x[i][j] = Double.parseDouble(st.nextToken()); temp_prev = chrom_x[i][j]; chrom_y[i][j] = Double.parseDouble(st.nextToken()); gridmin = chrom_x[i][j]; gridmax = chrom_x[i][j]; sext1[i][j] = Double.parseDouble(st.nextToken()); sext2[i][j] = Double.parseDouble(st.nextToken()); sext3[i][j] = Double.parseDouble(st.nextToken()); sext4[i][j] = Double.parseDouble(st.nextToken()); j++; while ((s = br.readLine()) != null) { st = new StringTokenizer(s); temp_new = Double.parseDouble(st.nextToken()); if (temp_new != temp_prev) { temp_prev = temp_new; i++; j = 0; } chrom_x[i][j] = temp_new; chrom_y[i][j] = Double.parseDouble(st.nextToken()); sext1[i][j] = Double.parseDouble(st.nextToken()); sext2[i][j] = Double.parseDouble(st.nextToken()); sext3[i][j] = Double.parseDouble(st.nextToken()); sext4[i][j] = Double.parseDouble(st.nextToken()); imax = i; jmax = j; j++; if (chrom_x[i][j] <= gridmin) gridmin = chrom_x[i][j]; if (chrom_x[i][j] >= gridmax) gridmax = chrom_x[i][j]; } }
11
Code Sample 1: public static void copy(String a, String b) throws IOException { File inputFile = new File(a); File outputFile = new File(b); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public static void main(String[] args) throws Exception { if (args.length < 3) { usage(System.out); System.exit(1); } final File tmpFile = File.createTempFile("sej", null); tmpFile.deleteOnExit(); final FileOutputStream destination = new FileOutputStream(tmpFile); final String mainClass = args[1]; final Collection jars = new LinkedList(); for (int i = 2; i < args.length; i++) { String arg = args[i]; jars.add(arg); } JarInterpretted interpretted = new JarInterpretted(destination); JarCat rowr = new JarCat(destination, createManifest(mainClass), jars); interpretted.write(); rowr.write(); destination.close(); final File finalDestinationFile = new File(args[0]); final FileOutputStream finalDestination = new FileOutputStream(finalDestinationFile); IOUtils.copy(new FileInputStream(tmpFile), finalDestination); finalDestination.close(); Chmod chmod = new Chmod("a+rx", new File[] { finalDestinationFile }); chmod.invoke(); }
00
Code Sample 1: public void login(String a_username, String a_password) throws GB_SecurityException { Exception l_exception = null; try { if (clientFtp == null) { clientFtp = new FTPClient(); clientFtp.connect("ftp://" + ftp); } boolean b = clientFtp.login(a_username, a_password); if (b) { username = a_username; password = a_password; return; } } catch (Exception ex) { l_exception = ex; } String l_msg = "Cannot login to ftp server with user [{1}], {2}"; String[] l_replaces = new String[] { a_username, ftp }; l_msg = STools.replace(l_msg, l_replaces); throw new GB_SecurityException(l_msg, l_exception); } Code Sample 2: @RequestMapping(value = "/privatefiles/{file_name}") public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response, Principal principal) { try { Boolean validUser = false; final String currentUser = principal.getName(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!auth.getPrincipal().equals(new String("anonymousUser"))) { MetabolightsUser metabolightsUser = (MetabolightsUser) auth.getPrincipal(); if (metabolightsUser != null && metabolightsUser.isCurator()) validUser = true; } if (currentUser != null) { Study study = studyService.getBiiStudy(fileName, true); Collection<User> users = study.getUsers(); Iterator<User> iter = users.iterator(); while (iter.hasNext()) { User user = iter.next(); if (user.getUserName().equals(currentUser)) { validUser = true; break; } } } if (!validUser) throw new RuntimeException(PropertyLookup.getMessage("Entry.notAuthorised")); try { InputStream is = new FileInputStream(privateFtpDirectory + fileName + ".zip"); response.setContentType("application/zip"); IOUtils.copy(is, response.getOutputStream()); } catch (Exception e) { throw new RuntimeException(PropertyLookup.getMessage("Entry.fileMissing")); } response.flushBuffer(); } catch (IOException ex) { logger.info("Error writing file to output stream. Filename was '" + fileName + "'"); throw new RuntimeException("IOError writing file to output stream"); } }
11
Code Sample 1: public RobotList<Location> sort_decr_Location(RobotList<Location> list, String field) { int length = list.size(); Index_value[] enemy_dist = new Index_value[length]; if (field.equals("") || field.equals("location")) { Location cur_loc = this.getLocation(); for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, distance(cur_loc, list.get(i))); } } else if (field.equals("x")) { for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, list.get(i).x); } } else if (field.equals("y")) { for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, list.get(i).y); } } else { say("impossible to sort list - nothing modified"); return list; } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (enemy_dist[i].value < enemy_dist[i + 1].value) { Index_value a = enemy_dist[i]; enemy_dist[i] = enemy_dist[i + 1]; enemy_dist[i + 1] = a; permut = true; } } } while (permut); RobotList<Location> new_location_list = new RobotList<Location>(Location.class); for (int i = 0; i < length; i++) { new_location_list.addLast(list.get(enemy_dist[i].index)); } return new_location_list; } Code Sample 2: public RobotList<Resource> sort_decr_Resource(RobotList<Resource> list, String field) { int length = list.size(); Index_value[] resource_dist = new Index_value[length]; if (field.equals("") || field.equals("location")) { Location cur_loc = this.getLocation(); for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, distance(cur_loc, list.get(i).location)); } } else if (field.equals("energy")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).energy); } } else if (field.equals("ammostash")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).ammostash); } } else if (field.equals("speed")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).speed); } } else if (field.equals("health")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).health); } } else { say("impossible to sort list - nothing modified"); return list; } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (resource_dist[i].value < resource_dist[i + 1].value) { Index_value a = resource_dist[i]; resource_dist[i] = resource_dist[i + 1]; resource_dist[i + 1] = a; permut = true; } } } while (permut); RobotList<Resource> new_resource_list = new RobotList<Resource>(Resource.class); for (int i = 0; i < length; i++) { new_resource_list.addLast(list.get(resource_dist[i].index)); } return new_resource_list; }
11
Code Sample 1: private static String getHashString(String text, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException { AssertUtility.notNull(text); AssertUtility.notNullAndNotSpace(algorithm); MessageDigest md; md = MessageDigest.getInstance(algorithm); md.update(text.getBytes("UTF-8"), 0, text.length()); byte[] hash = md.digest(); return convertToHex(hash); } Code Sample 2: public static String hashPassword(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); byte result[] = md5.digest("InTeRlOgY".getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < result.length; i++) { String s = Integer.toHexString(result[i]); int length = s.length(); if (length >= 2) { sb.append(s.substring(length - 2, length)); } else { sb.append("0"); sb.append(s); } } return "{md5}" + sb.toString(); } catch (NoSuchAlgorithmException e) { return password; } }
00
Code Sample 1: public void doAction() throws MalformedURLException, IOException, Exception { URL url = new URL(CheckNewVersionAction.VERSION_FILE); InputStream is = url.openStream(); byte[] buffer = Utils.loadBytes(is); is.close(); String version = new String(buffer); if (version != null) { version = version.substring(0, version.lastIndexOf("\n") == -1 ? version.length() : version.lastIndexOf("\n")); } hasNewVersion = !DAOSystem.getSystem().getVersion().equals(version); } Code Sample 2: private void updateIngredients(Recipe recipe, int id) throws Exception { PreparedStatement pst1 = null; PreparedStatement pst2 = null; try { conn = getConnection(); pst1 = conn.prepareStatement("DELETE FROM ingredients WHERE recipe_id = ?"); pst1.setInt(1, id); if (pst1.executeUpdate() >= 0) { pst2 = 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(); pst2.setInt(1, id); pst2.setString(2, ingBean.getName()); pst2.setDouble(3, ingBean.getAmount()); pst2.setInt(4, ingBean.getType()); pst2.setInt(5, ingBean.getShopFlag()); pst2.executeUpdate(); } } conn.commit(); } catch (Exception e) { conn.rollback(); MainFrame.appendStatusText("Can't add ingredient, the exception was " + e.getMessage()); } finally { try { if (pst1 != null) pst1.close(); pst1 = null; if (pst2 != null) pst2.close(); pst2 = null; } catch (Exception ex) { MainFrame.appendStatusText("Can't close database connection."); } } }
00
Code Sample 1: private ArrayList<String> getFiles(String date) { ArrayList<String> files = new ArrayList<String>(); String info = ""; try { obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Obtaining_Data")); URL url = new URL(URL_ROUTE_VIEWS + date + "/"); URLConnection conn = url.openConnection(); conn.setDoOutput(false); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (!line.equals("")) info += line + "%"; } obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Processing_Data")); info = Patterns.removeTags(info); StringTokenizer st = new StringTokenizer(info, "%"); info = ""; boolean alternador = false; int index = 1; while (st.hasMoreTokens()) { String token = st.nextToken(); if (!token.trim().equals("")) { int pos = token.indexOf(".bz2"); if (pos != -1) { token = token.substring(1, pos + 4); files.add(token); } } } rd.close(); } catch (Exception e) { e.printStackTrace(); } return files; } Code Sample 2: public String getMediaURL(String strLink) { try { String res = de.nomule.mediaproviders.KeepVid.getAnswer(strLink, "aa"); if (NoMuleRuntime.DEBUG) System.out.println(res); String regexp = "http:\\/\\/[^\"]+\\/get_video[^\"]+"; Pattern p = Pattern.compile(regexp); Matcher m = p.matcher(res); m.find(); String strRetUrl = res.substring(m.start(), m.end()); strRetUrl = URLDecoder.decode(strRetUrl, "UTF-8"); if (TRY_HIGH_QUALITY) { NoMuleRuntime.showDebug("HIGH_QUALITY"); strRetUrl += "&fmt=18"; try { URL url = new URL(strRetUrl); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { strRetUrl = strRetUrl.substring(0, strRetUrl.length() - 7); } } if (NoMuleRuntime.DEBUG) System.out.println(strRetUrl); return strRetUrl; } catch (UnsupportedEncodingException e) { System.out.println("Error in Youtube Media Provider. Encoding is not supported. (How would that happen?!)"); e.printStackTrace(); } return ""; }
11
Code Sample 1: public static File createGzip(File inputFile) { File targetFile = new File(inputFile.getParentFile(), inputFile.getName() + ".gz"); if (targetFile.exists()) { log.warn("The target file '" + targetFile + "' already exists. Will overwrite"); } FileInputStream in = null; GZIPOutputStream out = null; try { int read = 0; byte[] data = new byte[BUFFER_SIZE]; in = new FileInputStream(inputFile); out = new GZIPOutputStream(new FileOutputStream(targetFile)); while ((read = in.read(data, 0, BUFFER_SIZE)) != -1) { out.write(data, 0, read); } in.close(); out.close(); boolean deleteSuccess = inputFile.delete(); if (!deleteSuccess) { log.warn("Could not delete file '" + inputFile + "'"); } log.info("Successfully created gzip file '" + targetFile + "'."); } catch (Exception e) { log.error("Exception while creating GZIP.", e); } finally { StreamUtil.tryCloseStream(in); StreamUtil.tryCloseStream(out); } return targetFile; } Code Sample 2: public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpClientInfo clientInfo = HttpUtil.parseClientInfo((HttpServletRequest) request); if (request.getParameter("_debug_") != null) { StringBuffer buffer = new StringBuffer(); Enumeration iter = request.getHeaderNames(); while (iter.hasMoreElements()) { String name = (String) iter.nextElement(); buffer.append(name + "=" + request.getHeader(name)).append("\n"); } buffer.append("\n"); iter = request.getParameterNames(); while (iter.hasMoreElements()) { String name = (String) iter.nextElement(); String value = request.getParameter(name); if (!"ISO-8859-1".equalsIgnoreCase(clientInfo.getPreferCharset())) value = new String(value.getBytes("ISO-8859-1"), clientInfo.getPreferCharset()); buffer.append(name).append("=").append(value).append("\n"); } response.setContentType("text/plain; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(buffer.toString()); return null; } Object resultObj = handleRequest(request); if (resultObj == null) { String requestException = (String) request.getAttribute("XSMP.handleRequest.Exception"); if (requestException != null) response.sendError(500, requestException); else response.setContentLength(0); } else { if (resultObj instanceof DataHandler) { response.setContentType(((DataHandler) resultObj).getContentType()); response.setContentLength(((DataHandler) resultObj).getInputStream().available()); IOUtils.copy(((DataHandler) resultObj).getInputStream(), response.getOutputStream()); } else { String temp = resultObj.toString(); if (temp.startsWith("<") && temp.endsWith(">")) response.setContentType("text/html; charset=" + clientInfo.getPreferCharset()); else response.setContentType("text/plain; charset=" + clientInfo.getPreferCharset()); byte[] buffer = temp.getBytes(clientInfo.getPreferCharset()); response.setContentLength(buffer.length); response.getOutputStream().write(buffer); } } return null; }
00
Code Sample 1: public void generate(String rootDir, RootModel root) throws Exception { IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("stylesheet.css"), new FileOutputStream(new File(rootDir, "stylesheet.css"))); Velocity.init(); VelocityContext context = new VelocityContext(); context.put("model", root); context.put("util", new VelocityUtils()); context.put("msg", messages); processTemplate("index.html", new File(rootDir, "index.html"), context); processTemplate("list.html", new File(rootDir, "list.html"), context); processTemplate("summary.html", new File(rootDir, "summary.html"), context); File imageDir = new File(rootDir, "images"); imageDir.mkdir(); IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("primarykey.gif"), new FileOutputStream(new File(imageDir, "primarykey.gif"))); File tableDir = new File(rootDir, "tables"); tableDir.mkdir(); for (TableModel table : root.getTables()) { context.put("table", table); processTemplate("table.html", new File(tableDir, table.getTableName() + ".html"), context); } } Code Sample 2: private static void initialize() throws IOException { System.out.println("Getting startup cookies from localhostr.com"); HttpGet httpget = new HttpGet("http://localhostr.com/"); if (login) { httpget.setHeader("Cookie", sessioncookie); } HttpResponse myresponse = httpclient.execute(httpget); HttpEntity myresEntity = myresponse.getEntity(); localhostrurl = EntityUtils.toString(myresEntity); localhostrurl = parseResponse(localhostrurl, "url : '", "'"); System.out.println("Localhost url : " + localhostrurl); InputStream is = myresponse.getEntity().getContent(); is.close(); }
11
Code Sample 1: public static String hashPassword(String plaintext) { if (plaintext == null) { return ""; } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); md.update(plaintext.getBytes("UTF-8")); } catch (Exception e) { logger.log(Level.SEVERE, "Problem hashing password.", e); } return new String(Base64.encodeBase64(md.digest())); } Code Sample 2: public static String hashURL(String url) { if (url == null) { throw new IllegalArgumentException("URL may not be null. "); } String result = null; try { MessageDigest md = MessageDigest.getInstance("SHA-1"); if (md != null) { md.reset(); md.update(url.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); result = hash.toString(16); } md = null; } catch (NoSuchAlgorithmException ex) { result = null; } return result; }
11
Code Sample 1: public void write(HttpServletRequest req, HttpServletResponse res, Object bean) throws IntrospectionException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException { res.setContentType(contentType); final Object r; if (HttpRpcServer.HttpRpcOutput.class.isAssignableFrom(bean.getClass())) { HttpRpcServer.HttpRpcOutput output = (HttpRpcServer.HttpRpcOutput) bean; r = output.getResult(); } else r = bean; if (r != null) { if (File.class.isAssignableFrom(r.getClass())) { File file = (File) r; InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) in.close(); } } else if (InputStream.class.isAssignableFrom(r.getClass())) { InputStream in = null; try { in = (InputStream) r; IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) in.close(); } } else if (XFile.class.isAssignableFrom(r.getClass())) { XFile file = (XFile) r; InputStream in = null; try { in = new XFileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) in.close(); } } res.getOutputStream().flush(); } } Code Sample 2: public static void createModelZip(String filename, String tempdir) throws EDITSException { try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filename); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); int BUFFER = 2048; byte data[] = new byte[BUFFER]; File f = new File(tempdir); for (File fs : f.listFiles()) { FileInputStream fi = new FileInputStream(fs.getAbsolutePath()); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(fs.getName()); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) out.write(data, 0, count); out.closeEntry(); origin.close(); } out.close(); } catch (Exception e) { throw new EDITSException("Can not create a model in file " + filename + " from folder " + tempdir); } }
00
Code Sample 1: public static String downloadJar(URL url) throws IOException { String localFile = null; char[] buf = new char[4096]; int num; localFile = Settings.getFreeTsUserPath() + "lib" + Settings.SLASH + getURLFileName(url); DebugDialog.print("Downloading jar-file " + url + " to " + localFile + ".", 4); InputStreamReader in = new InputStreamReader(url.openStream()); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(localFile)); do { num = in.read(buf, 0, 4096); if (num > 0) { out.write(buf, 0, num); } } while (num > 0); in.close(); out.close(); return localFile; } Code Sample 2: private static String hashToMD5(String sig) { try { MessageDigest lDigest = MessageDigest.getInstance("MD5"); lDigest.update(sig.getBytes()); BigInteger lHashInt = new BigInteger(1, lDigest.digest()); return String.format("%1$032X", lHashInt).toLowerCase(); } catch (NoSuchAlgorithmException lException) { throw new RuntimeException(lException); } }
00
Code Sample 1: public void initGet() throws Exception { cl = new DefaultHttpClient(); GetAuthPromter hp = new GetAuthPromter(); cl.setCredentialsProvider(hp); get = new HttpGet(getURL()); get.setHeader("User-Agent", "test"); get.setHeader("Accept", "*/*"); get.setHeader("Range", "bytes=" + getPosition() + "-" + getRangeEnd()); HttpResponse resp = cl.execute(get); ent = resp.getEntity(); setInputStream(ent.getContent()); } Code Sample 2: public static String digest(String text, String algorithm, String charsetName) { try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(text.getBytes(charsetName), 0, text.length()); return convertToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("unexpected exception: " + e, e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("unexpected exception: " + e, e); } }
00
Code Sample 1: public InputStream sendReceive(String trackerURL) throws TorrentException { try { URL url = new URL(trackerURL); URLConnection conn = url.openConnection(); conn.setDoOutput(true); in = conn.getInputStream(); } catch (MalformedURLException e) { throw new TorrentException(e); } catch (IOException e) { throw new TorrentException(e); } return in; } Code Sample 2: @Test public void test_lookupResourceType_FullSearch_TwoWords() throws Exception { URL url = new URL(baseUrl + "/lookupResourceType/alloyed+tritanium"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("[{\"itemTypeID\":25595,\"itemCategoryID\":4,\"name\":\"Alloyed Tritanium Bar\",\"icon\":\"69_11\"}]")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/json; charset=utf-8")); }
11
Code Sample 1: public void run() { GZIPInputStream gzipInputStream = null; try { gzipInputStream = new GZIPInputStream(pipedInputStream); IOUtils.copy(gzipInputStream, outputStream); } catch (Throwable t) { ungzipThreadThrowableList.add(t); } finally { IOUtils.closeQuietly(gzipInputStream); IOUtils.closeQuietly(pipedInputStream); } } Code Sample 2: public static void copy(File srcDir, File dstDir) throws IOException { if (srcDir.isDirectory()) { if (!dstDir.exists()) dstDir.mkdir(); String[] children = srcDir.list(); for (int i = 0; i < children.length; i++) copy(new File(srcDir, children[i]), new File(dstDir, children[i])); } else { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(srcDir); out = new FileOutputStream(dstDir); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } } }
11
Code Sample 1: private static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static void generateCode(File flowFile, String packagePath, File destDir, File scriptRootFolder) throws IOException { InputStream javaSrcIn = generateCode(flowFile, packagePath, scriptRootFolder); File outputFolder = new File(destDir, packagePath.replace('.', File.separatorChar)); String fileName = flowFile.getName(); fileName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + Consts.FILE_EXTENSION_GROOVY; File outputFile = new File(outputFolder, fileName); OutputStream javaSrcOut = new FileOutputStream(outputFile); IOUtils.copyBufferedStream(javaSrcIn, javaSrcOut); javaSrcIn.close(); javaSrcOut.close(); }
11
Code Sample 1: public static String getDigest(String seed, String code) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(seed.getBytes("UTF-8")); byte[] passwordMD5Byte = md.digest(code.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); log.error(e); return null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); log.error(e); return null; } } 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 = secureRandom.nextLong(); } else { rand = random.nextLong(); } sbValueBeforeMD5.append(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: private int mergeFiles(Merge merge) throws MojoExecutionException { String encoding = DEFAULT_ENCODING; if (merge.getEncoding() != null && merge.getEncoding().length() > 0) { encoding = merge.getEncoding(); } int numMergedFiles = 0; Writer ostream = null; FileOutputStream fos = null; try { fos = new FileOutputStream(merge.getTargetFile(), true); ostream = new OutputStreamWriter(fos, encoding); BufferedWriter output = new BufferedWriter(ostream); for (String orderingName : this.orderingNames) { List<File> files = this.orderedFiles.get(orderingName); if (files != null) { getLog().info("Appending: " + files.size() + " files that matched the name: " + orderingName + " to the target file: " + merge.getTargetFile().getAbsolutePath() + "..."); for (File file : files) { String fileName = file.getName(); getLog().info("Appending file: " + fileName + " to the target file: " + merge.getTargetFile().getAbsolutePath() + "..."); InputStream input = null; try { input = new FileInputStream(file); if (merge.getSeparator() != null && merge.getSeparator().trim().length() > 0) { String replaced = merge.getSeparator().trim(); replaced = replaced.replace("\n", ""); replaced = replaced.replace("\t", ""); replaced = replaced.replace("#{file.name}", fileName); replaced = replaced.replace("#{parent.name}", file.getParentFile() != null ? file.getParentFile().getName() : ""); replaced = replaced.replace("\\n", "\n"); replaced = replaced.replace("\\t", "\t"); getLog().debug("Appending separator: " + replaced); IOUtils.copy(new StringReader(replaced), output); } IOUtils.copy(input, output, encoding); } catch (IOException ioe) { throw new MojoExecutionException("Failed to append file: " + fileName + " to output file", ioe); } finally { IOUtils.closeQuietly(input); } numMergedFiles++; } } } output.flush(); } catch (IOException ioe) { throw new MojoExecutionException("Failed to open stream file to output file: " + merge.getTargetFile().getAbsolutePath(), ioe); } finally { if (fos != null) { IOUtils.closeQuietly(fos); } if (ostream != null) { IOUtils.closeQuietly(ostream); } } return numMergedFiles; } Code Sample 2: public static void copieFichier(File fichier1, File fichier2) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(fichier1).getChannel(); out = new FileOutputStream(fichier2).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
00
Code Sample 1: public static Properties loadProperties() { try { if (url == null) url = ClassLoader.getSystemResource("application.properties"); if (url == null) throw new FileNotFoundException("application.properties"); props = new Properties(); props.load(url.openStream()); Enumeration e = System.getProperties().propertyNames(); String key; while (e.hasMoreElements()) { key = (String) e.nextElement(); props.setProperty(key, System.getProperty(key)); } return props; } catch (Exception e) { logger.log(Level.SEVERE, e.toString(), e); } return null; } Code Sample 2: public void getZipFiles(String filename) { try { String destinationname = "c:\\mods\\peu\\"; byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; ZipEntry zipentry; zipinputstream = new ZipInputStream(new FileInputStream(filename)); zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { String entryName = zipentry.getName(); System.out.println("entryname " + entryName); int n; FileOutputStream fileoutputstream; File newFile = new File(entryName); String directory = newFile.getParent(); if (directory == null) { if (newFile.isDirectory()) break; } fileoutputstream = new FileOutputStream(destinationname + entryName); while ((n = zipinputstream.read(buf, 0, 1024)) > -1) fileoutputstream.write(buf, 0, n); fileoutputstream.close(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static void copyFile(File input, File output) throws Exception { FileReader in = new FileReader(input); FileWriter out = new FileWriter(output); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
00
Code Sample 1: String extractTiffFile(String path) throws IOException { ZipInputStream in = new ZipInputStream(new FileInputStream(path)); OutputStream out = new FileOutputStream(dir + TEMP_NAME); byte[] buf = new byte[1024]; int len; ZipEntry entry = in.getNextEntry(); if (entry == null) return null; String name = entry.getName(); if (!name.endsWith(".tif")) throw new IOException("This ZIP archive does not appear to contain a TIFF file"); while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); return name; } Code Sample 2: protected InputSource defaultResolveEntity(String publicId, String systemId) throws SAXException { if (systemId == null) return null; if (systemId.indexOf("file:/") >= 0) { try { final InputSource is = new InputSource(new URL(systemId).openStream()); is.setSystemId(systemId); if (D.ON && log.finerable()) log.finer("Entity found " + systemId); return is; } catch (Exception ex) { if (D.ON && log.finerable()) log.finer("Unable to open " + systemId); } } final String PREFIX = "/metainfo/xml"; final org.zkoss.util.resource.Locator loader = Locators.getDefault(); URL url = null; int j = systemId.indexOf("://"); if (j > 0) { final String resId = PREFIX + systemId.substring(j + 2); url = loader.getResource(resId); } if (url == null) { j = systemId.lastIndexOf('/'); final String resId = j >= 0 ? PREFIX + systemId.substring(j) : PREFIX + '/' + systemId; url = loader.getResource(resId); } if (url != null) { if (D.ON && log.finerable()) log.finer("Entity resovled to " + url); try { final InputSource is = new InputSource(url.openStream()); is.setSystemId(url.toExternalForm()); return is; } catch (IOException ex) { throw new SAXException(ex); } } return null; }
11
Code Sample 1: private final long test(final boolean applyFilter, final int executionCount) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException, RuleLoadingException { final boolean stripHtmlEnabled = true; final boolean injectSecretTokensEnabled = true; final boolean encryptQueryStringsEnabled = true; final boolean protectParamsAndFormsEnabled = true; final boolean applyExtraProtectionForDisabledFormFields = true; final boolean applyExtraProtectionForReadonlyFormFields = false; final boolean applyExtraProtectionForRequestParamValueCount = false; final ContentInjectionHelper helper = new ContentInjectionHelper(); final RuleFileLoader ruleFileLoaderModificationExcludes = new ClasspathZipRuleFileLoader(); ruleFileLoaderModificationExcludes.setPath(WebCastellumFilter.MODIFICATION_EXCLUDES_DEFAULT); final ContentModificationExcludeDefinitionContainer containerModExcludes = new ContentModificationExcludeDefinitionContainer(ruleFileLoaderModificationExcludes); containerModExcludes.parseDefinitions(); helper.setContentModificationExcludeDefinitions(containerModExcludes); final AttackHandler attackHandler = new AttackHandler(null, 123, 600000, 100000, 300000, 300000, null, "MOCK", false, false, 0, false, false, Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), true); final SessionCreationTracker sessionCreationTracker = new SessionCreationTracker(attackHandler, 0, 600000, 300000, 0, "", "", "", ""); final RequestWrapper request = new RequestWrapper(new RequestMock(), helper, sessionCreationTracker, "123.456.789.000", false, true, true); final RuleFileLoader ruleFileLoaderResponseModifications = new ClasspathZipRuleFileLoader(); ruleFileLoaderResponseModifications.setPath(WebCastellumFilter.RESPONSE_MODIFICATIONS_DEFAULT); final ResponseModificationDefinitionContainer container = new ResponseModificationDefinitionContainer(ruleFileLoaderResponseModifications); container.parseDefinitions(); final ResponseModificationDefinition[] responseModificationDefinitions = downCast(container.getAllEnabledRequestDefinitions()); final List tmpPatternsToExcludeCompleteTag = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeCompleteScript = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeCompleteTag = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeCompleteScript = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpGroupNumbersToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpGroupNumbersToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); for (int i = 0; i < responseModificationDefinitions.length; i++) { final ResponseModificationDefinition responseModificationDefinition = responseModificationDefinitions[i]; if (responseModificationDefinition.isMatchesScripts()) { tmpPatternsToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPattern()); tmpPrefiltersToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPrefilter()); tmpPatternsToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinScripts.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } if (responseModificationDefinition.isMatchesTags()) { tmpPatternsToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPattern()); tmpPrefiltersToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPrefilter()); tmpPatternsToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinTags.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } } final Matcher[] matchersToExcludeCompleteTag = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteTag); final Matcher[] matchersToExcludeCompleteScript = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteScript); final Matcher[] matchersToExcludeLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinScripts); final Matcher[] matchersToExcludeLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinTags); final Matcher[] matchersToCaptureLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinScripts); final Matcher[] matchersToCaptureLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinTags); final WordDictionary[] prefiltersToExcludeCompleteTag = (WordDictionary[]) tmpPrefiltersToExcludeCompleteTag.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeCompleteScript = (WordDictionary[]) tmpPrefiltersToExcludeCompleteScript.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinTags = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinTags.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinTags = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinTags.toArray(new WordDictionary[0]); final int[][] groupNumbersToCaptureLinksWithinScripts = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinScripts); final int[][] groupNumbersToCaptureLinksWithinTags = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinTags); final Cipher cipher = CryptoUtils.getCipher(); final CryptoKeyAndSalt key = CryptoUtils.generateRandomCryptoKeyAndSalt(false); Cipher.getInstance("AES"); MessageDigest.getInstance("SHA-1"); final ResponseWrapper response = new ResponseWrapper(new ResponseMock(), request, attackHandler, helper, false, "___ENCRYPTED___", cipher, key, "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", false, false, false, false, "123.456.789.000", new HashSet(), prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, false, true, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false, false); final List durations = new ArrayList(); for (int i = 0; i < executionCount; i++) { final long start = System.currentTimeMillis(); Reader reader = null; Writer writer = null; try { reader = new BufferedReader(new FileReader(this.htmlFile)); writer = new FileWriter(this.outputFile); if (applyFilter) { writer = new ResponseFilterWriter(writer, true, "http://127.0.0.1/test/sample", "/test", "/test", "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", cipher, key, helper, "___ENCRYPTED___", request, response, stripHtmlEnabled, injectSecretTokensEnabled, protectParamsAndFormsEnabled, encryptQueryStringsEnabled, applyExtraProtectionForDisabledFormFields, applyExtraProtectionForReadonlyFormFields, applyExtraProtectionForRequestParamValueCount, prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, true, false, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false); writer = new BufferedWriter(writer); } char[] chars = new char[16 * 1024]; int read; while ((read = reader.read(chars)) != -1) { if (read > 0) { writer.write(chars, 0, read); } } durations.add(new Long(System.currentTimeMillis() - start)); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } if (writer != null) { try { writer.close(); } catch (IOException ignored) { } } } } long sum = 0; for (final Iterator iter = durations.iterator(); iter.hasNext(); ) { Long value = (Long) iter.next(); sum += value.longValue(); } return sum / durations.size(); } Code Sample 2: public static void copyFileStreams(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) { return; } FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); int read = 0; byte[] buf = new byte[1024]; while (-1 != read) { read = fis.read(buf); if (read >= 0) { fos.write(buf, 0, read); } } fos.close(); fis.close(); }
11
Code Sample 1: private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { GTLogger.getInstance().error(e); } } catch (FileNotFoundException e) { GTLogger.getInstance().error(e); } } Code Sample 2: public static void copy(File srcFile, File destFile) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(srcFile); out = new FileOutputStream(destFile); final byte[] buf = new byte[4096]; int read; while ((read = in.read(buf)) >= 0) { out.write(buf, 0, read); } } finally { try { if (in != null) in.close(); } catch (IOException ioe) { } try { if (out != null) out.close(); } catch (IOException ioe) { } } }
00
Code Sample 1: public static void copyFile(String sourceName, String destName) throws IOException { FileChannel sourceChannel = null; FileChannel destChannel = null; try { sourceChannel = new FileInputStream(sourceName).getChannel(); destChannel = new FileOutputStream(destName).getChannel(); destChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException exception) { throw exception; } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException ex) { } } if (destChannel != null) { try { destChannel.close(); } catch (IOException ex) { } } } } Code Sample 2: public static byte[] getHashedPassword(String password, byte[] randomBytes) { byte[] hashedPassword = null; try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(randomBytes); messageDigest.update(password.getBytes("UTF-8")); hashedPassword = messageDigest.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return hashedPassword; }
11
Code Sample 1: 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); } } Code Sample 2: private static void readFileEntry(Zip64File zip64File, FileEntry fileEntry, File destFolder) { FileOutputStream fileOut; File target = new File(destFolder, fileEntry.getName()); File targetsParent = target.getParentFile(); if (targetsParent != null) { targetsParent.mkdirs(); } try { fileOut = new FileOutputStream(target); log.info("[readFileEntry] writing entry: " + fileEntry.getName() + " to file: " + target.getAbsolutePath()); EntryInputStream entryReader = zip64File.openEntryInputStream(fileEntry.getName()); IOUtils.copyLarge(entryReader, fileOut); entryReader.close(); fileOut.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (ZipException e) { log.warning("ATTENTION PLEASE: Some strange, but obviously not serious ZipException occured! Extracted file '" + target.getName() + "' anyway! So don't Panic!" + "\n"); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: private void refreshCacheFile(RepositoryFile file, File cacheFile) throws FileNotFoundException, IOException { FileOutputStream fos = new FileOutputStream(cacheFile); InputStream is = file.getInputStream(); int count = IOUtils.copy(is, fos); logger.debug("===========================================================> wrote bytes to cache " + count); fos.flush(); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(file.getInputStream()); } Code Sample 2: protected <T extends AbstractResponse> T readResponse(HttpUriRequest httpUriRequest, Class<T> clazz) throws IOException, TranslatorException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Executing request " + httpUriRequest.getURI()); } HttpResponse httpResponse = httpClient.execute(httpUriRequest); String response = EntityUtils.toString(httpResponse.getEntity()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Reading '" + response + "' into " + clazz.getName()); } T abstractResponse = TranslatorObjectMapper.instance().readValue(response, clazz); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Response object " + abstractResponse); } if (abstractResponse.getError() != null) { throw new TranslatorException(abstractResponse.getError()); } return abstractResponse; }
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: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static void 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 compress(final File zip, final Map<InputStream, String> entries) throws IOException { if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet())) throw new IllegalArgumentException("One ore more parameters are empty!"); if (zip.exists()) zip.delete(); else if (!zip.getParentFile().exists()) zip.getParentFile().mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip))); out.setLevel(Deflater.BEST_COMPRESSION); InputStream in = null; try { for (InputStream inputStream : entries.keySet()) { in = inputStream; ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(in))); out.putNextEntry(zipEntry); IOUtils.copy(in, out); out.closeEntry(); in.close(); } } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
11
Code Sample 1: 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 jsFunction_addFile(ScriptableFile infile) throws IOException { if (!infile.jsFunction_exists()) throw new IllegalArgumentException("Cannot add a file that doesn't exists to an archive"); ZipArchiveEntry entry = new ZipArchiveEntry(infile.getName()); entry.setSize(infile.jsFunction_getSize()); out.putArchiveEntry(entry); try { InputStream inStream = infile.jsFunction_createInputStream(); IOUtils.copy(inStream, out); inStream.close(); } finally { out.closeArchiveEntry(); } }
11
Code Sample 1: @Override public void writeTo(final TrackRepresentation t, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws WebApplicationException { if (mediaType.isCompatible(MediaType.APPLICATION_OCTET_STREAM_TYPE)) { InputStream is = null; try { httpHeaders.add("Content-Type", "audio/mp3"); IOUtils.copy(is = t.getInputStream(mediaType), entityStream); } catch (final IOException e) { LOG.warn("IOException : maybe remote client has disconnected"); } finally { IOUtils.closeQuietly(is); } } } Code Sample 2: @Override public void copierPhotos(FileInputStream fichierACopier, FileOutputStream fichierDestination) { FileChannel in = null; FileChannel out = null; try { in = fichierACopier.getChannel(); out = fichierDestination.getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
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 static boolean copyFile(String sourceFileName, String destFileName) { if (sourceFileName == null || destFileName == null) return false; if (sourceFileName.equals(destFileName)) return false; try { java.io.FileInputStream in = new java.io.FileInputStream(sourceFileName); java.io.FileOutputStream out = new java.io.FileOutputStream(destFileName); try { byte[] buf = new byte[31000]; int read = in.read(buf); while (read > -1) { out.write(buf, 0, read); read = in.read(buf); } } finally { in.close(); out.close(); } } catch (Exception e) { System.out.println(e.toString()); return false; } return true; }
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 void copy(String fromFileName, String toFileName) throws IOException { log.info("copy() file:" + fromFileName + " toFile:" + toFileName); File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } 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); } finally { if (from != null) try { from.close(); } catch (IOException e) { log.error(e.getMessage()); } if (to != null) try { to.close(); } catch (IOException e) { log.error(e.getMessage()); } } }
00
Code Sample 1: protected Class findClass(String name) throws ClassNotFoundException { String classFile = name.replace('.', '/') + ".class"; InputStream classInputStream = null; if (this.extensionJars != null) { for (int i = 0; i < this.extensionJars.length; i++) { JarFile extensionJar = this.extensionJars[i]; JarEntry jarEntry = extensionJar.getJarEntry(classFile); if (jarEntry != null) { try { classInputStream = extensionJar.getInputStream(jarEntry); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } } } if (classInputStream == null) { URL url = getResource(classFile); if (url == null) { throw new ClassNotFoundException("Class " + name); } try { classInputStream = url.openStream(); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedInputStream in = new BufferedInputStream(classInputStream); byte[] buffer = new byte[8096]; int size; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } in.close(); return defineClass(name, out.toByteArray(), 0, out.size(), this.protectionDomain); } catch (IOException ex) { throw new ClassNotFoundException("Class " + name, ex); } } 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(); }
00
Code Sample 1: public static void copyFile(final String src, final String dest) { Runnable r1 = new Runnable() { 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); } } }; Thread cFile = new Thread(r1, "copyFile"); cFile.start(); } Code Sample 2: public String getShortToken(String md5Str) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.update(md5Str.getBytes(JspRunConfig.charset)); } catch (Exception e) { e.printStackTrace(); } StringBuffer token = toHex(md5.digest()); return token.substring(8, 24); }
11
Code Sample 1: public static void invokeMvnArtifact(final IProject project, final IModuleExtension moduleExtension, final String location) throws CoreException, InterruptedException, IOException { final Properties properties = new Properties(); properties.put("archetypeGroupId", "org.nexopenframework.plugins"); properties.put("archetypeArtifactId", "openfrwk-archetype-webmodule"); final String version = org.maven.ide.eclipse.ext.Maven2Plugin.getArchetypeVersion(); properties.put("archetypeVersion", version); properties.put("artifactId", moduleExtension.getArtifact()); properties.put("groupId", moduleExtension.getGroup()); properties.put("version", moduleExtension.getVersion()); final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); final ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(LAUNCH_CONFIGURATION_TYPE_ID); final ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, "Creating WEB module using Apache Maven archetype"); File archetypePomDirectory = getDefaultArchetypePomDirectory(); try { final String dfPom = getPomFile(moduleExtension.getGroup(), moduleExtension.getArtifact()); final ByteArrayInputStream bais = new ByteArrayInputStream(dfPom.getBytes()); final File f = new File(archetypePomDirectory, "pom.xml"); OutputStream fous = null; try { fous = new FileOutputStream(f); IOUtils.copy(bais, fous); } finally { try { if (fous != null) { fous.close(); } if (bais != null) { bais.close(); } } catch (final IOException e) { } } String goalName = "archetype:create"; boolean offline = false; try { final Class clazz = Thread.currentThread().getContextClassLoader().loadClass("org.maven.ide.eclipse.Maven2Plugin"); final Maven2Plugin plugin = (Maven2Plugin) clazz.getMethod("getDefault", new Class[0]).invoke(null, new Object[0]); offline = plugin.getPreferenceStore().getBoolean("eclipse.m2.offline"); } catch (final ClassNotFoundException e) { Logger.logException("No class [org.maven.ide.eclipse.ext.Maven2Plugin] in classpath", e); } catch (final NoSuchMethodException e) { Logger.logException("No method getDefault", e); } catch (final Throwable e) { Logger.logException(e); } if (offline) { goalName = new StringBuffer(goalName).append(" -o").toString(); } if (!offline) { final IPreferenceStore ps = Maven2Plugin.getDefault().getPreferenceStore(); final String repositories = ps.getString(Maven2PreferenceConstants.P_M2_REPOSITORIES); final String[] repos = repositories.split(org.maven.ide.eclipse.ext.Maven2Plugin.REPO_SEPARATOR); final StringBuffer sbRepos = new StringBuffer(); for (int k = 0; k < repos.length; k++) { sbRepos.append(repos[k]); if (k != repos.length - 1) { sbRepos.append(","); } } properties.put("remoteRepositories", sbRepos.toString()); } workingCopy.setAttribute(ATTR_GOALS, goalName); workingCopy.setAttribute(ATTR_POM_DIR, archetypePomDirectory.getAbsolutePath()); workingCopy.setAttribute(ATTR_PROPERTIES, convertPropertiesToList(properties)); final long timeout = org.maven.ide.eclipse.ext.Maven2Plugin.getTimeout(); TimeoutLaunchConfiguration.launchWithTimeout(new NullProgressMonitor(), workingCopy, project, timeout); FileUtils.copyDirectoryStructure(new File(archetypePomDirectory, project.getName()), new File(location)); FileUtils.deleteDirectory(new File(location + "/src")); FileUtils.forceDelete(new File(location, "pom.xml")); project.refreshLocal(IResource.DEPTH_INFINITE, null); } finally { FileUtils.deleteDirectory(archetypePomDirectory); Logger.log(Logger.INFO, "Invoked removing of archetype POM directory"); } } Code Sample 2: private static void readFileEntry(Zip64File zip64File, FileEntry fileEntry, File destFolder) { FileOutputStream fileOut; File target = new File(destFolder, fileEntry.getName()); File targetsParent = target.getParentFile(); if (targetsParent != null) { targetsParent.mkdirs(); } try { fileOut = new FileOutputStream(target); log.info("[readFileEntry] writing entry: " + fileEntry.getName() + " to file: " + target.getAbsolutePath()); EntryInputStream entryReader = zip64File.openEntryInputStream(fileEntry.getName()); IOUtils.copyLarge(entryReader, fileOut); entryReader.close(); fileOut.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (ZipException e) { log.warning("ATTENTION PLEASE: Some strange, but obviously not serious ZipException occured! Extracted file '" + target.getName() + "' anyway! So don't Panic!" + "\n"); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: private static String getHashString(String text, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException { AssertUtility.notNull(text); AssertUtility.notNullAndNotSpace(algorithm); MessageDigest md; md = MessageDigest.getInstance(algorithm); md.update(text.getBytes("UTF-8"), 0, text.length()); byte[] hash = md.digest(); return convertToHex(hash); } Code Sample 2: public static String getMD5(String text) { if (text == null) { return null; } String result = null; try { MessageDigest md5 = MessageDigest.getInstance(ALG_MD5); md5.update(text.getBytes(ENCODING)); result = "" + new BigInteger(1, md5.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; }
11
Code Sample 1: protected void extractArchive(File archive) { ZipInputStream zis = null; FileOutputStream fos; ZipEntry entry; File curEntry; int n; try { zis = new ZipInputStream(new FileInputStream(archive)); while ((entry = zis.getNextEntry()) != null) { curEntry = new File(workingDir, entry.getName()); if (entry.isDirectory()) { System.out.println("skip directory: " + entry.getName()); continue; } System.out.print("zip-entry (file): " + entry.getName()); System.out.println(" ==> real path: " + curEntry.getAbsolutePath()); if (!curEntry.getParentFile().exists()) curEntry.getParentFile().mkdirs(); fos = new FileOutputStream(curEntry); while ((n = zis.read(buf, 0, buf.length)) > -1) fos.write(buf, 0, n); fos.close(); zis.closeEntry(); } } catch (Throwable t) { t.printStackTrace(); } finally { try { if (zis != null) zis.close(); } catch (Throwable t) { } } } Code Sample 2: private static final void copyFile(File srcFile, File destDir, byte[] buffer) { try { File destFile = new File(destDir, srcFile.getName()); InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); int bytesRead; while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); out.close(); } catch (IOException ioe) { System.err.println("Couldn't copy file '" + srcFile + "' to directory '" + destDir + "'"); } }
11
Code Sample 1: private String MD5(String s) { Log.d("MD5", "Hashing '" + s + "'"); String hash = ""; try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(s.getBytes(), 0, s.length()); hash = new BigInteger(1, m.digest()).toString(16); Log.d("MD5", "Hash: " + hash); } catch (Exception e) { Log.e("MD5", e.getMessage()); } return hash; } Code Sample 2: public static String md5(String plainText) { String ret = null; 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)); } ret = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ret; }
11
Code Sample 1: public static void exportGestureSet(List<GestureSet> sets, File file) { try { FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(exportGestureSetsAsStream(sets), outputStream); outputStream.close(); } catch (FileNotFoundException e) { LOGGER.log(Level.SEVERE, "Could not export Gesture Sets. Export File not found.", e); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Could not export Gesture Sets.", e); } } Code Sample 2: protected void createFile(File sourceActionDirectory, File destinationActionDirectory, LinkedList<String> segments) throws DuplicateActionFileException { File currentSrcDir = sourceActionDirectory; File currentDestDir = destinationActionDirectory; String segment = ""; for (int i = 0; i < segments.size() - 1; i++) { segment = segments.get(i); currentSrcDir = new File(currentSrcDir, segment); currentDestDir = new File(currentDestDir, segment); } if (currentSrcDir != null && currentDestDir != null) { File srcFile = new File(currentSrcDir, segments.getLast()); if (srcFile.exists()) { File destFile = new File(currentDestDir, segments.getLast()); if (destFile.exists()) { throw new DuplicateActionFileException(srcFile.toURI().toASCIIString()); } try { FileChannel srcChannel = new FileInputStream(srcFile).getChannel(); FileChannel destChannel = new FileOutputStream(destFile).getChannel(); ByteBuffer buffer = ByteBuffer.allocate((int) srcChannel.size()); while (srcChannel.position() < srcChannel.size()) { srcChannel.read(buffer); } srcChannel.close(); buffer.rewind(); destChannel.write(buffer); destChannel.close(); } catch (Exception ex) { ex.printStackTrace(); } } } }
11
Code Sample 1: public static void s_copy(FileInputStream fis, FileOutputStream fos) throws Exception { FileChannel in = fis.getChannel(); FileChannel out = fos.getChannel(); in.transferTo(0, in.size(), out); if (in != null) in.close(); if (out != null) out.close(); } Code Sample 2: public static void copy(File srcDir, File dstDir) throws IOException { if (srcDir.isDirectory()) { if (!dstDir.exists()) dstDir.mkdir(); String[] children = srcDir.list(); for (int i = 0; i < children.length; i++) copy(new File(srcDir, children[i]), new File(dstDir, children[i])); } else { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(srcDir); out = new FileOutputStream(dstDir); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } } }
00
Code Sample 1: public void fetch(URL url, HTTPMethod method, String payload, WithResponse wr) throws IOException { System.out.println("fetchin' " + url.toString() + " with GAE fetch service"); HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setReadTimeout(10000); connection.setRequestMethod(method.name()); System.out.println(method.name().toString()); connection.setRequestProperty("Connection", "close"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (wr != null) { connection.setDoOutput(true); } connection.connect(); System.out.println(connection.toString()); if (payload != null) { OutputStream out = null; OutputStreamWriter outWriter = null; try { out = connection.getOutputStream(); outWriter = new OutputStreamWriter(out, "UTF-8"); outWriter.write(payload); System.out.println(out.toString()); } finally { close(outWriter); close(out); } } if (wr != null) { InputStream in = null; InputStreamReader reader = null; StringBuilder sb = new StringBuilder(); try { in = connection.getInputStream(); reader = new InputStreamReader(in); BufferedReader bufReader = new BufferedReader(reader); String line; while ((line = bufReader.readLine()) != null) { sb.append(line).append('\n'); } System.out.println(line); } finally { close(reader); close(in); } } } finally { if (connection != null) { connection.disconnect(); } } } Code Sample 2: protected void ensureProjectExists(String projectName) { List<IClasspathEntry> classpathEntries = new UniqueEList<IClasspathEntry>(); IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); try { boolean isEmptyProject = true; IProjectDescription projectDescription = null; IJavaProject javaProject = JavaCore.create(project); if (!project.exists()) { projectDescription = ResourcesPlugin.getWorkspace().newProjectDescription(projectName); project.create(new NullProgressMonitor()); } else { isEmptyProject = false; projectDescription = project.getDescription(); classpathEntries.addAll(Arrays.asList(javaProject.getRawClasspath())); } String[] natureIds = projectDescription.getNatureIds(); if (natureIds == null) { natureIds = new String[] { JavaCore.NATURE_ID }; } else { boolean hasJavaNature = false; boolean hasPDENature = false; for (int i = 0; i < natureIds.length; ++i) { if (JavaCore.NATURE_ID.equals(natureIds[i])) { hasJavaNature = true; } if ("org.eclipse.pde.PluginNature".equals(natureIds[i])) { hasPDENature = true; } } if (!hasJavaNature) { String[] oldNatureIds = natureIds; natureIds = new String[oldNatureIds.length + 1]; System.arraycopy(oldNatureIds, 0, natureIds, 0, oldNatureIds.length); natureIds[oldNatureIds.length] = JavaCore.NATURE_ID; } if (!hasPDENature) { String[] oldNatureIds = natureIds; natureIds = new String[oldNatureIds.length + 1]; System.arraycopy(oldNatureIds, 0, natureIds, 0, oldNatureIds.length); natureIds[oldNatureIds.length] = "org.eclipse.pde.PluginNature"; } } projectDescription.setNatureIds(natureIds); ICommand[] builders = projectDescription.getBuildSpec(); if (builders == null) { builders = new ICommand[0]; } boolean hasManifestBuilder = false; boolean hasSchemaBuilder = false; for (int i = 0; i < builders.length; ++i) { if ("org.eclipse.pde.ManifestBuilder".equals(builders[i].getBuilderName())) { hasManifestBuilder = true; } if ("org.eclipse.pde.SchemaBuilder".equals(builders[i].getBuilderName())) { hasSchemaBuilder = true; } } if (!hasManifestBuilder) { ICommand[] oldBuilders = builders; builders = new ICommand[oldBuilders.length + 1]; System.arraycopy(oldBuilders, 0, builders, 0, oldBuilders.length); builders[oldBuilders.length] = projectDescription.newCommand(); builders[oldBuilders.length].setBuilderName("org.eclipse.pde.ManifestBuilder"); } if (!hasSchemaBuilder) { ICommand[] oldBuilders = builders; builders = new ICommand[oldBuilders.length + 1]; System.arraycopy(oldBuilders, 0, builders, 0, oldBuilders.length); builders[oldBuilders.length] = projectDescription.newCommand(); builders[oldBuilders.length].setBuilderName("org.eclipse.pde.SchemaBuilder"); } projectDescription.setBuildSpec(builders); project.open(new NullProgressMonitor()); project.setDescription(projectDescription, new NullProgressMonitor()); if (isEmptyProject) { IFolder sourceContainer = project.getFolder("src"); sourceContainer.create(false, true, new NullProgressMonitor()); IClasspathEntry sourceClasspathEntry = JavaCore.newSourceEntry(new Path("/" + projectName + "/src")); classpathEntries.add(0, sourceClasspathEntry); String jreContainer = JavaRuntime.JRE_CONTAINER; String complianceLevel = CodeGenUtil.EclipseUtil.getJavaComplianceLevel(project); if ("1.5".equals(complianceLevel)) { jreContainer += "/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"; } else if ("1.6".equals(complianceLevel)) { jreContainer += "/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"; } classpathEntries.add(JavaCore.newContainerEntry(new Path(jreContainer))); classpathEntries.add(JavaCore.newContainerEntry(new Path("org.eclipse.pde.core.requiredPlugins"))); javaProject.setOutputLocation(new Path("/" + projectName + "/bin"), new NullProgressMonitor()); } javaProject.setRawClasspath(classpathEntries.toArray(new IClasspathEntry[classpathEntries.size()]), new NullProgressMonitor()); } catch (CoreException e) { e.printStackTrace(); CodeGenEcorePlugin.INSTANCE.log(e); } }
00
Code Sample 1: private boolean tryGet(String url, Hashtable<String, String> req) throws Exception { boolean result = false; Enumeration<String> keys = req.keys(); String key; String value; String data = ""; while (keys.hasMoreElements()) { key = keys.nextElement(); value = req.get(key); data += URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8") + "&"; } URLConnection conn = new URL(url).openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (line != null) result = true; } wr.close(); rd.close(); result = true; return result; } Code Sample 2: @Override public URLConnection openConnection(URL url, Proxy proxy) throws IOException { if (null == url) { throw new IllegalArgumentException(Messages.getString("luni.1B")); } String host = url.getHost(); if (host == null || host.length() == 0 || host.equalsIgnoreCase("localhost")) { return new FileURLConnection(url); } URL ftpURL = new URL("ftp", host, url.getFile()); return (proxy == null) ? ftpURL.openConnection() : ftpURL.openConnection(proxy); }
11
Code Sample 1: private static String calculateMD5(String s) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); m.update(s.getBytes()); return new BigInteger(1, m.digest()).toString(16); } catch (NoSuchAlgorithmException e) { throw new UndeclaredThrowableException(e); } } Code Sample 2: public static String generateMD5(String clear) { byte hash[] = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(clear.getBytes()); hash = md5.digest(); } catch (NoSuchAlgorithmException e) { } if (hash != null) { StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String tmp = Integer.toHexString(0xFF & hash[i]); if (tmp.length() == 1) { tmp = "0" + tmp; } hexString.append(tmp); } return hexString.toString(); } else { return null; } }
00
Code Sample 1: private static FTPClient getFtpClient(String ftpHost, String ftpUsername, String ftpPassword) throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.connect(ftpHost); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return null; } if (!ftp.login(ftpUsername, ftpPassword)) { return null; } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; } Code Sample 2: private static int ejecutaUpdate(String database, String SQL) throws Exception { int i = 0; DBConnectionManager dbm = null; Connection bd = null; try { dbm = DBConnectionManager.getInstance(); bd = dbm.getConnection(database); Statement st = bd.createStatement(); i = st.executeUpdate(SQL); bd.commit(); st.close(); dbm.freeConnection(database, bd); } catch (Exception e) { log.error("SQL error: " + SQL, e); Exception excep; if (dbm == null) excep = new Exception("Could not obtain pool object DbConnectionManager"); else if (bd == null) excep = new Exception("The Db connection pool could not obtain a database connection"); else { bd.rollback(); excep = new Exception("SQL Error: " + SQL + " error: " + e); dbm.freeConnection(database, bd); } throw excep; } return i; }
00
Code Sample 1: public static Version getWebRelease(String url) { InputStream is = null; try { is = new URL(url).openStream(); Reader reader = new InputStreamReader(new BufferedInputStream(is), "UTF-8"); String word = findWord(reader, "<description>Release:", "</description>").trim(); if (!isValid(word)) { word = "0"; } return new Version(word); } catch (Throwable ex) { LOGGER.log(Level.WARNING, null, ex); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } } } return null; } Code Sample 2: public static String getHashedPassword(String password) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); BigInteger hashedInt = new BigInteger(1, digest.digest()); return String.format("%1$032X", hashedInt); } catch (NoSuchAlgorithmException nsae) { System.err.println(nsae.getMessage()); } return ""; }
00
Code Sample 1: protected N save(String sql, Object[] args) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); this.setParameters(pstmt, args); pstmt.executeUpdate(); conn.commit(); conn.setAutoCommit(true); rs = pstmt.getGeneratedKeys(); return (N) rs.getObject(1); } catch (SQLException e) { try { if (conn != null) { conn.rollback(); conn.setAutoCommit(true); } } catch (SQLException ex) { ex.printStackTrace(); } throw new JdbcDaoException(e.getMessage(), e); } finally { JdbcUtils.free(rs, pstmt, conn); } } Code Sample 2: public boolean copier(String source, String nomFichierSource, java.io.File destination) { boolean resultat = false; OutputStream tmpOut; try { tmpOut = new BufferedOutputStream(new FileOutputStream(nomFichierSource + "001.tmp")); InputStream is = getClass().getResourceAsStream(source + nomFichierSource); int i; while ((i = is.read()) != -1) tmpOut.write(i); tmpOut.close(); is.close(); } catch (IOException ex) { ex.printStackTrace(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(new File(nomFichierSource + "001.tmp")).getChannel(); out = new FileOutputStream(destination).getChannel(); in.transferTo(0, in.size(), out); resultat = true; } catch (java.io.FileNotFoundException f) { } catch (java.io.IOException e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } new File(nomFichierSource + "001.tmp").delete(); return (resultat); }
11
Code Sample 1: public void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; Closer c = new Closer(); try { source = c.register(new FileInputStream(sourceFile).getChannel()); destination = c.register(new FileOutputStream(destFile).getChannel()); destination.transferFrom(source, 0, source.size()); } catch (IOException e) { c.doNotThrow(); throw e; } finally { c.closeAll(); } } Code Sample 2: @Test public void testCopy_inputStreamToWriter() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); }
11
Code Sample 1: @Test public void testCopy_inputStreamToWriter_Encoding_nullEncoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer, null); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public String login() { String authSuccess = "false"; try { String errorMesg = ""; int error; if ((error = utils.stringIsNull(passwd)) != -1) { errorMesg += rb.getString("passwdField") + ": " + utils.errors[error] + " "; } else if ((error = utils.stringIsEmpty(passwd)) != -1) { errorMesg += rb.getString("passwdField") + ": " + utils.errors[error] + " "; } if ((error = utils.stringIsNull(login)) != -1) { errorMesg += rb.getString("loginField") + ": " + utils.errors[error] + " "; } else if ((error = utils.stringIsEmpty(login)) != -1) { errorMesg += rb.getString("loginField") + ": " + utils.errors[error] + " "; } String[] admins = conf.getProperty("admin").split("\\s"); boolean admin = false; for (int i = 0; i < admins.length; i++) { if (admins[i].equals(login)) { admin = true; } } if (!admin) { errorMesg += rb.getString("noAdmin"); session.invalidate(); } else { session.setAttribute("conf", conf); } if (errorMesg.length() > 0) { status = errorMesg; System.out.println(status); FacesContext context = FacesContext.getCurrentInstance(); context.renderResponse(); } else { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(passwd.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { String hex = Integer.toHexString(0xFF & result[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } authSuccess = (sqlManager.getPassword(login).equals(hexString.toString())) ? "true" : "false"; if (authSuccess.equals("false")) session.invalidate(); } } catch (NoSuchAlgorithmException nsae) { utils.catchExp(nsae); status = utils.getStatus(); if (stacktrace) { stackTrace = utils.getStackTrace(); } FacesContext.getCurrentInstance().renderResponse(); } catch (SQLException sqle) { utils.catchExp(sqle); status = utils.getStatus(); if (stacktrace) { stackTrace = utils.getStackTrace(); } FacesContext.getCurrentInstance().renderResponse(); } return authSuccess; } Code Sample 2: public RobotList<Percentage> sort_decr_Percentage(RobotList<Percentage> list, String field) { int length = list.size(); Index_value[] distri = new Index_value[length]; for (int i = 0; i < length; i++) { distri[i] = new Index_value(i, list.get(i).percent); } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (distri[i].value < distri[i + 1].value) { Index_value a = distri[i]; distri[i] = distri[i + 1]; distri[i + 1] = a; permut = true; } } } while (permut); RobotList<Percentage> sol = new RobotList<Percentage>(Percentage.class); for (int i = 0; i < length; i++) { sol.addLast(new Percentage(distri[i].value)); } return sol; }
11
Code Sample 1: public static void zip() throws Exception { System.out.println("zip()"); ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(new File("/zip/myzip.zip"))); ZipEntry entry = new ZipEntry("asdf.script"); zipout.putNextEntry(entry); byte buffer[] = new byte[BLOCKSIZE]; FileInputStream in = new FileInputStream(new File("/zip/asdf.script")); for (int length; (length = in.read(buffer, 0, BLOCKSIZE)) != -1; ) zipout.write(buffer, 0, length); in.close(); zipout.closeEntry(); zipout.close(); } Code Sample 2: boolean copyFileStructure(File oldFile, File newFile) { if (oldFile == null || newFile == null) return false; File searchFile = newFile; do { if (oldFile.equals(searchFile)) return false; searchFile = searchFile.getParentFile(); } while (searchFile != null); if (oldFile.isDirectory()) { if (progressDialog != null) { progressDialog.setDetailFile(oldFile, ProgressDialog.COPY); } if (simulateOnly) { } else { if (!newFile.mkdirs()) return false; } File[] subFiles = oldFile.listFiles(); if (subFiles != null) { if (progressDialog != null) { progressDialog.addWorkUnits(subFiles.length); } for (int i = 0; i < subFiles.length; i++) { File oldSubFile = subFiles[i]; File newSubFile = new File(newFile, oldSubFile.getName()); if (!copyFileStructure(oldSubFile, newSubFile)) return false; if (progressDialog != null) { progressDialog.addProgress(1); if (progressDialog.isCancelled()) return false; } } } } else { if (simulateOnly) { } else { FileReader in = null; FileWriter out = null; try { in = new FileReader(oldFile); out = new FileWriter(newFile); int count; while ((count = in.read()) != -1) out.write(count); } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { return false; } } } } return true; }
11
Code Sample 1: private void copy(File fromFile, File toFile) throws IOException { String fromFileName = fromFile.getName(); File tmpFile = new File(fromFileName); String toFileName = toFile.getName(); if (!tmpFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!tmpFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!tmpFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(tmpFile); File toF = new File(toFile.getCanonicalPath()); if (!toF.exists()) ; toF.createNewFile(); if (!SBCMain.DEBUG_MODE) to = new FileOutputStream(toFile); else to = new FileOutputStream(toF); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: public static void notify(String msg) throws Exception { String url = "http://api.clickatell.com/http/sendmsg?"; url = add(url, "user", user); url = add(url, "password", password); url = add(url, "api_id", apiId); url = add(url, "to", to); url = add(url, "text", msg); URL u = new URL(url); URLConnection c = u.openConnection(); InputStream is = c.getInputStream(); IOUtils.copy(is, System.out); IOUtils.closeQuietly(is); System.out.println(); }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public static List importSymbol(Report report, Symbol symbol, TradingDate startDate, TradingDate endDate) throws IOException { List quotes = new ArrayList(); String URLString = constructURL(symbol, startDate, endDate); QuoteFilter filter = new YahooQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { Quote quote = filter.toQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("YAHOO") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); throw new IOException(); } catch (ConnectException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); throw new IOException(); } catch (UnknownHostException e) { DesktopManager.showErrorMessage(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); throw new IOException(); } catch (NoRouteToHostException e) { DesktopManager.showErrorMessage(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); throw new IOException(); } catch (MalformedURLException e) { DesktopManager.showErrorMessage(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); throw new IOException(); } catch (FileNotFoundException e) { report.addError(Locale.getString("YAHOO") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + Locale.getString("NO_QUOTES_FOUND")); } catch (IOException e) { DesktopManager.showErrorMessage(Locale.getString("ERROR_DOWNLOADING_QUOTES")); throw new IOException(); } return quotes; }
11
Code Sample 1: public FileBean create(MimeTypeBean mimeType, SanBean san) throws SQLException { long fileId = 0; DataSource ds = getDataSource(DEFAULT_DATASOURCE); Connection conn = ds.getConnection(); try { conn.setAutoCommit(false); Statement stmt = conn.createStatement(); stmt.execute(NEXT_FILE_ID); ResultSet rs = stmt.getResultSet(); while (rs.next()) { fileId = rs.getLong(NEXTVAL); } PreparedStatement pstmt = conn.prepareStatement(INSERT_FILE); pstmt.setLong(1, fileId); pstmt.setLong(2, mimeType.getId()); pstmt.setLong(3, san.getId()); pstmt.setLong(4, WORKFLOW_ATTENTE_VALIDATION); int nbrow = pstmt.executeUpdate(); if (nbrow == 0) { throw new SQLException(); } conn.commit(); closeRessources(conn, pstmt); } catch (SQLException e) { log.error("Can't FileDAOImpl.create " + e.getMessage()); conn.rollback(); throw e; } FileBean fileBean = new FileBean(); return fileBean; } Code Sample 2: public int commit() throws TransactionException, SQLException, ConnectionFactoryException { Connection conn = ConnectionFactoryProxy.getInstance().getConnection(_poolName); conn.setAutoCommit(false); int numRowsUpdated = 0; try { Iterator statements = _statements.iterator(); while (statements.hasNext()) { StatementData sd = (StatementData) statements.next(); PreparedStatement ps = conn.prepareStatement(sd.statement); Iterator params = sd.params.iterator(); int index = 1; while (params.hasNext()) { ps.setString(index++, (String) params.next()); } numRowsUpdated += ps.executeUpdate(); } conn.commit(); } catch (SQLException ex) { System.err.println("com.zenark.zsql.TransactionImpl.commit() failed: Queued Statements follow"); Iterator statements = _statements.iterator(); while (statements.hasNext()) { StatementData sd = (StatementData) statements.next(); System.err.println("+--Statement: " + sd.statement + " with " + sd.params.size() + " parameters"); for (int loop = 0; loop < sd.params.size(); loop++) { System.err.println("+--Param : " + (String) sd.params.get(loop)); } } throw ex; } finally { _statements.clear(); conn.rollback(); conn.clearWarnings(); ConnectionFactoryProxy.getInstance().releaseConnection(conn); } return numRowsUpdated; }
11
Code Sample 1: public static void copyFile(File source, File dest) { try { FileChannel in = new FileInputStream(source).getChannel(); if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); FileChannel out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static void copyFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
11
Code Sample 1: public synchronized String encrypt(String plaintext) throws SystemUnavailableException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new SystemUnavailableException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new SystemUnavailableException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: private String hash(String clearPassword) { if (salt == 0) return null; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(salt); md.update(saltString.getBytes()); md.update(clearPassword.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString(); return digestStr; }
00
Code Sample 1: protected byte[] retrieveImageData() throws IOException { URL url = new URL(imageUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int fileSize = connection.getContentLength(); if (fileSize < 0) { return null; } byte[] imageData = new byte[fileSize]; BufferedInputStream istream = new BufferedInputStream(connection.getInputStream(), 8192); int bytesRead = 0; int offset = 0; while (bytesRead != -1 && offset < fileSize) { bytesRead = istream.read(imageData, offset, fileSize - offset); offset += bytesRead; } istream.close(); connection.disconnect(); return imageData; } Code Sample 2: public String getWebPage(String url) { String content = ""; URL urlObj = null; try { urlObj = new URL(url); } catch (MalformedURLException urlEx) { urlEx.printStackTrace(); throw new Error("URL creation failed."); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(urlObj.openStream())); String line; while ((line = reader.readLine()) != null) { content += line; } } catch (IOException e) { e.printStackTrace(); throw new Error("Page retrieval failed."); } return content; }
11
Code Sample 1: public static void copyFile(String f_in, String f_out, boolean remove) throws FileNotFoundException, IOException { if (remove) { PogoString readcode = new PogoString(PogoUtil.readFile(f_in)); readcode = PogoUtil.removeLogMessages(readcode); PogoUtil.writeFile(f_out, readcode.str); } else { FileInputStream fid = new FileInputStream(f_in); FileOutputStream fidout = new FileOutputStream(f_out); int nb = fid.available(); byte[] inStr = new byte[nb]; if (fid.read(inStr) > 0) fidout.write(inStr); fid.close(); fidout.close(); } } Code Sample 2: public static void encryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); }
00
Code Sample 1: public static void copyFile(File from, File to) { try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[1024 * 16]; int read = 0; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public void createTableIfNotExisting(Connection conn) throws SQLException { String sql = "select * from " + tableName; PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); ps.executeQuery(); } catch (SQLException sqle) { ps.close(); sql = "create table " + tableName + " ( tableName varchar(255) not null primary key, " + " lastId numeric(18) not null)"; ps = conn.prepareStatement(sql); ps.executeUpdate(); } finally { ps.close(); try { if (!conn.getAutoCommit()) conn.commit(); } catch (Exception e) { conn.rollback(); } } }
00
Code Sample 1: @Override public String execute() throws Exception { SystemContext sc = getSystemContext(); if (sc.getExpireTime() == -1) { return LOGIN; } else if (upload != null) { try { Enterprise e = LicenceUtils.get(upload); sc.setEnterpriseName(e.getEnterpriseName()); sc.setExpireTime(e.getExpireTime()); String webPath = ServletActionContext.getServletContext().getRealPath("/"); File desFile = new File(webPath, LicenceUtils.LICENCE_FILE_NAME); FileChannel sourceChannel = new FileInputStream(upload).getChannel(); FileChannel destinationChannel = new FileOutputStream(desFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); return LOGIN; } catch (Exception e) { } } return "license"; } Code Sample 2: public static void main(String[] args) throws Exception { String urlString = "http://php.tech.sina.com.cn/download/d_load.php?d_id=7877&down_id=151542"; urlString = EncodeUtils.encodeURL(urlString); URL url = new URL(urlString); System.out.println("第一次:" + url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); Map req = conn.getRequestProperties(); System.out.println("第一次请求头:"); printMap(req); conn.connect(); System.out.println("第一次响应:"); System.out.println(conn.getResponseMessage()); int code = conn.getResponseCode(); System.out.println("第一次code:" + code); printMap(conn.getHeaderFields()); System.out.println(conn.getURL().getFile()); if (code == 404 && !(conn.getURL() + "").equals(urlString)) { System.out.println(conn.getURL()); String tmp = URLEncoder.encode(conn.getURL().toString(), "gbk"); System.out.println(URLEncoder.encode("在线音乐播放脚本", "GBK")); System.out.println(tmp); url = new URL(tmp); System.out.println("第二次:" + url); conn = (HttpURLConnection) url.openConnection(); System.out.println("第二次响应:"); System.out.println("code:" + code); printMap(conn.getHeaderFields()); } }
11
Code Sample 1: public static void resourceToFile(final String resource, final String filePath) throws IOException { log.debug("Classloader is " + IOCopyUtils.class.getClassLoader()); InputStream in = IOCopyUtils.class.getResourceAsStream(resource); if (in == null) { log.warn("Resource not '" + resource + "' found. Try to prefix with '/'"); in = IOCopyUtils.class.getResourceAsStream("/" + resource); } if (in == null) { throw new IOException("Resource not '" + resource + "' found."); } final File file = new File(filePath); final OutputStream out = FileUtils.openOutputStream(file); final int bytes = IOUtils.copy(in, out); IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); log.debug("Copied resource '" + resource + "' to file " + filePath + " (" + bytes + " bytes)"); } Code Sample 2: public static void copy(String sourceName, String destName) throws IOException { File src = new File(sourceName); File dest = new File(destName); BufferedInputStream source = null; BufferedOutputStream destination = null; byte[] buffer; int bytes_read; long byteCount = 0; if (!src.exists()) throw new IOException("Source not found: " + src); if (!src.canRead()) throw new IOException("Source is unreadable: " + src); if (src.isFile()) { if (!dest.exists()) { File parentdir = parent(dest); if (!parentdir.exists()) parentdir.mkdir(); } else if (dest.isDirectory()) { if (src.isDirectory()) dest = new File(dest + File.separator + src); else dest = new File(dest + File.separator + src.getName()); } } else if (src.isDirectory()) { if (dest.isFile()) throw new IOException("Cannot copy directory " + src + " to file " + dest); if (!dest.exists()) dest.mkdir(); } if ((!dest.canWrite()) && (dest.exists())) throw new IOException("Destination is unwriteable: " + dest); if (src.isFile()) { try { source = new BufferedInputStream(new FileInputStream(src)); destination = new BufferedOutputStream(new FileOutputStream(dest)); buffer = new byte[4096]; byteCount = 0; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } else if (src.isDirectory()) { String targetfile, target, targetdest; String[] files = src.list(); for (int i = 0; i < files.length; i++) { targetfile = files[i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File(target)).isDirectory()) { copy(new File(target).getCanonicalPath(), new File(targetdest).getCanonicalPath()); } else { try { byteCount = 0; source = new BufferedInputStream(new FileInputStream(target)); destination = new BufferedOutputStream(new FileOutputStream(targetdest)); buffer = new byte[4096]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } } } }
00
Code Sample 1: public static String encryptStringWithSHA2(String input) { String output = null; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(input.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } output = sb.toString(); return output; } Code Sample 2: public void command() { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(dir)); int returnVal = chooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { filename = chooser.getSelectedFile().getAbsolutePath(); String f2 = ""; for (int i = 0; i < filename.length(); ++i) { if (filename.charAt(i) != '\\') { f2 = f2 + filename.charAt(i); } else f2 = f2 + '/'; } filename = f2; if (filename.contains(dir)) { filename = filename.substring(dir.length()); } else { try { FileChannel srcFile = new FileInputStream(filename).getChannel(); FileChannel dstFile; filename = "ueditor_files/" + chooser.getSelectedFile().getName(); File newFile; if (!(newFile = new File(dir + filename)).createNewFile()) { dstFile = new FileInputStream(dir + filename).getChannel(); newFile = null; } else { dstFile = new FileOutputStream(newFile).getChannel(); } dstFile.transferFrom(srcFile, 0, srcFile.size()); srcFile.close(); dstFile.close(); System.out.println("file copyed to: " + dir + filename); } catch (Exception e) { e.printStackTrace(); label.setIcon(InputText.iconX); filename = null; for (Group g : groups) { g.updateValidity(true); } return; } } label.setIcon(InputText.iconV); for (Group g : groups) { g.updateValidity(true); } } }
00
Code Sample 1: public FTPUtil(final String server) { log.debug("~ftp.FTPUtil() : Creating object"); ftpClient = new FTPClient(); try { ftpClient.connect(server); ftpClient.login("anonymous", ""); ftpClient.setConnectTimeout(120000); ftpClient.setSoTimeout(120000); final int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { final String errMsg = "Non-positive completion connecting FTPClient"; log.warn("~ftp.FTPUtil() : [" + errMsg + "]"); } } catch (IOException ioe) { final String errMsg = "Cannot connect and login to ftpClient [" + ioe.getMessage() + "]"; log.warn("~ftp.FTPUtil() : [" + errMsg + "]"); ioe.printStackTrace(); } } Code Sample 2: public static String digest(String ha1, String ha2, String nonce) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(ha1, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(nonce, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(ha2, ISO_8859_1)); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } }
00
Code Sample 1: protected void downloadFile(String filename, java.io.File targetFile, File partFile, ProgressMonitor monitor) throws java.io.IOException { FileOutputStream out = null; InputStream is = null; try { filename = toCanonicalFilename(filename); URL url = new URL(root + filename.substring(1)); URLConnection urlc = url.openConnection(); int i = urlc.getContentLength(); monitor.setTaskSize(i); out = new FileOutputStream(partFile); is = urlc.getInputStream(); monitor.started(); copyStream(is, out, monitor); monitor.finished(); out.close(); is.close(); if (!partFile.renameTo(targetFile)) { throw new IllegalArgumentException("unable to rename " + partFile + " to " + targetFile); } } catch (IOException e) { if (out != null) out.close(); if (is != null) is.close(); if (partFile.exists() && !partFile.delete()) { throw new IllegalArgumentException("unable to delete " + partFile); } throw e; } } Code Sample 2: protected void doBackupOrganizeTypeRelation() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strSelQuery = "SELECT parent_organize_type,child_organize_type " + "FROM " + Common.ORGANIZE_TYPE_RELATION_TABLE; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_RELATION_B_TABLE + " " + "(version_no,parent_organize_type,child_organize_type) " + "VALUES (?,?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strSelQuery); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setInt(1, this.versionNO); ps.setString(2, result.getString("parent_organize_type")); ps.setString(3, result.getString("child_organize_type")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeTypeRelation(): ERROR Inserting data " + "in T_SYS_ORGANIZE_TYPE_RELATION_B INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeTypeRelation(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doBackupOrganizeTypeRelation(): SQLException while committing or rollback"); } }
00
Code Sample 1: private String send(String method, String contentType, String urlStr, String body) throws MalformedURLException, IOException { HttpURLConnection postCon = (HttpURLConnection) new URL(getUrl(urlStr)).openConnection(); postCon.setRequestMethod(method); postCon.setDoOutput(true); postCon.setDoInput(true); if (cookie != null) { postCon.setRequestProperty("Cookie", cookie); if (contentType != null) { postCon.setRequestProperty("Content-type", contentType); } postCon.setRequestProperty("Content-Length", body == null ? "0" : Integer.toString(body.length())); } if (body != null) { OutputStream os = postCon.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(os); out.write(body); out.close(); } InputStream is = null; try { is = postCon.getInputStream(); } catch (IOException ioe) { is = postCon.getErrorStream(); } int resCode = postCon.getResponseCode(); if (resCode == 201 || resCode == 202) { String loc = postCon.getHeaderField("Location"); System.out.println("loc:" + loc); return loc; } StringBuffer sb = StreamUtil.readStream(is); return sb.toString(); } Code Sample 2: public void guardarCantidad() { try { String can = String.valueOf(cantidadArchivos); File archivo = new File("cantidadArchivos.txt"); FileWriter fw = new FileWriter(archivo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter salida = new PrintWriter(bw); salida.print(can); salida.close(); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("cantidadArchivos.zip"); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[buffer]; File f = new File("cantidadArchivos.txt"); FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, buffer); ZipEntry entry = new ZipEntry("cantidadArchivos.txt"); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, buffer)) != -1) out.write(data, 0, count); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
11
Code Sample 1: public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel source = null; FileChannel destination = null; try { source = (inStream = new FileInputStream(sourceFile)).getChannel(); destination = (outStream = new FileOutputStream(destFile)).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { closeIO(source); closeIO(inStream); closeIO(destination); closeIO(outStream); } } Code Sample 2: public TapdocContextImpl(Registry registry, FileObject javaDom, List<String> javadocLinks, List<String> libraryLocations, FileObject outputDirectory, List<String> tapdocLinks, DocumentGenerator documentGenerator) { this.registry = registry; this.documentGenerator = documentGenerator; try { if (javaDom == null) { javaDom = outputDirectory.resolveFile("tapdoc-javadom.xml"); } if (!javaDom.exists()) { javaDom.createFile(); javaDom.close(); IOUtils.copy(new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?><tapdoc-javadom></tapdoc-javadom>"), javaDom.getContent().getOutputStream()); } this.javaDom = javaDom; this.javadocLinks = javadocLinks; this.tapdocLinks = tapdocLinks; this.libraryLocations = libraryLocations; this.outputDirectory = outputDirectory; } catch (Exception e) { throw new RuntimeException(e); } }
00
Code Sample 1: public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpClientInfo clientInfo = HttpUtil.parseClientInfo((HttpServletRequest) request); if (request.getParameter("_debug_") != null) { StringBuffer buffer = new StringBuffer(); Enumeration iter = request.getHeaderNames(); while (iter.hasMoreElements()) { String name = (String) iter.nextElement(); buffer.append(name + "=" + request.getHeader(name)).append("\n"); } buffer.append("\n"); iter = request.getParameterNames(); while (iter.hasMoreElements()) { String name = (String) iter.nextElement(); String value = request.getParameter(name); if (!"ISO-8859-1".equalsIgnoreCase(clientInfo.getPreferCharset())) value = new String(value.getBytes("ISO-8859-1"), clientInfo.getPreferCharset()); buffer.append(name).append("=").append(value).append("\n"); } response.setContentType("text/plain; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(buffer.toString()); return null; } Object resultObj = handleRequest(request); if (resultObj == null) { String requestException = (String) request.getAttribute("XSMP.handleRequest.Exception"); if (requestException != null) response.sendError(500, requestException); else response.setContentLength(0); } else { if (resultObj instanceof DataHandler) { response.setContentType(((DataHandler) resultObj).getContentType()); response.setContentLength(((DataHandler) resultObj).getInputStream().available()); IOUtils.copy(((DataHandler) resultObj).getInputStream(), response.getOutputStream()); } else { String temp = resultObj.toString(); if (temp.startsWith("<") && temp.endsWith(">")) response.setContentType("text/html; charset=" + clientInfo.getPreferCharset()); else response.setContentType("text/plain; charset=" + clientInfo.getPreferCharset()); byte[] buffer = temp.getBytes(clientInfo.getPreferCharset()); response.setContentLength(buffer.length); response.getOutputStream().write(buffer); } } return null; } Code Sample 2: void loadListFile(String listFileName, String majorType, String minorType, String languages, String annotationType) throws MalformedURLException, IOException { Lookup defaultLookup = new Lookup(listFileName, majorType, minorType, languages, annotationType); URL lurl = new URL(listsURL, listFileName); BufferedReader listReader = new BomStrippingInputStreamReader(lurl.openStream(), encoding); String line; int lines = 0; while (null != (line = listReader.readLine())) { GazetteerNode node = new GazetteerNode(line, unescapedSeparator, false); Lookup lookup = defaultLookup; Map<String, String> fm = node.getFeatureMap(); if (fm != null && fm.size() > 0) { lookup = new Lookup(listFileName, majorType, minorType, languages, annotationType); Set<String> keyset = fm.keySet(); if (keyset.size() <= 4) { Map<String, String> newfm = null; for (String key : keyset) { if (key.equals("majorType")) { String tmp = fm.get("majorType"); if (canonicalizeStrings) { tmp.intern(); } lookup.majorType = tmp; } else if (key.equals("minorType")) { String tmp = fm.get("minorType"); if (canonicalizeStrings) { tmp.intern(); } lookup.minorType = tmp; } else if (key.equals("languages")) { String tmp = fm.get("languages"); if (canonicalizeStrings) { tmp.intern(); } lookup.languages = tmp; } else if (key.equals("annotationType")) { String tmp = fm.get("annotationType"); if (canonicalizeStrings) { tmp.intern(); } lookup.annotationType = tmp; } else { if (newfm == null) { newfm = new HashMap<String, String>(); } String tmp = fm.get(key); if (canonicalizeStrings) { tmp.intern(); } newfm.put(key, tmp); } } if (newfm != null) { lookup.features = newfm; } } else { if (canonicalizeStrings) { for (String key : fm.keySet()) { String tmp = fm.get(key); tmp.intern(); fm.put(key, tmp); } } lookup.features = fm; } } addLookup(node.getEntry(), lookup); lines++; } logger.debug("Lines read: " + lines); }
00
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 = secureRandom.nextLong(); } else { rand = random.nextLong(); } sbValueBeforeMD5.append(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: private InputStream getPart() throws IOException { HttpGet get = new HttpGet(url); get.addHeader("Range", "bytes=" + startAt + "-"); HttpResponse res = client.execute(get); System.out.println("requesting kBs from " + startAt + " server reply:" + res.getStatusLine()); if (res.getStatusLine().getStatusCode() == 403 || res.getStatusLine().toString().toLowerCase().contains("forbidden")) { get.abort(); get = new HttpGet(url); get.addHeader("Range", "bytes=" + startAt + "-" + (startAt + downLimit)); res = client.execute(get); System.out.println("Again requesting from kBs " + startAt + " server reply:" + res.getStatusLine()); startAt += downLimit; } else { complete = true; } return res.getEntity() == null ? null : res.getEntity().getContent(); }
11
Code Sample 1: public synchronized AbstractBaseObject update(AbstractBaseObject obj) throws ApplicationException { PreparedStatement preStat = null; StringBuffer sqlStat = new StringBuffer(); MailSetting tmpMailSetting = (MailSetting) ((MailSetting) obj).clone(); synchronized (dbConn) { try { int updateCnt = 0; Timestamp currTime = Utility.getCurrentTimestamp(); sqlStat.append("UPDATE MAIL_SETTING "); sqlStat.append("SET USER_RECORD_ID=?, PROFILE_NAME=?, MAIL_SERVER_TYPE=?, DISPLAY_NAME=?, EMAIL_ADDRESS=?, REMEMBER_PWD_FLAG=?, SPA_LOGIN_FLAG=?, INCOMING_SERVER_HOST=?, INCOMING_SERVER_PORT=?, INCOMING_SERVER_LOGIN_NAME=?, INCOMING_SERVER_LOGIN_PWD=?, OUTGOING_SERVER_HOST=?, OUTGOING_SERVER_PORT=?, OUTGOING_SERVER_LOGIN_NAME=?, OUTGOING_SERVER_LOGIN_PWD=?, PARAMETER_1=?, PARAMETER_2=?, PARAMETER_3=?, PARAMETER_4=?, PARAMETER_5=?, UPDATE_COUNT=?, UPDATER_ID=?, UPDATE_DATE=? "); sqlStat.append("WHERE ID=? AND UPDATE_COUNT=? "); preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); setPrepareStatement(preStat, 1, tmpMailSetting.getUserRecordID()); setPrepareStatement(preStat, 2, tmpMailSetting.getProfileName()); setPrepareStatement(preStat, 3, tmpMailSetting.getMailServerType()); setPrepareStatement(preStat, 4, tmpMailSetting.getDisplayName()); setPrepareStatement(preStat, 5, tmpMailSetting.getEmailAddress()); setPrepareStatement(preStat, 6, tmpMailSetting.getRememberPwdFlag()); setPrepareStatement(preStat, 7, tmpMailSetting.getSpaLoginFlag()); setPrepareStatement(preStat, 8, tmpMailSetting.getIncomingServerHost()); setPrepareStatement(preStat, 9, tmpMailSetting.getIncomingServerPort()); setPrepareStatement(preStat, 10, tmpMailSetting.getIncomingServerLoginName()); setPrepareStatement(preStat, 11, tmpMailSetting.getIncomingServerLoginPwd()); setPrepareStatement(preStat, 12, tmpMailSetting.getOutgoingServerHost()); setPrepareStatement(preStat, 13, tmpMailSetting.getOutgoingServerPort()); setPrepareStatement(preStat, 14, tmpMailSetting.getOutgoingServerLoginName()); setPrepareStatement(preStat, 15, tmpMailSetting.getOutgoingServerLoginPwd()); setPrepareStatement(preStat, 16, tmpMailSetting.getParameter1()); setPrepareStatement(preStat, 17, tmpMailSetting.getParameter2()); setPrepareStatement(preStat, 18, tmpMailSetting.getParameter3()); setPrepareStatement(preStat, 19, tmpMailSetting.getParameter4()); setPrepareStatement(preStat, 20, tmpMailSetting.getParameter5()); setPrepareStatement(preStat, 21, new Integer(tmpMailSetting.getUpdateCount().intValue() + 1)); setPrepareStatement(preStat, 22, sessionContainer.getUserRecordID()); setPrepareStatement(preStat, 23, currTime); setPrepareStatement(preStat, 24, tmpMailSetting.getID()); setPrepareStatement(preStat, 25, tmpMailSetting.getUpdateCount()); updateCnt = preStat.executeUpdate(); dbConn.commit(); if (updateCnt == 0) { throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR); } else { tmpMailSetting.setUpdaterID(sessionContainer.getUserRecordID()); tmpMailSetting.setUpdateDate(currTime); tmpMailSetting.setUpdateCount(new Integer(tmpMailSetting.getUpdateCount().intValue() + 1)); tmpMailSetting.setCreatorName(UserInfoFactory.getUserFullName(tmpMailSetting.getCreatorID())); tmpMailSetting.setUpdaterName(UserInfoFactory.getUserFullName(tmpMailSetting.getUpdaterID())); return (tmpMailSetting); } } catch (Exception e) { try { dbConn.rollback(); } catch (Exception ex) { } log.error(e, e); throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR, e); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } } } Code Sample 2: @Override public String resolveItem(String oldJpgFsPath) throws DatabaseException { if (oldJpgFsPath == null || "".equals(oldJpgFsPath)) throw new NullPointerException("oldJpgFsPath"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } PreparedStatement statement = null; String ret = null; try { statement = getConnection().prepareStatement(SELECT_ITEM_STATEMENT); statement.setString(1, oldJpgFsPath); ResultSet rs = statement.executeQuery(); int i = 0; int id = -1; int rowsAffected = 0; while (rs.next()) { id = rs.getInt("id"); ret = rs.getString("imageFile"); i++; } if (id != -1 && new File(ret).exists()) { statement = getConnection().prepareStatement(UPDATE_ITEM_STATEMENT); statement.setInt(1, id); rowsAffected = statement.executeUpdate(); } else { return null; } if (rowsAffected == 1) { getConnection().commit(); LOGGER.debug("DB has been updated."); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback!"); } } catch (SQLException e) { LOGGER.error(e); } finally { closeConnection(); } return ret; }
00
Code Sample 1: public void readHTMLFromURL(URL url) throws IOException { InputStream in = url.openStream(); try { readHTMLFromStream(new InputStreamReader(in)); } finally { try { in.close(); } catch (IOException ex) { Logger.getLogger(HTMLTextAreaModel.class.getName()).log(Level.SEVERE, "Exception while closing InputStream", ex); } } } Code Sample 2: public void testDecode1000BinaryStore() throws Exception { EXISchema corpus = EXISchemaFactoryTestUtil.getEXISchema("/DataStore/DataStore.xsd", getClass(), m_compilerErrors); Assert.assertEquals(0, m_compilerErrors.getTotalCount()); GrammarCache grammarCache = new GrammarCache(corpus, GrammarOptions.STRICT_OPTIONS); String[] base64Values100 = { "R0lGODdhWALCov////T09M7Ozqampn19fVZWVi0tLQUFBSxYAsJAA/8Iutz+MMpJq7046827/2Ao\n", "/9j/4BBKRklGAQEBASwBLP/hGlZFeGlmTU0qF5ZOSUtPTiBDT1JQT1JBVElPTk5J", "R0lGODlhHh73KSkpOTk5QkJCSkpKUlJSWlpaY2Nja2trc3Nze3t7hISEjIyMlJSUnJycpaWlra2t\n" + "tbW1vb29xsbGzs7O1tbW3t7e5+fn7+/v//////////8=", "/9j/4BBKRklGAQEBAf/bQwYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBc=", "R0lGODlhHh73M2aZzP8zMzNmM5kzzDP/M2YzZmZmmWbM", "/9j/4BBKRklGAQEBAf/bQwYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsj\n" + "HBYWICwgIyYnKSopGR8tMC0oMCUoKSj/20M=", "R0lGODdhWAK+ov////j4+NTU1JOTk0tLSx8fHwkJCSxYAr5AA/8IMkzjrEEmahy23SpC", "R0lGODdh4QIpAncJIf4aU29mdHdhcmU6IE1pY3Jvc29mdCBPZmZpY2Us4QIpAof//////8z//5n/\n", "R0lGODdhWAK+ov////v7++fn58DAwI6Ojl5eXjExMQMDAyxYAr5AA/8Iutz+MMpJq7046827/2Ao\n" + "jmRpnmiqPsKxvg==", "R0lGODdh4QIpAncJIf4aU29mdHdhcmU6IE1pY3Jvc29mdCBPZmZpY2Us4QIpAob//////8z//5n/\nzP//zMw=" }; AlignmentType alignment = AlignmentType.bitPacked; Transmogrifier encoder = new Transmogrifier(); encoder.setEXISchema(grammarCache); encoder.setAlignmentType(alignment); ByteArrayOutputStream baos = new ByteArrayOutputStream(); encoder.setOutputStream(baos); URL url = resolveSystemIdAsURL("/DataStore/instance/1000BinaryStore.xml"); encoder.encode(new InputSource(url.openStream())); byte[] bts = baos.toByteArray(); Scanner scanner; int n_texts; EXIDecoder decoder = new EXIDecoder(999); decoder.setEXISchema(grammarCache); decoder.setAlignmentType(alignment); decoder.setInputStream(new ByteArrayInputStream(bts)); scanner = decoder.processHeader(); EXIEvent exiEvent; n_texts = 0; while ((exiEvent = scanner.nextEvent()) != null) { if (exiEvent.getEventVariety() == EXIEvent.EVENT_CH) { if (++n_texts % 100 == 0) { String expected = base64Values100[(n_texts / 100) - 1]; String val = exiEvent.getCharacters().makeString(); Assert.assertEquals(expected, val); } } } Assert.assertEquals(1000, n_texts); }
00
Code Sample 1: public static String sha1(String clearText, String seed) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update((seed + clearText).getBytes()); return convertToHex(md.digest()); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } Code Sample 2: public void executeUpdate(Native nativeResource) throws Exception { Connection con = null; boolean autoCommit = true; PreparedStatement st = null; try { HrRecord hr = getRepository(); ManagedConnection mc = returnConnection(); con = mc.getJdbcConnection(); autoCommit = con.getAutoCommit(); con.setAutoCommit(false); String sql = ""; boolean isUpdate = false; String sUuid = ""; boolean finableBeforeUpdate = false; if (UuidUtil.isUuid(hr.getUuid())) { sUuid = hr.getUuid(); finableBeforeUpdate = queryFindable(con); sql = createUpdateSQL(); st = con.prepareStatement(sql); isUpdate = true; } else { sUuid = UuidUtil.makeUuid(true); finableBeforeUpdate = hr.getFindable(); sql = createInsertSQL(); st = con.prepareStatement(sql); } if (hr.getOwnerId() < 0) { hr.setOwnerId(getOwner().getLocalID()); } int n = 1; st.setInt(n++, hr.getOwnerId()); st.setTimestamp(n++, makeTimestamp(hr.getInputDate())); st.setTimestamp(n++, makeTimestamp(hr.getUpdateDate())); st.setString(n++, hr.getName()); st.setString(n++, hr.getHostUrl()); st.setString(n++, hr.getHarvestFrequency().toString()); st.setString(n++, Boolean.toString(hr.getSendNotification())); st.setString(n++, hr.getProtocol().getKind().toLowerCase()); st.setString(n++, ProtocolSerializer.toXmlString(hr.getProtocol())); st.setString(n++, PublicationMethod.registration.name()); if (!isUpdate) { if (getRequestContext().getApplicationConfiguration().getHarvesterConfiguration().getResourceAutoApprove()) { st.setString(n++, ApprovalStatus.approved.name()); } else { st.setString(n++, ApprovalStatus.posted.name()); } } st.setString(n++, Boolean.toString(hr.getSearchable())); st.setString(n++, Boolean.toString(hr.getSynchronizable())); st.setString(n++, sUuid); logExpression(sql); int nRowCount = st.executeUpdate(); getActionResult().setNumberOfRecordsModified(nRowCount); if (!isUpdate && nRowCount == 1) { closeStatement(st); st = con.prepareStatement("SELECT ID FROM " + getHarvestingTableName() + " WHERE UPPER(DOCUUID)=?"); st.setString(1, sUuid.toUpperCase()); ResultSet genKeys = st.executeQuery(); genKeys.next(); int nLocalId = genKeys.getInt(1); hr.setLocalId(nLocalId); hr.setUuid(sUuid); closeResultSet(genKeys); } con.commit(); if (nativeResource != null || (isUpdate && finableBeforeUpdate != hr.getFindable())) { try { if (nativeResource == null && isUpdate) { nativeResource = queryNative(con); } if (nativeResource != null) { String content = nativeResource.getContent(); String sourceUri = nativeResource.getSourceUri().asString(); Publisher publisher = createPublisherOfRepository(); PublicationRequest publicationRequest = createPublicationRequest(publisher, content, sourceUri); publicationRequest.publish(); } } catch (Exception ex) { LOGGER.log(Level.INFO, "Unable to create resource definition.", ex); } } Harvester harvestEngine = getRequestContext().getApplicationContext().getHarvestingEngine(); if (_repository.getIsHarvestDue()) { harvestEngine.submit(getRequestContext(), _repository, null, _repository.getLastSyncDate()); } harvestEngine.reselect(); } catch (Exception ex) { if (con != null) { con.rollback(); } throw ex; } finally { closeStatement(st); if (con != null) { con.setAutoCommit(autoCommit); } } }
00
Code Sample 1: private static String loadUrlToString(String a_url) throws IOException { URL l_url1 = new URL(a_url); BufferedReader br = new BufferedReader(new InputStreamReader(l_url1.openStream())); String l_content = ""; String l_ligne = null; l_content = br.readLine(); while ((l_ligne = br.readLine()) != null) { l_content += AA.SL + l_ligne; } return l_content; } Code Sample 2: private void writeToUrl(byte[] data, String url) throws IOException, MalformedURLException { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); OutputStream out = connection.getOutputStream(); out.write(data); out.flush(); out.close(); }
11
Code Sample 1: @Override public Class<?> loadClass(final String name) throws ClassNotFoundException { final String baseName = StringUtils.substringBefore(name, "$"); if (baseName.startsWith("java") && !whitelist.contains(baseName) && !additionalWhitelist.contains(baseName)) { throw new NoClassDefFoundError(name + " is a restricted class for GAE"); } if (!name.startsWith("com.gargoylesoftware")) { return super.loadClass(name); } super.loadClass(name); final InputStream is = getResourceAsStream(name.replaceAll("\\.", "/") + ".class"); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { IOUtils.copy(is, bos); final byte[] bytes = bos.toByteArray(); return defineClass(name, bytes, 0, bytes.length); } catch (final IOException e) { throw new RuntimeException(e); } } Code Sample 2: private void writeInputStreamToFile(InputStream stream, File file) { try { FileOutputStream fOut = new FileOutputStream(file); IOUtils.copy(stream, fOut); fOut.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public File createWindow(String pdfUrl) { URL url; InputStream is; try { int fileLength = 0; String str; if (pdfUrl.startsWith("jar:/")) { str = "file.pdf"; is = this.getClass().getResourceAsStream(pdfUrl.substring(4)); } else { url = new URL(pdfUrl); is = url.openStream(); str = url.getPath().substring(url.getPath().lastIndexOf('/') + 1); fileLength = url.openConnection().getContentLength(); } final String filename = str; tempURLFile = File.createTempFile(filename.substring(0, filename.lastIndexOf('.')), filename.substring(filename.lastIndexOf('.')), new File(ObjectStore.temp_dir)); FileOutputStream fos = new FileOutputStream(tempURLFile); if (visible) { download.setLocation((coords.x - (download.getWidth() / 2)), (coords.y - (download.getHeight() / 2))); download.setVisible(true); } if (visible) { pb.setMinimum(0); pb.setMaximum(fileLength); String message = Messages.getMessage("PageLayoutViewMenu.DownloadWindowMessage"); message = message.replaceAll("FILENAME", filename); downloadFile.setText(message); Font f = turnOff.getFont(); turnOff.setFont(new Font(f.getName(), f.getStyle(), 8)); turnOff.setAlignmentY(JLabel.RIGHT_ALIGNMENT); turnOff.setText(Messages.getMessage("PageLayoutViewMenu.DownloadWindowTurnOff")); } byte[] buffer = new byte[4096]; int read; int current = 0; String rate = "kb"; int mod = 1000; if (fileLength > 1000000) { rate = "mb"; mod = 1000000; } if (visible) { progress = Messages.getMessage("PageLayoutViewMenu.DownloadWindowProgress"); if (fileLength < 1000000) progress = progress.replaceAll("DVALUE", (fileLength / mod) + " " + rate); else { String fraction = String.valueOf(((fileLength % mod) / 10000)); if (((fileLength % mod) / 10000) < 10) fraction = "0" + fraction; progress = progress.replaceAll("DVALUE", (fileLength / mod) + "." + fraction + " " + rate); } } while ((read = is.read(buffer)) != -1) { current = current + read; downloadCount = downloadCount + read; if (visible) { if (fileLength < 1000000) downloadMessage.setText(progress.replaceAll("DSOME", (current / mod) + " " + rate)); else { String fraction = String.valueOf(((current % mod) / 10000)); if (((current % mod) / 10000) < 10) fraction = "0" + fraction; downloadMessage.setText(progress.replaceAll("DSOME", (current / mod) + "." + fraction + " " + rate)); } pb.setValue(current); download.repaint(); } fos.write(buffer, 0, read); } fos.flush(); is.close(); fos.close(); if (visible) downloadMessage.setText("Download of " + filename + " is complete."); } catch (Exception e) { LogWriter.writeLog("[PDF] Exception " + e + " opening URL " + pdfUrl); e.printStackTrace(); } if (visible) download.setVisible(false); return tempURLFile; } Code Sample 2: public String post() { if (content == null || content.equals("")) return "Type something to publish!!"; OutputStreamWriter wr = null; BufferedReader rd = null; try { String data = URLEncoder.encode("api", "UTF-8") + "=" + URLEncoder.encode(apiKey, "UTF-8"); data += "&" + URLEncoder.encode("content", "UTF-8") + "=" + URLEncoder.encode(content, "UTF-8"); data += "&" + URLEncoder.encode("description", "UTF-8") + "=" + URLEncoder.encode(descriptionTextArea.getText() + description_suffix, "UTF-8"); data += "&" + URLEncoder.encode("expiry", "UTF-8") + "=" + URLEncoder.encode((String) expiryComboBox.getSelectedItem(), "UTF-8"); data += "&" + URLEncoder.encode("type", "UTF-8") + "=" + URLEncoder.encode(type, "UTF-8"); data += "&" + URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(nameTextBox.getText(), "UTF-8"); URL url = new URL("http://pastebin.ca/quiet-paste.php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; line = rd.readLine(); if (line == null || line.length() < 8 || !line.substring(0, 8).equals("SUCCESS:")) return "Unknown error in publishing the post"; else return "*Publish successful.! The link to your post is.: " + "http://pastebin.ca/" + line.substring(8); } catch (IOException ex) { return "Unable to connect to http://pastebin.ca/\nPlease check your internet connection"; } finally { try { if (wr != null) wr.close(); if (rd != null) rd.close(); } catch (IOException ex) { } } }
00
Code Sample 1: public static void copyFile(File source, File target) throws Exception { if (source == null || target == null) { throw new IllegalArgumentException("The arguments may not be null."); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dtnChannel = new FileOutputStream(target).getChannel(); srcChannel.transferTo(0, srcChannel.size(), dtnChannel); srcChannel.close(); dtnChannel.close(); } catch (Exception e) { String message = "Unable to copy file '" + source.getName() + "' to '" + target.getName() + "'."; logger.error(message, e); throw new Exception(message, e); } } Code Sample 2: public static void readTestData(String getDkpUrl) throws Exception { final URL url = new URL(getDkpUrl); final InputStream is = url.openStream(); try { final LineNumberReader rd = new LineNumberReader(new BufferedReader(new InputStreamReader(is))); String line = rd.readLine(); while (line != null) { System.out.println(line); line = rd.readLine(); } } finally { is.close(); } }
00
Code Sample 1: public void addGames(List<Game> games) throws StadiumException, SQLException { Connection conn = ConnectionManager.getManager().getConnection(); conn.setAutoCommit(false); PreparedStatement stm = null; ResultSet rs = null; try { for (Game game : games) { stm = conn.prepareStatement(Statements.SELECT_STADIUM); stm.setString(1, game.getStadiumName()); stm.setString(2, game.getStadiumCity()); rs = stm.executeQuery(); int stadiumId = -1; while (rs.next()) { stadiumId = rs.getInt("stadiumID"); } if (stadiumId == -1) throw new StadiumException("No such stadium"); stm = conn.prepareStatement(Statements.INSERT_GAME); stm.setInt(1, stadiumId); stm.setDate(2, game.getGameDate()); stm.setTime(3, game.getGameTime()); stm.setString(4, game.getTeamA()); stm.setString(5, game.getTeamB()); stm.executeUpdate(); int gameId = getMaxId(); List<SectorPrice> sectorPrices = game.getSectorPrices(); for (SectorPrice price : sectorPrices) { stm = conn.prepareStatement(Statements.INSERT_TICKET_PRICE); stm.setInt(1, gameId); stm.setInt(2, price.getSectorId()); stm.setInt(3, price.getPrice()); stm.executeUpdate(); } } } catch (SQLException e) { conn.rollback(); throw e; } finally { rs.close(); stm.close(); } conn.commit(); conn.setAutoCommit(true); } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: private void copyFile(String sourceFilename, String targetFilename) throws IOException { File source = new File(sourceFilename); File target = new File(targetFilename); InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(target); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public stock(String ticker) { try { URL url = new URL("http://finance.yahoo.com/q?s=" + ticker + "&d=v1"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; StringBuffer page = new StringBuffer(8192); while ((line = reader.readLine()) != null) { page.append(line); } LispInterpreter lisp = InterpreterFactory.getInterpreter(); lisp.eval("(load \"nregex\")"); String quote = lisp.eval("(second (regex \"<b>([0-9][0-9]\\.[0-9][0-9])</b>\" \"" + cleanse(page) + "\"))"); System.out.println("Current quote: " + quote); lisp.exit(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: protected static void copyFile(File from, File to) throws IOException { if (!from.isFile() || !to.isFile()) { throw new IOException("Both parameters must be files. from is " + from.isFile() + ", to is " + to.isFile()); } FileChannel in = (new FileInputStream(from)).getChannel(); FileChannel out = (new FileOutputStream(to)).getChannel(); in.transferTo(0, from.length(), out); in.close(); out.close(); }
00
Code Sample 1: public void removeUserFromRealm(final List<NewUser> users) { try { connection.setAutoCommit(false); final List<Integer> removeFromNullRealm = (List<Integer>) new ProcessEnvelope().executeObject(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public Object executeProcessReturnObject() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("realm.removeUser")); Iterator<NewUser> iter = users.iterator(); NewUser user; int realmId; Iterator<Integer> iter2; List<Integer> removeFromNullRealm = new ArrayList<Integer>(); while (iter.hasNext()) { user = iter.next(); psImpl.setInt(1, user.userId); iter2 = user.realmIds.iterator(); while (iter2.hasNext()) { realmId = iter2.next(); if (realmId == 0) { removeFromNullRealm.add(user.userId); continue; } psImpl.setInt(2, realmId); psImpl.executeUpdate(); } cmDB.removeUser(user.userId); } return removeFromNullRealm; } }); if (!removeFromNullRealm.isEmpty()) { new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("realm.removeUserFromNullRealm")); Iterator<Integer> iter2 = removeFromNullRealm.iterator(); while (iter2.hasNext()) { psImpl.setInt(1, iter2.next()); psImpl.executeUpdate(); } } }); } connection.commit(); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } } Code Sample 2: private static void userAuth(String challenge) throws IOException { try { MessageDigest md = MessageDigest.getInstance("BrokenMD4"); String passwd = null; if (System.getProperty("jarsync.password.gui") != null) { JPasswordField pass = new JPasswordField(); JPanel panel = new JPanel(new GridLayout(2, 1)); panel.add(new JLabel("Password:")); panel.add(pass); JOptionPane.showMessageDialog(null, panel, remoteUser + '@' + remoteHost + "'s Password", JOptionPane.QUESTION_MESSAGE); passwd = new String(pass.getPassword()); } else { System.out.print(remoteUser + '@' + remoteHost + "'s password: "); passwd = Util.readLine(System.in); System.out.println(); } md.update(new byte[4]); md.update(passwd.getBytes("US-ASCII")); md.update(challenge.getBytes("US-ASCII")); byte[] response = md.digest(); Util.writeASCII(out, remoteUser + " " + Util.base64(response) + '\n'); out.flush(); } catch (NoSuchAlgorithmException nsae) { throw new IOException("could not create message digest."); } }
00
Code Sample 1: public void playSIDFromHVSC(String name) { player.reset(); player.setStatus("Loading song: " + name); URL url; try { if (name.startsWith("/")) { name = name.substring(1); } url = getResource(hvscBase + name); if (player.readSID(url.openConnection().getInputStream())) { player.playSID(); } } catch (IOException ioe) { System.out.println("Could not load: "); ioe.printStackTrace(); player.setStatus("Could not load SID: " + ioe.getMessage()); } } Code Sample 2: private static String connect(String apiURL, boolean secure) throws IOException { String baseUrl; if (secure) baseUrl = "https://todoist.com/API/"; else baseUrl = "http://todoist.com/API/"; URL url = new URL(baseUrl + apiURL); URLConnection c = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream())); StringBuilder toReturn = new StringBuilder(""); String toAppend; while ((toAppend = in.readLine()) != null) toReturn.append(toAppend); return toReturn.toString(); }
00
Code Sample 1: protected String getPostRequestContent(String urlText, String postParam) throws Exception { URL url = new URL(urlText); HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); String line = null; try { urlcon.setRequestMethod("POST"); urlcon.setUseCaches(false); urlcon.setDoOutput(true); PrintStream ps = new PrintStream(urlcon.getOutputStream()); ps.print(postParam); ps.close(); urlcon.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream())); line = reader.readLine(); reader.close(); } finally { urlcon.disconnect(); } return line; } Code Sample 2: private void startOpening(final URL url) { final WebAccessor wa = this; openerThread = new Thread() { public void run() { iStream = null; try { tryProxy = false; URLConnection connection = url.openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection htc = (HttpURLConnection) connection; contentLength = htc.getContentLength(); } InputStream i = connection.getInputStream(); iStream = new LoggedInputStream(i, wa); } catch (ConnectException x) { tryProxy = true; exception = x; } catch (Exception x) { exception = x; } finally { if (dialog != null) { Thread.yield(); dialog.setVisible(false); } } } }; openerThread.start(); }
00
Code Sample 1: public static String getBiopaxId(Reaction reaction) { String id = null; if (reaction.getId() > Reaction.NO_ID_ASSIGNED) { id = reaction.getId().toString(); } else { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(reaction.getTextualRepresentation().getBytes()); byte[] digestBytes = md.digest(); StringBuilder digesterSb = new StringBuilder(32); for (int i = 0; i < digestBytes.length; i++) { int intValue = digestBytes[i] & 0xFF; if (intValue < 0x10) digesterSb.append('0'); digesterSb.append(Integer.toHexString(intValue)); } id = digesterSb.toString(); } catch (NoSuchAlgorithmException e) { } } return id; } 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(); }
00
Code Sample 1: public static synchronized String encrypt(String plaintext) throws SinaduraCoreException { MessageDigest md = null; String hash = null; try { md = MessageDigest.getInstance("SHA"); try { md.update(plaintext.getBytes(CHARSET_UTF8)); } catch (UnsupportedEncodingException e) { throw new SinaduraCoreException(e.getMessage(), e); } byte raw[] = md.digest(); hash = (new BASE64Encoder()).encode(raw); } catch (NoSuchAlgorithmException e) { throw new SinaduraCoreException(e.getMessage(), e); } return hash; } Code Sample 2: @Override public void parse() throws IOException { URL url = new URL(getDataUrl()); URLConnection con = url.openConnection(); BufferedReader bStream = new BufferedReader(new InputStreamReader(con.getInputStream())); String s = bStream.readLine(); String[] tokens = s.split("</html>"); tokens = tokens[1].split("<br>"); for (String sToken : tokens) { String[] sTokens = sToken.split(";"); CurrencyUnit unit = new CurrencyUnit(sTokens[4], Float.valueOf(sTokens[9]), Integer.valueOf(sTokens[5])); this.set.add(unit); } }
00
Code Sample 1: private void callbackWS(String xmlControl, String ws_results, long docId) { SimpleProvider config; Service service; Object ret; Call call; Object[] parameter; String method; String wsurl; URL url; NodeList delegateNodes; Node actualNode; InputSource xmlcontrolstream; try { xmlcontrolstream = new InputSource(new StringReader(xmlControl)); delegateNodes = SimpleXMLParser.parseDocument(xmlcontrolstream, AgentBehaviour.XML_CALLBACK); actualNode = delegateNodes.item(0); wsurl = SimpleXMLParser.findChildEntry(actualNode, AgentBehaviour.XML_URL); method = SimpleXMLParser.findChildEntry(actualNode, AgentBehaviour.XML_METHOD); if (wsurl == null || method == null) { System.out.println("----- Did not get method or wsurl from the properties! -----"); return; } url = new java.net.URL(wsurl); try { url.openConnection().connect(); } catch (IOException ex) { System.out.println("----- Could not connect to the webservice! -----"); } Vector v_param = new Vector(); v_param.add(ws_results); v_param.add(new Long(docId)); parameter = v_param.toArray(); config = new SimpleProvider(); config.deployTransport("http", new HTTPSender()); service = new Service(config); call = (Call) service.createCall(); call.setTargetEndpointAddress(url); call.setOperationName(new QName("http://schemas.xmlsoap.org/soap/encoding/", method)); try { ret = call.invoke(parameter); if (ret == null) { ret = new String("No response from callback function!"); } System.out.println("Callback function returned: " + ret); } catch (RemoteException ex) { System.out.println("----- Could not invoke the method! -----"); } } catch (Exception ex) { ex.printStackTrace(System.err); } } Code Sample 2: public static String encrypt(String password) throws NoSuchAlgorithmException { java.security.MessageDigest d = null; d = java.security.MessageDigest.getInstance("MD5"); d.reset(); d.update(password.getBytes()); byte[] cr = d.digest(); return getString(cr).toLowerCase(); }
11
Code Sample 1: public static boolean copyFile(File from, File to, byte[] buf) { if (buf == null) buf = new byte[BUFFER_SIZE]; FileInputStream from_s = null; FileOutputStream to_s = null; try { from_s = new FileInputStream(from); to_s = new FileOutputStream(to); for (int bytesRead = from_s.read(buf); bytesRead != -1; bytesRead = from_s.read(buf)) to_s.write(buf, 0, bytesRead); from_s.close(); from_s = null; to_s.getFD().sync(); to_s.close(); to_s = null; } catch (IOException ioe) { return false; } finally { if (from_s != null) { try { from_s.close(); } catch (IOException ioe) { } } if (to_s != null) { try { to_s.close(); } catch (IOException ioe) { } } } return true; } Code Sample 2: @Override protected void copy(InputStream inputs, OutputStream outputs) throws IOException { if (outputs == null) { throw new NullPointerException(); } if (inputs == null) { throw new NullPointerException(); } ZipOutputStream zipoutputs = null; try { zipoutputs = new ZipOutputStream(outputs); zipoutputs.putNextEntry(new ZipEntry("default")); IOUtils.copy(inputs, zipoutputs); } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (zipoutputs != null) { zipoutputs.close(); } if (inputs != null) { inputs.close(); } } }
11
Code Sample 1: @Override public void send() { BufferedReader in = null; StringBuffer result = new StringBuffer(); try { URL url = new URL(getUrl()); in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { result.append(str); } } catch (ConnectException ce) { logger.error("MockupExecutableCommand excute fail: " + ce.getMessage()); } catch (Exception e) { logger.error("MockupExecutableCommand excute fail: " + e.getMessage()); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("BufferedReader could not be closed", e); } } } } Code Sample 2: private void initialize() { List providers = new ArrayList(); while (this.urls.hasMoreElements()) { URL url = (URL) this.urls.nextElement(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { String provider = uncommentLine(line).trim(); if (provider != null && provider.length() > 0) { providers.add(provider); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } this.iterator = providers.iterator(); }
11
Code Sample 1: public Writer createWriter(File outfile, String encoding) throws UnsupportedEncodingException, IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outfile)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot; ZipInputStream zis = new ZipInputStream(new FileInputStream(infile)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); return new OutputStreamWriter(zos, "UTF-8"); } Code Sample 2: public static void copyfile(String src, String dst) throws IOException { dst = new File(dst).getAbsolutePath(); new File(new File(dst).getParent()).mkdirs(); FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }