label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public void render(final HttpServletRequest request, final HttpServletResponse response, InputStream inputStream, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } IOUtils.copy(inputStream, response.getOutputStream()); } Code Sample 2: private void trySend(Primitive p) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { mSerializer.serialize(p, out); } catch (SerializerException e) { mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.SERIALIZER_ERROR, "Internal serializer error, primitive: " + p.getType()); out.close(); return; } HttpPost req = new HttpPost(mPostUri); req.addHeader(mContentTypeHeader); if (mMsisdnHeader != null) { req.addHeader(mMsisdnHeader); } ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray()); req.setEntity(entity); mLastActive = SystemClock.elapsedRealtime(); if (Log.isLoggable(ImpsLog.TAG, Log.DEBUG)) { long sendBytes = entity.getContentLength() + 176; ImpsLog.log(mConnection.getLoginUserName() + " >> " + p.getType() + " HTTP payload approx. " + sendBytes + " bytes"); } if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) { ImpsLog.dumpRawPacket(out.toByteArray()); ImpsLog.dumpPrimitive(p); } HttpResponse res = mHttpClient.execute(req); StatusLine statusLine = res.getStatusLine(); HttpEntity resEntity = res.getEntity(); InputStream in = resEntity.getContent(); if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) { Log.d(ImpsLog.PACKET_TAG, statusLine.toString()); Header[] headers = res.getAllHeaders(); for (Header h : headers) { Log.d(ImpsLog.PACKET_TAG, h.toString()); } int len = (int) resEntity.getContentLength(); if (len > 0) { byte[] content = new byte[len]; int offset = 0; int bytesRead = 0; do { bytesRead = in.read(content, offset, len); offset += bytesRead; len -= bytesRead; } while (bytesRead > 0); in.close(); ImpsLog.dumpRawPacket(content); in = new ByteArrayInputStream(content); } } try { if (statusLine.getStatusCode() != HttpURLConnection.HTTP_OK) { mTxManager.notifyErrorResponse(p.getTransactionID(), statusLine.getStatusCode(), statusLine.getReasonPhrase()); return; } if (resEntity.getContentLength() == 0) { if ((p.getTransactionMode() != TransactionMode.Response) && !p.getType().equals(ImpsTags.Polling_Request)) { mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.ILLEGAL_SERVER_RESPONSE, "bad response from server"); } return; } Primitive response = mParser.parse(in); if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) { ImpsLog.dumpPrimitive(response); } if (Log.isLoggable(ImpsLog.TAG, Log.DEBUG)) { long len = 2 + resEntity.getContentLength() + statusLine.toString().length() + 2; Header[] headers = res.getAllHeaders(); for (Header header : headers) { len += header.getName().length() + header.getValue().length() + 4; } ImpsLog.log(mConnection.getLoginUserName() + " << " + response.getType() + " HTTP payload approx. " + len + "bytes"); } if (!mReceiveQueue.offer(response)) { mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.UNKNOWN_ERROR, "receiving queue full"); } } catch (ParserException e) { ImpsLog.logError(e); mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.PARSER_ERROR, "Parser error, received a bad response from server"); } finally { resEntity.consumeContent(); } }
00
Code Sample 1: private void setInlineXML(Entry entry, DatastreamXMLMetadata ds) throws UnsupportedEncodingException, StreamIOException { String content; if (m_obj.hasContentModel(Models.SERVICE_DEPLOYMENT_3_0) && (ds.DatastreamID.equals("SERVICE-PROFILE") || ds.DatastreamID.equals("WSDL"))) { content = DOTranslationUtility.normalizeInlineXML(new String(ds.xmlContent, m_encoding), m_transContext); } else { content = new String(ds.xmlContent, m_encoding); } if (m_format.equals(ATOM_ZIP1_1)) { String name = ds.DSVersionID + ".xml"; try { m_zout.putNextEntry(new ZipEntry(name)); InputStream is = new ByteArrayInputStream(content.getBytes(m_encoding)); IOUtils.copy(is, m_zout); m_zout.closeEntry(); is.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); entry.setSummary(ds.DSVersionID); entry.setContent(iri, ds.DSMIME); } else { entry.setContent(content, ds.DSMIME); } } Code Sample 2: public static Book GetReviewsForBook(String bookId, int page, int rating) throws Exception { Uri.Builder builder = new Uri.Builder(); builder.scheme("http"); builder.authority("www.goodreads.com"); builder.path("book/show"); builder.appendQueryParameter("key", _ConsumerKey); builder.appendQueryParameter("page", Integer.toString(page)); builder.appendQueryParameter("rating", Integer.toString(rating)); builder.appendQueryParameter("id", bookId); HttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(builder.build().toString()); if (get_IsAuthenticated()) { _Consumer.sign(getRequest); } HttpResponse response = httpClient.execute(getRequest); Response responseData = ResponseParser.parse(response.getEntity().getContent()); return responseData.get_Book(); }
00
Code Sample 1: public static void copyFile(File from, File to) throws FileNotFoundException, IOException { requireFile(from); requireFile(to); if (to.isDirectory()) { to = new File(to, getFileName(from)); } FileChannel sourceChannel = new FileInputStream(from).getChannel(); FileChannel destinationChannel = new FileOutputStream(to).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: @Override public Object init() throws Exception { if (url != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); ClassLoader parent = getClass().getClassLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); Class groovyClass = loader.parseClass(new File(url.getFile())); groovyObject = (GroovyObject) groovyClass.newInstance(); reader.close(); initDeclaredMethods(); return groovyObject; } else return null; }
11
Code Sample 1: protected static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); URLConnection c = url.openConnection(); c.setConnectTimeout(2000); IOUtils.copy(c.getInputStream(), output); return output.toString(); } Code Sample 2: public void _saveWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user, String subcmd) throws WebAssetException, Exception { long maxsize = 50; long maxwidth = 3000; long maxheight = 3000; long minheight = 10; ActionRequestImpl reqImpl = (ActionRequestImpl) req; HttpServletRequest httpReq = reqImpl.getHttpServletRequest(); try { UploadPortletRequest uploadReq = PortalUtil.getUploadPortletRequest(req); String parent = ParamUtil.getString(req, "parent"); int countFiles = ParamUtil.getInteger(req, "countFiles"); int fileCounter = 0; Folder folder = (Folder) InodeFactory.getInode(parent, Folder.class); _checkUserPermissions(folder, user, PERMISSION_WRITE); String userId = user.getUserId(); String customMessage = "Some file does not match the filters specified by the folder: "; boolean filterError = false; for (int k = 0; k < countFiles; k++) { File file = new File(); String title = ParamUtil.getString(req, "title" + k); String friendlyName = ParamUtil.getString(req, "friendlyName" + k); Date publishDate = new Date(); String fileName = ParamUtil.getString(req, "fileName" + k); fileName = checkMACFileName(fileName); if (!FolderFactory.matchFilter(folder, fileName)) { customMessage += fileName + ", "; filterError = true; continue; } if (fileName.length() > 0) { String mimeType = FileFactory.getMimeType(fileName); String URI = folder.getPath() + fileName; String suffix = UtilMethods.getFileExtension(fileName); file.setTitle(title); file.setFileName(fileName); file.setFriendlyName(friendlyName); file.setPublishDate(publishDate); file.setModUser(userId); InodeFactory.saveInode(file); String filePath = FileFactory.getRealAssetsRootPath(); new java.io.File(filePath).mkdir(); java.io.File uploadedFile = uploadReq.getFile("uploadedFile" + k); Logger.debug(this, "bytes" + uploadedFile.length()); file.setSize((int) uploadedFile.length() - 2); file.setMimeType(mimeType); Host host = HostFactory.getCurrentHost(httpReq); Identifier ident = IdentifierFactory.getIdentifierByURI(URI, host); String message = ""; if ((FileFactory.existsFileName(folder, fileName))) { InodeFactory.deleteInode(file); message = "The uploaded file " + fileName + " already exists in this folder"; SessionMessages.add(req, "custommessage", message); } else { String fileInodePath = String.valueOf(file.getInode()); if (fileInodePath.length() == 1) { fileInodePath = fileInodePath + "0"; } fileInodePath = fileInodePath.substring(0, 1) + java.io.File.separator + fileInodePath.substring(1, 2); new java.io.File(filePath + java.io.File.separator + fileInodePath.substring(0, 1)).mkdir(); new java.io.File(filePath + java.io.File.separator + fileInodePath).mkdir(); java.io.File f = new java.io.File(filePath + java.io.File.separator + fileInodePath + java.io.File.separator + file.getInode() + "." + suffix); java.io.FileOutputStream fout = new java.io.FileOutputStream(f); FileChannel outputChannel = fout.getChannel(); FileChannel inputChannel = new java.io.FileInputStream(uploadedFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); outputChannel.force(false); outputChannel.close(); inputChannel.close(); Logger.debug(this, "SaveFileAction New File in =" + filePath + java.io.File.separator + fileInodePath + java.io.File.separator + file.getInode() + "." + suffix); if (suffix.equals("jpg") || suffix.equals("gif")) { com.dotmarketing.util.Thumbnail.resizeImage(filePath + java.io.File.separator + fileInodePath + java.io.File.separator, String.valueOf(file.getInode()), suffix); int height = javax.imageio.ImageIO.read(f).getHeight(); file.setHeight(height); Logger.debug(this, "File height=" + height); int width = javax.imageio.ImageIO.read(f).getWidth(); file.setWidth(width); Logger.debug(this, "File width=" + width); long size = (f.length() / 1024); WebAssetFactory.createAsset(file, userId, folder); } else { WebAssetFactory.createAsset(file, userId, folder); } WorkingCache.addToWorkingAssetToCache(file); _setFilePermissions(folder, file, user); fileCounter += 1; if ((subcmd != null) && subcmd.equals(com.dotmarketing.util.Constants.PUBLISH)) { try { PublishFactory.publishAsset(file, httpReq); if (fileCounter > 1) { SessionMessages.add(req, "message", "message.file_asset.save"); } else { SessionMessages.add(req, "message", "message.fileupload.save"); } } catch (WebAssetException wax) { Logger.error(this, wax.getMessage(), wax); SessionMessages.add(req, "error", "message.webasset.published.failed"); } } } } } if (filterError) { customMessage = customMessage.substring(0, customMessage.lastIndexOf(",")); SessionMessages.add(req, "custommessage", customMessage); } } catch (IOException e) { Logger.error(this, "Exception saving file: " + e.getMessage()); throw new ActionException(e.getMessage()); } }
11
Code Sample 1: private byte[] streamToBytes(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); } return out.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(); } }
11
Code Sample 1: private String fetchCompareContent() throws IOException { URL url = new URL(compareTo); StringWriter sw = new StringWriter(); IOUtils.copy(url.openStream(), sw); return sw.getBuffer().toString(); } Code Sample 2: public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("camel/exec-context.xml"); CamelContext context = appContext.getBean(CamelContext.class); Exchange exchange = new DefaultExchange(context); List<String> arg = new ArrayList<String>(); arg.add("/home/sumit/derby.log"); arg.add("helios:cameltesting/"); exchange.getIn().setHeader(ExecBinding.EXEC_COMMAND_ARGS, arg); Exchange res = context.createProducerTemplate().send("direct:input", exchange); ExecResult result = (ExecResult) res.getIn().getBody(); System.out.println(result.getExitValue()); System.out.println(result.getCommand()); if (result.getStderr() != null) { IOUtils.copy(result.getStderr(), new FileOutputStream(new File("/home/sumit/error.log"))); } if (result.getStdout() != null) { IOUtils.copy(result.getStdout(), new FileOutputStream(new File("/home/sumit/out.log"))); } appContext.close(); }
11
Code Sample 1: private File Gzip(File f) throws IOException { if (f == null || !f.exists()) return null; File dest_dir = f.getParentFile(); String dest_filename = f.getName() + ".gz"; File zipfile = new File(dest_dir, dest_filename); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(zipfile)); FileInputStream in = new FileInputStream(f); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.finish(); try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } try { f.delete(); } catch (Exception e) { } return zipfile; } Code Sample 2: private void stripOneFilex(File inFile, File outFile) throws IOException { StreamTokenizer reader = new StreamTokenizer(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); reader.slashSlashComments(false); reader.slashStarComments(false); reader.eolIsSignificant(true); int token; while ((token = reader.nextToken()) != StreamTokenizer.TT_EOF) { switch(token) { case StreamTokenizer.TT_NUMBER: throw new IllegalStateException("didn't expect TT_NUMBER: " + reader.nval); case StreamTokenizer.TT_WORD: System.out.print(reader.sval); writer.write("WORD:" + reader.sval, 0, reader.sval.length()); default: char outChar = (char) reader.ttype; System.out.print(outChar); writer.write(outChar); } } }
00
Code Sample 1: private static String getDigestPassword(String streamId, String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw (RuntimeException) new IllegalStateException().initCause(e); } md.update((streamId + password).getBytes()); byte[] uid = md.digest(); int length = uid.length; StringBuilder digPass = new StringBuilder(); for (int i = 0; i < length; ) { int k = uid[i++]; int iint = k & 0xff; String buf = Integer.toHexString(iint); if (buf.length() == 1) { buf = "0" + buf; } digPass.append(buf); } return digPass.toString(); } Code Sample 2: @Test public void testXMLDBURLStreamHandler() { System.out.println("testXMLDBURLStreamHandler"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { URL url = new URL(XMLDB_URL_1); InputStream is = url.openStream(); copyDocument(is, baos); is.close(); } catch (Exception ex) { ex.printStackTrace(); LOG.error(ex); fail(ex.getMessage()); } }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static String MD5(byte[] data) throws NoSuchAlgorithmException, UnsupportedEncodingException { String text = convertToHex(data); MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: private String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); } Code Sample 2: public String preProcessHTML(String uri) { final StringBuffer buf = new StringBuffer(); try { HTMLDocument doc = new HTMLDocument() { public HTMLEditorKit.ParserCallback getReader(int pos) { return new HTMLEditorKit.ParserCallback() { public void handleText(char[] data, int pos) { buf.append(data); buf.append('\n'); } }; } }; URL url = new URI(uri).toURL(); URLConnection conn = url.openConnection(); Reader rd = new InputStreamReader(conn.getInputStream()); new ParserDelegator().parse(rd, doc.getReader(0), Boolean.TRUE); } catch (MalformedURLException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (URISyntaxException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } return buf.toString(); }
11
Code Sample 1: private boolean copy(File in, File out) { try { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); FileChannel readableChannel = fis.getChannel(); FileChannel writableChannel = fos.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); fis.close(); fos.close(); return true; } catch (IOException ioe) { System.out.println("Copy Error: IOException during copy\r\n" + ioe.getMessage()); return false; } } Code Sample 2: public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getName()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getName()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getName()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); 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) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
11
Code Sample 1: protected void zipFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(to)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); } Code Sample 2: public void testOptionalSections() throws Exception { final File implementationDirectory = this.getTestSourcesDirectory(); final File specificationDirectory = this.getTestSourcesDirectory(); IOUtils.copy(this.getClass().getResourceAsStream("ImplementationWithoutConstructorsSection.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("ImplementationWithoutDefaultConstructorSection.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("ImplementationWithoutDocumentationSection.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("ImplementationWithoutLicenseSection.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("SpecificationWithoutDocumentationSection.java.txt"), new FileOutputStream(new File(specificationDirectory, "Specification.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("SpecificationWithoutLicenseSection.java.txt"), new FileOutputStream(new File(specificationDirectory, "Specification.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); }
00
Code Sample 1: public void setContentAsStream(final InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { output.close(); } this.content = output.toByteArray(); } Code Sample 2: static Properties readAllProps(Hashtable<?, ?> env) throws IOException { Properties props = new Properties(); if (env != null) { props = mergProps(props, env); } props = mergSysProps(props, System.getProperties()); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Enumeration<?> resources = classLoader.getResources(jndiProp); while (resources.hasMoreElements()) { URL url = (URL) resources.nextElement(); InputStream fis = url.openStream(); Properties resource = new Properties(); resource.load(fis); fis.close(); props = mergProps(props, resource); } return props; }
11
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: 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(); } }
11
Code Sample 1: public boolean visar() throws SQLException, ClassNotFoundException, Exception { Connection conn = null; PreparedStatement ps = null; Date fechaSystem = new Date(); DateFormat aaaammdd = new SimpleDateFormat("yyyyMMdd"); DateFormat hhmmss = new SimpleDateFormat("HHmmss"); DateFormat sss = new SimpleDateFormat("S"); String ss = sss.format(fechaSystem); if (ss.length() > 2) { ss = ss.substring(0, 2); } boolean visado = false; try { conn = ToolsBD.getConn(); conn.setAutoCommit(false); String sentenciaSql = "UPDATE BZMODIF SET FZJCUSVI=?, FZJFVISA=?, FZJHVISA=?" + ((hayVisadoExtracto) ? ", FZJIEXTR=?" : "") + ((hayVisadoRemitente) ? ", FZJIREMI=?" : "") + " WHERE FZJCENSA='E' AND FZJCAGCO=? AND FZJNUMEN=? AND FZJANOEN=? AND FZJFMODI=? AND FZJHMODI=?"; ps = conn.prepareStatement(sentenciaSql); ps.setString(1, usuarioVisado); ps.setInt(2, Integer.parseInt(aaaammdd.format(fechaSystem))); ps.setInt(3, Integer.parseInt(hhmmss.format(fechaSystem) + ss)); int contador = 4; if (hayVisadoExtracto) { ps.setString(contador++, "X"); } if (hayVisadoRemitente) { ps.setString(contador++, "X"); } ps.setInt(contador++, oficina); ps.setInt(contador++, numeroRegistro); ps.setInt(contador++, anoEntrada); ps.setString(contador++, fechaModificacion); ps.setString(contador++, horaModificacion); int registrosAfectados = ps.executeUpdate(); if (registrosAfectados > 0 && !hayVisadoExtracto && !hayVisadoRemitente) { visado = true; } if (registrosAfectados > 0 && (hayVisadoExtracto || hayVisadoRemitente)) { boolean generado = generarBZVISAD(conn, Integer.parseInt(aaaammdd.format(fechaSystem)), Integer.parseInt(hhmmss.format(fechaSystem) + ss)); if (generado) { visado = actualizarBZENTRA(conn); } String rem = ""; String com = ""; if (hayVisadoRemitente) { if (!remitente.trim().equals("")) { rem = remitente; } else { javax.naming.InitialContext contexto = new javax.naming.InitialContext(); Object ref = contexto.lookup("es.caib.regweb.ValoresHome"); ValoresHome home = (ValoresHome) javax.rmi.PortableRemoteObject.narrow(ref, ValoresHome.class); Valores valor = home.create(); rem = valor.recuperaRemitenteCastellano(entidad1, entidad2 + ""); valor.remove(); } } else { if (!altres.trim().equals("")) { rem = remitente; } else { javax.naming.InitialContext contexto = new javax.naming.InitialContext(); Object ref = contexto.lookup("es.caib.regweb.ValoresHome"); ValoresHome home = (ValoresHome) javax.rmi.PortableRemoteObject.narrow(ref, ValoresHome.class); Valores valor = home.create(); rem = valor.recuperaRemitenteCastellano(entidad1Old, entidad2Old + ""); valor.remove(); } } if (hayVisadoExtracto) { com = extracto; } else { com = comentario; } try { Class t = Class.forName("es.caib.regweb.module.PluginHook"); Class[] partypes = { String.class, Integer.class, Integer.class, Integer.class, Integer.class, String.class, String.class, String.class, Integer.class, Integer.class, String.class, Integer.class, String.class, String.class, Integer.class, Integer.class, Integer.class, String.class, String.class, String.class }; Object[] params = { "V", new Integer(anoEntrada), new Integer(numeroRegistro), new Integer(oficina), new Integer(fechaDocumento), rem, com, tipoDocumento, new Integer(fechaRegistro), new Integer(fzacagge), fora, new Integer(destinatario), idioma, null, null, null, null, null, null, null }; java.lang.reflect.Method metodo = t.getMethod("entrada", partypes); metodo.invoke(null, params); } catch (IllegalAccessException iae) { } catch (IllegalArgumentException iae) { } catch (InvocationTargetException ite) { } catch (NullPointerException npe) { } catch (ExceptionInInitializerError eiie) { } catch (NoSuchMethodException nsme) { } catch (SecurityException se) { } catch (LinkageError le) { } catch (ClassNotFoundException le) { } } conn.commit(); int fzahsis = Integer.parseInt(hhmmss.format(fechaSystem) + ss); String Stringsss = sss.format(fechaSystem); switch(Stringsss.length()) { case (1): Stringsss = "00" + Stringsss; break; case (2): Stringsss = "0" + Stringsss; break; } int horamili = Integer.parseInt(hhmmss.format(fechaSystem) + Stringsss); int fzafsis = Integer.parseInt(aaaammdd.format(fechaSystem)); logLopdBZMODIF("UPDATE", sessioEjb.getCallerPrincipal().getName().toUpperCase(), fzafsis, horamili, 'E', numeroRegistro, anoEntrada, oficina, Integer.parseInt(fechaModificacion), Integer.parseInt(horaModificacion)); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); e.printStackTrace(); visado = false; try { if (conn != null) conn.rollback(); else System.out.println("ERROR: No es pot fer rollback sense connexió!"); } catch (Exception ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } } finally { ToolsBD.closeConn(conn, ps, null); } return visado; } Code Sample 2: private void recvMessage(String from, String to) throws Exception { ConnectionFactoryImpl factory = new ConnectionFactoryImpl(); Receiver receiver = null; ProviderConnection connection = factory.createConnection(from, to); Connection conn = DBUtil.getConnection(); PreparedStatement pstmt = null; ResultSet rs = null; String sql = ""; try { receiver = Receiver.createReceiver(connection); receiver.open(); EXTSSPMessage message = (EXTSSPMessage) receiver.receiveEX(); if (message == null) { System.out.println("no message"); } else { conn.setAutoCommit(false); EXTSSPHeader header = message.getEXHeader(); UUIDHexGenerator u = new UUIDHexGenerator(); String id = u.generate().toString(); pstmt = conn.prepareStatement(drawOutRecvSql(header, id)); pstmt.executeUpdate(); String xml = ""; TSSPBody body = message.getBody(); xml = body.getDomAsString(); xml = xml.replaceAll("ns1:", ""); saveClobMessage(pstmt, conn, rs, xml, id); String notify_id = ""; Iterator iter = message.getAttachments(); while (iter.hasNext()) { AttachmentPart a = (AttachmentPart) iter.next(); String contentId = a.getContentId(); if (contentId.startsWith(Constant.PREFIX_PERSON)) { DataHandler dh = a.getDataHandler(); InputStream is = dh.getInputStream(); byte[] temp = FileCopyUtils.copyToByteArray(is); String content = new String(temp); RecvDto recv = (RecvDto) XStreamConvert.xmlToBean(content); if (recv == null) throw new Exception("接收方信息对象转换错误!请检查存入的信息对象xml字符串是否正确:" + content); if (notify_id.equals("")) { notify_id = u.generate().toString(); header.setType(Constant.MESSAGETYPE_NOTIFY); pstmt = conn.prepareStatement(drawOutRecvSql(header, notify_id)); pstmt.executeUpdate(); String notify_content = header.getNotifyContent(); if (notify_content == null) notify_content = "接收到新的esb消息,但未定义通知消息内容!"; saveClobMessage(pstmt, conn, rs, notify_content, notify_id); } savePersonInfo(pstmt, conn, recv, notify_id); } else { DataHandler dh = a.getDataHandler(); InputStream is = dh.getInputStream(); String attid = u.generate().toString(); sql = "insert into message_recv_attachment(ATTACHMENTID," + "VERSION,MRECVID,BUSS_ID,ATTACHMENT) values('" + attid + "',0,'" + id + "','" + contentId + "',empty_blob())"; pstmt = conn.prepareStatement(sql); pstmt.executeUpdate(); sql = "select attachment from message_recv_attachment" + " where attachmentid = '" + attid + "' for update"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); rs.next(); Blob blob = rs.getBlob(1); OutputStream blobOutputStream = ((oracle.sql.BLOB) blob).getBinaryOutputStream(); FileCopyUtils.copy(is, blobOutputStream); is.close(); blobOutputStream.close(); } } conn.commit(); conn.setAutoCommit(true); } receiver.commit(); } catch (Exception e) { e.printStackTrace(); try { System.out.println("received message, rollback"); if (receiver != null) { receiver.rollback(); } } catch (JAXMException e1) { e1.printStackTrace(); } } finally { DBUtil.close(rs, pstmt, conn); if (receiver != null) { try { receiver.close(); } catch (JAXMException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (JAXMException e) { e.printStackTrace(); } } } }
11
Code Sample 1: public String loadFileContent(final String _resourceURI) { final Lock readLock = this.fileLock.readLock(); final Lock writeLock = this.fileLock.writeLock(); boolean hasReadLock = false; boolean hasWriteLock = false; try { readLock.lock(); hasReadLock = true; if (!this.cachedResources.containsKey(_resourceURI)) { readLock.unlock(); hasReadLock = false; writeLock.lock(); hasWriteLock = true; if (!this.cachedResources.containsKey(_resourceURI)) { final InputStream resourceAsStream = this.getClass().getResourceAsStream(_resourceURI); final StringWriter writer = new StringWriter(); try { IOUtils.copy(resourceAsStream, writer); } catch (final IOException ex) { throw new IllegalStateException("Resource not read-able", ex); } final String loadedResource = writer.toString(); this.cachedResources.put(_resourceURI, loadedResource); } writeLock.unlock(); hasWriteLock = false; readLock.lock(); hasReadLock = true; } return this.cachedResources.get(_resourceURI); } finally { if (hasReadLock) { readLock.unlock(); } if (hasWriteLock) { writeLock.unlock(); } } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public void copyServer(int id) throws Exception { File in = new File("servers" + File.separatorChar + "server_" + id); File serversDir = new File("servers" + File.separatorChar); int newNumber = serversDir.listFiles().length + 1; System.out.println("New File Number: " + newNumber); File out = new File("servers" + File.separatorChar + "server_" + newNumber); FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (Exception e) { e.printStackTrace(); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } getServer(newNumber - 1); } Code Sample 2: public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, NULL_OUTPUT_STREAM); } finally { IOUtils.close(in); } return checksum; }
11
Code Sample 1: public static void copyFile(File sourceFile, File targetFile) throws IOException { FileInputStream iStream = new FileInputStream(sourceFile); FileOutputStream oStream = new FileOutputStream(targetFile); FileChannel inChannel = iStream.getChannel(); FileChannel outChannel = oStream.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { buffer.clear(); int readCount = inChannel.read(buffer); if (readCount == -1) { break; } buffer.flip(); outChannel.write(buffer); } iStream.close(); oStream.close(); } Code Sample 2: public static void downloadFile(HttpServletResponse response, String file) throws IOException { response.setContentType(FileUtils.getContentType(file)); response.setContentLength(FileUtils.getContentLength(file)); response.setHeader("Content-type", ResponseUtils.DOWNLOAD_CONTENT_TYPE); response.setHeader("Content-Disposition", "attachment; filename=\"" + FileUtils.getFileName(file) + "\""); response.setHeader("Content-Length", Integer.toString(FileUtils.getContentLength(file))); InputStream input = new FileInputStream(file); OutputStream output = response.getOutputStream(); IOUtils.copy(input, output, true); }
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 doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } long time = System.currentTimeMillis(); FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size && continueWriting(pos, size)) { count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos); pos += output.transferFrom(input, pos, count); } } finally { output.close(); IOUtils.closeQuietly(fos); input.close(); IOUtils.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { if (DiskManager.isLocked()) throw new IOException("Copy stopped since VtM was working"); else throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } else { time = System.currentTimeMillis() - time; long speed = (destFile.length() / time) / 1000; DiskManager.addDiskSpeed(speed); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
00
Code Sample 1: public void test() throws Exception { StringDocument doc = new StringDocument("Test", "UTF-8"); doc.open(); try { assertEquals("UTF-8", doc.getCharacterEncoding()); assertEquals("Test", doc.getText()); InputStream input = doc.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { writer.close(); } assertEquals("Test", writer.toString()); } finally { doc.close(); } } Code Sample 2: private String getData(String method, String arg) { try { URL url; String str; StringBuilder strBuilder; BufferedReader stream; url = new URL(API_BASE_URL + "/2.1/" + method + "/en/xml/" + API_KEY + "/" + URLEncoder.encode(arg, "UTF-8")); stream = new BufferedReader(new InputStreamReader(url.openStream())); strBuilder = new StringBuilder(); while ((str = stream.readLine()) != null) { strBuilder.append(str); } stream.close(); return strBuilder.toString(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } }
00
Code Sample 1: public static byte[] clearPassToUserPassword(String clearpass, HashAlg alg, byte[] salt) { if (alg == null) { throw new IllegalArgumentException("Invalid hash argorithm."); } try { MessageDigest digester = null; StringBuilder resultInText = new StringBuilder(); switch(alg) { case MD5: resultInText.append("{MD5}"); digester = MessageDigest.getInstance("MD5"); break; case SMD5: resultInText.append("{SMD5}"); digester = MessageDigest.getInstance("MD5"); break; case SHA: resultInText.append("{SHA}"); digester = MessageDigest.getInstance("SHA"); break; case SSHA: resultInText.append("{SSHA}"); digester = MessageDigest.getInstance("SHA"); break; default: break; } digester.reset(); digester.update(clearpass.getBytes(DEFAULT_ENCODING)); byte[] hash = null; if (salt != null && (alg == HashAlg.SMD5 || alg == HashAlg.SSHA)) { digester.update(salt); hash = ArrayUtils.addAll(digester.digest(), salt); } else { hash = digester.digest(); } resultInText.append(new String(Base64.encodeBase64(hash), DEFAULT_ENCODING)); return resultInText.toString().getBytes(DEFAULT_ENCODING); } catch (UnsupportedEncodingException uee) { log.warn("Error occurred while hashing password ", uee); return new byte[0]; } catch (java.security.NoSuchAlgorithmException nse) { log.warn("Error occurred while hashing password ", nse); return new byte[0]; } } Code Sample 2: @Test public void testCopy_readerToOutputStream_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null); fail(); } catch (NullPointerException ex) { } }
11
Code Sample 1: void copyFileOnPeer(String path, RServerInfo peerserver, boolean allowoverwrite) throws IOException { RFile file = new RFile(path); OutputStream out = null; FileInputStream in = null; try { in = fileManager.openFileRead(path); out = localClient.openWrite(file, false, WriteMode.TRANSACTED, 1, peerserver, !allowoverwrite); IOUtils.copyLarge(in, out); out.close(); out = null; } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (out != null) { try { out.close(); } catch (Throwable t) { } } } } Code Sample 2: public static void writeToFile(InputStream input, File file, ProgressListener listener, long length) { OutputStream output = null; try { output = new CountingOutputStream(new FileOutputStream(file), listener, length); IOUtils.copy(input, output); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } }
11
Code Sample 1: private static File copyFileTo(File file, File directory) throws IOException { File newFile = new File(directory, file.getName()); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(file); fos = new FileOutputStream(newFile); byte buff[] = new byte[1024]; int val; while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val); } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } return newFile; } 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: private void copy(File source, File destination) throws PackageException { try { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(destination); byte[] buff = new byte[1024]; int len; while ((len = in.read(buff)) > 0) out.write(buff, 0, len); in.close(); out.close(); } catch (IOException e) { throw new PackageException("Unable to copy " + source.getPath() + " to " + destination.getPath() + " :: " + e.toString()); } } Code Sample 2: void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); }
00
Code Sample 1: public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GUnzip source"); return; } String zipname, source; if (args[0].endsWith(".gz")) { zipname = args[0]; source = args[0].substring(0, args[0].length() - 3); } else { zipname = args[0] + ".gz"; source = args[0]; } GZIPInputStream zipin; try { FileInputStream in = new FileInputStream(zipname); zipin = new GZIPInputStream(in); } catch (IOException e) { System.out.println("Couldn't open " + zipname + "."); return; } byte[] buffer = new byte[sChunk]; try { FileOutputStream out = new FileOutputStream(source); int length; while ((length = zipin.read(buffer, 0, sChunk)) != -1) out.write(buffer, 0, length); out.close(); } catch (IOException e) { System.out.println("Couldn't decompress " + args[0] + "."); } try { zipin.close(); } catch (IOException e) { } } Code Sample 2: public void mouseClicked(MouseEvent e) { String userNameString; String passwordString; String md5String = ""; MessageDigest md; userNameString = userNameJTextField.getText(); passwordString = passwordJTextField.getText(); try { md = MessageDigest.getInstance("MD5"); md.update(passwordString.getBytes()); md5String = new String(md.digest()); md5String = Base64.encode(md5String.getBytes()); System.out.println(md5String); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); System.out.println("ʧ��"); } if (userNameString.equals("zouwulingde") && md5String.equals("aKdtP09kSTkWCD/cylk=")) { JOptionPane.showMessageDialog(null, "��ӭʹ��ѧ���ڹ���ϵͳ��"); } else { JOptionPane.showMessageDialog(null, "�û�������벻��ȷ!!!!"); } }
11
Code Sample 1: public static void unzip(final File file, final ZipFile zipFile, final File targetDirectory) throws PtException { LOG.info("Unzipping zip file '" + file.getAbsolutePath() + "' to directory " + "'" + targetDirectory.getAbsolutePath() + "'."); assert (file.exists() && file.isFile()); if (targetDirectory.exists() == false) { LOG.debug("Creating target directory."); if (targetDirectory.mkdirs() == false) { throw new PtException("Could not create target directory at " + "'" + targetDirectory.getAbsolutePath() + "'!"); } } ZipInputStream zipin = null; try { zipin = new ZipInputStream(new FileInputStream(file)); ZipEntry nextZipEntry = zipin.getNextEntry(); while (nextZipEntry != null) { LOG.debug("Unzipping entry '" + nextZipEntry.getName() + "'."); if (nextZipEntry.isDirectory()) { LOG.debug("Skipping directory."); continue; } final File targetFile = new File(targetDirectory, nextZipEntry.getName()); final File parentTargetFile = targetFile.getParentFile(); if (parentTargetFile.exists() == false) { LOG.debug("Creating directory '" + parentTargetFile.getAbsolutePath() + "'."); if (parentTargetFile.mkdirs() == false) { throw new PtException("Could not create target directory at " + "'" + parentTargetFile.getAbsolutePath() + "'!"); } } InputStream input = null; FileOutputStream output = null; try { input = zipFile.getInputStream(nextZipEntry); if (targetFile.createNewFile() == false) { throw new PtException("Could not create target file " + "'" + targetFile.getAbsolutePath() + "'!"); } output = new FileOutputStream(targetFile); byte[] buffer = new byte[BUFFER_SIZE]; int readBytes = input.read(buffer, 0, buffer.length); while (readBytes > 0) { output.write(buffer, 0, readBytes); readBytes = input.read(buffer, 0, buffer.length); } } finally { PtCloseUtil.close(input, output); } nextZipEntry = zipin.getNextEntry(); } } catch (IOException e) { throw new PtException("Could not unzip file '" + file.getAbsolutePath() + "'!", e); } finally { PtCloseUtil.close(zipin); } } Code Sample 2: public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_name); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
00
Code Sample 1: protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ejb.bprocess.OAIPMH.AutoHarvesterSession ahSession = home.create(); java.util.Vector vector = new java.util.Vector(1, 1); Integer libraryId = new Integer(1); String xmlstr = ""; String str = ""; String arr[] = new String[2]; String[] subarr = new String[4]; String mdPrefix = "", mdPrefixValue = ""; String from = "", fromValue = ""; String until = "", untilValue = ""; String set = "", setValue = ""; String oai_pmhRequest = request.getParameter("verb"); String oai_pmhQuery = request.getQueryString(); String urlStr = ""; urlStr = "http://" + request.getServerName() + ":" + request.getServerPort() + "/newgenlibctxt/HarvestServlet"; String attribute = oai_pmhQuery; String arguments = attribute.substring(attribute.indexOf("?") + 1); StringTokenizer st = new StringTokenizer(arguments, "&"); int i = 0; int j = 0; int z = 0; int count = 0; String type = ""; while (st.hasMoreTokens()) { arr[i] = st.nextToken(); StringTokenizer subst = new StringTokenizer(arr[i], "="); while (subst.hasMoreTokens()) { subarr[j] = subst.nextToken(); j++; } i++; count++; } int mdfCount = 0, fromCount = 0, untilCount = 0, setCount = 0; ListRecords lr = new ListRecords(); for (int k = 0; k < j; k += 2) { if (subarr[k].equals("from")) { from = "from"; fromCount++; fromValue = subarr[k + 1]; fromValue = lr.validateDate(fromValue); } else if (subarr[k].equals("until")) { until = "until"; untilCount++; untilValue = subarr[k + 1]; untilValue = lr.validateDate(untilValue); } } if (fromValue.equals("") && untilCount == 1) { fromValue = lr.validateDate("0001-01-01"); } else if (untilValue.equals("") && fromCount == 1) { String a = (new Resdate()).getDate(); untilValue = a.substring(0, a.indexOf("T")); } System.out.println("This is fromValue:" + fromValue); System.out.println("This is untilValue:" + untilValue); vector = ahSession.getHarvestLibrary(null, libraryId); String harlibraryId = ""; if (vector.size() > 0) { for (int k = 0; k < vector.size(); k = k + 3) { harlibraryId = vector.elementAt(k).toString(); String harvesturl = vector.elementAt(k + 1).toString(); String status = vector.elementAt(k + 2).toString(); if (status.equals("A")) { String oai_pmhRequest1 = request.getParameter("verb"); String oai_pmhQuery1 = request.getQueryString(); urlStr = "http://" + harvesturl + ":8080/newgenlibctxt/oai2.0?verb=ListRecords&metadataPrefix=marc21&from=" + fromValue + "&until=" + untilValue + ""; boolean resExists = true; for (int n = 0; resExists == true; n++) { java.net.URL url = new java.net.URL(urlStr); java.net.URLConnection urlCon = url.openConnection(); urlCon.setDoInput(true); urlCon.connect(); InputStream is = urlCon.getInputStream(); System.out.println("input" + is.available()); org.jdom.input.SAXBuilder sb = new org.jdom.input.SAXBuilder(); org.jdom.Document doc = sb.build(is); xmlstr = (new org.jdom.output.XMLOutputter()).outputString(doc); System.out.println("xmlStr:" + xmlstr); doc = null; sb = null; java.util.Vector vec = new java.util.Vector(); vec = ahSession.autoInitialHarvest(null, xmlstr, harlibraryId); String resT = doc.getRootElement().getChildText("resumptionToken", doc.getRootElement().getNamespace()); if (!(resT == null)) { urlStr = "http://" + harvesturl + ":8080/newgenlibctxt/oai2.0?verb=ListRecords&resumptionToken=" + resT; } else { resExists = false; } } } else if (status.equals("B")) { java.io.File file = new java.io.File(harvesturl); java.io.File[] file1 = file.listFiles(); for (int b = 0; b < file1.length; b++) { File file2 = (File) file1[b]; System.out.println("File2:" + file2); long lastmodifed = file2.lastModified(); StringTokenizer st1 = new StringTokenizer(fromValue, "-"); String dar[] = new String[3]; java.util.Calendar c1 = java.util.Calendar.getInstance(); int g = 0; while (st1.hasMoreElements()) { dar[g] = st1.nextToken(); g++; } c1.set(Integer.parseInt(dar[0]), Integer.parseInt(dar[1]), Integer.parseInt(dar[2])); StringTokenizer st2 = new StringTokenizer(untilValue, "-"); String dar1[] = new String[3]; java.util.Calendar c2 = java.util.Calendar.getInstance(); int d = 0; while (st2.hasMoreElements()) { dar1[d] = st2.nextToken(); d++; } c2.set(Integer.parseInt(dar1[0]), Integer.parseInt(dar1[1]), Integer.parseInt(dar1[2])); java.util.Calendar c3 = java.util.Calendar.getInstance(); c3.setTimeInMillis(lastmodifed); c3.set(java.util.Calendar.HOUR, 0); c3.set(java.util.Calendar.AM_PM, java.util.Calendar.AM); c3.set(java.util.Calendar.MINUTE, 0); c3.set(java.util.Calendar.SECOND, 0); c3.set(java.util.Calendar.MILLISECOND, 0); java.util.Date d1 = c1.getTime(); java.util.Date d2 = c2.getTime(); java.util.Date d3 = c3.getTime(); System.out.println("This is d1:" + d1); System.out.println("This is d2:" + d2); System.out.println("This is d3:" + d3); if (d3.after(d1) && d3.before(d2)) { org.jdom.input.SAXBuilder sb1 = new org.jdom.input.SAXBuilder(); org.jdom.Document doc1 = sb1.build(new java.io.FileInputStream(file2)); xmlstr = (new org.jdom.output.XMLOutputter()).outputString(doc1); java.util.Vector vec = new java.util.Vector(); vec = ahSession.autoInitialHarvest(null, xmlstr, harlibraryId); } } } } } } catch (Exception ex) { ex.printStackTrace(); } } Code Sample 2: 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(); }
00
Code Sample 1: public static void main(String args[]) { int summ = 0; int temp = 0; int[] a1 = { 0, 6, -7, -7, 61, 8, 20, 0, 8, 3, 6, 2, 7, 99, 0, 23, 12, 7, 9, 5, 33, 1, 3, 99, 99, 61, 99, 99, 99, 61, 61, 61, -3, -3, -3, -3 }; for (int j = 0; j < (a1.length * a1.length); j++) { for (int i = 0; i < a1.length - 1; i++) { if (a1[i] > a1[i + 1]) { temp = a1[i]; a1[i] = a1[i + 1]; a1[i + 1] = temp; } } } for (int i = 0; i < a1.length; i++) { System.out.print(" " + a1[i]); } int min = 0; int max = 0; summ = (a1[1]) + (a1[a1.length - 1]); for (int i = 0; i < a1.length; i++) { if (a1[i] > a1[0] && a1[i] != a1[0]) { min = a1[i]; break; } } for (int i = a1.length - 1; i > 0; i--) { if (a1[i] < a1[a1.length - 1] & a1[i] != a1[a1.length - 1]) { max = a1[i]; break; } } System.out.println(); System.out.print("summa 2 min N 2 max = " + summ); System.out.println(min); System.out.println(max); System.out.println("summa 2 min N 2 max = " + (min + max)); } Code Sample 2: public static List<String> getServers() throws Exception { List<String> servers = new ArrayList<String>(); URL url = new URL("http://tfast.org/en/servers.php"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = in.readLine()) != null) { if (line.contains("serv=")) { int i = line.indexOf("serv="); servers.add(line.substring(i + 5, line.indexOf("\"", i))); } } in.close(); return servers; }
00
Code Sample 1: public static boolean insert(final Cargo cargo) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into cargo (nome) values (?)"; pst = c.prepareStatement(sql); pst.setString(1, cargo.getNome()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { e1.printStackTrace(); } System.out.println("[CargoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } } Code Sample 2: 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 Map getBlackHoleData() throws Exception { File dataFile = new File(Kit.getDataDir() + BLACK_HOLE); if (dataFile.exists() && daysOld(dataFile) < 1) { return getStoredData(dataFile); } InputStream stream = null; try { String bh_url = "http://www.critique.org/users/critters/blackholes/sightdata.html"; URL url = new URL(bh_url); stream = url.openStream(); } catch (IOException e) { return getStoredData(dataFile); } BufferedReader br = new BufferedReader(new InputStreamReader(stream)); StringBuffer data = new StringBuffer(); String line; while ((line = br.readLine()) != null) { data.append(line); } br.close(); Pattern p = Pattern.compile(regexp); Matcher m = p.matcher(data); Map map = new THashMap(); while (m.find()) { map.put(m.group(1).trim(), new ReplyTimeDatum(Integer.parseInt(m.group(3)), Integer.parseInt(m.group(4)), 0, Integer.parseInt(m.group(2)))); } ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(dataFile)); oos.writeObject(map); oos.close(); return map; } Code Sample 2: public Constructor run() throws Exception { String path = "META-INF/services/" + ComponentApplicationContext.class.getName(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Enumeration<URL> urls; if (loader == null) { urls = ComponentApplicationContext.class.getClassLoader().getResources(path); } else { urls = loader.getResources(path); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String className = null; while ((className = reader.readLine()) != null) { final String name = className.trim(); if (!name.startsWith("#") && !name.startsWith(";") && !name.startsWith("//")) { final Class<?> cls; if (loader == null) { cls = Class.forName(name); } else { cls = Class.forName(name, true, loader); } int m = cls.getModifiers(); if (ComponentApplicationContext.class.isAssignableFrom(cls) && !Modifier.isAbstract(m) && !Modifier.isInterface(m)) { Constructor constructor = cls.getDeclaredConstructor(); if (!Modifier.isPublic(constructor.getModifiers())) { constructor.setAccessible(true); } return constructor; } else { throw new ClassCastException(cls.getName()); } } } } finally { reader.close(); } } throw new ComponentApplicationException("No " + "ComponentApplicationContext implementation " + "found."); }
11
Code Sample 1: public void createIndex(File indexDir) throws SearchLibException, IOException { if (!indexDir.mkdir()) throw new SearchLibException("directory creation failed (" + indexDir + ")"); InputStream is = null; FileWriter target = null; for (String resource : resources) { String res = rootPath + '/' + resource; is = getClass().getResourceAsStream(res); if (is == null) is = getClass().getResourceAsStream("common" + '/' + resource); if (is == null) throw new SearchLibException("Unable to find resource " + res); try { File f = new File(indexDir, resource); if (f.getParentFile() != indexDir) f.getParentFile().mkdirs(); target = new FileWriter(f); IOUtils.copy(is, target); } finally { if (target != null) target.close(); if (is != null) is.close(); } } } Code Sample 2: public static void copy(File src, File dest) throws IOException { if (!src.exists()) { throw new IOException(StaticUtils.format(OStrings.getString("LFC_ERROR_FILE_DOESNT_EXIST"), new Object[] { src.getAbsolutePath() })); } FileInputStream fis = new FileInputStream(src); dest.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(dest); byte[] b = new byte[BUFSIZE]; int readBytes; while ((readBytes = fis.read(b)) > 0) fos.write(b, 0, readBytes); fis.close(); fos.close(); }
11
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: public static void main(String[] args) throws IOException { String paramFileName = args[0]; BufferedReader inFile_params = new BufferedReader(new FileReader(paramFileName)); String cands_fileName = (inFile_params.readLine().split("\\s+"))[0]; String alignSrcCand_phrasal_fileName = (inFile_params.readLine().split("\\s+"))[0]; String alignSrcCand_word_fileName = (inFile_params.readLine().split("\\s+"))[0]; String source_fileName = (inFile_params.readLine().split("\\s+"))[0]; String trainSrc_fileName = (inFile_params.readLine().split("\\s+"))[0]; String trainTgt_fileName = (inFile_params.readLine().split("\\s+"))[0]; String trainAlign_fileName = (inFile_params.readLine().split("\\s+"))[0]; String alignCache_fileName = (inFile_params.readLine().split("\\s+"))[0]; String alignmentsType = "AlignmentGrids"; int maxCacheSize = 1000; inFile_params.close(); int numSentences = countLines(source_fileName); InputStream inStream_src = new FileInputStream(new File(source_fileName)); BufferedReader srcFile = new BufferedReader(new InputStreamReader(inStream_src, "utf8")); String[] srcSentences = new String[numSentences]; for (int i = 0; i < numSentences; ++i) { srcSentences[i] = srcFile.readLine(); } srcFile.close(); println("Creating src vocabulary @ " + (new Date())); srcVocab = new Vocabulary(); int[] sourceWordsSentences = Vocabulary.initializeVocabulary(trainSrc_fileName, srcVocab, true); int numSourceWords = sourceWordsSentences[0]; int numSourceSentences = sourceWordsSentences[1]; println("Reading src corpus @ " + (new Date())); srcCorpusArray = SuffixArrayFactory.createCorpusArray(trainSrc_fileName, srcVocab, numSourceWords, numSourceSentences); println("Creating src SA @ " + (new Date())); srcSA = SuffixArrayFactory.createSuffixArray(srcCorpusArray, maxCacheSize); println("Creating tgt vocabulary @ " + (new Date())); tgtVocab = new Vocabulary(); int[] targetWordsSentences = Vocabulary.initializeVocabulary(trainTgt_fileName, tgtVocab, true); int numTargetWords = targetWordsSentences[0]; int numTargetSentences = targetWordsSentences[1]; println("Reading tgt corpus @ " + (new Date())); tgtCorpusArray = SuffixArrayFactory.createCorpusArray(trainTgt_fileName, tgtVocab, numTargetWords, numTargetSentences); println("Creating tgt SA @ " + (new Date())); tgtSA = SuffixArrayFactory.createSuffixArray(tgtCorpusArray, maxCacheSize); int trainingSize = srcCorpusArray.getNumSentences(); if (trainingSize != tgtCorpusArray.getNumSentences()) { throw new RuntimeException("Source and target corpora have different number of sentences. This is bad."); } println("Reading alignment data @ " + (new Date())); alignments = null; if ("AlignmentArray".equals(alignmentsType)) { alignments = SuffixArrayFactory.createAlignments(trainAlign_fileName, srcSA, tgtSA); } else if ("AlignmentGrids".equals(alignmentsType) || "AlignmentsGrid".equals(alignmentsType)) { alignments = new AlignmentGrids(new Scanner(new File(trainAlign_fileName)), srcCorpusArray, tgtCorpusArray, trainingSize, true); } else if ("MemoryMappedAlignmentGrids".equals(alignmentsType)) { alignments = new MemoryMappedAlignmentGrids(trainAlign_fileName, srcCorpusArray, tgtCorpusArray); } if (!fileExists(alignCache_fileName)) { alreadyResolved_srcSet = new HashMap<String, TreeSet<Integer>>(); alreadyResolved_tgtSet = new HashMap<String, TreeSet<Integer>>(); } else { try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(alignCache_fileName)); alreadyResolved_srcSet = (HashMap<String, TreeSet<Integer>>) in.readObject(); alreadyResolved_tgtSet = (HashMap<String, TreeSet<Integer>>) in.readObject(); in.close(); } catch (FileNotFoundException e) { System.err.println("FileNotFoundException in AlignCandidates.main(String[]): " + e.getMessage()); System.exit(99901); } catch (IOException e) { System.err.println("IOException in AlignCandidates.main(String[]): " + e.getMessage()); System.exit(99902); } catch (ClassNotFoundException e) { System.err.println("ClassNotFoundException in AlignCandidates.main(String[]): " + e.getMessage()); System.exit(99904); } } println("Processing candidates @ " + (new Date())); PrintWriter outFile_alignSrcCand_phrasal = new PrintWriter(alignSrcCand_phrasal_fileName); PrintWriter outFile_alignSrcCand_word = new PrintWriter(alignSrcCand_word_fileName); InputStream inStream_cands = new FileInputStream(new File(cands_fileName)); BufferedReader candsFile = new BufferedReader(new InputStreamReader(inStream_cands, "utf8")); String line = ""; String cand = ""; line = candsFile.readLine(); int countSatisfied = 0; int countAll = 0; int countSatisfied_sizeOne = 0; int countAll_sizeOne = 0; int prev_i = -1; String srcSent = ""; String[] srcWords = null; int candsRead = 0; int C50count = 0; while (line != null) { ++candsRead; println("Read candidate on line #" + candsRead); int i = toInt((line.substring(0, line.indexOf("|||"))).trim()); if (i != prev_i) { srcSent = srcSentences[i]; srcWords = srcSent.split("\\s+"); prev_i = i; println("New value for i: " + i + " seen @ " + (new Date())); C50count = 0; } else { ++C50count; } line = (line.substring(line.indexOf("|||") + 3)).trim(); cand = (line.substring(0, line.indexOf("|||"))).trim(); cand = cand.substring(cand.indexOf(" ") + 1, cand.length() - 1); JoshuaDerivationTree DT = new JoshuaDerivationTree(cand, 0); String candSent = DT.toSentence(); String[] candWords = candSent.split("\\s+"); String alignSrcCand = DT.alignments(); outFile_alignSrcCand_phrasal.println(alignSrcCand); println(" i = " + i + ", alignSrcCand: " + alignSrcCand); String alignSrcCand_res = ""; String[] linksSrcCand = alignSrcCand.split("\\s+"); for (int k = 0; k < linksSrcCand.length; ++k) { String link = linksSrcCand[k]; if (link.indexOf(',') == -1) { alignSrcCand_res += " " + link.replaceFirst("--", "-"); } else { alignSrcCand_res += " " + resolve(link, srcWords, candWords); } } alignSrcCand_res = alignSrcCand_res.trim(); println(" i = " + i + ", alignSrcCand_res: " + alignSrcCand_res); outFile_alignSrcCand_word.println(alignSrcCand_res); if (C50count == 50) { println("50C @ " + (new Date())); C50count = 0; } line = candsFile.readLine(); } outFile_alignSrcCand_phrasal.close(); outFile_alignSrcCand_word.close(); candsFile.close(); println("Finished processing candidates @ " + (new Date())); try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(alignCache_fileName)); out.writeObject(alreadyResolved_srcSet); out.writeObject(alreadyResolved_tgtSet); out.flush(); out.close(); } catch (IOException e) { System.err.println("IOException in AlignCandidates.main(String[]): " + e.getMessage()); System.exit(99902); } }
11
Code Sample 1: public void handle() { FileChannel srcChannel, destChannel; String destOutFile = databaseName + ".script." + System.currentTimeMillis(); String destOutFileCompressed = databaseName + ".script." + System.currentTimeMillis() + ".gz"; if (rotateDest != null) { (new File(rotateDest)).mkdirs(); if (destOutFile.indexOf("/") != -1) { destOutFile = rotateDest + "/" + destOutFile.substring(destOutFile.lastIndexOf("/") + 1); } if (destOutFileCompressed.indexOf("/") != -1) { destOutFileCompressed = rotateDest + "/" + destOutFileCompressed.substring(destOutFileCompressed.lastIndexOf("/") + 1); } } if (rotateCompress) { try { GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(destOutFileCompressed)); FileInputStream in = new FileInputStream(databaseName + ".script"); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.finish(); out.close(); buf = null; in = null; out = null; Debug.debug("Rotated database file '" + databaseName + ".script' to '" + destOutFileCompressed + "'"); } catch (Exception e) { Debug.debug("Unable to rotate database file '" + databaseName + ".script': " + e); } } else { try { srcChannel = new FileInputStream(databaseName + ".script").getChannel(); } catch (IOException e) { Debug.debug("Unable to read file '" + databaseName + ".script' for database rotation."); return; } try { destChannel = new FileOutputStream(destOutFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to rotate file to '" + destOutFile + "': " + e.getMessage()); return; } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); srcChannel = null; destChannel = null; } catch (IOException e) { Debug.debug("Unable to copy data for file rotation: " + e.getMessage()); return; } Debug.debug("Rotated database file '" + databaseName + ".script' to '" + destOutFile + "'"); } if (rotateDest != null) { long comparisonTime = rotateDays * (60 * 60 * 24 * 1000); long currentTime = System.currentTimeMillis(); File fileList[] = (new File(rotateDest)).listFiles(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(currentTime); String archiveFile = format1.format(date).toString() + ".zip"; if (rotateArchive != null) { archiveFile = rotateArchive + "/" + archiveFile; (new File(rotateArchive)).mkdirs(); } Archive archive = new Archive(archiveFile); for (int i = 0; i < fileList.length; i++) { String currentFilename = fileList[i].getName(); long timeDifference = (currentTime - fileList[i].lastModified()); if ((rotateCompress && currentFilename.endsWith(".gz")) || (!rotateCompress && currentFilename.indexOf(".script.") != -1)) { if (rotateDest != null) { currentFilename = rotateDest + "/" + currentFilename; } if (timeDifference > comparisonTime) { archive.addFile(fileList[i].getName(), currentFilename); fileList[i].delete(); } } } archive = null; fileList = null; format1 = null; date = null; } } Code Sample 2: public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
11
Code Sample 1: public static void decryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.DECRYPT_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(); } Code Sample 2: private static void cut() { File inputFile = new File(inputFileName); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), inputCharSet)); } catch (FileNotFoundException e) { System.err.print("Invalid File Name!"); System.err.flush(); System.exit(1); } catch (UnsupportedEncodingException e) { System.err.print("Invalid Char Set Name!"); System.err.flush(); System.exit(1); } switch(cutMode) { case charMode: { int outputFileIndex = 1; char[] readBuf = new char[charPerFile]; while (true) { int readCount = 0; try { readCount = in.read(readBuf); } catch (IOException e) { System.err.println("Read IO Error!"); System.err.flush(); System.exit(1); } if (-1 == readCount) break; else { try { int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = "html"; DecimalFormat outputFileIndexFormat = new DecimalFormat("0000"); File outputFile = new File(prefixInputFileName + "-" + outputFileIndexFormat.format(outputFileIndex) + "." + postfixInputFileName); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), outputCharSet)); out.write(readBuf, 0, readCount); out.flush(); out.close(); outputFileIndex++; } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } } } break; } case lineMode: { boolean isFileEnd = false; int outputFileIndex = 1; while (!isFileEnd) { try { int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = inputFileName.substring(ppos + 1); DecimalFormat outputFileIndexFormat = new DecimalFormat("0000"); File outputFile = new File(prefixInputFileName + outputFileIndexFormat.format(outputFileIndex) + "." + postfixInputFileName); PrintStream out = new PrintStream(new FileOutputStream(outputFile), false, outputCharSet); int p = 0; while (p < linePerFile) { String line = in.readLine(); if (null == line) { isFileEnd = true; break; } out.println(line); ++p; } out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } ++outputFileIndex; } break; } case htmlMode: { boolean isFileEnd = false; int outputFileIndex = 1; int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = "html"; DecimalFormat df = new DecimalFormat("0000"); while (!isFileEnd) { try { File outputFile = new File(prefixInputFileName + "-" + df.format(outputFileIndex) + "." + postfixInputFileName); PrintStream out = new PrintStream(new FileOutputStream(outputFile), false, outputCharSet); out.println("<html><head><title>" + prefixInputFileName + "-" + df.format(outputFileIndex) + "</title>" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; " + "charset=" + outputCharSet + "\" />" + "<link rel =\"stylesheet\" " + "type=\"text/css\" " + "href=\"stylesheet.css\" />" + "</head><body><div id=\"content\">"); int p = 0; while (p < pPerFile) { String line = in.readLine(); if (null == line) { isFileEnd = true; break; } if (line.length() > 0) out.println("<p>" + line + "</p>"); ++p; } out.println("</div><a href=\"" + prefixInputFileName + "-" + df.format(outputFileIndex + 1) + "." + postfixInputFileName + "\">NEXT</a></body></html>"); out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } ++outputFileIndex; } try { File indexFile = new File("index.html"); PrintStream out = new PrintStream(new FileOutputStream(indexFile), false, outputCharSet); out.println("<html><head><title>" + "Index" + "</title>" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; " + "charset=" + outputCharSet + "\" />" + "<link rel =\"stylesheet\" " + "type=\"text/css\" " + "href=\"stylesheet.css\" />" + "</head><body><h2>" + htmlTitle + "</h2><div id=\"content\"><ul>"); for (int i = 1; i < outputFileIndex; i++) { out.println("<li><a href=\"" + prefixInputFileName + "-" + df.format(i) + "." + postfixInputFileName + "\">" + df.format(i) + "</a></li>"); } out.println("</ul></body></html>"); out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } break; } } }
00
Code Sample 1: public String getValidationKey(String transactionId, double transactionAmount) { try { java.security.MessageDigest d = java.security.MessageDigest.getInstance("MD5"); d.reset(); String value = this.getPostingKey() + transactionId + transactionAmount; d.update(value.getBytes()); byte[] buf = d.digest(); return Base64.encodeBytes(buf); } catch (java.security.NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } 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 String postData(String result, DefaultHttpClient httpclient) { try { HttpPost post = new HttpPost("http://3dforandroid.appspot.com/api/v1/note/create"); StringEntity se = new StringEntity(result); se.setContentEncoding(HTTP.UTF_8); se.setContentType("application/json"); post.setEntity(se); post.setHeader("Content-Type", "application/json"); post.setHeader("Accept", "*/*"); HttpResponse response = httpclient.execute(post); HttpEntity entity = response.getEntity(); InputStream instream; instream = entity.getContent(); responseMessage = read(instream); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return responseMessage; } 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 String computeDigest(String str, String alg) { MessageDigest currentAlgorithm = null; try { currentAlgorithm = MessageDigest.getInstance(alg); } catch (NoSuchAlgorithmException e) { return str; } currentAlgorithm.reset(); currentAlgorithm.update(str.getBytes()); byte[] hash = currentAlgorithm.digest(); String d = ""; int usbyte = 0; for (int i = 0; i < hash.length; i++) { usbyte = hash[i] & 0xFF; if (usbyte < 16) d += "0" + Integer.toHexString(usbyte); else d += Integer.toHexString(usbyte); } return d.toUpperCase(); } Code Sample 2: byte[] calculateDigest(String value) { try { MessageDigest mg = MessageDigest.getInstance("SHA1"); mg.update(value.getBytes()); return mg.digest(); } catch (Exception e) { throw Bark.unchecker(e); } }
11
Code Sample 1: public static boolean copyFile(File dest, File source) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("copy error (" + source.getAbsolutePath() + " => " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
00
Code Sample 1: public static InputStream getInputStream(String filepath) throws Exception { if (isUrl(filepath)) { URL url = URI.create(filepath).toURL(); return url.openStream(); } else { return new FileInputStream(new File(filepath)); } } Code Sample 2: @Override public int deleteStatement(String sql) { Statement statement = null; try { statement = getConnection().createStatement(); int result = statement.executeUpdate(sql.toString()); if (result == 0) log.warn(sql + " result row count is 0"); getConnection().commit(); return result; } catch (SQLException e) { try { getConnection().rollback(); } catch (SQLException e1) { log.error(e1.getMessage(), e1); } log.error(e.getMessage(), e); throw new RuntimeException(); } finally { try { statement.close(); getConnection().close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } }
00
Code Sample 1: public void copyFile(File sourceFile, File destFile) throws IOException { Log.level3("Copying " + sourceFile.getPath() + " to " + destFile.getPath()); if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } } if (destination != null) { destination.close(); } } Code Sample 2: public static void main(String[] args) { try { String user = "techbeherca"; String targetUrl = "http://api.fanfou.com/statuses/user_timeline.xml?id=" + user; URL url = new URL(targetUrl); InputStream in = url.openStream(); ArrayList<MessageObj> list; if (in != null) { MessageListDOMParser parser = new MessageListDOMParser(); list = (ArrayList<MessageObj>) parser.parseXML(in); TransactionDAO dao = new TransactionDAO(); dao.insert(list); } } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public static void copyFile(File in, File out) throws ObclipseException { try { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (FileNotFoundException e) { Msg.error("The file ''{0}'' to copy does not exist!", e, in.getAbsolutePath()); } catch (IOException e) { Msg.ioException(in, out, e); } } Code Sample 2: public List<String> generate(String geronimoVersion, String geronimoHome, String instanceNumber) { geronimoRepository = geronimoHome + "/repository"; Debug.logInfo("The WASCE or Geronimo Repository is " + geronimoRepository, module); Classpath classPath = new Classpath(System.getProperty("java.class.path")); List<File> elements = classPath.getElements(); List<String> jar_version = new ArrayList<String>(); String jarPath = null; String jarName = null; String newJarName = null; String jarNameSimple = null; String jarVersion = "1.0"; int lastDash = -1; for (File f : elements) { if (f.exists()) { if (f.isFile()) { jarPath = f.getAbsolutePath(); jarName = f.getName(); String jarNameWithoutExt = (String) jarName.subSequence(0, jarName.length() - 4); lastDash = jarNameWithoutExt.lastIndexOf("-"); if (lastDash > -1) { jarVersion = jarNameWithoutExt.substring(lastDash + 1, jarNameWithoutExt.length()); jarNameSimple = jarNameWithoutExt.substring(0, lastDash); boolean alreadyVersioned = 0 < StringUtil.removeRegex(jarVersion, "[^.0123456789]").length(); if (!alreadyVersioned) { jarVersion = "1.0"; jarNameSimple = jarNameWithoutExt; newJarName = jarNameWithoutExt + "-" + jarVersion + ".jar"; } else { newJarName = jarName; } } else { jarVersion = "1.0"; jarNameSimple = jarNameWithoutExt; newJarName = jarNameWithoutExt + "-" + jarVersion + ".jar"; } jar_version.add(jarNameSimple + "#" + jarVersion); String targetDirectory = geronimoRepository + "/org/ofbiz/" + jarNameSimple + "/" + jarVersion; File targetDir = new File(targetDirectory); if (!targetDir.exists()) { boolean created = targetDir.mkdirs(); if (!created) { Debug.logFatal("Unable to create target directory - " + targetDirectory, module); return null; } } if (!targetDirectory.endsWith("/")) { targetDirectory = targetDirectory + "/"; } String newCompleteJarName = targetDirectory + newJarName; File newJarFile = new File(newCompleteJarName); try { FileChannel srcChannel = new FileInputStream(jarPath).getChannel(); FileChannel dstChannel = new FileOutputStream(newCompleteJarName).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); Debug.log("Created jar file : " + newJarName + " in WASCE or Geronimo repository", module); srcChannel.close(); dstChannel.close(); } catch (IOException e) { Debug.logFatal("Unable to create jar file - " + newJarName + " in WASCE or Geronimo repository (certainly already exists)", module); return null; } } } } List<ComponentConfig.WebappInfo> webApps = ComponentConfig.getAllWebappResourceInfos(); File geronimoWebXml = new File(System.getProperty("ofbiz.home") + "/framework/appserver/templates/" + geronimoVersion + "/geronimo-web.xml"); for (ComponentConfig.WebappInfo webApp : webApps) { if (null != webApp) { parseTemplate(geronimoWebXml, webApp); } } return jar_version; }
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 FlickrObject perform(boolean chkResponse) throws FlickrException { validate(); String data = getRequestData(); OutputStream os = null; InputStream is = null; try { URL url = null; try { url = new URL(m_url); } catch (MalformedURLException mux) { IllegalStateException iax = new IllegalStateException(); iax.initCause(mux); throw iax; } HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setRequestMethod("POST"); os = con.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); osw.write(data); osw.flush(); is = con.getInputStream(); return processRespons(is, chkResponse); } catch (FlickrException fx) { throw fx; } catch (IOException iox) { throw new FlickrException(iox); } finally { if (os != null) try { os.close(); } catch (IOException _) { } if (is != null) try { is.close(); } catch (IOException _) { } } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static final void copy(File src, File dest) throws IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; 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()) { dest = new File(dest + File.separator + src); } } else if (src.isDirectory()) { if (dest.isFile()) { throw new IOException("Cannot copy directory " + src + " to file " + dest); } if (!dest.exists()) { dest.mkdir(); } } if (src.isFile()) { try { source = new FileInputStream(src); destination = new FileOutputStream(dest); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) { break; } destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { } } if (destination != null) { try { destination.close(); } catch (IOException e) { } } } } 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), new File(targetdest)); } else { try { source = new FileInputStream(target); destination = new FileOutputStream(targetdest); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) { break; } destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { } } if (destination != null) { try { destination.close(); } catch (IOException e) { } } } } } } }
00
Code Sample 1: public void connect() throws ClientProtocolException, IOException { HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); inputStream = entity.getContent(); Header contentEncodingHeader = entity.getContentEncoding(); if (contentEncodingHeader != null) { HeaderElement[] codecs = contentEncodingHeader.getElements(); for (HeaderElement encoding : codecs) { if (encoding.getName().equalsIgnoreCase("gzip")) { inputStream = new GZIPInputStream(inputStream); } } } inputStream = new BufferedInputStream(inputStream, 2048); } Code Sample 2: private boolean handlePart(Part p) throws MessagingException, GetterException { String filename = p.getFileName(); if (!p.isMimeType("multipart/*")) { String disp = p.getDisposition(); if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) { if (checkCriteria(p)) { if (filename == null) filename = "Attachment" + attnum++; if (result == null) { try { File f = File.createTempFile("amorph_pop3-", ".tmp"); f.deleteOnExit(); OutputStream os = new BufferedOutputStream(new FileOutputStream(f)); InputStream is = p.getInputStream(); int c; while ((c = is.read()) != -1) os.write(c); os.close(); result = new FileInputStream(f); System.out.println("saved attachment to file: " + f.getAbsolutePath()); return true; } catch (IOException ex) { throw new GetterException(ex, "Failed to save attachment: " + ex); } } } } } 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: public void testGetOldVersion() throws ServiceException, IOException, SAXException, ParserConfigurationException { JCRNodeSource emptySource = loadTestSource(); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } } String testSourceUri = BASE_URL + "users/lars.trieloff?revision=1.1"; JCRNodeSource secondSource = (JCRNodeSource) resolveSource(testSourceUri); System.out.println("Read again at:" + secondSource.getSourceRevision()); InputStream expected = emptySource.getInputStream(); InputStream actual = secondSource.getInputStream(); assertTrue(isXmlEqual(expected, actual)); }
11
Code Sample 1: private Dataset(File f, Properties p, boolean ro) throws DatabaseException { folder = f; logger.debug("Opening dataset [" + ((ro) ? "readOnly" : "read/write") + " mode]"); readOnly = ro; logger = Logger.getLogger(Dataset.class); logger.debug("Opening environment: " + f); EnvironmentConfig envConfig = new EnvironmentConfig(); envConfig.setTransactional(false); envConfig.setAllowCreate(!readOnly); envConfig.setReadOnly(readOnly); env = new Environment(f, envConfig); File props = new File(folder, "dataset.properties"); if (!ro && p != null) { this.properties = p; try { FileOutputStream fos = new FileOutputStream(props); p.store(fos, null); fos.close(); } catch (IOException e) { logger.warn("Error saving dataset properties", e); } } else { if (props.exists()) { try { Properties pr = new Properties(); FileInputStream fis = new FileInputStream(props); pr.load(fis); fis.close(); this.properties = pr; } catch (IOException e) { logger.warn("Error reading dataset properties", e); } } } getPaths(); getNamespaces(); getTree(); pathDatabases = new HashMap(); frequencyDatabases = new HashMap(); lengthDatabases = new HashMap(); clustersDatabases = new HashMap(); pathMaps = new HashMap(); frequencyMaps = new HashMap(); lengthMaps = new HashMap(); clustersMaps = new HashMap(); } Code Sample 2: public static File copyFile(File srcFile, File destFolder, FileCopyListener copyListener) { File dest = new File(destFolder, srcFile.getName()); try { FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; long totalCopiedSize = 0; long totalSize = srcFile.length(); boolean canceled = false; if (copyListener == null) { while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } } else { while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); if (!copyListener.updateCheck(readLength, totalSize)) { canceled = true; break; } } } in.close(); out.close(); if (canceled) { dest.delete(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
11
Code Sample 1: public void render(final HttpServletRequest request, final HttpServletResponse response, final byte[] bytes, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } response.setContentLength(bytes.length); IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream()); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } Code Sample 2: @Override public List<SheetFullName> importSheets(INetxiliaSystem workbookProcessor, WorkbookId workbookName, URL url, IProcessingConsole console) throws ImportException { try { return importSheets(workbookProcessor, workbookName, url.openStream(), console); } catch (IOException e) { throw new ImportException(url, "Cannot open workbook:" + e, e); } }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String 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 void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: @Override public void run() { long timeout = 10 * 1000L; long start = (new Date()).getTime(); try { InputStream is = socket.getInputStream(); boolean available = false; while (!available && !socket.isClosed()) { try { if (is.available() != 0) { available = true; } else { Thread.sleep(100); } } catch (Exception e) { LOG.error("Error checking socket", e); } long curr = (new Date()).getTime(); if ((curr - start) >= timeout) { break; } } if (socket.isClosed()) { } else { tmpFile = File.createTempFile("ftp", "dat", new File("./tmp")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile)); IOUtils.copy(is, bos); bos.flush(); bos.close(); } String msg = FtpResponse.ReadComplete.asString() + ClientCommand.SP + "Read Complete" + ClientCommand.CRLF; List<String> list = new ArrayList<String>(); list.add(msg); ClientResponse response = new ClientResponse(list); ftpClient.notifyListeners(response); } catch (Exception e) { LOG.error("Error reading server response", e); } } Code Sample 2: private void putAlgosFromJar(File jarfile, AlgoDir dir, Model model) throws FileNotFoundException, IOException { URLClassLoader urlLoader = new URLClassLoader(new URL[] { jarfile.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(jarfile)); JarEntry entry = jis.getNextJarEntry(); String name = null; String tmpdir = System.getProperty("user.dir") + File.separator + Application.getProperty("dir.tmp") + File.separator; byte[] buffer = new byte[1000]; while (entry != null) { name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); try { Class<?> cls = urlLoader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && ((cls.getModifiers() & Modifier.ABSTRACT) == 0)) { dir.addAlgorithm(cls); model.putClass(cls.getName(), cls); } else if (ISerializable.class.isAssignableFrom(cls)) { model.putClass(cls.getName(), cls); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else if (Constants.isAllowedImageType(name)) { int lastSep = name.lastIndexOf("/"); if (lastSep != -1) { String dirs = tmpdir + name.substring(0, lastSep); File d = new File(dirs); if (!d.exists()) d.mkdirs(); } String filename = tmpdir + name; File f = new File(filename); if (!f.exists()) { f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); int read = -1; while ((read = jis.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.close(); } } entry = jis.getNextJarEntry(); } }
11
Code Sample 1: public String getMd5CodeOf16(String str) { StringBuffer buf = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte b[] = md.digest(); int i; 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)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { return buf.toString().substring(8, 24); } } Code Sample 2: public synchronized String encrypt(String plaintext) throws ServiceUnavailableException { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new ServiceUnavailableException(e.getMessage()); } try { md.reset(); md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new ServiceUnavailableException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
11
Code Sample 1: private void prepareQueryResultData(ZipEntryRef zer, String nodeDir, String reportDir, Set<ZipEntryRef> statusZers) throws Exception { String jobDir = nodeDir + File.separator + "job_" + zer.getUri(); if (!WorkDirectory.isWorkingDirectoryValid(jobDir)) { throw new Exception("Cannot acces to " + jobDir); } File f = new File(jobDir + File.separator + "result.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to result file " + f.getAbsolutePath()); } String fcopyName = reportDir + File.separator + zer.getName() + ".xml"; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); zer.setUri(fcopyName); f = new File(jobDir + File.separator + "status.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to status file " + f.getAbsolutePath()); } fcopyName = reportDir + File.separator + zer.getName() + "_status.xml"; bis = new BufferedInputStream(new FileInputStream(f)); bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); statusZers.add(new ZipEntryRef(ZipEntryRef.SINGLE_FILE, zer.getName(), fcopyName, ZipEntryRef.WITH_REL)); } Code Sample 2: public void addEntry(InputStream jis, JarEntry entry) throws IOException, URISyntaxException { File target = new File(this.target.getPath() + entry.getName()).getAbsoluteFile(); if (!target.exists()) { target.createNewFile(); } if ((new File(this.source.toURI())).isDirectory()) { File sourceEntry = new File(this.source.getPath() + entry.getName()); FileInputStream fis = new FileInputStream(sourceEntry); byte[] classBytes = new byte[fis.available()]; fis.read(classBytes); (new FileOutputStream(target)).write(classBytes); } else { readwriteStreams(jis, (new FileOutputStream(target))); } }
00
Code Sample 1: public void retrieveFiles() throws DataSyncException { try { ftp.connect(hostname, port); boolean success = ftp.login(username, password); log.info("FTP Login:" + success); if (success) { System.out.println(directory); ftp.changeWorkingDirectory(directory); ftp.setFileType(FTP.ASCII_FILE_TYPE); ftp.enterLocalPassiveMode(); ftp.setRemoteVerificationEnabled(false); FTPFile[] files = ftp.listFiles(); for (FTPFile file : files) { ftp.setFileType(file.getType()); log.debug(file.getName() + "," + file.getSize()); FileOutputStream output = new FileOutputStream(localDirectory + file.getName()); try { ftp.retrieveFile(file.getName(), output); } finally { IOUtils.closeQuietly(output); } } } } catch (Exception e) { throw new DataSyncException(e); } finally { try { ftp.disconnect(); } catch (IOException e) { } } } Code Sample 2: private static BufferedReader createReaderConnection(String urlString) throws SiteNotFoundException { BufferedReader reader = null; try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-agent", "Mozilla/4.5"); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { Logger.logln("Response code for url [" + urlString + "] was " + conn.getResponseCode() + " [" + conn.getResponseMessage() + "]"); throw new SiteNotFoundException(urlString); } reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); } catch (IOException ex) { Logger.logln("" + ex); } return reader; }
00
Code Sample 1: private static void checkClients() { try { sendMultiListEntry('l'); } catch (Exception e) { if (Util.getDebugLevel() > 90) e.printStackTrace(); } try { if (CANT_CHECK_CLIENTS != null) KeyboardHero.removeStatus(CANT_CHECK_CLIENTS); URL url = new URL(URL_STR + "?req=clients" + (server != null ? "&port=" + server.getLocalPort() : "")); URLConnection connection = url.openConnection(getProxy()); connection.setRequestProperty("User-Agent", USER_AGENT); BufferedReader bufferedRdr = new BufferedReader(new InputStreamReader(connection.getInputStream())); String ln; if (Util.getDebugLevel() > 30) Util.debug("URL: " + url); while ((ln = bufferedRdr.readLine()) != null) { String[] parts = ln.split(":", 2); if (parts.length < 2) { Util.debug(12, "Line read in checkClients: " + ln); continue; } try { InetSocketAddress address = new InetSocketAddress(parts[0], Integer.parseInt(parts[1])); boolean notFound = true; if (Util.getDebugLevel() > 25) Util.debug("NEW Address: " + address.toString()); synchronized (clients) { Iterator<Client> iterator = clients.iterator(); while (iterator.hasNext()) { final Client client = iterator.next(); if (client.socket.isClosed()) { iterator.remove(); continue; } if (Util.getDebugLevel() > 26 && client.address != null) Util.debug("Address: " + client.address.toString()); if (address.equals(client.address)) { notFound = false; break; } } } if (notFound) { connectClient(address); } } catch (NumberFormatException e) { } } bufferedRdr.close(); } catch (MalformedURLException e) { Util.conditionalError(PORT_IN_USE, "Err_PortInUse"); Util.error(Util.getMsg("Err_CantCheckClients")); } catch (FileNotFoundException e) { Util.error(Util.getMsg("Err_CantCheckClients_Proxy"), Util.getMsg("Err_FileNotFound")); } catch (SocketException e) { Util.error(Util.getMsg("Err_CantCheckClients_Proxy"), e.getLocalizedMessage()); } catch (Exception e) { CANT_CHECK_CLIENTS.setException(e.toString()); KeyboardHero.addStatus(CANT_CHECK_CLIENTS); } } Code Sample 2: public static URL getIconURLForUser(String id) { try { URL url = new URL("http://profiles.yahoo.com/" + id); BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream())); String input = null; while ((input = r.readLine()) != null) { if (input.indexOf("<a href=\"") < 0) continue; if (input.indexOf("<img src=\"") < 0) continue; if (input.indexOf("<a href=\"") > input.indexOf("<img src=\"")) continue; String href = input.substring(input.indexOf("<a href=\"") + 9); String src = input.substring(input.indexOf("<img src=\"") + 10); if (href.indexOf("\"") < 0) continue; if (src.indexOf("\"") < 0) continue; href = href.substring(0, href.indexOf("\"")); src = src.substring(0, src.indexOf("\"")); if (href.equals(src)) { return new URL(href); } } } catch (IOException e) { } URL toReturn = null; try { toReturn = new URL("http://us.i1.yimg.com/us.yimg.com/i/ppl/no_photo.gif"); } catch (MalformedURLException e) { Debug.assrt(false); } return toReturn; }
00
Code Sample 1: public static InputStream call(String serviceUrl, Map parameters) throws IOException, RestException { StringBuffer urlString = new StringBuffer(serviceUrl); String query = RestClient.buildQueryString(parameters); HttpURLConnection conn; if ((urlString.length() + query.length() + 1) > MAX_URI_LENGTH_FOR_GET) { URL url = new URL(urlString.toString()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT_STRING); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); conn.getOutputStream().write(query.getBytes()); } else { if (query.length() > 0) { urlString.append("?").append(query); } URL url = new URL(urlString.toString()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT_STRING); conn.setRequestMethod("GET"); } int responseCode = conn.getResponseCode(); if (HttpURLConnection.HTTP_OK != responseCode) { ByteArrayOutputStream errorBuffer = new ByteArrayOutputStream(); int read; byte[] readBuffer = new byte[ERROR_READ_BUFFER_SIZE]; InputStream errorStream = conn.getErrorStream(); while (-1 != (read = errorStream.read(readBuffer))) { errorBuffer.write(readBuffer, 0, read); } throw new RestException("Request failed, HTTP " + responseCode + ": " + conn.getResponseMessage(), errorBuffer.toByteArray()); } return conn.getInputStream(); } 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(); }
11
Code Sample 1: private String createDefaultRepoConf() throws IOException { InputStream confIn = getClass().getResourceAsStream(REPO_CONF_PATH); File tempConfFile = File.createTempFile("repository", "xml"); tempConfFile.deleteOnExit(); IOUtils.copy(confIn, new FileOutputStream(tempConfFile)); return tempConfFile.getAbsolutePath(); } Code Sample 2: @Test public void testWriteAndReadBiggerUnbuffered() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwriteb.txt"); RFileOutputStream out = new RFileOutputStream(file); String body = ""; int size = 50 * 1024; for (int i = 0; i < size; i++) { body = body + "a"; } out.write(body.getBytes("utf-8")); out.close(); File expected = new File(dir, "testreadwriteb.txt"); assertTrue(expected.isFile()); assertEquals(body.length(), expected.length()); RFileInputStream in = new RFileInputStream(file); ByteArrayOutputStream tmp = new ByteArrayOutputStream(); int b = in.read(); while (b != -1) { tmp.write(b); b = in.read(); } byte[] buffer = tmp.toByteArray(); in.close(); assertEquals(body.length(), buffer.length); String resultRead = new String(buffer, "utf-8"); assertEquals(body, resultRead); } finally { server.stop(); } }
00
Code Sample 1: public Resultado procesar() { if (resultado != null) return resultado; int[] a = new int[elems.size()]; Iterator iter = elems.iterator(); int w = 0; while (iter.hasNext()) { a[w] = ((Integer) iter.next()).intValue(); w++; } int n = a.length; long startTime = System.currentTimeMillis(); int i, j, temp; for (i = 0; i < n - 1; i++) { for (j = i; j < n - 1; j++) { if (a[i] > a[j + 1]) { temp = a[i]; a[i] = a[j + 1]; a[j + 1] = temp; pasos++; } } } long endTime = System.currentTimeMillis(); resultado = new Resultado((int) (endTime - startTime), pasos, a.length); System.out.println("Resultado BB: " + resultado); return resultado; } Code Sample 2: public static void copyFile(File in, File out, boolean read, boolean write, boolean execute) throws FileNotFoundException, IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); File outFile = null; if (out.isDirectory()) { outFile = new File(out.getAbsolutePath() + File.separator + in.getName()); } else { outFile = out; } FileChannel outChannel = new FileOutputStream(outFile).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } outFile.setReadable(read); outFile.setWritable(write); outFile.setExecutable(execute); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: public InputPort getInputPort(String file) throws IOException { if (file.equals("/dev/null")) { return new StreamInputPort(new NullInputStream(), file); } URL url = Util.tryURL(file); if (url != null) { return new StreamInputPort(url.openStream(), url.toExternalForm()); } else return new FileInputPort(getFile(file)); } Code Sample 2: private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException, XMLStreamException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); byte[] byteArray = baos.toByteArray(); String resMessage = new String(byteArray, "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + resMessage); return resMessage; }
00
Code Sample 1: @Override public boolean checkConnection() { int status = 0; try { URL url = new URL(TupeloProxy.endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); status = conn.getResponseCode(); } catch (Exception e) { logger.severe("Connection test failed with code:" + status); e.printStackTrace(); } return status > 199 && status < 400; } Code Sample 2: protected void handleHttp(String path, IProgressMonitor monitor, SchemaGeneratorContext ctx) throws CoreException, DuplicateFileException { InputStream is = null; try { URL url = new URL(path); is = url.openStream(); IFolder folder = getXsdFolder(); String _path = url.getPath(); String[] contents = StringUtils.tokenizeToStringArray(_path, "/"); String file = contents[contents.length - 1]; if (file.indexOf(".") > -1) { IFile f = folder.getFile(file); if (!f.exists()) { f.create(is, false, monitor); String schemaFile = f.getLocation().toFile().getAbsolutePath(); ctx.setSchemaFiles(schemaFile); return; } throw new DuplicateFileException("File " + file + " already exists"); } IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "I/O Exception", new FileNotFoundException("No file associated to " + url)); throw new CoreException(status); } catch (MalformedURLException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "Malformed URL Exception", e); throw new CoreException(status); } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "I/O Exception", e); throw new CoreException(status); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } }
00
Code Sample 1: public static String rename_file(String sessionid, String key, String newFileName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_file"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "rename_file")); nameValuePairs.add(new BasicNameValuePair("new_name", newFileName)); nameValuePairs.add(new BasicNameValuePair("key", key)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; } Code Sample 2: public void copy(File source, File destination) { try { FileInputStream fileInputStream = new FileInputStream(source); FileOutputStream fileOutputStream = new FileOutputStream(destination); FileChannel inputChannel = fileInputStream.getChannel(); FileChannel outputChannel = fileOutputStream.getChannel(); transfer(inputChannel, outputChannel, source.length(), false); fileInputStream.close(); fileOutputStream.close(); destination.setLastModified(source.lastModified()); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: private void exportJar(File root, List<File> list, Manifest manifest) throws Exception { JarOutputStream jarOut = null; FileInputStream fin = null; try { jarOut = new JarOutputStream(new FileOutputStream(jarFile), manifest); for (int i = 0; i < list.size(); i++) { String filename = list.get(i).getAbsolutePath(); filename = filename.substring(root.getAbsolutePath().length() + 1); fin = new FileInputStream(list.get(i)); JarEntry entry = new JarEntry(filename.replace('\\', '/')); jarOut.putNextEntry(entry); byte[] buf = new byte[4096]; int read; while ((read = fin.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); jarOut.flush(); } } finally { if (fin != null) { try { fin.close(); } catch (Exception e) { ExceptionOperation.operate(e); } } if (jarOut != null) { try { jarOut.close(); } catch (Exception e) { } } } } Code Sample 2: public void insertStringInFile(String file, String textToInsert, long fromByte, long toByte) throws Exception { String tmpFile = file + ".tmp"; BufferedInputStream in = null; BufferedOutputStream out = null; long byteCount = 0; try { in = new BufferedInputStream(new FileInputStream(new File(file))); out = new BufferedOutputStream(new FileOutputStream(tmpFile)); long size = fromByte; byte[] buf = null; if (size == 0) { } else { buf = new byte[(int) size]; int length = -1; if ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } else { String msg = "Failed to read the first '" + size + "' bytes of file '" + file + "'. This might be a programming error."; logger.warning(msg); throw new Exception(msg); } } buf = textToInsert.getBytes(); int length = buf.length; out.write(buf, 0, length); byteCount = byteCount + length; long skipLength = toByte - fromByte; long skippedBytes = in.skip(skipLength); if (skippedBytes == -1) { } else { buf = new byte[4096]; length = -1; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } } in.close(); in = null; out.close(); out = null; File fileToDelete = new File(file); boolean wasDeleted = fileToDelete.delete(); if (!wasDeleted) { String msg = "Failed to delete the original file '" + file + "' to replace it with the modified file after text insertion."; logger.warning(msg); throw new Exception(msg); } File fileToRename = new File(tmpFile); boolean wasRenamed = fileToRename.renameTo(fileToDelete); if (!wasRenamed) { String msg = "Failed to rename tmp file '" + tmpFile + "' to the name of the original file '" + file + "'"; logger.warning(msg); throw new Exception(msg); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to read/write file '" + file + "'.", e); throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.log(Level.FINEST, "Ignoring error closing input file '" + file + "'.", e); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.log(Level.FINEST, "Ignoring error closing output file '" + tmpFile + "'.", e); } } } }
00
Code Sample 1: public static File copy(String inFileName, String outFileName) throws IOException { File inputFile = new File(inFileName); File outputFile = new File(outFileName); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return outputFile; } Code Sample 2: public String digest(String password, String digestType, String inputEncoding) throws CmsPasswordEncryptionException { MessageDigest md; String result; try { if (DIGEST_TYPE_PLAIN.equals(digestType.toLowerCase())) { result = password; } else if (DIGEST_TYPE_SSHA.equals(digestType.toLowerCase())) { byte[] salt = new byte[4]; byte[] digest; byte[] total; if (m_secureRandom == null) { m_secureRandom = SecureRandom.getInstance("SHA1PRNG"); } m_secureRandom.nextBytes(salt); md = MessageDigest.getInstance(DIGEST_TYPE_SHA); md.reset(); md.update(password.getBytes(inputEncoding)); md.update(salt); digest = md.digest(); total = new byte[digest.length + salt.length]; System.arraycopy(digest, 0, total, 0, digest.length); System.arraycopy(salt, 0, total, digest.length, salt.length); result = new String(Base64.encodeBase64(total)); } else { md = MessageDigest.getInstance(digestType); md.reset(); md.update(password.getBytes(inputEncoding)); result = new String(Base64.encodeBase64(md.digest())); } } catch (NoSuchAlgorithmException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_ALGORITHM_1, digestType); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsPasswordEncryptionException(message, e); } catch (UnsupportedEncodingException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_PASSWORD_ENCODING_1, inputEncoding); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsPasswordEncryptionException(message, e); } return result; }
11
Code Sample 1: public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public static String CreateZip(String[] filesToZip, String zipFileName) { byte[] buffer = new byte[18024]; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); out.setLevel(Deflater.BEST_COMPRESSION); for (int i = 0; i < filesToZip.length; i++) { FileInputStream in = new FileInputStream(filesToZip[i]); String fileName = null; for (int X = filesToZip[i].length() - 1; X >= 0; X--) { if (filesToZip[i].charAt(X) == '\\' || filesToZip[i].charAt(X) == '/') { fileName = filesToZip[i].substring(X + 1); break; } else if (X == 0) fileName = filesToZip[i]; } out.putNextEntry(new ZipEntry(fileName)); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); } out.close(); } catch (IllegalArgumentException e) { return "Failed to create zip: " + e.toString(); } catch (FileNotFoundException e) { return "Failed to create zip: " + e.toString(); } catch (IOException e) { return "Failed to create zip: " + e.toString(); } return "Success"; }
00
Code Sample 1: private static void addFolderToZip(File folder, ZipOutputStream zip, String baseName) throws IOException { File[] files = folder.listFiles(); for (File file : files) { if (file.isDirectory()) { String name = file.getAbsolutePath().substring(baseName.length()); ZipEntry zipEntry = new ZipEntry(name + "/"); zip.putNextEntry(zipEntry); zip.closeEntry(); addFolderToZip(file, zip, baseName); } else { String name = file.getAbsolutePath().substring(baseName.length()); ZipEntry zipEntry = new ZipEntry(updateFilename(name)); zip.putNextEntry(zipEntry); IOUtils.copy(new FileInputStream(file), zip); zip.closeEntry(); } } } Code Sample 2: public SearchHandler(String criteria, int langId) { try { URL url = new URL("http://eiffel.itba.edu.ar/hci/service/Catalog.groovy?method=GetProductListByName&criteria=" + criteria + "&language_id=" + langId); URLConnection urlc = url.openConnection(); urlc.setDoOutput(false); urlc.setAllowUserInteraction(false); BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); String response = sb.toString(); if (response == null) { return; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document dom = db.parse(is); NodeList nl = dom.getElementsByTagName("product"); for (int i = 0; i < nl.getLength(); i++) { Element nodes = (Element) nl.item(i); String id = nodes.getAttribute("id").toString(); NodeList name = nodes.getElementsByTagName("name"); NodeList rank2 = nodes.getElementsByTagName("sales_rank"); NodeList price = nodes.getElementsByTagName("price"); NodeList url2 = nodes.getElementsByTagName("image_url"); String nameS = getCharacterDataFromElement((Element) name.item(0)); String rank2S = getCharacterDataFromElement((Element) rank2.item(0)); String priceS = getCharacterDataFromElement((Element) price.item(0)); String url2S = getCharacterDataFromElement((Element) url2.item(0)); list.add(new ProductShort(id, nameS, rank2S, priceS, url2S)); } } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: @Override public InputStream getResourceStream(final String arg0) throws ResourceNotFoundException { try { final ServletContext context = CContext.getInstance().getContext(); final URL url = context.getResource(arg0); return url.openStream(); } catch (final Exception e) { return null; } } Code Sample 2: private File downloadPDB(String pdbId) { File tempFile = new File(path + "/" + pdbId + ".pdb.gz"); File pdbHome = new File(path); if (!pdbHome.canWrite()) { System.err.println("can not write to " + pdbHome); return null; } String ftp = String.format("ftp://ftp.ebi.ac.uk/pub/databases/msd/pdb_uncompressed/pdb%s.ent", pdbId.toLowerCase()); System.out.println("Fetching " + ftp); try { URL url = new URL(ftp); InputStream conn = url.openStream(); System.out.println("writing to " + tempFile); FileOutputStream outPut = new FileOutputStream(tempFile); GZIPOutputStream gzOutPut = new GZIPOutputStream(outPut); PrintWriter pw = new PrintWriter(gzOutPut); BufferedReader fileBuffer = new BufferedReader(new InputStreamReader(conn)); String line; while ((line = fileBuffer.readLine()) != null) { pw.println(line); } pw.flush(); pw.close(); outPut.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); return null; } return tempFile; }
00
Code Sample 1: protected Set<String> moduleNamesFromReader(URL url) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); Set<String> names = new HashSet<String>(); String line; while ((line = reader.readLine()) != null) { line = line.trim(); Matcher m = nonCommentPattern.matcher(line); if (m.find()) { names.add(m.group().trim()); } } return names; } Code Sample 2: protected void createGraphicalViewer(Composite parent) { final RulerComposite rc = new RulerComposite(parent, SWT.NONE); viewer = new ScrollingGraphicalViewer(); viewer.createControl(rc); editDomain.addViewer(viewer); rc.setGraphicalViewer(viewer); viewer.getControl().setBackground(ColorConstants.white); viewer.setEditPartFactory(new EditPartFactory() { public EditPart createEditPart(EditPart context, Object model) { return new RecorderEditPart(TopLevelModel.getRecorderModel()); } }); viewer.setContents(TopLevelModel.getRecorderModel()); Control control = viewer.getControl(); System.out.println("widget: " + control); DropTarget dt = new DropTarget(control, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_DEFAULT); dt.setTransfer(new Transfer[] { TextTransfer.getInstance() }); dt.addDropListener(new SensorTransferDropTargetListener(viewer)); }
11
Code Sample 1: public void beforeMethod(TestBase testBase) throws IOException { TFileFactory fileFactory = new TFileFactory(new InMemoryFileSystem()); ftpServer.cleanFileSystem(fileFactory); TDirectory rootDir = fileFactory.dir("/"); testBase.inject(rootDir); FTPClient ftpClient = new FTPClient(); ftpClient.connect("localhost", 8021); ftpClient.login("anonymous", "test@test.com"); testBase.inject(ftpClient); } Code Sample 2: public void runTask(HashMap pjobParms) throws Exception { FTPClient lftpClient = null; FileInputStream lfisSourceFile = null; JBJFPluginDefinition lpluginCipher = null; IJBJFPluginCipher theCipher = null; try { JBJFFTPDefinition lxmlFTP = null; if (getFTPDefinition() != null) { lxmlFTP = getFTPDefinition(); this.mstrSourceDirectory = lxmlFTP.getSourceDirectory(); this.mstrTargetDirectory = lxmlFTP.getTargetDirectory(); this.mstrFilename = lxmlFTP.getFilename(); this.mstrRemoteServer = lxmlFTP.getServer(); if (getResources().containsKey("plugin-cipher")) { lpluginCipher = (JBJFPluginDefinition) getResources().get("plugin-cipher"); } if (lpluginCipher != null) { theCipher = getTaskPlugins().getCipherPlugin(lpluginCipher.getPluginId()); } if (theCipher != null) { this.mstrServerUsr = theCipher.decryptString(lxmlFTP.getUser()); this.mstrServerPwd = theCipher.decryptString(lxmlFTP.getPass()); } else { this.mstrServerUsr = lxmlFTP.getUser(); this.mstrServerPwd = lxmlFTP.getPass(); } } else { throw new Exception("Work unit [ " + SHORT_NAME + " ] is missing an FTP Definition. Please check" + " your JBJF Batch Definition file an make sure" + " this work unit has a <resource> element added" + " within the <task> element."); } lfisSourceFile = new FileInputStream(mstrSourceDirectory + File.separator + mstrFilename); lftpClient = new FTPClient(); lftpClient.connect(mstrRemoteServer); lftpClient.setFileType(lxmlFTP.getFileTransferType()); if (!FTPReply.isPositiveCompletion(lftpClient.getReplyCode())) { throw new Exception("FTP server [ " + mstrRemoteServer + " ] refused connection."); } if (!lftpClient.login(mstrServerUsr, mstrServerPwd)) { throw new Exception("Unable to login to server [ " + mstrTargetDirectory + " ]."); } if (!lftpClient.changeWorkingDirectory(mstrTargetDirectory)) { throw new Exception("Unable to change to remote directory [ " + mstrTargetDirectory + "]"); } lftpClient.enterLocalPassiveMode(); if (!lftpClient.storeFile(mstrFilename, lfisSourceFile)) { throw new Exception("Unable to upload [ " + mstrSourceDirectory + "/" + mstrFilename + " ]" + " to " + mstrTargetDirectory + File.separator + mstrFilename + " to " + mstrRemoteServer); } lfisSourceFile.close(); lftpClient.logout(); } catch (Exception e) { throw e; } finally { if (lftpClient != null && lftpClient.isConnected()) { try { lftpClient.disconnect(); } catch (IOException ioe) { } } if (lfisSourceFile != null) { try { lfisSourceFile.close(); } catch (Exception e) { } } } }
11
Code Sample 1: protected void innerProcess(CrawlURI curi) throws InterruptedException { if (!curi.isHttpTransaction()) { return; } if (!TextUtils.matches("^text.*$", curi.getContentType())) { return; } long maxsize = DEFAULT_MAX_SIZE_BYTES.longValue(); try { maxsize = ((Long) getAttribute(curi, ATTR_MAX_SIZE_BYTES)).longValue(); } catch (AttributeNotFoundException e) { logger.severe("Missing max-size-bytes attribute when processing " + curi.toString()); } if (maxsize < curi.getContentSize() && maxsize > -1) { return; } String regexpr = ""; try { regexpr = (String) getAttribute(curi, ATTR_STRIP_REG_EXPR); } catch (AttributeNotFoundException e2) { logger.severe("Missing strip-reg-exp when processing " + curi.toString()); return; } ReplayCharSequence cs = null; try { cs = curi.getHttpRecorder().getReplayCharSequence(); } catch (Exception e) { curi.addLocalizedError(this.getName(), e, "Failed get of replay char sequence " + curi.toString() + " " + e.getMessage()); logger.warning("Failed get of replay char sequence " + curi.toString() + " " + e.getMessage() + " " + Thread.currentThread().getName()); return; } MessageDigest digest = null; try { try { digest = MessageDigest.getInstance(SHA1); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); return; } digest.reset(); String s = null; if (regexpr.length() == 0) { s = cs.toString(); } else { Matcher m = TextUtils.getMatcher(regexpr, cs); s = m.replaceAll(" "); TextUtils.recycleMatcher(m); } digest.update(s.getBytes()); byte[] newDigestValue = digest.digest(); if (logger.isLoggable(Level.FINEST)) { logger.finest("Recalculated content digest for " + curi.toString() + " old: " + Base32.encode((byte[]) curi.getContentDigest()) + ", new: " + Base32.encode(newDigestValue)); } curi.setContentDigest(SHA1, newDigestValue); } finally { if (cs != null) { try { cs.close(); } catch (IOException ioe) { logger.warning(TextUtils.exceptionToString("Failed close of ReplayCharSequence.", ioe)); } } } } Code Sample 2: private void doLogin(String password) throws LoginFailedException, IncorrectPasswordException { final long mgr = Constants.MANAGER; Data data, response; try { response = sendAndWait(new Request(mgr)).get(0); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 hash not supported."); } byte[] challenge = response.getBytes(); md.update(challenge); md.update(password.getBytes(Data.STRING_ENCODING)); data = Data.valueOf(md.digest()); try { response = sendAndWait(new Request(mgr).add(0, data)).get(0); } catch (ExecutionException ex) { throw new IncorrectPasswordException(); } setLoginMessage(response.getString()); response = sendAndWait(new Request(mgr).add(0, getLoginData())).get(0); setID(response.getWord()); } catch (InterruptedException ex) { throw new LoginFailedException(ex); } catch (ExecutionException ex) { throw new LoginFailedException(ex); } catch (IOException ex) { throw new LoginFailedException(ex); } }
00
Code Sample 1: private File writeResourceToFile(String resource) throws IOException { File tmp = File.createTempFile("zfppt" + resource, null); InputStream res = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); OutputStream out = new FileOutputStream(tmp); IOUtils.copy(res, out); out.close(); return tmp; } Code Sample 2: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final EditText eText = (EditText) findViewById(R.id.address); final Button button = (Button) findViewById(R.id.ButtonGo); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("m", "login")); nameValuePairs.add(new BasicNameValuePair("c", "User")); nameValuePairs.add(new BasicNameValuePair("password", "cloudisgreat")); nameValuePairs.add(new BasicNameValuePair("alias", "cs588")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); String result = ""; try { HttpResponse response = httpclient.execute(httppost); result = EntityUtils.toString(response.getEntity()); } catch (Exception e) { result = e.getMessage(); } LayoutInflater inflater = (LayoutInflater) WebTest.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View layout = inflater.inflate(R.layout.window1, null); final PopupWindow popup = new PopupWindowTest(layout, 100, 100); Button b = (Button) layout.findViewById(R.id.test_button); b.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.d("Debug", "Button activate"); popup.dismiss(); return false; } }); popup.showAtLocation(layout, Gravity.CENTER, 0, 0); View layout2 = inflater.inflate(R.layout.window1, null); final PopupWindow popup2 = new PopupWindowTest(layout2, 100, 100); TextView tview = (TextView) layout2.findViewById(R.id.pagetext); tview.setText(result); popup2.showAtLocation(layout, Gravity.CENTER, 50, -90); } catch (Exception e) { Log.d("Debug", e.toString()); } } }); }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile) { FileChannel source = null; FileChannel destination = null; try { if (!destFile.exists()) { destFile.createNewFile(); } source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } catch (Exception e) { e.printStackTrace(); } } } Code Sample 2: public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getName()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getName()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getName()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); 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) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
00
Code Sample 1: public File extractID3v2TagDataIntoFile(File outputFile) throws TagNotFoundException, IOException { int startByte = (int) ((MP3AudioHeader) audioHeader).getMp3StartByte(); if (startByte >= 0) { FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer bb = ByteBuffer.allocate(startByte); fc.read(bb); FileOutputStream out = new FileOutputStream(outputFile); out.write(bb.array()); out.close(); fc.close(); fis.close(); return outputFile; } throw new TagNotFoundException("There is no ID3v2Tag data in this file"); } Code Sample 2: public static void main(String[] args) { String email = "josh888@byu.net"; String username = "josh8573"; String password = "josh8573"; String IDnumber = "3030"; double[] apogee = { 1000 }; double[] perigee = apogee; double[] inclination = { 58.0 }; int[] trp_solmax = { 0, 1, 2 }; double[] init_long_ascend = { 0 }; double[] init_displ_ascend = { 0 }; double[] displ_perigee_ascend = { 0 }; double[] orbit_sect = null; boolean[] gtrn_weather = { false, true }; boolean print_altitude = true; boolean print_inclination = false; boolean print_gtrn_weather = true; boolean print_ita = false; boolean print_ida = false; boolean print_dpa = false; ORBIT[] orbit_array; orbit_array = ORBIT.CreateOrbits(apogee, perigee, inclination, gtrn_weather, trp_solmax, init_long_ascend, init_displ_ascend, displ_perigee_ascend, orbit_sect, print_altitude, print_inclination, print_gtrn_weather, print_ita, print_ida, print_dpa); TRP[] trp_array = {}; GTRN[] gtrn_array = {}; if (orbit_array != null) { Vector trp_vector = new Vector(); for (int i = 0; i < orbit_array.length; i++) { TRP temp_t = orbit_array[i].getTRP(); if (temp_t != null) { trp_vector.add(temp_t); } } if (trp_vector.size() != 0) { TRP[] trp_to_convert = new TRP[trp_vector.size()]; trp_array = (TRP[]) trp_vector.toArray(trp_to_convert); } Vector gtrn_vector = new Vector(); for (int i = 0; i < orbit_array.length; i++) { GTRN temp_g = orbit_array[i].getGTRN(); if (temp_g != null) { gtrn_vector.add(temp_g); } } if (gtrn_vector.size() != 0) { GTRN[] gtrn_to_convert = new GTRN[gtrn_vector.size()]; gtrn_array = (GTRN[]) gtrn_vector.toArray(gtrn_to_convert); } } int[] flux_min_element = { 1 }; int[] flux_max_element = { 92 }; int[] weather_flux = { 00, 01, 11, 12, 13 }; boolean print_weather = true; boolean print_min_elem = false; boolean print_max_elem = false; ORBIT[] orbit_array_into_flux = orbit_array; FLUX[] flux_array; flux_array = FLUX.CreateFLUX_URF(flux_min_element, flux_max_element, weather_flux, orbit_array_into_flux, print_weather, print_min_elem, print_max_elem); FLUX[] flx_objects_into_trans = flux_array; int[] units = { 1 }; double[] thickness = { 100 }; boolean print_shielding = false; TRANS[] trans_array; trans_array = TRANS.CreateTRANS_URF(flx_objects_into_trans, units, thickness, print_shielding); URFInterface[] input_files_for_letspec = trans_array; int[] letspec_min_element = { 2 }; int[] letspec_max_element = { 0 }; double[] min_energy_value = { .1 }; boolean[] diff_spect = { false }; boolean print_min_energy = false; LETSPEC[] letspec_array; letspec_array = LETSPEC.CreateLETSPEC_URF(input_files_for_letspec, letspec_min_element, letspec_max_element, min_energy_value, diff_spect, print_min_energy); URFInterface[] input_files_for_pup = trans_array; double[] pup_params = { 20, 4, 0.5, .0153 }; PUP_Device[][] pup_device_array = { { new PUP_Device("sample", null, null, 50648448, 4, pup_params) } }; boolean print_bits_in_device_pup = false; boolean print_weibull_onset_pup = false; boolean print_weibull_width_pup = false; boolean print_weibull_exponent_pup = false; boolean print_weibull_cross_sect_pup = false; PUP[] pup_array; pup_array = PUP.CreatePUP_URF(input_files_for_pup, pup_device_array, print_bits_in_device_pup, print_weibull_onset_pup, print_weibull_width_pup, print_weibull_exponent_pup, print_weibull_cross_sect_pup); LETSPEC[] let_objects_into_hup = letspec_array; double[][] weib_params = { { 9.74, 30.25, 2.5, 22600 }, { 9.74, 30.25, 2.5, 2260 }, { 9.74, 30.25, 2.5, 226 }, { 9.74, 30.25, 2.5, 22.6 }, { 9.74, 30.25, 2.5, 2.26 }, { 9.74, 30.25, 2.5, .226 }, { 9.74, 30.25, 2.5, .0226 } }; HUP_Device[][] hup_device_array = new HUP_Device[7][1]; double z_depth = (float) 0.01; for (int i = 0; i < 7; i++) { hup_device_array[i][0] = new HUP_Device("sample", null, null, 0, 0, (Math.sqrt(weib_params[i][3]) / 100), 0, (int) Math.pow(10, i), 4, weib_params[i]); z_depth += .01; } boolean print_label = false; boolean print_commenta = false; boolean print_commentb = false; boolean print_RPP_x = false; boolean print_RPP_y = false; boolean print_RPP_z = false; boolean print_funnel_length = false; boolean print_bits_in_device_hup = true; boolean print_weibull_onset_hup = false; boolean print_weibull_width_hup = false; boolean print_weibull_exponent_hup = false; boolean print_weibull_cross_sect_hup = false; HUP[] hup_array; hup_array = HUP.CreateHUP_URF(let_objects_into_hup, hup_device_array, print_label, print_commenta, print_commentb, print_RPP_x, print_RPP_y, print_RPP_z, print_funnel_length, print_bits_in_device_hup, print_weibull_onset_hup, print_weibull_width_hup, print_weibull_exponent_hup, print_weibull_cross_sect_hup); System.out.println("Finished creating User Request Files"); int num_of_files = trp_array.length + gtrn_array.length + flux_array.length + trans_array.length + letspec_array.length + pup_array.length + hup_array.length; int index = 0; String[] files_to_upload = new String[num_of_files]; for (int a = 0; a < trp_array.length; a++) { files_to_upload[index] = trp_array[a].getThisFileName(); index++; } for (int a = 0; a < gtrn_array.length; a++) { files_to_upload[index] = gtrn_array[a].getThisFileName(); index++; } for (int a = 0; a < flux_array.length; a++) { files_to_upload[index] = flux_array[a].getThisFileName(); index++; } for (int a = 0; a < trans_array.length; a++) { files_to_upload[index] = trans_array[a].getThisFileName(); index++; } for (int a = 0; a < letspec_array.length; a++) { files_to_upload[index] = letspec_array[a].getThisFileName(); index++; } for (int a = 0; a < pup_array.length; a++) { files_to_upload[index] = pup_array[a].getThisFileName(); index++; } for (int a = 0; a < hup_array.length; a++) { files_to_upload[index] = hup_array[a].getThisFileName(); index++; } Logger log = Logger.getLogger(CreateAStudy.class); String host = "creme96.nrl.navy.mil"; String user = "anonymous"; String ftppass = email; Logger.setLevel(Level.ALL); FTPClient ftp = null; try { ftp = new FTPClient(); ftp.setRemoteHost(host); FTPMessageCollector listener = new FTPMessageCollector(); ftp.setMessageListener(listener); log.info("Connecting"); ftp.connect(); log.info("Logging in"); ftp.login(user, ftppass); log.debug("Setting up passive, ASCII transfers"); ftp.setConnectMode(FTPConnectMode.ACTIVE); ftp.setType(FTPTransferType.BINARY); log.info("Putting file"); for (int u = 0; u < files_to_upload.length; u++) { ftp.put(files_to_upload[u], files_to_upload[u]); } log.info("Quitting client"); ftp.quit(); log.debug("Listener log:"); log.info("Test complete"); } catch (Exception e) { log.error("Demo failed", e); e.printStackTrace(); } System.out.println("Finished FTPing User Request Files to common directory"); Upload_Files.upload(files_to_upload, username, password, IDnumber); System.out.println("Finished transfering User Request Files to your CREME96 personal directory"); RunRoutines.routines(files_to_upload, username, password, IDnumber); System.out.println("Finished running all of your uploaded routines"); }
11
Code Sample 1: private static String fetchUrl(String url, boolean keepLineEnds) throws IOException, MalformedURLException { URLConnection destConnection = (new URL(url)).openConnection(); BufferedReader br; String inputLine; StringBuffer doc = new StringBuffer(); String contentEncoding; destConnection.setRequestProperty("Accept-Encoding", "gzip"); if (proxyAuth != null) destConnection.setRequestProperty("Proxy-Authorization", proxyAuth); destConnection.connect(); contentEncoding = destConnection.getContentEncoding(); if ((contentEncoding != null) && contentEncoding.equals("gzip")) { br = new BufferedReader(new InputStreamReader(new GZIPInputStream(destConnection.getInputStream()))); } else { br = new BufferedReader(new InputStreamReader(destConnection.getInputStream())); } while ((inputLine = br.readLine()) != null) { if (keepLineEnds) doc.append(inputLine + "\n"); else doc.append(inputLine); } br.close(); return doc.toString(); } Code Sample 2: public static void executePost(String targetURL, File file, int msec) { URL url; HttpURLConnection connection = null; try { long wrCount = 0; long fileLen = file.length(); log("File length is " + fileLen); log("Sleep " + msec + " between each send"); FileInputStream fis = new FileInputStream(file); url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml"); connection.setRequestProperty("Content-Length", Long.toString(fileLen)); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); OutputStream wr = connection.getOutputStream(); int count = 0; byte[] buffer = new byte[1024 * 10]; while ((count = fis.read(buffer)) != -1) { wr.write(buffer, 0, count); wr.flush(); wrCount += (long) count; log("Progress is " + (wrCount * 100) / fileLen + "%"); Thread.sleep(msec); } wr.close(); fis.close(); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } rd.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return; }
00
Code Sample 1: private Document getDocument(URL url) throws SAXException, IOException { InputStream is; try { is = url.openStream(); } catch (IOException io) { System.out.println("parameter error : The specified reading data is mistaken."); System.out.println(" Request URL is " + sourceUri); throw new IOException("\t" + io.toString()); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException pce) { System.out.println("error : The error of DocumentBuilder instance generation"); throw new RuntimeException(pce.toString()); } Document doc; try { doc = builder.parse(is); } catch (Exception e) { System.out.println("error : parse of reading data went wrong."); System.out.println(" Request URL is " + sourceUri); throw new RuntimeException(e.toString()); } return doc; } Code Sample 2: @Override public String getHash(String text) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(text.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void copyClassPathResource(String classPathResourceName, String fileSystemDirectoryName) { InputStream resourceInputStream = null; OutputStream fileOutputStream = null; try { resourceInputStream = FileUtils.class.getResourceAsStream(classPathResourceName); String fileName = StringUtils.substringAfterLast(classPathResourceName, "/"); File fileSystemDirectory = new File(fileSystemDirectoryName); fileSystemDirectory.mkdirs(); fileOutputStream = new FileOutputStream(fileSystemDirectoryName + "/" + fileName); IOUtils.copy(resourceInputStream, fileOutputStream); } catch (IOException e) { throw new UnitilsException(e); } finally { closeQuietly(resourceInputStream); closeQuietly(fileOutputStream); } }
11
Code Sample 1: public static void copyFile(File src, File dest, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file: " + dest); } } byte[] buffer = new byte[1]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } } Code Sample 2: @Override public void createCopy(File sourceFile, File destinnationFile) throws IOException { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinnationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
00
Code Sample 1: public void deleteMessageBuffer(String messageBufferName) throws AppFabricException { MessageBufferUtil msgBufferUtilObj = new MessageBufferUtil(solutionName, TokenConstants.getSimpleAuthAuthenticationType()); String requestUri = msgBufferUtilObj.getRequestUri(); String messageBufferUri = msgBufferUtilObj.getCreateMessageBufferUri(messageBufferName); String authorizationToken = ""; try { ACSTokenProvider tp = new ACSTokenProvider(httpWebProxyServer_, httpWebProxyPort_, this.credentials); authorizationToken = tp.getACSToken(requestUri, messageBufferUri); } catch (Exception e) { throw new AppFabricException(e.getMessage()); } try { messageBufferUri = messageBufferUri.replaceAll("http", "https"); URL urlConn = new URL(messageBufferUri); HttpURLConnection connection; if (httpWebProxy_ != null) connection = (HttpURLConnection) urlConn.openConnection(httpWebProxy_); else connection = (HttpURLConnection) urlConn.openConnection(); connection.setRequestMethod("DELETE"); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Content-type", MessageBufferConstants.getCONTENT_TYPE_PROPERTY_FOR_ATOM_XML()); String authStr = TokenConstants.getWrapAuthenticationType() + " " + TokenConstants.getWrapAuthorizationHeaderKey() + "=\"" + authorizationToken + "\""; connection.setRequestProperty("Authorization", authStr); if (LoggerUtil.getIsLoggingOn()) SDKLoggerHelper.logRequest(connection, SDKLoggerHelper.RecordType.DeleteMessageBuffer_REQUEST); String responseCode = "<responseCode>" + connection.getResponseCode() + "</responseCode>"; if ((connection.getResponseCode() == MessageBufferConstants.HTTP_STATUS_CODE_OK)) { InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); } else { throw new AppFabricException("MessageBuffer could not be deleted.Error...Response code: " + connection.getResponseCode()); } if (LoggerUtil.getIsLoggingOn()) SDKLoggerHelper.logMessage(URLEncoder.encode(responseCode, "UTF-8"), SDKLoggerHelper.RecordType.DeleteMessageBuffer_RESPONSE); } catch (Exception e) { throw new AppFabricException(e.getMessage()); } } Code Sample 2: public void xtest11() throws Exception { PDFManager manager = new ITextManager(); InputStream pdf = new FileInputStream("/tmp/UML2.pdf"); InputStream page1 = manager.cut(pdf, 1, 1); OutputStream outputStream = new FileOutputStream("/tmp/page.pdf"); IOUtils.copy(page1, outputStream); outputStream.close(); pdf.close(); }
00
Code Sample 1: public static void copyAll(URL url, StringBuilder ret) { Reader in = null; try { in = new InputStreamReader(new BufferedInputStream(url.openStream())); copyAll(in, ret); } catch (IOException e) { throw new RuntimeException(e); } finally { close(in); } } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
11
Code Sample 1: private void saveFile(Folder folder, Object key, InputStream stream) throws FileManagerException { File file = new File(folder, key.toString()); LOGGER.debug("Writing file: " + file.getAbsolutePath()); Writer writer = null; Writer encodedWriter = null; try { encodedWriter = new OutputStreamWriter(new FileOutputStream(file), getEncodeCharset()); IOUtils.copy(stream, encodedWriter, getDecodeCharset()); LOGGER.info("saveFile(), decode charset: " + getDecodeCharset() + ", encode charset: " + getEncodeCharset()); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } finally { try { encodedWriter.close(); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } } } Code Sample 2: @Test public void testCopy_inputStreamToWriter_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); try { IOUtils.copy((InputStream) null, writer); fail(); } catch (NullPointerException ex) { } }
11
Code Sample 1: public boolean copyFile(File destinationFolder, File fromFile) { boolean result = false; String toFileName = destinationFolder.getAbsolutePath() + "/" + fromFile.getName(); File toFile = new File(toFileName); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (from != null) { try { from.close(); } catch (IOException e2) { e2.printStackTrace(); } if (to != null) { try { to.close(); result = true; } catch (IOException e3) { e3.printStackTrace(); } } } } return result; } Code Sample 2: public static void copyFile(File source, File destination) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
00
Code Sample 1: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public Graph<N, E> read(final URL url) throws IOException { if (url == null) { throw new IllegalArgumentException("url must not be null"); } InputStream inputStream = null; try { inputStream = url.openStream(); return read(inputStream); } catch (IOException e) { throw e; } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { } } }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String 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: private boolean write(File file) { String filename = file.getPath(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PrintStream out = new PrintStream(byteArrayOutputStream); try { StringBuffer xml = null; if (MainFrame.getInstance().getAnimation() != null) { MainFrame.getInstance().getAnimation().xml(out, "\t"); } else { xml = MainFrame.getInstance().getModel().xml("\t"); } if (file.exists()) { BufferedReader reader = new BufferedReader(new FileReader(filename)); BufferedWriter writer = new BufferedWriter(new FileWriter(filename + "~")); char[] buffer = new char[65536]; int charsRead = 0; while ((charsRead = reader.read(buffer)) > 0) writer.write(buffer, 0, charsRead); reader.close(); writer.close(); } BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writer.write("<jpatch version=\"" + VersionInfo.ver + "\">\n"); if (xml != null) writer.write(xml.toString()); else writer.write(byteArrayOutputStream.toString()); writer.write("</jpatch>\n"); writer.close(); MainFrame.getInstance().getUndoManager().setChange(false); if (MainFrame.getInstance().getAnimation() != null) MainFrame.getInstance().getAnimation().setFile(file); else MainFrame.getInstance().getModel().setFile(file); MainFrame.getInstance().setFilename(file.getName()); return true; } catch (IOException ioException) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "Unable to save file \"" + filename + "\"\n" + ioException, "Error", JOptionPane.ERROR_MESSAGE); return false; } }
11
Code Sample 1: @SuppressWarnings("unchecked") @Override public synchronized void drop(DropTargetDropEvent arg0) { Helper.log().debug("Dropped"); Transferable t = arg0.getTransferable(); try { arg0.acceptDrop(arg0.getDropAction()); List<File> filelist = (List<File>) t.getTransferData(t.getTransferDataFlavors()[0]); for (File file : filelist) { Helper.log().debug(file.getAbsolutePath()); if (file.getName().toLowerCase().contains(".lnk")) { Helper.log().debug(file.getName() + " is a link"); File target = new File(rp.getRoot().getFullPath() + "/" + file.getName()); Helper.log().debug("I have opened the mayor at " + target.getAbsolutePath()); FileOutputStream fo = new FileOutputStream(target); FileInputStream fi = new FileInputStream(file); int i = 0; while (fi.available() > 0) { fo.write(fi.read()); System.out.print("."); i++; } Helper.log().debug(i + " bytes have been written to " + target.getAbsolutePath()); fo.close(); fi.close(); } } rp.redraw(); } catch (Throwable tr) { tr.printStackTrace(); } Helper.log().debug(arg0.getSource().toString()); } Code Sample 2: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } }
00
Code Sample 1: public String insertBuilding() { homeMap = homeMapDao.getHomeMapById(homeMap.getId()); homeBuilding.setHomeMap(homeMap); Integer id = homeBuildingDao.saveHomeBuilding(homeBuilding); String dir = "E:\\ganymede_workspace\\training01\\web\\user_buildings\\"; FileOutputStream fos; try { fos = new FileOutputStream(dir + id); IOUtils.copy(new FileInputStream(imageFile), fos); IOUtils.closeQuietly(fos); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return execute(); } Code Sample 2: private ShaderProgram loadShaderProgram() { ShaderProgram sp = null; String vertexProgram = null; String fragmentProgram = null; Shader[] shaders = new Shader[2]; try { ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("Shaders/ivory.vert"); System.out.println("url " + url); InputStream inputSteam = cl.getResourceAsStream("Shaders/ivory.vert"); Reader reader = null; if (inputSteam != null) { reader = new InputStreamReader(inputSteam); } else { File file = new File("lib"); URL url2 = new URL("jar:file:" + file.getAbsolutePath() + "/j3d-vrml97-i3mainz.jar!/Shaders/ivory.vert"); InputStream inputSteam2 = url2.openStream(); reader = new InputStreamReader(inputSteam2); } char[] buffer = new char[10000]; int len = reader.read(buffer); vertexProgram = new String(buffer); vertexProgram = vertexProgram.substring(0, len); } catch (Exception e) { System.err.println("could'nt load ivory.vert"); e.printStackTrace(); } try { ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("Shaders/ivory.frag"); System.out.println("url " + url); InputStream inputSteam = cl.getResourceAsStream("Shaders/ivory.frag"); Reader reader = null; if (inputSteam != null) { reader = new InputStreamReader(inputSteam); } else { File file = new File("lib"); URL url2 = new URL("jar:file:" + file.getAbsolutePath() + "/j3d-vrml97-i3mainz.jar!/Shaders/ivory.frag"); InputStream inputSteam2 = url2.openStream(); reader = new InputStreamReader(inputSteam2); } char[] buffer = new char[10000]; int len = reader.read(buffer); fragmentProgram = new String(buffer); fragmentProgram = fragmentProgram.substring(0, len); } catch (Exception e) { System.err.println("could'nt load ivory.frag"); e.printStackTrace(); } if (vertexProgram != null && fragmentProgram != null) { shaders[0] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_VERTEX, vertexProgram); shaders[1] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_FRAGMENT, fragmentProgram); sp = new GLSLShaderProgram(); sp.setShaders(shaders); } return sp; }
00
Code Sample 1: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } Code Sample 2: @TestTargetNew(level = TestLevel.PARTIAL_COMPLETE, notes = "Tests Proxy functionality. Indirect test.", method = "Proxy", args = { java.net.Proxy.Type.class, java.net.SocketAddress.class }) @BrokenTest("the host address isn't working anymore") public void test_openConnectionLjava_net_Proxy() throws IOException { SocketAddress addr1 = new InetSocketAddress(Support_Configuration.ProxyServerTestHost, 808); SocketAddress addr2 = new InetSocketAddress(Support_Configuration.ProxyServerTestHost, 1080); Proxy proxy1 = new Proxy(Proxy.Type.HTTP, addr1); Proxy proxy2 = new Proxy(Proxy.Type.SOCKS, addr2); Proxy proxyList[] = { proxy1, proxy2 }; for (int i = 0; i < proxyList.length; ++i) { String posted = "just a test"; URL u = new URL("http://" + Support_Configuration.ProxyServerTestHost + "/cgi-bin/test.pl"); java.net.HttpURLConnection conn = (java.net.HttpURLConnection) u.openConnection(proxyList[i]); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-length", String.valueOf(posted.length())); OutputStream out = conn.getOutputStream(); out.write(posted.getBytes()); out.close(); conn.getResponseCode(); InputStream is = conn.getInputStream(); String response = ""; byte[] b = new byte[1024]; int count = 0; while ((count = is.read(b)) > 0) { response += new String(b, 0, count); } assertTrue("Response to POST method invalid", response.equals(posted)); } URL httpUrl = new URL("http://abc.com"); URL jarUrl = new URL("jar:" + Support_Resources.getResourceURL("/JUC/lf.jar!/plus.bmp")); URL ftpUrl = new URL("ftp://" + Support_Configuration.FTPTestAddress + "/nettest.txt"); URL fileUrl = new URL("file://abc"); URL[] urlList = { httpUrl, jarUrl, ftpUrl, fileUrl }; for (int i = 0; i < urlList.length; ++i) { try { urlList[i].openConnection(null); } catch (IllegalArgumentException iae) { } } fileUrl.openConnection(Proxy.NO_PROXY); }
00
Code Sample 1: public void delete(String name) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); AttributeTable attribute = new AttributeTable(); attribute.deleteAllForType(stmt, name); String sql = "delete from AttributeCategories " + "where CategoryName = '" + name + "'"; stmt.executeUpdate(sql); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: public static void upload(FTPDetails ftpDetails) { FTPClient ftp = new FTPClient(); try { String host = ftpDetails.getHost(); logger.info("Connecting to ftp host: " + host); ftp.connect(host); logger.info("Received reply from ftp :" + ftp.getReplyString()); ftp.login(ftpDetails.getUserName(), ftpDetails.getPassword()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.makeDirectory(ftpDetails.getRemoterDirectory()); logger.info("Created directory :" + ftpDetails.getRemoterDirectory()); ftp.changeWorkingDirectory(ftpDetails.getRemoterDirectory()); BufferedInputStream ftpInput = new BufferedInputStream(new FileInputStream(new File(ftpDetails.getLocalFilePath()))); OutputStream storeFileStream = ftp.storeFileStream(ftpDetails.getRemoteFileName()); IOUtils.copy(ftpInput, storeFileStream); logger.info("Copied file : " + ftpDetails.getLocalFilePath() + " >>> " + host + ":/" + ftpDetails.getRemoterDirectory() + "/" + ftpDetails.getRemoteFileName()); ftpInput.close(); storeFileStream.close(); ftp.logout(); ftp.disconnect(); logger.info("Logged out. "); } catch (Exception e) { throw new RuntimeException(e); } }
11
Code Sample 1: private void addIngredients(Recipe recipe, int id) throws Exception { PreparedStatement pst = null; try { conn = getConnection(); pst = conn.prepareStatement("INSERT INTO ingredients (recipe_id, name, amount, measure_id, shop_flag) VALUES (?,?,?,?,?)"); IngredientContainer ings = recipe.getIngredients(); Ingredient ingBean = null; Iterator it; for (it = ings.getIngredients().iterator(); it.hasNext(); ) { ingBean = (Ingredient) it.next(); pst.setInt(1, id); pst.setString(2, ingBean.getName()); pst.setDouble(3, ingBean.getAmount()); pst.setInt(4, ingBean.getType()); pst.setInt(5, ingBean.getShopFlag()); pst.executeUpdate(); } conn.commit(); } catch (Exception e) { conn.rollback(); MainFrame.appendStatusText("Can't add ingredient, the exception was " + e.getMessage()); } finally { try { if (pst != null) pst.close(); pst = null; } catch (Exception ex) { MainFrame.appendStatusText("Can't close database connection."); } } } Code Sample 2: public static void batchInsertOrder(Order o) throws AppException { Connection conn = DBUtils.getDataConnection(); PreparedStatement pstmt = null; ResultSet rs = null; String sqlOrder = null; String sqlDetail = null; try { conn.setAutoCommit(false); sqlOrder = "insert into SO_SOMain (ID,cSOCode,dDate," + "cBusType,cCusCode,cCusName," + "cDepCode,cSTCode," + "iVTid,cMaker,cMemo) values (?,?,?,?,?,?,?,?,?,?,?)"; sqlDetail = "insert into SO_SODetails (ID,cSOCode,cInvCode,cInvName," + "iNum,iQuantity,iTaxUnitPrice,iSum,dPreDate,iSOsID,cFree1,cUnitID) values(?,?,?,?,?,?,?,?,?,?,?,?)"; pstmt = conn.prepareStatement(sqlOrder); long maxId = getMaxID(conn, pstmt, rs); maxId++; pstmt.setLong(1, maxId); Long l = maxId; o.setId(l.intValue()); String code = o.getCode(); long maxCSOCode = getMaxCSOCode(code, conn, pstmt, rs); String csOCode = getCSOCode(code, maxCSOCode); o.setCode(csOCode); pstmt.setString(2, csOCode); pstmt.setDate(3, DateUtil.getSqlDateFormUtilDate(o.getOrderDate())); pstmt.setString(4, o.getBusinessType()); pstmt.setString(5, o.getC().getId()); pstmt.setString(6, o.getC().getName()); pstmt.setString(7, o.getP().getDept().getId()); pstmt.setString(8, o.getSaleType().getId()); pstmt.setInt(9, o.getiVtid()); pstmt.setString(10, o.getP().getName()); pstmt.setString(11, o.getRemark()); pstmt.executeUpdate(); pstmt.clearParameters(); pstmt = conn.prepareStatement(sqlDetail); ArrayList<OrderDetail> ods = o.getOds(); long iSOsID = getiSOsID(conn, pstmt, rs); for (OrderDetail od : ods) { pstmt.setLong(1, maxId); pstmt.setString(2, csOCode); pstmt.setString(3, od.getInventory().getId()); pstmt.setString(4, od.getInventory().getName()); pstmt.setInt(5, od.getPiece()); pstmt.setBigDecimal(6, od.getCount()); pstmt.setBigDecimal(7, od.getPrice()); pstmt.setBigDecimal(8, od.getSum()); pstmt.setDate(9, DateUtil.getSqlDateFormUtilDate(od.getSendDate())); pstmt.setLong(10, ++iSOsID); pstmt.setString(11, od.getPacking().getcValue()); pstmt.setString(12, od.getInventory().getSAComUnitCode()); pstmt.executeUpdate(); pstmt.clearParameters(); } conn.commit(); } catch (SQLException sqle) { try { conn.rollback(); throw new AppException(sqle.getMessage()); } catch (SQLException ex) { Logger.getLogger(OrderDAO.class.getName()).log(Level.SEVERE, null, ex); throw new AppException(ex.getMessage()); } } finally { DBUtils.closeAll(rs, pstmt, conn); } }
00
Code Sample 1: private String sha1(String s) { String encrypt = s; try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(s.getBytes()); byte[] digest = sha.digest(); final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { final byte b = digest[i]; final int value = (b & 0x7F) + (b < 0 ? 128 : 0); buffer.append(value < 16 ? "0" : ""); buffer.append(Integer.toHexString(value)); } encrypt = buffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encrypt; } Code Sample 2: public static List<ServerInfo> getStartedServers() { List<ServerInfo> infos = new ArrayList<ServerInfo>(); try { StringBuilder request = new StringBuilder(); request.append(url).append("/").append(displayServlet); request.append("?ingame=1"); URL objUrl = new URL(request.toString()); URLConnection urlConnect = objUrl.openConnection(); InputStream in = urlConnect.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); while (reader.ready()) { String name = reader.readLine(); String ip = reader.readLine(); int port = Integer.valueOf(reader.readLine()); ServerInfo server = new ServerInfo(name, ip, port); server.nbPlayers = Integer.valueOf(reader.readLine()); infos.add(server); } in.close(); return infos; } catch (Exception e) { return infos; } }
00
Code Sample 1: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } 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: void copyFileOnPeer(String path, RServerInfo peerserver, boolean allowoverwrite) throws IOException { RFile file = new RFile(path); OutputStream out = null; FileInputStream in = null; try { in = fileManager.openFileRead(path); out = localClient.openWrite(file, false, WriteMode.TRANSACTED, 1, peerserver, !allowoverwrite); IOUtils.copyLarge(in, out); out.close(); out = null; } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (out != null) { try { out.close(); } catch (Throwable t) { } } } } Code Sample 2: public static void transfer(File src, File dest, boolean removeSrc) throws FileNotFoundException, IOException { Log.warning("source: " + src); Log.warning("dest: " + dest); if (!src.canRead()) { throw new IOException("can not read src file: " + src); } if (!dest.getParentFile().isDirectory()) { if (!dest.getParentFile().mkdirs()) { throw new IOException("failed to make directories: " + dest.getParent()); } } FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); Log.warning("starting transfer from position " + fcin.position() + " to size " + fcin.size()); fcout.transferFrom(fcin, 0, fcin.size()); Log.warning("closing streams and channels"); fcin.close(); fcout.close(); fis.close(); fos.close(); if (removeSrc) { Log.warning("deleting file " + src); src.delete(); } }
11
Code Sample 1: public static String scramble(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (byte b : md.digest()) sb.append(Integer.toString(b & 0xFF, 16)); return sb.toString(); } catch (UnsupportedEncodingException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } } Code Sample 2: public static String SHA1(String string) throws XLWrapException { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new XLWrapException("SHA-1 message digest is not available."); } byte[] data = new byte[40]; md.update(string.getBytes()); data = md.digest(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); }
11
Code Sample 1: private static String md5(String input) { String res = ""; try { MessageDigest cript = MessageDigest.getInstance("MD5"); cript.reset(); cript.update(input.getBytes()); byte[] md5 = cript.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (NoSuchAlgorithmException ex) { Log4k.error(pdfPrinter.class.getName(), ex.getMessage()); } return res; } Code Sample 2: protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { ChallengeAction challengeAction; ManagerResponse challengeResponse; String challenge; String key; LoginAction loginAction; ManagerResponse loginResponse; if (socket == null) { connect(); } synchronized (protocolIdentifier) { if (protocolIdentifier.value == null) { try { protocolIdentifier.wait(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (protocolIdentifier.value == null) { disconnect(); if (reader != null && reader.getTerminationException() != null) { throw reader.getTerminationException(); } else { throw new TimeoutException("Timeout waiting for protocol identifier"); } } } challengeAction = new ChallengeAction("MD5"); try { challengeResponse = sendAction(challengeAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send challenge action", e); } if (challengeResponse instanceof ChallengeResponse) { challenge = ((ChallengeResponse) challengeResponse).getChallenge(); } else { disconnect(); throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + challengeResponse.getMessage()); } try { MessageDigest md; md = MessageDigest.getInstance("MD5"); if (challenge != null) { md.update(challenge.getBytes()); } if (password != null) { md.update(password.getBytes()); } key = ManagerUtil.toHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { disconnect(); throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } loginAction = new LoginAction(username, "MD5", key, eventMask); try { loginResponse = sendAction(loginAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send login action", e); } if (loginResponse instanceof ManagerError) { disconnect(); throw new AuthenticationFailedException(loginResponse.getMessage()); } state = CONNECTED; logger.info("Successfully logged in"); version = determineVersion(); writer.setTargetVersion(version); logger.info("Determined Asterisk version: " + version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); }
11
Code Sample 1: public void delete(Connection conn, boolean commit) throws SQLException { PreparedStatement stmt = null; if (isNew()) { String errorMessage = "Unable to delete non-persistent DAO '" + getClass().getName() + "'"; if (log.isErrorEnabled()) { log.error(errorMessage); } throw new SQLException(errorMessage); } try { stmt = conn.prepareStatement(getDeleteSql()); stmt.setObject(1, getPrimaryKey()); int rowCount = stmt.executeUpdate(); if (rowCount != 1) { if (commit) { conn.rollback(); } String errorMessage = "Invalid number of rows changed!"; if (log.isErrorEnabled()) { log.error(errorMessage); } throw new SQLException(errorMessage); } else if (commit) { conn.commit(); } } finally { OvJdbcUtils.closeStatement(stmt); } } Code Sample 2: private void alterarArtista(Artista artista) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "UPDATE artista SET nome = ?,sexo = ?,email = ?,obs = ?,telefone = ? where numeroinscricao = ?"; ps = conn.prepareStatement(sql); ps.setString(1, artista.getNome()); ps.setBoolean(2, artista.isSexo()); ps.setString(3, artista.getEmail()); ps.setString(4, artista.getObs()); ps.setString(5, artista.getTelefone()); ps.setInt(6, artista.getNumeroInscricao()); ps.executeUpdate(); alterarEndereco(conn, ps, artista); delObras(conn, ps, artista.getNumeroInscricao()); sql = "insert into obra VALUES (?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); for (Obra obra : artista.getListaObras()) { salvarObra(conn, ps, obra, artista.getNumeroInscricao()); } conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } }
00
Code Sample 1: public final String encrypt(String input) throws Exception { try { MessageDigest messageDigest = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); messageDigest.reset(); messageDigest.update(input.getBytes()); String output = convert(messageDigest.digest()); return output; } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Fatal Error while digesting input string", ex); } } return input; } Code Sample 2: public static AudioInputStream getWavFromURL(String urlstr) { URL url; AudioInputStream ais = null; try { url = new URL(urlstr); URLConnection c = url.openConnection(); c.connect(); InputStream stream = c.getInputStream(); ais = new AudioInputStream(stream, playFormat, AudioSystem.NOT_SPECIFIED); LOG.debug("[getWavFromURL]Getting audio from URL: {}", url); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ais; }
11
Code Sample 1: public static final void copyFile(File source, File destination) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(destination).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); } Code Sample 2: @Override public void run() { try { FileChannel in = new FileInputStream(inputfile).getChannel(); long pos = 0; for (int i = 1; i <= noofparts; i++) { FileChannel out = new FileOutputStream(outputfile.getAbsolutePath() + "." + "v" + i).getChannel(); status.setText("Rozdělovač: Rozděluji část " + i + ".."); in.transferTo(pos, splitsize, out); pos += splitsize; remainingsize -= splitsize; if (remainingsize < splitsize) in.transferTo(pos, remainingsize, out); pb.setValue(100 * i / noofparts); out.close(); } in.close(); if (deleteOnFinish) new File(inputfile + "").delete(); status.setText("Rozdělovač: Hotovo.."); JOptionPane.showMessageDialog(null, "Rozděleno!", "Rozdělovač", JOptionPane.INFORMATION_MESSAGE); } catch (IOException ex) { } }
00
Code Sample 1: private static String readJarURL(URL url) throws IOException { JarURLConnection juc = (JarURLConnection) url.openConnection(); InputStream in = juc.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int i = in.read(); while (i != -1) { out.write(i); i = in.read(); } return out.toString(); } Code Sample 2: public static boolean matchPassword(String prevPassStr, String newPassword) throws NoSuchAlgorithmException, java.io.IOException, java.io.UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] seed = new byte[12]; byte[] prevPass = new sun.misc.BASE64Decoder().decodeBuffer(prevPassStr); System.arraycopy(prevPass, 0, seed, 0, 12); md.update(seed); md.update(newPassword.getBytes("UTF8")); byte[] digestNewPassword = md.digest(); byte[] choppedPrevPassword = new byte[prevPass.length - 12]; System.arraycopy(prevPass, 12, choppedPrevPassword, 0, prevPass.length - 12); boolean isMatching = Arrays.equals(digestNewPassword, choppedPrevPassword); return isMatching; }
11
Code Sample 1: private void execute(String file, String[] ebms, String[] eems, String[] ims, String[] efms) throws BuildException { if (verbose) { System.out.println("Preprocessing file " + file + " (type: " + type + ")"); } try { File targetFile = new File(file); FileReader fr = new FileReader(targetFile); BufferedReader reader = new BufferedReader(fr); File preprocFile = File.createTempFile(targetFile.getName(), "tmp", targetFile.getParentFile()); FileWriter fw = new FileWriter(preprocFile); BufferedWriter writer = new BufferedWriter(fw); int result = preprocess(reader, writer, ebms, eems, ims, efms); reader.close(); writer.close(); switch(result) { case OVERWRITE: if (!targetFile.delete()) { System.out.println("Can't overwrite target file with preprocessed file"); throw new BuildException("Can't overwrite target file " + target + " with preprocessed file"); } preprocFile.renameTo(targetFile); if (verbose) { System.out.println("File " + preprocFile.getName() + " modified."); } modifiedCnt++; break; case REMOVE: if (!targetFile.delete()) { System.out.println("Can't delete target file"); throw new BuildException("Can't delete target file " + target); } if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file " + preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file " + preprocFile.getName()); } if (verbose) { System.out.println("File " + preprocFile.getName() + " removed."); } removedCnt++; break; case KEEP: if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file " + preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file " + preprocFile.getName()); } break; default: throw new BuildException("Unexpected preprocessing result for file " + preprocFile.getName()); } } catch (Exception e) { e.printStackTrace(); throw new BuildException(e.getMessage()); } } Code Sample 2: private File writeResourceToFile(String resource) throws IOException { File tmp = File.createTempFile("zfppt" + resource, null); InputStream res = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); OutputStream out = new FileOutputStream(tmp); IOUtils.copy(res, out); out.close(); return tmp; }
00
Code Sample 1: public Request call() { InputStream is = null; try { if (DEBUG) Log.d(TAG, "Requesting: " + request.uri); HttpGet httpGet = new HttpGet(request.uri.toString()); httpGet.addHeader("Accept-Encoding", "gzip"); HttpResponse response = mHttpClient.execute(httpGet); String mimeType = response.getHeaders("Content-Type")[0].getValue(); if (DEBUG) Log.d(TAG, "mimeType:" + mimeType); if (mimeType.startsWith("image")) { HttpEntity entity = response.getEntity(); is = getUngzippedContent(entity); Bitmap bitmap = BitmapFactory.decodeStream(is); if (mResourceCache.store(request.hash, bitmap)) { mCache.put(request.uri.toString(), new SoftReference<Bitmap>(bitmap)); if (DEBUG) Log.d(TAG, "Request successful: " + request.uri); } else { mResourceCache.invalidate(request.hash); } } } catch (IOException e) { if (DEBUG) Log.d(TAG, "IOException", e); } finally { if (DEBUG) Log.e(TAG, "Request finished: " + request.uri); mActiveRequestsMap.remove(request); if (is != null) { notifyObservers(request.uri); } try { if (is != null) { is.close(); } } catch (IOException e) { if (DEBUG) e.printStackTrace(); } } return request; } Code Sample 2: public static void copy(File source, File dest) throws java.io.IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: public void sendFile(File file, String filename, String contentType) throws SearchLibException { response.setContentType(contentType); response.addHeader("Content-Disposition", "attachment; filename=" + filename); FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); ServletOutputStream outputStream = getOutputStream(); IOUtils.copy(inputStream, outputStream); outputStream.close(); } catch (FileNotFoundException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } finally { if (inputStream != null) IOUtils.closeQuietly(inputStream); } } Code Sample 2: public byte[] getHash(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(salt.getBytes("UTF-8")); return digest.digest(plaintext.getBytes("UTF-8")); }
00
Code Sample 1: public void testStreamURL() throws Exception { boolean ok = false; String url = "http://www.apache.org/dist/lucene/solr/"; String txt = null; try { txt = IOUtils.toString(new URL(url).openStream()); } catch (Exception ex) { fail("this test only works if you have a network connection."); return; } SolrCore core = h.getCore(); Map<String, String[]> args = new HashMap<String, String[]>(); args.put(CommonParams.STREAM_URL, new String[] { url }); List<ContentStream> streams = new ArrayList<ContentStream>(); parser.buildRequestFrom(core, new MultiMapSolrParams(args), streams); assertEquals(1, streams.size()); assertEquals(txt, IOUtils.toString(streams.get(0).getStream())); } Code Sample 2: public static void bubble(double[] a) { for (int i = a.length - 1; i > 0; i--) for (int j = 0; j < i; j++) if (a[j] > a[j + 1]) { double temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } }
00
Code Sample 1: public void xtestGetThread() throws Exception { GMSearchOptions options = new GMSearchOptions(); options.setFrom(loginInfo.getUsername() + "*"); options.setSubject("message*"); GMSearchResponse mail = client.getMail(options); for (Iterator it = mail.getThreadSnapshots().iterator(); it.hasNext(); ) { GMThreadSnapshot threadSnapshot = (GMThreadSnapshot) it.next(); GMThread thread = client.getThread(threadSnapshot.getThreadID()); log.info("Most Recent Thread: " + thread); for (Iterator iter = thread.getMessages().iterator(); iter.hasNext(); ) { GMMessage message = (GMMessage) iter.next(); log.info("Message: " + message); Iterable<GMAttachment> attachments = message.getAttachments(); for (Iterator iterator = attachments.iterator(); iterator.hasNext(); ) { GMAttachment attachment = (GMAttachment) iterator.next(); String ext = FilenameUtils.getExtension(attachment.getFilename()); if (ext.trim().length() > 0) ext = "." + ext; String base = FilenameUtils.getBaseName(attachment.getFilename()); File file = File.createTempFile(base, ext, new File(System.getProperty("user.home"))); log.info("Saving attachment: " + file.getPath()); InputStream attStream = client.getAttachmentAsStream(attachment.getId(), message.getMessageID()); IOUtils.copy(attStream, new FileOutputStream(file)); attStream.close(); assertEquals(file.length(), attachment.getSize()); log.info("Done. Successfully saved: " + file.getPath()); file.delete(); } } } } Code Sample 2: public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { URL url; URLConnection urlConn; DataOutputStream dos; DataInputStream dis; monitor.beginTask("Uploading log to placelab.org", 100); StringBuffer dfsb = new SimpleDateFormat("M/dd/yyyy").format(new java.util.Date(), new StringBuffer(), new FieldPosition(0)); String dateStr = dfsb.toString(); monitor.subTask("Connecting"); if (monitor.isCanceled()) throw new InterruptedException(); url = new URL(urlString); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); dos = new DataOutputStream(urlConn.getOutputStream()); monitor.worked(10); monitor.subTask("Encoding headers"); if (monitor.isCanceled()) throw new InterruptedException(); String args = "username=" + URLEncoder.encode(username) + "&" + "passwd=" + URLEncoder.encode(passwd) + "&" + "readDisclaimer=agree&" + "cvt_to_ns=true&" + "trace_device=" + URLEncoder.encode(device) + "&" + "trace_descr=" + URLEncoder.encode(description) + "&" + "mailBack=on&" + "simple_output=true&" + "trace_date=" + URLEncoder.encode(dateStr) + "&" + "trace_data="; if (header != null) { args = args + URLEncoder.encode(header); } System.out.println("upload args = " + args); dos.writeBytes(args); monitor.worked(5); monitor.subTask("Sending log"); if (monitor.isCanceled()) throw new InterruptedException(); File f = new File(file); long numBytes = f.length(); FileInputStream is = new FileInputStream(file); boolean done = false; byte[] buf = new byte[1024]; while (!done) { int cnt = is.read(buf, 0, buf.length); if (cnt == -1) { done = true; } else { if (monitor.isCanceled()) throw new InterruptedException(); dos.writeBytes(URLEncoder.encode(new String(buf, 0, cnt))); Logger.println(URLEncoder.encode(new String(buf, 0, cnt)), Logger.HIGH); monitor.worked((int) (((double) cnt / (double) numBytes) * 80)); } } is.close(); dos.flush(); dos.close(); monitor.subTask("getting response from placelab.org"); if (monitor.isCanceled()) throw new InterruptedException(); dis = new DataInputStream(urlConn.getInputStream()); StringBuffer sb = new StringBuffer(); done = false; while (!done) { int read = dis.read(buf, 0, buf.length); if (read == -1) { done = true; } else { sb.append(new String(buf, 0, read)); } } String s = sb.toString(); dis.close(); Logger.println("Got back " + s, Logger.LOW); if (s.equals("SUCCESS")) { Logger.println("Whoo!!!", Logger.HIGH); } else { Logger.println("Post Error!", Logger.HIGH); throw new InvocationTargetException(new PlacelabOrgFailure(s)); } monitor.worked(5); monitor.done(); } catch (InterruptedException ie) { throw new InterruptedException(); } catch (Exception e) { throw new InvocationTargetException(e); } }