label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: private String save(UploadedFile imageFile) { try { File saveFld = new File(imageFolder + File.separator + userDisplay.getUser().getUsername()); if (!saveFld.exists()) { if (!saveFld.mkdir()) { logger.info("Unable to create folder: " + saveFld.getAbsolutePath()); return null; } } File tmp = File.createTempFile("img", "img"); IOUtils.copy(imageFile.getInputstream(), new FileOutputStream(tmp)); File thumbnailImage = new File(saveFld + File.separator + UUID.randomUUID().toString() + ".png"); File fullResolution = new File(saveFld + File.separator + UUID.randomUUID().toString() + ".png"); BufferedImage image = ImageIO.read(tmp); Image thumbnailIm = image.getScaledInstance(310, 210, Image.SCALE_SMOOTH); BufferedImage thumbnailBi = new BufferedImage(thumbnailIm.getWidth(null), thumbnailIm.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics bg = thumbnailBi.getGraphics(); bg.drawImage(thumbnailIm, 0, 0, null); bg.dispose(); ImageIO.write(thumbnailBi, "png", thumbnailImage); ImageIO.write(image, "png", fullResolution); if (!tmp.delete()) { logger.info("Unable to delete: " + tmp.getAbsolutePath()); } String imageId = UUID.randomUUID().toString(); imageBean.addImage(imageId, new ImageRecord(imageFile.getFileName(), fullResolution.getAbsolutePath(), thumbnailImage.getAbsolutePath(), userDisplay.getUser().getUsername())); return imageId; } catch (Throwable t) { logger.log(Level.SEVERE, "Unable to save the image.", t); return null; } } Code Sample 2: public void execute() throws MojoExecutionException, MojoFailureException { try { this.getLog().info("copy source web.xml - " + this.getWebXml() + " to build dir (source web.xml required if mergewebxml execution is enabled)"); File destination = new File(this.getBuildDir(), "web.xml"); if (!destination.exists()) { destination.getParentFile().mkdirs(); destination.createNewFile(); } FileIOUtils.copyFile(this.getWebXml(), destination); for (int i = 0; i < this.getCompileTarget().length; i++) { File moduleFile = null; for (Iterator it = this.getProject().getCompileSourceRoots().iterator(); it.hasNext() && moduleFile == null; ) { File check = new File(it.next().toString() + "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"); getLog().debug("Looking for file: " + check.getAbsolutePath()); if (check.exists()) { moduleFile = check; } } for (Iterator it = this.getProject().getResources().iterator(); it.hasNext(); ) { Resource r = (Resource) it.next(); File check = new File(r.getDirectory() + "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"); getLog().debug("Looking for file: " + check.getAbsolutePath()); if (check.exists()) { moduleFile = check; } } ClassLoader loader = this.fixThreadClasspath(); if (moduleFile == null) { try { String classpath = "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"; InputStream is = loader.getResourceAsStream(classpath); System.out.println("Looking for classpath: " + classpath + "(" + (is != null) + ")"); if (is != null) { File temp = new File(this.getBuildDir(), this.getCompileTarget()[i].concat(".gwt.xml")); FileOutputStream fos = new FileOutputStream(temp); FileIOUtils.copyStream(is, fos); moduleFile = temp; } } catch (IOException e) { this.getLog().info(e); } } GwtWebInfProcessor processor = null; try { if (moduleFile != null) { getLog().info("Module file: " + moduleFile.getAbsolutePath()); processor = new GwtWebInfProcessor(this.getCompileTarget()[i], moduleFile, destination.getAbsolutePath(), destination.getAbsolutePath(), this.isWebXmlServletPathAsIs()); processor.process(); } else { throw new MojoExecutionException("module file null"); } } catch (ExitException e) { this.getLog().info(e.getMessage()); } } } catch (Exception e) { throw new MojoExecutionException("Unable to merge web.xml", e); } }
11
Code Sample 1: protected boolean loadJarLibrary(final String jarLib) { final String tempLib = System.getProperty("java.io.tmpdir") + File.separator + jarLib; boolean copied = IOUtils.copyFile(jarLib, tempLib); if (!copied) { return false; } System.load(tempLib); return true; } 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 static void uploadFile(File in, String out, String host, int port, String path, String login, String password, boolean renameIfExist) throws IOException { FTPClient ftp = null; try { m_logCat.info("Uploading " + in + " to " + host + ":" + port + " at " + path); ftp = new FTPClient(); int reply; ftp.connect(host, port); m_logCat.info("Connected to " + host + "... Trying to authenticate"); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); m_logCat.error("FTP server " + host + " refused connection."); throw new IOException("Cannot connect to the FTP Server: connection refused."); } if (!ftp.login(login, password)) { ftp.logout(); throw new IOException("Cannot connect to the FTP Server: login / password is invalid!"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (!ftp.changeWorkingDirectory(path)) { m_logCat.warn("Remote working directory: " + path + "does not exist on the FTP Server ..."); m_logCat.info("Trying to create remote directory: " + path); if (!ftp.makeDirectory(path)) { m_logCat.error("Failed to create remote directory: " + path); throw new IOException("Failed to store " + in + " in the remote directory: " + path); } if (!ftp.changeWorkingDirectory(path)) { m_logCat.error("Failed to change directory. Unexpected error"); throw new IOException("Failed to change to remote directory : " + path); } } if (out == null) { out = in.getName(); if (out.startsWith("/")) { out = out.substring(1); } } if (renameIfExist) { String[] files = ftp.listNames(); String f = in + out; for (int i = 0; i < files.length; i++) { if (files[i].equals(out)) { m_logCat.debug("Found existing file on the server: " + out); boolean rename_ok = false; String bak = "_bak"; int j = 0; String newExt = null; while (!rename_ok) { if (j == 0) newExt = bak; else newExt = bak + j; if (ftp.rename(out, out + newExt)) { m_logCat.info(out + " renamed to " + out + newExt); rename_ok = true; } else { m_logCat.warn("Renaming to " + out + newExt + " has failed!, trying again ..."); j++; } } break; } } } InputStream input = new FileInputStream(in); m_logCat.info("Starting transfert of " + in); ftp.storeFile(out, input); m_logCat.info(in + " uploaded successfully"); input.close(); ftp.logout(); } catch (FTPConnectionClosedException e) { m_logCat.error("Server closed connection.", e); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { } } } } 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 static String getDeclaredXMLEncoding(URL url) throws IOException { InputStream stream = url.openStream(); BufferedReader buffReader = new BufferedReader(new InputStreamReader(stream)); String firstLine = buffReader.readLine(); if (firstLine == null) { return SYSTEM_ENCODING; } int piStart = firstLine.indexOf("<?xml version=\"1.0\""); if (piStart != -1) { int attributeStart = firstLine.indexOf("encoding=\""); if (attributeStart >= 0) { int nextQuote = firstLine.indexOf('"', attributeStart + 10); if (nextQuote >= 0) { String encoding = firstLine.substring(attributeStart + 10, nextQuote); return encoding.trim(); } } } stream.close(); return SYSTEM_ENCODING; } Code Sample 2: private void nioBuild() { try { final ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 4); final FileChannel out = new FileOutputStream(dest).getChannel(); for (File part : parts) { setState(part.getName(), BUILDING); FileChannel in = new FileInputStream(part).getChannel(); while (in.read(buffer) > 0) { buffer.flip(); written += out.write(buffer); buffer.clear(); } in.close(); } out.close(); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static final void copy(String source, String destination) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } catch (FileNotFoundException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } }
00
Code Sample 1: public String readURL(URL url) throws JasenException { OutputStream out = new ByteArrayOutputStream(); InputStream in = null; String html = null; NonBlockingStreamReader reader = null; try { in = url.openStream(); reader = new NonBlockingStreamReader(); reader.read(in, out, readBufferSize, readTimeout, null); html = new String(((ByteArrayOutputStream) out).toByteArray()); } catch (IOException e) { throw new JasenException(e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } return html; } Code Sample 2: PackageFileImpl(PackageDirectoryImpl dir, String name, InputStream data) throws IOException { this.dir = dir; this.name = name; this.updates = dir.getUpdates(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); IOUtils.copy(data, stream); updates.setNewData(getFullName(), stream.toByteArray()); stream.close(); }
11
Code Sample 1: @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); } Code Sample 2: public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream())); File targetDirectoryAsFile = new File(targetDirectory); if (!targetDirectoryAsFile.exists()) { FileUtils.forceMkdir(targetDirectoryAsFile); } File target = new File(targetDirectory, targetFile); BufferedOutputStream dest = null; while (zis.getNextEntry() != null) { if (!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos); IOUtils.copy(zis, dest); dest.flush(); dest.close(); } zis.close(); if (!target.exists()) { throw new IllegalStateException("Could not decompress anything from the archive!"); } return RepeatStatus.FINISHED; }
11
Code Sample 1: void copyFile(File inputFile, File outputFile) { try { FileReader in; in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: protected void copy(File source, File destination) throws IOException { final FileChannel inChannel = new FileInputStream(source).getChannel(); final FileChannel outChannel = new FileOutputStream(destination).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
00
Code Sample 1: private Element makeRequest(String link) { try { URL url = new URL(link); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); InputStream in = conn.getInputStream(); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(in); Element element = document.getDocumentElement(); element.normalize(); if (checkRootTag(element)) { return element; } else { return null; } } catch (IOException e) { e.printStackTrace(); return null; } catch (ParserConfigurationException e) { e.printStackTrace(); return null; } catch (SAXException e) { e.printStackTrace(); return null; } } Code Sample 2: protected int doExecuteUpdate(PreparedStatement statement) throws SQLException { connection.setAutoCommit(isAutoCommit()); int rs = -1; try { lastError = null; rs = statement.executeUpdate(); if (!isAutoCommit()) connection.commit(); } catch (Exception ex) { if (!isAutoCommit()) { lastError = ex; connection.rollback(); LogUtils.log(Level.SEVERE, "Transaction is being rollback. Error: " + ex.toString()); } } finally { if (statement != null) statement.close(); } return rs; }
00
Code Sample 1: @Override public void execute(IAlert alert, IReport report, Rule rule, Row row) { try { URL url = new URL(getUrl()); URLConnection con = url.openConnection(); con.setConnectTimeout(getTimeout()); con.setDoOutput(true); OutputStream out = con.getOutputStream(); out.write(formatOutput(report, alert, rule, row).getBytes()); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder input = new StringBuilder(); String line = null; while ((line = in.readLine()) != null) { input.append(line); input.append('\n'); } in.close(); this.lastResult = input.toString(); } catch (Throwable e) { logError("Error sending alert", e); if (!isHeadless()) { alert.setEnabled(false); JOptionPane.showMessageDialog(null, "Can't send alert " + e + "\n" + alert.getName() + " alert disabled.", "Action Error", JOptionPane.ERROR_MESSAGE); } } } Code Sample 2: public static String genDigest(String info) { MessageDigest alga; byte[] digesta = null; try { alga = MessageDigest.getInstance("SHA-1"); alga.update(info.getBytes()); digesta = alga.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return byte2hex(digesta); }
00
Code Sample 1: private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static boolean copyFile(final File fileFrom, final File fileTo) { assert fileFrom != null : "fileFrom is null"; assert fileTo != null : "fileTo is null"; LOGGER.info(buildLogString(COPY_FILE_INFO, new Object[] { fileFrom, fileTo })); boolean error = true; FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(fileFrom); outputStream = new FileOutputStream(fileTo); final FileChannel inChannel = inputStream.getChannel(); final FileChannel outChannel = outputStream.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); error = false; } catch (final IOException e) { LOGGER.log(SEVERE, buildLogString(COPY_FILE_ERROR, new Object[] { fileFrom, fileTo }), e); } finally { closeCloseable(inputStream, fileFrom); closeCloseable(outputStream, fileTo); } return error; } Code Sample 2: @Override public HostRecord addressForHost(String domainName) throws Exception { String fullUrl = requestUrlStub + domainName; URL url = new URL(fullUrl); HttpURLConnection connection = null; connection = null; connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setReadTimeout(10000); connection.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; HostRecord result = new HostRecord(domainName); byte parts[] = new byte[4]; while ((inputLine = in.readLine()) != null) { String pat1 = "<span class='orange'>"; String pat2 = "</span>"; int index1 = inputLine.indexOf(pat1); int index2 = inputLine.indexOf(pat2); if ((index1 > 0) && (index2 > 0)) { String ipStr = inputLine.substring(index1 + pat1.length(), index2); String[] s = ipStr.split("\\."); for (int i = 0; i < s.length; i++) parts[i] = (byte) Integer.parseInt(s[i]); } } IPAddress ipAddress = new IPAddress(parts); result.addIpAddress(ipAddress); in.close(); return result; }
00
Code Sample 1: public void loginToServer() { new Thread(new Runnable() { public void run() { if (!shouldLogin) { u.p("skipping the auto-login"); return; } try { u.p("logging in to the server"); String query = "hostname=blahfoo2.com" + "&osname=" + URLEncoder.encode(System.getProperty("os.name"), "UTF-8") + "&javaver=" + URLEncoder.encode(System.getProperty("java.runtime.version"), "UTF-8") + "&timezone=" + URLEncoder.encode(TimeZone.getDefault().getID(), "UTF-8"); u.p("unencoded query: \n" + query); String login_url = "http://joshy.org:8088/org.glossitopeTracker/login.jsp?"; String url = login_url + query; u.p("final encoded url = \n" + url); InputStream in = new URL(url).openStream(); byte[] buf = new byte[256]; while (true) { int n = in.read(buf); if (n == -1) break; for (int i = 0; i < n; i++) { } } } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } }, "LoginToServerAction").start(); } Code Sample 2: public static boolean copyFile(File from, File tu) { final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(tu); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { return false; } return true; }
00
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public static void main(String[] a) throws Exception { HashMap<String, Integer> numberOfOccurencesOfThisComboe = new HashMap<String, Integer>(); HashMap<String, String> fileToCATHMapping = new HashMap<String, String>(); ArrayList<String> allFilesToBeCopied = new ArrayList<String>(); new File(outputDir).mkdirs(); FileReader fis = new FileReader(completeFileWithDirToCathFileList); BufferedReader bis = new BufferedReader(fis); String line = ""; String currentCombo = ""; while ((line = bis.readLine()) != null) { String[] allEntries = line.split("\\s+"); String fileName = allEntries[0]; String thisCombo = allEntries[1] + allEntries[2] + allEntries[3] + allEntries[4]; String reducedComboForFilteringOut = allEntries[1] + allEntries[2] + allEntries[3]; fileToCATHMapping.put(fileName, reducedComboForFilteringOut); if (currentCombo.equals(thisCombo)) { } else { System.out.println("merke: " + fileName); allFilesToBeCopied.add(fileName); currentCombo = thisCombo; } } for (String fileName : allFilesToBeCopied) { String reducedComboForFilteringOut = fileToCATHMapping.get(fileName); if (!numberOfOccurencesOfThisComboe.containsKey(reducedComboForFilteringOut)) { numberOfOccurencesOfThisComboe.put(reducedComboForFilteringOut, 1); } else { Integer thisCounter = numberOfOccurencesOfThisComboe.get(reducedComboForFilteringOut); thisCounter = thisCounter + 1; numberOfOccurencesOfThisComboe.put(reducedComboForFilteringOut, thisCounter); } } HashSet<String> isSingleElement = new HashSet<String>(); for (Entry<String, Integer> thisEntry : numberOfOccurencesOfThisComboe.entrySet()) { if (thisEntry.getValue() == 1) { System.out.println("single: " + thisEntry.getKey()); isSingleElement.add(thisEntry.getKey()); } else { System.out.println("not single: " + thisEntry.getKey()); } } System.out.println(allFilesToBeCopied.size()); for (String file : allFilesToBeCopied) { if (!isSingleElement.contains(fileToCATHMapping.get(file))) { try { FileChannel srcChannel = new FileInputStream(CathDir + file).getChannel(); FileChannel dstChannel = new FileOutputStream(outputDir + file).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } }
00
Code Sample 1: public boolean parseResults(URL url, String analysis_type, CurationI curation, Date analysis_date, String regexp) throws OutputMalFormatException { boolean parsed = false; try { InputStream data_stream = url.openStream(); parsed = parseResults(data_stream, analysis_type, curation, analysis_date, regexp); } catch (OutputMalFormatException ex) { throw new OutputMalFormatException(ex.getMessage(), ex); } catch (Exception ex) { System.out.println(ex.getMessage()); } return parsed; } Code Sample 2: public ISOMsg filter(ISOChannel channel, ISOMsg m, LogEvent evt) throws VetoException { if (key == null || fields == null) throw new VetoException("MD5Filter not configured"); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getKey()); int[] f = getFields(m); for (int i = 0; i < f.length; i++) { int fld = f[i]; if (m.hasField(fld)) { ISOComponent c = m.getComponent(fld); if (c instanceof ISOBinaryField) md.update((byte[]) c.getValue()); else md.update(((String) c.getValue()).getBytes()); } } byte[] digest = md.digest(); if (m.getDirection() == ISOMsg.OUTGOING) { m.set(new ISOBinaryField(64, digest, 0, 8)); m.set(new ISOBinaryField(128, digest, 8, 8)); } else { byte[] rxDigest = new byte[16]; if (m.hasField(64)) System.arraycopy((byte[]) m.getValue(64), 0, rxDigest, 0, 8); if (m.hasField(128)) System.arraycopy((byte[]) m.getValue(128), 0, rxDigest, 8, 8); if (!Arrays.equals(digest, rxDigest)) { evt.addMessage(m); evt.addMessage("MAC expected: " + ISOUtil.hexString(digest)); evt.addMessage("MAC received: " + ISOUtil.hexString(rxDigest)); throw new VetoException("invalid MAC"); } m.unset(64); m.unset(128); } } catch (NoSuchAlgorithmException e) { throw new VetoException(e); } catch (ISOException e) { throw new VetoException(e); } return m; }
00
Code Sample 1: public void mousePressed(MouseEvent e) { bannerLbl.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); HttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpGet method = new HttpGet(bannerURL); try { HttpResponse response = ProxyManager.httpClient.execute(method, context); HttpEntity entity = response.getEntity(); HttpHost host = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest request = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); String targetURL = host.toURI() + request.getURI(); DesktopUtil.browseAndWarn(targetURL, bannerLbl); EntityUtils.consume(entity); } catch (Exception ex) { NotifyUtil.error("Banner Error", "Could not open the default web browser.", ex, false); } finally { method.abort(); } bannerLbl.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } Code Sample 2: private ImageReader findImageReader(URL url) { ImageInputStream input = null; try { input = ImageIO.createImageInputStream(url.openStream()); } catch (IOException e) { logger.log(Level.WARNING, "zly adres URL obrazka " + url, e); } ImageReader reader = null; if (input != null) { Iterator readers = ImageIO.getImageReaders(input); while ((reader == null) && (readers != null) && readers.hasNext()) { reader = (ImageReader) readers.next(); } reader.setInput(input); } return reader; }
00
Code Sample 1: public static String getMD5Hash(String data) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(data.getBytes()); byte[] hash = digest.digest(); StringBuffer hexString = new StringBuffer(); String hexChar = ""; for (int i = 0; i < hash.length; i++) { hexChar = Integer.toHexString(0xFF & hash[i]); if (hexChar.length() < 2) { hexChar = "0" + hexChar; } hexString.append(hexChar); } return hexString.toString(); } catch (NoSuchAlgorithmException ex) { return null; } } Code Sample 2: private boolean postLogin() { URL url = null; URLConnection urlConn = null; OutputStream out = null; int code = 0; boolean gotPhpsessid = false; try { url = new URL("http://" + m_host + "/forums/index.php?action=login2"); } catch (MalformedURLException e) { e.printStackTrace(); return false; } try { urlConn = url.openConnection(); ((HttpURLConnection) urlConn).setRequestMethod("POST"); ((HttpURLConnection) urlConn).setInstanceFollowRedirects(false); urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setRequestProperty("Host", m_host); urlConn.setRequestProperty("Accept", "*/*"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConn.setRequestProperty("Connection", "Keep-Alive"); urlConn.setRequestProperty("Cache-Control", "no-cache"); out = urlConn.getOutputStream(); out.write(new String("user=" + m_username + "&passwrd=" + m_password + "&cookielength=60").getBytes()); out.flush(); out.close(); do { readCookies(urlConn); m_referer = url.toString(); code = ((HttpURLConnection) urlConn).getResponseCode(); if (code == 301 || code == 302) { url = new URL(urlConn.getHeaderField("Location")); urlConn = url.openConnection(); ((HttpURLConnection) urlConn).setRequestMethod("GET"); ((HttpURLConnection) urlConn).setInstanceFollowRedirects(false); urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setRequestProperty("Host", m_host); urlConn.setRequestProperty("Accept", "*/*"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConn.setRequestProperty("Connection", "Keep-Alive"); urlConn.setRequestProperty("Cache-Control", "no-cache"); if (m_referer != null) urlConn.setRequestProperty("Referer", m_referer); if (m_cookies != null) urlConn.setRequestProperty("Cookie", m_cookies); continue; } if (code == 200) { String refreshHdr = urlConn.getHeaderField("Refresh"); Pattern p_phpsessid = Pattern.compile(".*?\\?PHPSESSID=(\\w+).*"); Matcher match_phpsessid = p_phpsessid.matcher(refreshHdr); if (match_phpsessid.matches()) { gotPhpsessid = true; } urlConn = null; continue; } String msg = ((HttpURLConnection) urlConn).getResponseMessage(); m_turnSummaryRef = String.valueOf(code) + ": " + msg; return false; } while (urlConn != null); } catch (Exception e) { e.printStackTrace(); return false; } if (!gotPhpsessid) { m_turnSummaryRef = "Error: PHPSESSID not found after login. "; return false; } if (m_cookies == null) { m_turnSummaryRef = "Error: cookies not found after login. "; return false; } try { Thread.sleep(m_loginDelayInSeconds * 1000); } catch (InterruptedException ie) { ie.printStackTrace(); } return true; }
00
Code Sample 1: public boolean save(String trxName) { if (m_value == null || (!(m_value instanceof String || m_value instanceof byte[])) || (m_value instanceof String && m_value.toString().length() == 0) || (m_value instanceof byte[] && ((byte[]) m_value).length == 0)) { StringBuffer sql = new StringBuffer("UPDATE ").append(m_tableName).append(" SET ").append(m_columnName).append("=null WHERE ").append(m_whereClause); int no = DB.executeUpdate(sql.toString(), trxName); log.fine("save [" + trxName + "] #" + no + " - no data - set to null - " + m_value); if (no == 0) log.warning("[" + trxName + "] - not updated - " + sql); return true; } StringBuffer sql = new StringBuffer("UPDATE ").append(m_tableName).append(" SET ").append(m_columnName).append("=? WHERE ").append(m_whereClause); boolean success = true; if (DB.isRemoteObjects()) { log.fine("[" + trxName + "] - Remote - " + m_value); Server server = CConnection.get().getServer(); try { if (server != null) { success = server.updateLOB(sql.toString(), m_displayType, m_value, trxName, SecurityToken.getInstance()); if (CLogMgt.isLevelFinest()) log.fine("server.updateLOB => " + success); return success; } log.log(Level.SEVERE, "AppsServer not found"); } catch (RemoteException ex) { log.log(Level.SEVERE, "AppsServer error", ex); } return false; } log.fine("[" + trxName + "] - Local - " + m_value); Trx trx = null; if (trxName != null) trx = Trx.get(trxName, false); Connection con = null; if (trx != null) con = trx.getConnection(); if (con == null) con = DB.createConnection(false, Connection.TRANSACTION_READ_COMMITTED); if (con == null) { log.log(Level.SEVERE, "Could not get Connection"); return false; } PreparedStatement pstmt = null; success = true; try { pstmt = con.prepareStatement(sql.toString()); if (m_displayType == DisplayType.TextLong) pstmt.setString(1, (String) m_value); else pstmt.setBytes(1, (byte[]) m_value); int no = pstmt.executeUpdate(); if (no != 1) { log.warning("[" + trxName + "] - Not updated #" + no + " - " + sql); success = false; } } catch (Throwable e) { log.log(Level.SEVERE, "[" + trxName + "] - " + sql, e); success = false; } finally { DB.close(pstmt); pstmt = null; } if (success) { if (trx != null) { trx = null; con = null; } else { try { con.commit(); } catch (Exception e) { log.log(Level.SEVERE, "[" + trxName + "] - commit ", e); success = false; } finally { try { con.close(); } catch (SQLException e) { } con = null; } } } if (!success) { log.severe("[" + trxName + "] - rollback"); if (trx != null) { trx.rollback(); trx = null; con = null; } else { try { con.rollback(); } catch (Exception ee) { log.log(Level.SEVERE, "[" + trxName + "] - rollback", ee); } finally { try { con.close(); } catch (SQLException e) { } con = null; } } } return success; } Code Sample 2: public static int getNetFileSize(String netFile) throws InvalidActionException { URL url; URLConnection conn; int size; try { url = new URL(netFile); conn = url.openConnection(); size = conn.getContentLength(); conn.getInputStream().close(); if (size < 0) { throw new InvalidActionException("Could not determine file size."); } else { return size; } } catch (Exception e) { throw new InvalidActionException(e.getMessage()); } }
11
Code Sample 1: public static void main(String[] args) throws Exception { InputStream in = null; try { in = new URL(args[0]).openStream(); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } } Code Sample 2: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
00
Code Sample 1: private synchronized void connect() throws IOException { long now = System.currentTimeMillis(); if (lastConnect == 0 || lastConnect + 500 < now) { Log.logRB(Resource.CONNECTINGTO, new Object[] { getName() }); String auth = setProxy(); conn = url.openConnection(); if (auth != null) conn.setRequestProperty("Proxy-Authorization", auth); conn.connect(); lastModified = conn.getLastModified(); lastConnect = System.currentTimeMillis(); } } Code Sample 2: private void loadInitialDbState() throws IOException { InputStream in = SchemaAndDataPopulator.class.getClassLoader().getResourceAsStream(resourceName); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer); for (String statement : writer.toString().split(SQL_STATEMENT_DELIMITER)) { logger.info("Executing SQL Statement {}", statement); template.execute(statement); } }
00
Code Sample 1: public void schema(final Row row, TestResults testResults) throws Exception { String urlString = row.text(1); String schemaBase = null; if (row.cellExists(2)) { schemaBase = row.text(2); } try { StreamSource schemaSource; if (urlString.startsWith(CLASS_PREFIX)) { InputStream schema = XmlValidator.class.getClassLoader().getResourceAsStream(urlString.substring(CLASS_PREFIX.length())); schemaSource = new StreamSource(schema); } else { URL url = new URL(urlString); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); schemaSource = new StreamSource(inputStream); } SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); if (schemaBase != null) { DefaultLSResourceResolver resolver = new DefaultLSResourceResolver(schemaBase); factory.setResourceResolver(resolver); } factory.newSchema(new URL(urlString)); Validator validator = factory.newSchema(schemaSource).newValidator(); StreamSource source = new StreamSource(new StringReader(xml)); validator.validate(source); row.pass(testResults); } catch (SAXException e) { Loggers.SERVICE_LOG.warn("schema error", e); throw new FitFailureException(e.getMessage()); } catch (IOException e) { Loggers.SERVICE_LOG.warn("schema error", e); throw new FitFailureException(e.getMessage()); } } Code Sample 2: private static String fetchFile(String urlLocation) { try { URL url = new URL(urlLocation); URLConnection conn = url.openConnection(); File tempFile = File.createTempFile("marla", ".jar"); OutputStream os = new FileOutputStream(tempFile); IOUtils.copy(conn.getInputStream(), os); return tempFile.getAbsolutePath(); } catch (IOException ex) { throw new MarlaException("Unable to fetch file '" + urlLocation + "' from server", ex); } }
11
Code Sample 1: 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; } Code Sample 2: protected List<Datastream> getDatastreams(final DepositCollection pDeposit) throws IOException, SWORDException { LOG.debug("copying file"); String tTempFileName = this.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tTempFileName)); Datastream tDatastream = new LocalDatastream(this.getGenericFileName(pDeposit), this.getContentType(), tTempFileName); List<Datastream> tDatastreams = new ArrayList<Datastream>(); tDatastreams.add(tDatastream); return tDatastreams; }
11
Code Sample 1: public static final byte[] getBytesFromUrl(final String urlString) throws BT747Exception { byte[] result = null; try { final URL url = new URL(urlString); final URLConnection urlc = url.openConnection(); urlc.setConnectTimeout(timeout); urlc.setReadTimeout(timeout); final InputStream ins = urlc.getInputStream(); final ByteArrayOutputStream bout = new ByteArrayOutputStream(120 * 1024); final byte[] buf = new byte[1024]; while (true) { final int n = ins.read(buf); if (n == -1) { break; } bout.write(buf, 0, n); } result = bout.toByteArray(); bout.close(); } catch (final Exception e) { throw new BT747Exception(I18N.i18n("Problem downloading AGPS data."), e); } return result; } Code Sample 2: private static String loadUrlToString(String a_url) throws IOException { URL l_url1 = new URL(a_url); BufferedReader br = new BufferedReader(new InputStreamReader(l_url1.openStream())); String l_content = ""; String l_ligne = null; l_content = br.readLine(); while ((l_ligne = br.readLine()) != null) { l_content += AA.SL + l_ligne; } return l_content; }
00
Code Sample 1: @Override protected void service(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { res.setHeader("X-Generator", "VisualMon"); String path = req.getPathInfo(); if (null == path || "".equals(path)) res.sendRedirect(req.getServletPath() + "/"); else if ("/chart".equals(path)) { try { res.setHeader("Cache-Control", "private,no-cache,no-store,must-revalidate"); res.addHeader("Cache-Control", "post-check=0,pre-check=0"); res.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); renderChart(req, res); } catch (InterruptedException e) { log.info("Chart generation was interrupted", e); Thread.currentThread().interrupt(); } } else if (path.startsWith("/log_")) { String name = path.substring(5); LogProvider provider = null; for (LogProvider prov : cfg.getLogProviders()) { if (name.equals(prov.getName())) { provider = prov; break; } } if (null == provider) { log.error("Log provider with name \"{}\" not found", name); res.sendError(HttpServletResponse.SC_NOT_FOUND); } else { render(res, provider.getLog(filter.getLocale())); } } else if ("/".equals(path)) { List<LogEntry> logs = new ArrayList<LogEntry>(); for (LogProvider provider : cfg.getLogProviders()) logs.add(new LogEntry(provider.getName(), provider.getTitle(filter.getLocale()))); render(res, new ProbeDataList(filter.getSnapshot(), filter.getAlerts(), logs, ResourceBundle.getBundle("de.frostcode.visualmon.stats", filter.getLocale()).getString("category.empty"), cfg.getDashboardTitle().get(filter.getLocale()))); } else { URL url = Thread.currentThread().getContextClassLoader().getResource(getClass().getPackage().getName().replace('.', '/') + req.getPathInfo()); if (null == url) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } res.setDateHeader("Last-Modified", new File(url.getFile()).lastModified()); res.setDateHeader("Expires", new Date().getTime() + YEAR_IN_SECONDS * 1000L); res.setHeader("Cache-Control", "max-age=" + YEAR_IN_SECONDS); URLConnection conn = url.openConnection(); String resourcePath = url.getPath(); String contentType = conn.getContentType(); if (resourcePath.endsWith(".xsl")) { contentType = "text/xml"; res.setCharacterEncoding(ENCODING); } if (contentType == null || "content/unknown".equals(contentType)) { if (resourcePath.endsWith(".css")) contentType = "text/css"; else contentType = getServletContext().getMimeType(resourcePath); } res.setContentType(contentType); res.setContentLength(conn.getContentLength()); OutputStream out = res.getOutputStream(); IOUtils.copy(conn.getInputStream(), out); IOUtils.closeQuietly(conn.getInputStream()); IOUtils.closeQuietly(out); } } Code Sample 2: private ArrayList<XSPFTrackInfo> getPlaylist() { try { Log.d(TAG, "Getting playlist started"); String urlString = "http://" + mBaseURL + "/xspf.php?sk=" + mSession + "&discovery=0&desktop=1.4.1.57486"; if (mAlternateConn) { urlString += "&api_key=9d1bbaef3b443eb97973d44181d04e4b"; Log.d(TAG, "Using alternate connection method"); } URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); DocumentBuilderFactory dbFac = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbFac.newDocumentBuilder(); Document doc = db.parse(is); Element root = doc.getDocumentElement(); NodeList titleNs = root.getElementsByTagName("title"); String stationName = "<unknown station>"; if (titleNs.getLength() > 0) { Element titleElement = (Element) titleNs.item(0); String res = ""; for (int i = 0; i < titleElement.getChildNodes().getLength(); i++) { Node item = titleElement.getChildNodes().item(i); if (item.getNodeType() == Node.TEXT_NODE) res += item.getNodeValue(); } stationName = URLDecoder.decode(res, "UTF-8"); } NodeList tracks = doc.getElementsByTagName("track"); ArrayList<XSPFTrackInfo> result = new ArrayList<XSPFTrackInfo>(); for (int i = 0; i < tracks.getLength(); i++) try { result.add(new XSPFTrackInfo(stationName, (Element) tracks.item(i))); } catch (Utils.ParseException e) { Log.e(TAG, "in getPlaylist", e); return null; } Log.d(TAG, "Getting playlist successful"); return result; } catch (Exception e) { Log.e(TAG, "in getPlaylist", e); return null; } }
00
Code Sample 1: private int[] get51JobId(String address, String category, int pageNum) { StringBuffer htmlContent = null; try { URL url = new URL(ConfigJob51.STR_51JOB_ADVANCE); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStream raw = connection.getOutputStream(); OutputStream buf = new BufferedOutputStream(raw); OutputStreamWriter out = new OutputStreamWriter(buf, "gb2312"); out.write("jobarea=" + address + "&funtype=" + category + "&curr_page=" + pageNum + ""); out.flush(); out.close(); InputStream in = connection.getInputStream(); in = new BufferedInputStream(in); Reader r = new InputStreamReader(in); int c; htmlContent = new StringBuffer(); while ((c = r.read()) != -1) { htmlContent.append((char) c); } in.close(); } catch (IOException e) { e.printStackTrace(); } Pattern p = Pattern.compile(JOB51_SEARCHLIST_URL_PATTERN, Pattern.CASE_INSENSITIVE); Matcher matcher = p.matcher(htmlContent); int idSum = 0; int writeToDBSuccessful = 0; while (matcher.find()) { String s = matcher.group(); String sql = "insert into `job51`(`id`,`retryCnt`,`Category`) values('" + s.replaceAll("[^0-9]", "") + "','0','" + category + "')"; if (mysql.executeInsert(sql)) { writeToDBSuccessful++; } idSum++; } return new int[] { idSum, writeToDBSuccessful }; } Code Sample 2: public void addScanURL(final URL url) { if (url == null) throw new NullArgumentException(); try { url.openConnection().connect(); } catch (IOException e) { e.printStackTrace(); } urlList.add(url); }
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 static void notify(String msg) throws Exception { String url = "http://api.clickatell.com/http/sendmsg?"; url = add(url, "user", user); url = add(url, "password", password); url = add(url, "api_id", apiId); url = add(url, "to", to); url = add(url, "text", msg); URL u = new URL(url); URLConnection c = u.openConnection(); InputStream is = c.getInputStream(); IOUtils.copy(is, System.out); IOUtils.closeQuietly(is); System.out.println(); }
00
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: private void handleInterfaceReparented(String ipAddr, Parms eventParms) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (log.isDebugEnabled()) log.debug("interfaceReparented event received..."); if (ipAddr == null || eventParms == null) { log.warn(EventConstants.INTERFACE_REPARENTED_EVENT_UEI + " ignored - info incomplete - ip/parms: " + ipAddr + "/" + eventParms); return; } long oldNodeId = -1; long newNodeId = -1; String parmName = null; Value parmValue = null; String parmContent = null; Enumeration parmEnum = eventParms.enumerateParm(); while (parmEnum.hasMoreElements()) { Parm parm = (Parm) parmEnum.nextElement(); parmName = parm.getParmName(); parmValue = parm.getValue(); if (parmValue == null) continue; else parmContent = parmValue.getContent(); if (parmName.equals(EventConstants.PARM_OLD_NODEID)) { try { oldNodeId = Integer.valueOf(parmContent).intValue(); } catch (NumberFormatException nfe) { log.warn("Parameter " + EventConstants.PARM_OLD_NODEID + " cannot be non-numeric"); oldNodeId = -1; } } else if (parmName.equals(EventConstants.PARM_NEW_NODEID)) { try { newNodeId = Integer.valueOf(parmContent).intValue(); } catch (NumberFormatException nfe) { log.warn("Parameter " + EventConstants.PARM_NEW_NODEID + " cannot be non-numeric"); newNodeId = -1; } } } if (newNodeId == -1 || oldNodeId == -1) { log.warn("Unable to process 'interfaceReparented' event, invalid event parm."); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement reparentOutagesStmt = dbConn.prepareStatement(OutageConstants.DB_REPARENT_OUTAGES); reparentOutagesStmt.setLong(1, newNodeId); reparentOutagesStmt.setLong(2, oldNodeId); reparentOutagesStmt.setString(3, ipAddr); int count = reparentOutagesStmt.executeUpdate(); try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("Reparented " + count + " outages - ip: " + ipAddr + " reparented from " + oldNodeId + " to " + newNodeId); } catch (SQLException se) { log.warn("Rolling back transaction, reparent outages failed for newNodeId/ipAddr: " + newNodeId + "/" + ipAddr); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } reparentOutagesStmt.close(); } catch (SQLException se) { log.warn("SQL exception while handling \'interfaceReparented\'", se); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } }
00
Code Sample 1: private static void copyFile(File inputFile, File outputFile) throws IOException { FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: private Document getResponse(HttpGet request) throws ClientProtocolException, IOException, ParserConfigurationException, IllegalStateException, SAXException, NoRoutesException { HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() != HTTP_STATUS_OK) throw new ClientProtocolException("The HTTP request is wrong."); allResponse = EntityUtils.toString(response.getEntity()); String responseText = ""; switch(modeOption) { case DRIVING: try { responseText = allResponse.substring(allResponse.indexOf("<ol"), allResponse.indexOf("</ol>") + 5); } catch (Exception e) { throw new NoRoutesException(); } break; case WALKING: try { responseText = allResponse.substring(allResponse.indexOf("<ol"), allResponse.indexOf("</ol>") + 5); } catch (Exception e) { throw new NoRoutesException(); } break; case PUBLIC_TRANSIT: String responseWithErrors = ""; try { responseWithErrors = allResponse.substring(allResponse.indexOf("<div id=\"tsp\">"), allResponse.indexOf("<div class=\"ddwpt\" id=\"panel_ddw1\" oi=\"wi1\">")); } catch (Exception e) { throw new NoRoutesException(); } responseText = responseWithErrors.replaceAll(".gif\">", ".gif\"/>").replaceAll("colspan=2", "colspan=\"2\"").replaceAll("nowrap", "").replaceAll("&laquo;", "").replaceAll("&nbsp;", "").replaceAll("&raquo;", ""); break; } File xmlFile = new File("./data/temp/response.xml"); PrintWriter writer = new PrintWriter(xmlFile); writer.println(responseText); writer.close(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); return dBuilder.parse(xmlFile); }
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: @Test public void test_blueprintDetailsForTypeName() throws Exception { URL url = new URL(baseUrl + "/blueprintDetailsForTypeName/Anshar+Blueprint"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("{\"invBlueprintTypeDto\":{\"blueprintTypeID\":28849,\"blueprintTypeName\":\"Anshar Blueprint\",\"productTypeID\":28848,\"productTypeName\":\"Anshar\",\"productCategoryID\":6,\"parentBlueprintTypeID\":20188,\"parentBlueprintTypeName\":\"Obelisk Blueprint\",\"parentProductTypeID\":20187,\"parentProductTypeName\":\"Obelisk\",\"techLevel\":2,\"productionTime\":1920000,\"researchProductivityTime\":11520000,\"researchMaterialTime\":7680000,\"researchCopyTime\":2560000,\"researchTechTime\":3840000,\"productivityModifier\":384000,\"wasteFactor\":10,\"maxProductionLimit\":10,\"productVolume\":\"17550000\",\"productPortionSize\":1,\"dumpVersion\":\"cru16\"},\"materialDtos\":[{\"materialTypeID\":3828,\"materialTypeName\":\"Construction Blocks\",\"materialTypeCategoryID\":43,\"materialTypeIcon\":\"06_05\",\"materialVolume\":\"1.5\",\"quantity\":1500},{\"materialTypeID\":11399,\"materialTypeName\":\"Morphite\",\"materialTypeCategoryID\":4,\"materialTypeIcon\":\"35_02\",\"materialVolume\":\"0.01\",\"quantity\":2500},{\"materialTypeID\":21025,\"materialTypeName\":\"Capital Jump Drive\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"54_08\",\"materialVolume\":\"10000.0\",\"quantity\":20},{\"materialTypeID\":29041,\"materialTypeName\":\"Capital Crystalline Carbonide Armor Plate\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_14\",\"materialVolume\":\"10.0\",\"quantity\":1013},{\"materialTypeID\":29051,\"materialTypeName\":\"Capital Fusion Reactor Unit\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_02\",\"materialVolume\":\"10.0\",\"quantity\":518},{\"materialTypeID\":29061,\"materialTypeName\":\"Capital Ion Thruster\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_02\",\"materialVolume\":\"10.0\",\"quantity\":422},{\"materialTypeID\":29069,\"materialTypeName\":\"Capital Magnetometric Sensor Cluster\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_06\",\"materialVolume\":\"10.0\",\"quantity\":443},{\"materialTypeID\":29081,\"materialTypeName\":\"Capital Oscillator Capacitor Unit\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_06\",\"materialVolume\":\"10.0\",\"quantity\":704},{\"materialTypeID\":29085,\"materialTypeName\":\"Capital Photon Microprocessor\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_10\",\"materialVolume\":\"10.0\",\"quantity\":704},{\"materialTypeID\":29091,\"materialTypeName\":\"Capital Pulse Shield Emitter\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_10\",\"materialVolume\":\"10.0\",\"quantity\":449}],\"manufacturingRequirementDtos\":[{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":3380,\"requiredTypeName\":\"Industry\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":268,\"requiredTypeGroupName\":\"Industry\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11478,\"requiredTypeName\":\"R.A.M.- Starship Tech\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_02\",\"damagePerJob\":\"0.95\",\"quantity\":40,\"requiredTypeVolume\":\"4.0\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":20187,\"requiredTypeName\":\"Obelisk\",\"requiredTypeCategoryID\":6,\"requiredTypeGroupID\":513,\"requiredTypeGroupName\":\"Freighter\",\"damagePerJob\":\"1.0\",\"quantity\":1,\"requiredTypeVolume\":\"17550000\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":22242,\"requiredTypeName\":\"Capital Ship Construction\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":269,\"requiredTypeGroupName\":\"Mechanic\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"}],\"timeProductivityRequirementDtos\":[{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":3403,\"requiredTypeName\":\"Research\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":3814,\"requiredTypeName\":\"Reports\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":120,\"requiredTypeVolume\":\"0.1\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":9836,\"requiredTypeName\":\"Consumer Electronics\",\"requiredTypeCategoryID\":43,\"requiredTypeGroupID\":1034,\"requiredTypeGroupName\":\"Refined Commodities\",\"requiredTypeIcon\":\"24_08\",\"damagePerJob\":\"1.0\",\"quantity\":100,\"requiredTypeVolume\":\"1.5\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.8\",\"quantity\":30,\"requiredTypeVolume\":\"4.0\"}],\"materialProductivityRequirementDtos\":[{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":3409,\"requiredTypeName\":\"Metallurgy\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":3814,\"requiredTypeName\":\"Reports\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":140,\"requiredTypeVolume\":\"0.1\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":9836,\"requiredTypeName\":\"Consumer Electronics\",\"requiredTypeCategoryID\":43,\"requiredTypeGroupID\":1034,\"requiredTypeGroupName\":\"Refined Commodities\",\"requiredTypeIcon\":\"24_08\",\"damagePerJob\":\"1.0\",\"quantity\":100,\"requiredTypeVolume\":\"1.5\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.6\",\"quantity\":30,\"requiredTypeVolume\":\"4.0\"}],\"copyingRequirementDtos\":[{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":3812,\"requiredTypeName\":\"Data Sheets\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":600,\"requiredTypeVolume\":\"1.0\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.95\",\"quantity\":40,\"requiredTypeVolume\":\"4.0\"}],\"reverseEngineeringRequirementDtos\":[],\"inventionRequirementDtos\":[]}")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/json; charset=utf-8")); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><blueprintDetailsDto><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>1.0</damagePerJob><quantity>600</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3812</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Data Sheets</requiredTypeName><requiredTypeVolume>1.0</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.95</damagePerJob><quantity>40</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></copyingRequirementDtos><invBlueprintTypeDto><blueprintTypeID>28849</blueprintTypeID><blueprintTypeName>Anshar Blueprint</blueprintTypeName><dumpVersion>cru16</dumpVersion><maxProductionLimit>10</maxProductionLimit><parentBlueprintTypeID>20188</parentBlueprintTypeID><parentBlueprintTypeName>Obelisk Blueprint</parentBlueprintTypeName><parentProductTypeID>20187</parentProductTypeID><parentProductTypeName>Obelisk</parentProductTypeName><productCategoryID>6</productCategoryID><productPortionSize>1</productPortionSize><productTypeID>28848</productTypeID><productTypeName>Anshar</productTypeName><productVolume>17550000</productVolume><productionTime>1920000</productionTime><productivityModifier>384000</productivityModifier><researchCopyTime>2560000</researchCopyTime><researchMaterialTime>7680000</researchMaterialTime><researchProductivityTime>11520000</researchProductivityTime><researchTechTime>3840000</researchTechTime><techLevel>2</techLevel><wasteFactor>10</wasteFactor></invBlueprintTypeDto><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>268</requiredTypeGroupID><requiredTypeGroupName>Industry</requiredTypeGroupName><requiredTypeID>3380</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Industry</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.95</damagePerJob><quantity>40</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11478</requiredTypeID><requiredTypeIcon>41_02</requiredTypeIcon><requiredTypeName>R.A.M.- Starship Tech</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>1.0</damagePerJob><quantity>1</quantity><requiredTypeCategoryID>6</requiredTypeCategoryID><requiredTypeGroupID>513</requiredTypeGroupID><requiredTypeGroupName>Freighter</requiredTypeGroupName><requiredTypeID>20187</requiredTypeID><requiredTypeName>Obelisk</requiredTypeName><requiredTypeVolume>17550000</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>269</requiredTypeGroupID><requiredTypeGroupName>Mechanic</requiredTypeGroupName><requiredTypeID>22242</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Capital Ship Construction</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><materialDtos><materialTypeCategoryID>43</materialTypeCategoryID><materialTypeID>3828</materialTypeID><materialTypeIcon>06_05</materialTypeIcon><materialTypeName>Construction Blocks</materialTypeName><materialVolume>1.5</materialVolume><quantity>1500</quantity></materialDtos><materialDtos><materialTypeCategoryID>4</materialTypeCategoryID><materialTypeID>11399</materialTypeID><materialTypeIcon>35_02</materialTypeIcon><materialTypeName>Morphite</materialTypeName><materialVolume>0.01</materialVolume><quantity>2500</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>21025</materialTypeID><materialTypeIcon>54_08</materialTypeIcon><materialTypeName>Capital Jump Drive</materialTypeName><materialVolume>10000.0</materialVolume><quantity>20</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29041</materialTypeID><materialTypeIcon>37_14</materialTypeIcon><materialTypeName>Capital Crystalline Carbonide Armor Plate</materialTypeName><materialVolume>10.0</materialVolume><quantity>1013</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29051</materialTypeID><materialTypeIcon>39_02</materialTypeIcon><materialTypeName>Capital Fusion Reactor Unit</materialTypeName><materialVolume>10.0</materialVolume><quantity>518</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29061</materialTypeID><materialTypeIcon>37_02</materialTypeIcon><materialTypeName>Capital Ion Thruster</materialTypeName><materialVolume>10.0</materialVolume><quantity>422</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29069</materialTypeID><materialTypeIcon>37_06</materialTypeIcon><materialTypeName>Capital Magnetometric Sensor Cluster</materialTypeName><materialVolume>10.0</materialVolume><quantity>443</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29081</materialTypeID><materialTypeIcon>39_06</materialTypeIcon><materialTypeName>Capital Oscillator Capacitor Unit</materialTypeName><materialVolume>10.0</materialVolume><quantity>704</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29085</materialTypeID><materialTypeIcon>37_10</materialTypeIcon><materialTypeName>Capital Photon Microprocessor</materialTypeName><materialVolume>10.0</materialVolume><quantity>704</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29091</materialTypeID><materialTypeIcon>39_10</materialTypeIcon><materialTypeName>Capital Pulse Shield Emitter</materialTypeName><materialVolume>10.0</materialVolume><quantity>449</quantity></materialDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>3409</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Metallurgy</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>140</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3814</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Reports</requiredTypeName><requiredTypeVolume>0.1</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>100</quantity><requiredTypeCategoryID>43</requiredTypeCategoryID><requiredTypeGroupID>1034</requiredTypeGroupID><requiredTypeGroupName>Refined Commodities</requiredTypeGroupName><requiredTypeID>9836</requiredTypeID><requiredTypeIcon>24_08</requiredTypeIcon><requiredTypeName>Consumer Electronics</requiredTypeName><requiredTypeVolume>1.5</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.6</damagePerJob><quantity>30</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></materialProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>3403</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Research</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>120</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3814</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Reports</requiredTypeName><requiredTypeVolume>0.1</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>100</quantity><requiredTypeCategoryID>43</requiredTypeCategoryID><requiredTypeGroupID>1034</requiredTypeGroupID><requiredTypeGroupName>Refined Commodities</requiredTypeGroupName><requiredTypeID>9836</requiredTypeID><requiredTypeIcon>24_08</requiredTypeIcon><requiredTypeName>Consumer Electronics</requiredTypeName><requiredTypeVolume>1.5</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.8</damagePerJob><quantity>30</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></timeProductivityRequirementDtos></blueprintDetailsDto>")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/xml; charset=utf-8")); url = new URL(baseUrl + "/blueprintDetailsForTypeName/Anshar%20Blueprint"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("{\"invBlueprintTypeDto\":{\"blueprintTypeID\":28849,\"blueprintTypeName\":\"Anshar Blueprint\",\"productTypeID\":28848,\"productTypeName\":\"Anshar\",\"productCategoryID\":6,\"parentBlueprintTypeID\":20188,\"parentBlueprintTypeName\":\"Obelisk Blueprint\",\"parentProductTypeID\":20187,\"parentProductTypeName\":\"Obelisk\",\"techLevel\":2,\"productionTime\":1920000,\"researchProductivityTime\":11520000,\"researchMaterialTime\":7680000,\"researchCopyTime\":2560000,\"researchTechTime\":3840000,\"productivityModifier\":384000,\"wasteFactor\":10,\"maxProductionLimit\":10,\"productVolume\":\"17550000\",\"productPortionSize\":1,\"dumpVersion\":\"cru16\"},\"materialDtos\":[{\"materialTypeID\":3828,\"materialTypeName\":\"Construction Blocks\",\"materialTypeCategoryID\":43,\"materialTypeIcon\":\"06_05\",\"materialVolume\":\"1.5\",\"quantity\":1500},{\"materialTypeID\":11399,\"materialTypeName\":\"Morphite\",\"materialTypeCategoryID\":4,\"materialTypeIcon\":\"35_02\",\"materialVolume\":\"0.01\",\"quantity\":2500},{\"materialTypeID\":21025,\"materialTypeName\":\"Capital Jump Drive\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"54_08\",\"materialVolume\":\"10000.0\",\"quantity\":20},{\"materialTypeID\":29041,\"materialTypeName\":\"Capital Crystalline Carbonide Armor Plate\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_14\",\"materialVolume\":\"10.0\",\"quantity\":1013},{\"materialTypeID\":29051,\"materialTypeName\":\"Capital Fusion Reactor Unit\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_02\",\"materialVolume\":\"10.0\",\"quantity\":518},{\"materialTypeID\":29061,\"materialTypeName\":\"Capital Ion Thruster\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_02\",\"materialVolume\":\"10.0\",\"quantity\":422},{\"materialTypeID\":29069,\"materialTypeName\":\"Capital Magnetometric Sensor Cluster\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_06\",\"materialVolume\":\"10.0\",\"quantity\":443},{\"materialTypeID\":29081,\"materialTypeName\":\"Capital Oscillator Capacitor Unit\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_06\",\"materialVolume\":\"10.0\",\"quantity\":704},{\"materialTypeID\":29085,\"materialTypeName\":\"Capital Photon Microprocessor\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_10\",\"materialVolume\":\"10.0\",\"quantity\":704},{\"materialTypeID\":29091,\"materialTypeName\":\"Capital Pulse Shield Emitter\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_10\",\"materialVolume\":\"10.0\",\"quantity\":449}],\"manufacturingRequirementDtos\":[{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":3380,\"requiredTypeName\":\"Industry\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":268,\"requiredTypeGroupName\":\"Industry\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11478,\"requiredTypeName\":\"R.A.M.- Starship Tech\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_02\",\"damagePerJob\":\"0.95\",\"quantity\":40,\"requiredTypeVolume\":\"4.0\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":20187,\"requiredTypeName\":\"Obelisk\",\"requiredTypeCategoryID\":6,\"requiredTypeGroupID\":513,\"requiredTypeGroupName\":\"Freighter\",\"damagePerJob\":\"1.0\",\"quantity\":1,\"requiredTypeVolume\":\"17550000\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":22242,\"requiredTypeName\":\"Capital Ship Construction\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":269,\"requiredTypeGroupName\":\"Mechanic\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"}],\"timeProductivityRequirementDtos\":[{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":3403,\"requiredTypeName\":\"Research\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":3814,\"requiredTypeName\":\"Reports\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":120,\"requiredTypeVolume\":\"0.1\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":9836,\"requiredTypeName\":\"Consumer Electronics\",\"requiredTypeCategoryID\":43,\"requiredTypeGroupID\":1034,\"requiredTypeGroupName\":\"Refined Commodities\",\"requiredTypeIcon\":\"24_08\",\"damagePerJob\":\"1.0\",\"quantity\":100,\"requiredTypeVolume\":\"1.5\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.8\",\"quantity\":30,\"requiredTypeVolume\":\"4.0\"}],\"materialProductivityRequirementDtos\":[{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":3409,\"requiredTypeName\":\"Metallurgy\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":3814,\"requiredTypeName\":\"Reports\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":140,\"requiredTypeVolume\":\"0.1\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":9836,\"requiredTypeName\":\"Consumer Electronics\",\"requiredTypeCategoryID\":43,\"requiredTypeGroupID\":1034,\"requiredTypeGroupName\":\"Refined Commodities\",\"requiredTypeIcon\":\"24_08\",\"damagePerJob\":\"1.0\",\"quantity\":100,\"requiredTypeVolume\":\"1.5\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.6\",\"quantity\":30,\"requiredTypeVolume\":\"4.0\"}],\"copyingRequirementDtos\":[{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":3812,\"requiredTypeName\":\"Data Sheets\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":600,\"requiredTypeVolume\":\"1.0\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.95\",\"quantity\":40,\"requiredTypeVolume\":\"4.0\"}],\"reverseEngineeringRequirementDtos\":[],\"inventionRequirementDtos\":[]}")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/json; charset=utf-8")); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><blueprintDetailsDto><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>1.0</damagePerJob><quantity>600</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3812</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Data Sheets</requiredTypeName><requiredTypeVolume>1.0</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.95</damagePerJob><quantity>40</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></copyingRequirementDtos><invBlueprintTypeDto><blueprintTypeID>28849</blueprintTypeID><blueprintTypeName>Anshar Blueprint</blueprintTypeName><dumpVersion>cru16</dumpVersion><maxProductionLimit>10</maxProductionLimit><parentBlueprintTypeID>20188</parentBlueprintTypeID><parentBlueprintTypeName>Obelisk Blueprint</parentBlueprintTypeName><parentProductTypeID>20187</parentProductTypeID><parentProductTypeName>Obelisk</parentProductTypeName><productCategoryID>6</productCategoryID><productPortionSize>1</productPortionSize><productTypeID>28848</productTypeID><productTypeName>Anshar</productTypeName><productVolume>17550000</productVolume><productionTime>1920000</productionTime><productivityModifier>384000</productivityModifier><researchCopyTime>2560000</researchCopyTime><researchMaterialTime>7680000</researchMaterialTime><researchProductivityTime>11520000</researchProductivityTime><researchTechTime>3840000</researchTechTime><techLevel>2</techLevel><wasteFactor>10</wasteFactor></invBlueprintTypeDto><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>268</requiredTypeGroupID><requiredTypeGroupName>Industry</requiredTypeGroupName><requiredTypeID>3380</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Industry</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.95</damagePerJob><quantity>40</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11478</requiredTypeID><requiredTypeIcon>41_02</requiredTypeIcon><requiredTypeName>R.A.M.- Starship Tech</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>1.0</damagePerJob><quantity>1</quantity><requiredTypeCategoryID>6</requiredTypeCategoryID><requiredTypeGroupID>513</requiredTypeGroupID><requiredTypeGroupName>Freighter</requiredTypeGroupName><requiredTypeID>20187</requiredTypeID><requiredTypeName>Obelisk</requiredTypeName><requiredTypeVolume>17550000</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>269</requiredTypeGroupID><requiredTypeGroupName>Mechanic</requiredTypeGroupName><requiredTypeID>22242</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Capital Ship Construction</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><materialDtos><materialTypeCategoryID>43</materialTypeCategoryID><materialTypeID>3828</materialTypeID><materialTypeIcon>06_05</materialTypeIcon><materialTypeName>Construction Blocks</materialTypeName><materialVolume>1.5</materialVolume><quantity>1500</quantity></materialDtos><materialDtos><materialTypeCategoryID>4</materialTypeCategoryID><materialTypeID>11399</materialTypeID><materialTypeIcon>35_02</materialTypeIcon><materialTypeName>Morphite</materialTypeName><materialVolume>0.01</materialVolume><quantity>2500</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>21025</materialTypeID><materialTypeIcon>54_08</materialTypeIcon><materialTypeName>Capital Jump Drive</materialTypeName><materialVolume>10000.0</materialVolume><quantity>20</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29041</materialTypeID><materialTypeIcon>37_14</materialTypeIcon><materialTypeName>Capital Crystalline Carbonide Armor Plate</materialTypeName><materialVolume>10.0</materialVolume><quantity>1013</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29051</materialTypeID><materialTypeIcon>39_02</materialTypeIcon><materialTypeName>Capital Fusion Reactor Unit</materialTypeName><materialVolume>10.0</materialVolume><quantity>518</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29061</materialTypeID><materialTypeIcon>37_02</materialTypeIcon><materialTypeName>Capital Ion Thruster</materialTypeName><materialVolume>10.0</materialVolume><quantity>422</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29069</materialTypeID><materialTypeIcon>37_06</materialTypeIcon><materialTypeName>Capital Magnetometric Sensor Cluster</materialTypeName><materialVolume>10.0</materialVolume><quantity>443</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29081</materialTypeID><materialTypeIcon>39_06</materialTypeIcon><materialTypeName>Capital Oscillator Capacitor Unit</materialTypeName><materialVolume>10.0</materialVolume><quantity>704</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29085</materialTypeID><materialTypeIcon>37_10</materialTypeIcon><materialTypeName>Capital Photon Microprocessor</materialTypeName><materialVolume>10.0</materialVolume><quantity>704</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29091</materialTypeID><materialTypeIcon>39_10</materialTypeIcon><materialTypeName>Capital Pulse Shield Emitter</materialTypeName><materialVolume>10.0</materialVolume><quantity>449</quantity></materialDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>3409</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Metallurgy</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>140</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3814</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Reports</requiredTypeName><requiredTypeVolume>0.1</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>100</quantity><requiredTypeCategoryID>43</requiredTypeCategoryID><requiredTypeGroupID>1034</requiredTypeGroupID><requiredTypeGroupName>Refined Commodities</requiredTypeGroupName><requiredTypeID>9836</requiredTypeID><requiredTypeIcon>24_08</requiredTypeIcon><requiredTypeName>Consumer Electronics</requiredTypeName><requiredTypeVolume>1.5</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.6</damagePerJob><quantity>30</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></materialProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>3403</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Research</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>120</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3814</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Reports</requiredTypeName><requiredTypeVolume>0.1</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>100</quantity><requiredTypeCategoryID>43</requiredTypeCategoryID><requiredTypeGroupID>1034</requiredTypeGroupID><requiredTypeGroupName>Refined Commodities</requiredTypeGroupName><requiredTypeID>9836</requiredTypeID><requiredTypeIcon>24_08</requiredTypeIcon><requiredTypeName>Consumer Electronics</requiredTypeName><requiredTypeVolume>1.5</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.8</damagePerJob><quantity>30</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></timeProductivityRequirementDtos></blueprintDetailsDto>")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/xml; charset=utf-8")); url = new URL(baseUrl + "/blueprintDetailsForTypeName/Anshar Blueprint"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(400)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(400)); }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: private String choosePivotVertex() throws ProcessorExecutionException { String result = null; Graph src; Graph dest; Path tmpDir; System.out.println("##########>" + _dirMgr.getSeqNum() + " Choose the pivot vertex"); src = new Graph(Graph.defaultGraph()); src.setPath(_curr_path); dest = new Graph(Graph.defaultGraph()); try { tmpDir = _dirMgr.getTempDir(); } catch (IOException e) { throw new ProcessorExecutionException(e); } dest.setPath(tmpDir); GraphAlgorithm choose_pivot = new PivotChoose(); choose_pivot.setConf(context); choose_pivot.setSource(src); choose_pivot.setDestination(dest); choose_pivot.setMapperNum(getMapperNum()); choose_pivot.setReducerNum(getReducerNum()); choose_pivot.execute(); try { Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); result = the_line.substring(PivotChoose.KEY_PIVOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("##########> Chosen pivot id = " + result); } catch (IOException e) { throw new ProcessorExecutionException(e); } return result; }
00
Code Sample 1: public XlsBook(String path) throws IOException { boolean isHttp = path.startsWith("http://"); InputStream is = null; if (isHttp) { URL url = new URL(path); is = url.openStream(); } else { File file = new File(path); is = new FileInputStream(file); } workbook = XlsBook.createWorkbook(is); is.close(); } Code Sample 2: public Result request(URL url) { try { return xmlUtil.unmarshall(urlOpener.openStream(url)); } catch (FileNotFoundException e) { log.info("File not found: " + url); } catch (IOException e) { log.error("Failed to read from url: " + url + ". " + e.getMessage(), e); } return null; }
11
Code Sample 1: public void postProcess() throws StopWriterVisitorException { shpWriter.postProcess(); try { FileChannel fcinShp = new FileInputStream(fTemp).getChannel(); FileChannel fcoutShp = new FileOutputStream(fileShp).getChannel(); DriverUtilities.copy(fcinShp, fcoutShp); File shxFile = SHP.getShxFile(fTemp); FileChannel fcinShx = new FileInputStream(shxFile).getChannel(); FileChannel fcoutShx = new FileOutputStream(SHP.getShxFile(fileShp)).getChannel(); DriverUtilities.copy(fcinShx, fcoutShx); File dbfFile = getDataFile(fTemp); short originalEncoding = DbfEncodings.getInstance().getDbfIdForCharset(shpWriter.getCharset()); RandomAccessFile fo = new RandomAccessFile(dbfFile, "rw"); fo.seek(29); fo.writeByte(originalEncoding); fo.close(); FileChannel fcinDbf = new FileInputStream(dbfFile).getChannel(); FileChannel fcoutDbf = new FileOutputStream(getDataFile(fileShp)).getChannel(); DriverUtilities.copy(fcinDbf, fcoutDbf); fTemp.delete(); shxFile.delete(); dbfFile.delete(); reload(); } catch (FileNotFoundException e) { throw new StopWriterVisitorException(getName(), e); } catch (IOException e) { throw new StopWriterVisitorException(getName(), e); } catch (ReloadDriverException e) { throw new StopWriterVisitorException(getName(), e); } } Code Sample 2: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
11
Code Sample 1: private void copy(File source, File target) throws IOException { FileChannel in = (new FileInputStream(source)).getChannel(); FileChannel out = (new FileOutputStream(target)).getChannel(); in.transferTo(0, source.length(), out); in.close(); out.close(); } Code Sample 2: private void performDownload() { List<String> selected = filesPane.getSelectedValuesList(); if (selected == null || selected.isEmpty() || selected.size() != 1) { JOptionPane.showMessageDialog(this, "Please select one path"); return; } RFile file = new RFile(selected.get(0)); if (!file.isFile()) { JOptionPane.showMessageDialog(this, "file does not exist anymore"); return; } chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), file.getName())); int ok = chooser.showSaveDialog(this); if (ok != JFileChooser.APPROVE_OPTION) { return; } FileOutputStream fout = null; RFileInputStream in = null; try { fout = new FileOutputStream(chooser.getSelectedFile()); in = new RFileInputStream(file); IOUtils.copy(in, fout); JOptionPane.showMessageDialog(this, "File downloaded to " + chooser.getSelectedFile(), "Download finished", JOptionPane.INFORMATION_MESSAGE); } catch (IOException iOException) { JOptionPane.showMessageDialog(this, "Error: " + iOException, "Error", JOptionPane.ERROR_MESSAGE); } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (fout != null) { try { fout.close(); } catch (Throwable t) { } } } }
11
Code Sample 1: @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { req.setCharacterEncoding("UTF-8"); resp.setContentType(req.getContentType()); IOUtils.copy(req.getReader(), resp.getWriter()); } Code Sample 2: 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) { guiBuilder.showError("Copy Error", "IOException during copy", ioe.getMessage()); return false; } }
00
Code Sample 1: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); } Code Sample 2: public void fetchFile(String ID) { String url = "http://www.nal.usda.gov/cgi-bin/agricola-ind?bib=" + ID + "&conf=010000++++++++++++++&screen=MA"; System.out.println(url); try { PrintWriter pw = new PrintWriter(new FileWriter("MARC" + ID + ".txt")); if (!id.contains("MARC" + ID + ".txt")) { id.add("MARC" + ID + ".txt"); } in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); in.readLine(); String inputLine, stx = ""; StringBuffer sb = new StringBuffer(); while ((inputLine = in.readLine()) != null) { if (inputLine.startsWith("<TR><TD><B>")) { String sts = (inputLine.substring(inputLine.indexOf("B>") + 2, inputLine.indexOf("</"))); int i = 0; try { i = Integer.parseInt(sts); } catch (NumberFormatException nfe) { } if (i > 0) { stx = stx + "\n" + sts + " - "; } else { stx += sts; } } if (!(inputLine.startsWith("<") || inputLine.startsWith(" <") || inputLine.startsWith(">"))) { String tx = inputLine.trim(); stx += tx; } } pw.println(stx); pw.close(); } catch (Exception e) { System.out.println("Couldn't open stream"); System.out.println(e); } }
00
Code Sample 1: public ImageData getJPEGDiagram() { Shell shell = new Shell(); GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(shell); viewer.setEditDomain(new DefaultEditDomain(null)); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setEditPartFactory(new CsdeEditPartFactory()); viewer.setContents(getDiagram()); viewer.flush(); LayerManager lm = (LayerManager) viewer.getEditPartRegistry().get(LayerManager.ID); IFigure fig = lm.getLayer(LayerConstants.PRINTABLE_LAYERS); Dimension d = fig.getSize(); Image image = new Image(null, d.width, d.height); GC tmpGC = new GC(image); SWTGraphics graphics = new SWTGraphics(tmpGC); fig.paint(graphics); shell.dispose(); return image.getImageData(); } Code Sample 2: @Override public String encode(String password) { String hash = null; MessageDigest m; try { m = MessageDigest.getInstance("MD5"); m.update(password.getBytes(), 0, password.length()); hash = String.format("%1$032X", new BigInteger(1, m.digest())); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hash; }
11
Code Sample 1: public static String hash(String in, String algorithm) { if (StringUtils.isBlank(algorithm)) algorithm = DEFAULT_ALGORITHM; try { md = MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException nsae) { logger.error("No such algorithm exception", nsae); } md.reset(); md.update(in.getBytes()); String out = null; try { out = Base64Encoder.encode(md.digest()); } catch (IOException e) { logger.error("Error converting to Base64 ", e); } if (out.endsWith("\n")) out = out.substring(0, out.length() - 1); return out; } Code Sample 2: public String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
00
Code Sample 1: public static void reset() throws Exception { Session session = DataStaticService.getHibernateSessionFactory().openSession(); try { Connection connection = session.connection(); try { Statement statement = connection.createStatement(); try { statement.executeUpdate("delete from Bundle"); connection.commit(); } finally { statement.close(); } } catch (HibernateException e) { connection.rollback(); throw new Exception(e); } catch (SQLException e) { connection.rollback(); throw new Exception(e); } } catch (SQLException e) { throw new Exception(e); } finally { session.close(); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static String md5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (NoSuchAlgorithmException ex) { if (globali.jcVariabili.DEBUG) globali.jcFunzioni.erroreSQL(ex.toString()); } return res; } 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: public static boolean copyFile(final File src, final File dst) throws FileNotFoundException { if (src == null || dst == null || src.equals(dst)) { return false; } boolean result = false; if (src.exists()) { if (dst.exists() && !dst.canWrite()) { return false; } final FileInputStream srcStream = new FileInputStream(src); final FileOutputStream dstStream = new FileOutputStream(dst); final FileChannel srcChannel = srcStream.getChannel(); final FileChannel dstChannel = dstStream.getChannel(); FileLock dstLock = null; FileLock srcLock = null; try { srcLock = srcChannel.tryLock(0, Long.MAX_VALUE, true); dstLock = dstChannel.tryLock(); if (srcLock != null && dstLock != null) { int maxCount = 64 * 1024 * 1024 - 32 * 1024; long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, maxCount, dstChannel); } } } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } finally { if (srcChannel != null) { try { if (srcLock != null) { srcLock.release(); } srcChannel.close(); srcStream.close(); } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } } if (dstChannel != null) { try { if (dstLock != null) { dstLock.release(); } dstChannel.close(); dstStream.close(); result = true; } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } } } } return result; } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: public void doInsertImage() { logger.debug(">>> Inserting image..."); logger.debug(" fullFileName : #0", uploadedFileName); String fileName = uploadedFileName.substring(uploadedFileName.lastIndexOf(File.separator) + 1); logger.debug(" fileName : #0", fileName); String newFileName = System.currentTimeMillis() + "_" + fileName; String filePath = ImageResource.getResourceDirectory() + File.separator + newFileName; logger.debug(" filePath : #0", filePath); try { File file = new File(filePath); file.createNewFile(); FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(uploadedFile).getChannel(); dstChannel = new FileOutputStream(file).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { closeChannel(srcChannel); closeChannel(dstChannel); } StringBuilder imageTag = new StringBuilder(); imageTag.append("<img src=\""); imageTag.append(getRequest().getContextPath()); imageTag.append("/seam/resource"); imageTag.append(ImageResource.RESOURCE_PATH); imageTag.append("/"); imageTag.append(newFileName); imageTag.append("\"/>"); if (getQuestionDefinition().getDescription() == null) { getQuestionDefinition().setDescription(""); } getQuestionDefinition().setDescription(getQuestionDefinition().getDescription() + imageTag); } catch (IOException e) { logger.error("Error during saving image file", e); } uploadedFile = null; uploadedFileName = null; logger.debug("<<< Inserting image...Ok"); } Code Sample 2: public static void copyFile(File sourceFile, File targetFile) throws FileCopyingException { try { FileInputStream inputStream = new FileInputStream(sourceFile); FileOutputStream outputStream = new FileOutputStream(targetFile); FileChannel readableChannel = inputStream.getChannel(); FileChannel writableChannel = outputStream.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); inputStream.close(); outputStream.close(); } catch (IOException ioException) { String exceptionMessage = "An error occurred when copying from the file \"" + sourceFile.getAbsolutePath() + "\" to the file \"" + targetFile.getAbsolutePath() + "\"."; throw new FileCopyingException(exceptionMessage, ioException); } }
11
Code Sample 1: public void load(String filename) throws VisbardException { String defaultFilename = VisbardMain.getSettingsDir() + File.separator + DEFAULT_SETTINGS_FILE; File defaultFile = new File(defaultFilename); InputStream settingsInStreamFromFile = null; try { sLogger.info("Loading settings from : " + defaultFilename); settingsInStreamFromFile = new FileInputStream(defaultFile); } catch (FileNotFoundException fnf) { sLogger.info("Unable to load custom settings from user's settings directory (" + fnf.getMessage() + "); reverting to default settings"); try { InputStream settingsInStreamFromJar = VisbardMain.class.getClassLoader().getResourceAsStream(filename); FileOutputStream settingsOutStream = new FileOutputStream(defaultFile); int c; while ((c = settingsInStreamFromJar.read()) != -1) settingsOutStream.write(c); settingsInStreamFromJar.close(); settingsOutStream.close(); settingsInStreamFromFile = new FileInputStream(defaultFile); } catch (IOException ioe) { sLogger.warn("Unable to copy default settings to user's settings directory (" + ioe.getMessage() + "); using default settings from ViSBARD distribution package"); settingsInStreamFromFile = VisbardMain.class.getClassLoader().getResourceAsStream(filename); } } this.processSettingsFile(settingsInStreamFromFile, filename); } Code Sample 2: public static int convertImage(InputStream is, OutputStream os, String command) throws IOException, InterruptedException { if (logger.isInfoEnabled()) { logger.info(command); } Process p = Runtime.getRuntime().exec(command); ByteArrayOutputStream errOut = new ByteArrayOutputStream(); StreamGobbler errGobbler = new StreamGobbler(p.getErrorStream(), errOut, "Convert Thread (err gobbler): " + command); errGobbler.start(); StreamGobbler outGobbler = new StreamGobbler(new BufferedInputStream(is), p.getOutputStream(), "Convert Thread (out gobbler): " + command); outGobbler.start(); try { IOUtils.copy(p.getInputStream(), os); os.flush(); if (p.waitFor() != 0) { logger.error("Unable to convert, stderr: " + new String(errOut.toByteArray(), "UTF-8")); } return p.exitValue(); } finally { IOUtils.closeQuietly(os); } }
00
Code Sample 1: public byte[] getDigest(OMText text, String digestAlgorithm) throws OMException { byte[] digest = new byte[0]; try { MessageDigest md = MessageDigest.getInstance(digestAlgorithm); md.update((byte) 0); md.update((byte) 0); md.update((byte) 0); md.update((byte) 3); md.update(text.getText().getBytes("UnicodeBigUnmarked")); digest = md.digest(); } catch (NoSuchAlgorithmException e) { throw new OMException(e); } catch (UnsupportedEncodingException e) { throw new OMException(e); } return digest; } Code Sample 2: private File getTestFile() { final URL url = TestCrueLOG.class.getResource(FICHIER_TEST_XML); final File ctfaFile = new File(createTempDir(), "resultat.rtfa.xml"); try { CtuluLibFile.copyStream(url.openStream(), new FileOutputStream(ctfaFile), true, true); } catch (Exception e) { e.printStackTrace(); fail(); } return ctfaFile; }
00
Code Sample 1: private static byte[] createHash(EHashType hashType, String string) { MessageDigest md; try { md = MessageDigest.getInstance(hashType.getJavaHashType()); md.reset(); md.update(string.getBytes()); byte[] byteResult = md.digest(); return byteResult; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } Code Sample 2: public long copyDirAllFilesToDirectory(String baseDirStr, String destDirStr) throws Exception { long plussQuotaSize = 0; if (baseDirStr.endsWith(sep)) { baseDirStr = baseDirStr.substring(0, baseDirStr.length() - 1); } if (destDirStr.endsWith(sep)) { destDirStr = destDirStr.substring(0, destDirStr.length() - 1); } FileUtils.getInstance().createDirectory(destDirStr); BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File baseDir = new File(baseDirStr); baseDir.mkdirs(); if (!baseDir.exists()) { createDirectory(baseDirStr); } if ((baseDir.exists()) && (baseDir.isDirectory())) { String[] entryList = baseDir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String oldPathFileName = baseDirStr + sep + entryName; File entryFile = new File(oldPathFileName); if (entryFile.isFile()) { String newPathFileName = destDirStr + sep + entryName; File newFile = new File(newPathFileName); if (newFile.exists()) { plussQuotaSize -= newFile.length(); newFile.delete(); } in = new BufferedInputStream(new FileInputStream(oldPathFileName), bufferSize); out = new BufferedOutputStream(new FileOutputStream(newPathFileName), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } } } } else { throw new Exception("Base dir not exist ! baseDirStr = (" + baseDirStr + ")"); } return plussQuotaSize; }
00
Code Sample 1: public void run() { if (withlinlyn == true) { try { xlin.erase(file); } catch (Exception e) { System.out.println("Error erasing"); } } else if (as_php) { try { URL url = new URL(http + "REM:" + pservname); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); System.out.println("Response from REMOVE:"); String s; while ((s = br.readLine()) != null) { System.out.println(s); } br.close(); } catch (Exception e) { System.out.println("Error erasing/php!"); } } try { InetAddress ia = InetAddress.getLocalHost(); ss = new ServerSocket(0, 50, ia); startserv = System.currentTimeMillis(); ss.setSoTimeout(0); String svname = ia.getHostAddress(); System.out.println(svname + ":sv"); String mssg = "<SERVER><IP>" + svname + "</IP><PORT>" + ss.getLocalPort() + "</PORT></SERVER>"; if (withlinlyn == true) { try { xlin.replace(file, mssg); System.out.println("mssg:" + mssg + ", sent"); } catch (Exception e) { System.out.println("Error posting address"); return; } } else if (as_php) { try { URL url = new URL(http + "ADD:" + svname + ":" + ss.getLocalPort() + ":" + pservname); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String response = ""; String s; while ((s = br.readLine()) != null) { response = response + s + System.getProperty("line.separator"); } br.close(); String resp = new xLineSplit().ssplit("REPLY", response); if (!resp.equalsIgnoreCase("ADDED")) { System.out.println("potential error posting via php:\nReponse was:\n" + response); } } catch (Exception e) { System.out.println("Error in posting php:" + e.toString()); } } xsl.regserver(svname, new String("" + ss.getLocalPort())); Socket server = null; listening = true; while (listening) { server = ss.accept(); if (server != null) { xsl.add(server); System.out.println("added connect"); } else { System.out.println("Received null socket"); } server = null; listening = control_listening; } finserv = System.currentTimeMillis(); long l = finserv - startserv; long m = l / 1000; System.err.println("Server socket has closed, time elapsed:" + m); System.out.println("Server socket has closed, time elapsed:" + m); } catch (Exception e) { System.out.println(e.toString()); } } Code Sample 2: public APIResponse create(Item item) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/item/create").openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setUseCaches(false); connection.setConnectTimeout(TIMEOUT); connection.connect(); marshaller.marshal(item, new MappedXMLStreamWriter(new MappedNamespaceConvention(new Configuration()), new OutputStreamWriter(connection.getOutputStream(), "utf-8"))); connection.getOutputStream().flush(); connection.getOutputStream().close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { JSONObject obj = new JSONObject(new String(new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")).readLine())); response.setDone(true); response.setMessage(unmarshaller.unmarshal(new MappedXMLStreamReader(obj, new MappedNamespaceConvention(new Configuration())))); connection.getInputStream().close(); } else { response.setDone(false); response.setMessage("Create Item Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; }
11
Code Sample 1: public static void copy(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IOException { InputStream input = (InputStream) ((NativeJavaObject) args[0]).unwrap(); OutputStream output = (OutputStream) ((NativeJavaObject) args[1]).unwrap(); IOUtils.copy(input, output); } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: 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 PieceSet[] getPieceSets() { Resource[] resources = boardManager.getResources("pieces"); PieceSet[] pieceSets = new PieceSet[resources.length]; for (int i = 0; i < resources.length; i++) pieceSets[i] = (PieceSet) resources[i]; for (int i = 0; i < resources.length; i++) { for (int j = 0; j < resources.length - (i + 1); j++) { String name1 = pieceSets[j].getName(); String name2 = pieceSets[j + 1].getName(); if (name1.compareTo(name2) > 0) { PieceSet tmp = pieceSets[j]; pieceSets[j] = pieceSets[j + 1]; pieceSets[j + 1] = tmp; } } } return pieceSets; }
00
Code Sample 1: private PropertiesLoader(String masterFileLocation, String extraFileLocation) throws IOException { List propertiesList = new ArrayList(); ClassLoader classLoader = this.getClass().getClassLoader(); try { InputStream is = classLoader.getResourceAsStream(masterFileLocation); Properties p = new Properties(); p.load(is); is.close(); propertiesList.add(p); } catch (IOException ioex) { IOException ex = new IOException("could not load ROME master plugins file [" + masterFileLocation + "], " + ioex.getMessage()); ex.setStackTrace(ioex.getStackTrace()); throw ex; } Enumeration urls = classLoader.getResources(extraFileLocation); while (urls.hasMoreElements()) { URL url = (URL) urls.nextElement(); Properties p = new Properties(); try { InputStream is = url.openStream(); p.load(is); is.close(); } catch (IOException ioex) { IOException ex = new IOException("could not load ROME extensions plugins file [" + url.toString() + "], " + ioex.getMessage()); ex.setStackTrace(ioex.getStackTrace()); throw ex; } propertiesList.add(p); } _properties = new Properties[propertiesList.size()]; propertiesList.toArray(_properties); } Code Sample 2: public static String digest(String ha1, String ha2, String nonce) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(ha1, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(nonce, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(ha2, ISO_8859_1)); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } }
00
Code Sample 1: private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } } Code Sample 2: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
00
Code Sample 1: protected void migrateOnDemand() { try { if (fso.fileExists(prefix + ".fat") && !fso.fileExists(prefix + EXTENSIONS[UBM_FILE])) { RandomAccessFile ubm, meta, ctr, rbm; InputStream inputStream; OutputStream outputStream; fso.renameFile(prefix + ".fat", prefix + EXTENSIONS[UBM_FILE]); ubm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); meta = fso.openFile(prefix + EXTENSIONS[MTD_FILE], "rw"); ctr = fso.openFile(prefix + EXTENSIONS[CTR_FILE], "rw"); ubm.seek(ubm.length() - 16); meta.writeInt(blockSize = ubm.readInt()); meta.writeInt(size = ubm.readInt()); ctr.setLength(ubm.readLong() + blockSize); ctr.close(); meta.close(); ubm.setLength(ubm.length() - 16); ubm.seek(0); rbm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); inputStream = new BufferedInputStream(new RandomAccessFileInputStream(ubm)); outputStream = new BufferedOutputStream(new RandomAccessFileOutputStream(rbm)); for (int b; (b = inputStream.read()) != -1; ) outputStream.write(b); outputStream.close(); inputStream.close(); rbm.close(); ubm.close(); } } catch (IOException ie) { throw new WrappingRuntimeException(ie); } } Code Sample 2: public ISpieler[] sortiereSpielerRamsch(ISpieler[] spieler) { for (int i = 0; i < spieler.length; i++) { for (int j = 0; j < spieler.length - 1; j++) { if (werteAugen(spieler[j].getStiche()) > werteAugen(spieler[j + 1].getStiche())) { ISpieler a = spieler[j]; spieler[j] = spieler[j + 1]; spieler[j + 1] = a; } } } return spieler; }
00
Code Sample 1: public void atualizarLivro(LivroBean livro) { PreparedStatement pstmt = null; String sql = "update livro " + "set " + "isbn = ?, " + "autor = ?, " + "editora = ?, " + "edicao = ?, " + "titulo = ? " + "where " + "isbn = ?"; try { pstmt = connection.prepareStatement(sql); pstmt.setString(1, livro.getISBN()); pstmt.setString(2, livro.getAutor()); pstmt.setString(3, livro.getEditora()); pstmt.setString(4, livro.getEdicao()); pstmt.setString(5, livro.getTitulo()); pstmt.executeUpdate(); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (SQLException ex1) { throw new RuntimeException("Erro ao tentar atualizar livro.", ex1); } throw new RuntimeException("Erro ao tentar atualizar livro.", ex); } finally { try { if (pstmt != null) { pstmt.close(); } if (connection != null) { connection.close(); } } catch (SQLException ex) { throw new RuntimeException("Erro ao tentar atualizar livro.", ex); } } } Code Sample 2: public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
00
Code Sample 1: public static void fileCopy(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 void run(IAction action) { Shell shell = new Shell(); GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(shell); viewer.setEditDomain(new DefaultEditDomain(null)); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setEditPartFactory(new GraphicalPartFactory()); viewer.setContents(getContents()); viewer.flush(); int printMode = new PrintModeDialog(shell).open(); if (printMode == -1) return; PrintDialog dialog = new PrintDialog(shell, SWT.NULL); PrinterData data = dialog.open(); if (data != null) { PrintGraphicalViewerOperation op = new PrintGraphicalViewerOperation(new Printer(data), viewer); op.setPrintMode(printMode); op.run(selectedFile.getName()); } }
11
Code Sample 1: public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { String name = metadata.get(Metadata.RESOURCE_NAME_KEY); if (name != null && wanted.containsKey(name)) { FileOutputStream out = new FileOutputStream(wanted.get(name)); IOUtils.copy(stream, out); out.close(); } else { if (downstreamParser != null) { downstreamParser.parse(stream, handler, metadata, context); } } } Code Sample 2: private void processStylesheetFile() { InputStream in = null; OutputStream out = null; try { String filename; if (line.hasOption("stylesheetfile")) { filename = line.getOptionValue("stylesheetfile"); in = new FileInputStream(filename); filename = filename.replace('\\', '/'); filename = filename.substring(filename.lastIndexOf('/') + 1); } else { ClassLoader cl = this.getClass().getClassLoader(); filename = "stylesheet.css"; in = cl.getResourceAsStream(RESOURCE_PKG + "/stylesheet.css"); } baseProperties.setProperty("stylesheetfilename", filename); File outFile = new File(outputDir, filename); if (LOG.isInfoEnabled()) { LOG.info("Processing generated file " + outFile.getAbsolutePath()); } out = new FileOutputStream(outFile); IOUtils.copy(in, out); } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } }
00
Code Sample 1: private int writeTraceFile(final File destination_file, final String trace_file_name, final String trace_file_path) { URL url = null; BufferedInputStream is = null; FileOutputStream fo = null; BufferedOutputStream os = null; int b = 0; if (destination_file == null) { return 0; } try { url = new URL("http://" + trace_file_path + "/" + trace_file_name); is = new BufferedInputStream(url.openStream()); fo = new FileOutputStream(destination_file); os = new BufferedOutputStream(fo); while ((b = is.read()) != -1) { os.write(b); } os.flush(); is.close(); os.close(); } catch (Exception e) { System.err.println(url.toString()); Utilities.unexpectedException(e, this, CONTACT); return 0; } return 1; } Code Sample 2: private static void copyFile(File sourceFile, File targetFile) throws FileSaveException { try { FileInputStream inputStream = new FileInputStream(sourceFile); FileOutputStream outputStream = new FileOutputStream(targetFile); FileChannel readableChannel = inputStream.getChannel(); FileChannel writableChannel = outputStream.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); inputStream.close(); outputStream.close(); } catch (IOException ioException) { String exceptionMessage = "An error occurred when copying from the file \"" + sourceFile.getAbsolutePath() + "\" to the file \"" + targetFile.getAbsolutePath() + "\"."; throw new FileSaveException(exceptionMessage, ioException); } }
00
Code Sample 1: public static void readDefault() { ClassLoader l = Skeleton.class.getClassLoader(); URL url; if (l != null) { url = l.getResource(DEFAULT_LOC); } else { url = ClassLoader.getSystemResource(DEFAULT_LOC); } if (url == null) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } try { InputStreamReader reader = new InputStreamReader(url.openStream()); readSkel(new BufferedReader(reader)); } catch (IOException e) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } } Code Sample 2: public static void insertTableData(Connection dest, TableMetaData tableMetaData) throws Exception { PreparedStatement ps = null; try { dest.setAutoCommit(false); String sql = "INSERT INTO " + tableMetaData.getSchema() + "." + tableMetaData.getTableName() + " ("; for (String columnName : tableMetaData.getColumnsNames()) { sql += columnName + ","; } sql = sql.substring(0, sql.length() - 1); sql += ") VALUES ("; for (String columnName : tableMetaData.getColumnsNames()) { sql += "?" + ","; } sql = sql.substring(0, sql.length() - 1); sql += ")"; IOHelper.writeInfo(sql); ps = dest.prepareStatement(sql); for (Row r : tableMetaData.getData()) { try { int param = 1; for (String columnName : tableMetaData.getColumnsNames()) { if (dest instanceof OracleConnection) { if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("BLOB")) { BLOB blob = new BLOB((OracleConnection) dest, (byte[]) r.getRowData().get(columnName)); ((OraclePreparedStatement) ps).setBLOB(param, blob); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("CLOB")) { ((OraclePreparedStatement) ps).setStringForClob(param, (String) r.getRowData().get(columnName)); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("LONG")) { ps.setBytes(param, (byte[]) r.getRowData().get(columnName)); } } else { IOHelper.writeInfo(columnName + " = " + r.getRowData().get(columnName)); ps.setObject(param, r.getRowData().get(columnName)); } param++; } if (ps.executeUpdate() != 1) { dest.rollback(); updateTableData(dest, tableMetaData, r); } } catch (Exception ex) { try { dest.rollback(); updateTableData(dest, tableMetaData, r); } catch (Exception ex2) { IOHelper.writeError("Error in update " + sql, ex2); } } ps.clearParameters(); } dest.commit(); dest.setAutoCommit(true); } finally { if (ps != null) ps.close(); } }
11
Code Sample 1: public static void copy(final File src, final File dst) throws IOException, IllegalArgumentException { long fileSize = src.length(); final FileInputStream fis = new FileInputStream(src); final FileOutputStream fos = new FileOutputStream(dst); final FileChannel in = fis.getChannel(), out = fos.getChannel(); try { long offs = 0, doneCnt = 0; final long copyCnt = Math.min(65536, fileSize); do { doneCnt = in.transferTo(offs, copyCnt, out); offs += doneCnt; fileSize -= doneCnt; } while (fileSize > 0); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } try { fis.close(); } catch (final IOException e) { } try { fos.close(); } catch (final IOException e) { } src.delete(); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public boolean setCliente(int IDcliente, String nombre, String paterno, String materno, String ocupacion, String rfc) { boolean inserto = false; try { stm = conexion.prepareStatement("insert into clientes values( '" + IDcliente + "' , '" + nombre.toUpperCase() + "' , '" + paterno.toUpperCase() + "' , '" + materno.toUpperCase() + "' , '" + ocupacion.toUpperCase() + "' , '" + rfc + "' )"); stm.executeUpdate(); conexion.commit(); inserto = true; } catch (SQLException e) { System.out.println("error al insertar registro en la tabla clientes general " + e.getMessage()); try { conexion.rollback(); } catch (SQLException ee) { System.out.println(ee.getMessage()); } return inserto = false; } return inserto; } Code Sample 2: public void delete(String user) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate("delete from Principals where PrincipalId = '" + user + "'"); stmt.executeUpdate("delete from Roles where PrincipalId = '" + user + "'"); 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); } }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static Object fetchCached(String address, int hours) throws MalformedURLException, IOException { String cacheName = md5(address); checkAndCreateDirectoryIfNeeded(); File r = new File(CACHELOCATION + cacheName); Date d = new Date(); long limit = d.getTime() - (1000 * 60 * 60 * hours); if (!r.exists() || (hours != -1 && r.lastModified() < limit)) { InputStream is = (InputStream) fetch(address); FileOutputStream fos = new FileOutputStream(CACHELOCATION + cacheName); int nextChar; while ((nextChar = is.read()) != -1) fos.write((char) nextChar); fos.flush(); } FileInputStream fis = new FileInputStream(CACHELOCATION + cacheName); return fis; }
11
Code Sample 1: @Override public boolean update(String consulta, boolean autocommit, int transactionIsolation, Connection cx) throws SQLException { filasUpdate = 0; if (!consulta.contains(";")) { this.tipoConsulta = new Scanner(consulta); if (this.tipoConsulta.hasNext()) { execConsulta = this.tipoConsulta.next(); if (execConsulta.equalsIgnoreCase("update")) { Connection conexion = cx; Statement st = null; try { conexion.setAutoCommit(autocommit); if (transactionIsolation == 1 || transactionIsolation == 2 || transactionIsolation == 4 || transactionIsolation == 8) { conexion.setTransactionIsolation(transactionIsolation); } else { throw new IllegalArgumentException("Valor invalido sobre TransactionIsolation,\n TRANSACTION_NONE no es soportado por MySQL"); } st = (Statement) conexion.createStatement(ResultSetImpl.TYPE_SCROLL_SENSITIVE, ResultSetImpl.CONCUR_UPDATABLE); conexion.setReadOnly(false); filasUpdate = st.executeUpdate(consulta.trim(), Statement.RETURN_GENERATED_KEYS); if (filasUpdate > -1) { if (autocommit == false) { conexion.commit(); } return true; } else { return false; } } catch (MySQLIntegrityConstraintViolationException e) { System.out.println("Posible duplicacion de DATOS"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } catch (MySQLNonTransientConnectionException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } catch (MySQLDataException e) { System.out.println("Datos incorrectos"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } return false; } catch (MySQLSyntaxErrorException e) { System.out.println("Error en la sintaxis de la Consulta en MySQL"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } return false; } catch (SQLException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } finally { try { if (st != null) { if (!st.isClosed()) { st.close(); } } if (!conexion.isClosed()) { conexion.close(); } } catch (NullPointerException ne) { ne.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } else { throw new IllegalArgumentException("No es una instruccion Update"); } } else { try { throw new JMySQLException("Error Grave , notifique al departamento de Soporte Tecnico \n" + email); } catch (JMySQLException ex) { Logger.getLogger(JMySQL.class.getName()).log(Level.SEVERE, null, ex); return false; } } } else { throw new IllegalArgumentException("No estan permitidas las MultiConsultas en este metodo"); } } Code Sample 2: private void runUpdate(String sql, boolean transactional) { log().info("Vacuumd executing statement: " + sql); Connection dbConn = null; boolean commitRequired = false; boolean autoCommitFlag = !transactional; try { dbConn = getDataSourceFactory().getConnection(); dbConn.setAutoCommit(autoCommitFlag); PreparedStatement stmt = dbConn.prepareStatement(sql); int count = stmt.executeUpdate(); stmt.close(); if (log().isDebugEnabled()) { log().debug("Vacuumd: Ran update " + sql + ": this affected " + count + " rows"); } commitRequired = transactional; } catch (SQLException ex) { log().error("Vacuumd: Database error execuating statement " + sql, ex); } finally { if (dbConn != null) { try { if (commitRequired) { dbConn.commit(); } else if (transactional) { dbConn.rollback(); } } catch (SQLException ex) { } finally { if (dbConn != null) { try { dbConn.close(); } catch (Exception e) { } } } } } }
00
Code Sample 1: public static void main(String[] args) throws Exception { URL url = new URL("http://obs-he-lm:8888/XCATDR3/getproduct?obsid=0113060201&dtype=flatfiles&prd=P0113060201M2S003STSPLT8004.PDF"); URLConnection conn = url.openConnection(); Map<String, List<String>> map = conn.getHeaderFields(); JSONObject jso = new JSONObject(); for (Entry<String, List<String>> s : map.entrySet()) { System.out.println(s.getKey()); for (String v : s.getValue()) { System.out.println(" " + v); } jso.put(s.getKey(), s.getValue().get(0)); } conn.getInputStream().close(); System.out.println(jso.toJSONString()); } Code Sample 2: public Resource readResource(URL url, ResourceManager resourceManager) throws NAFException { XMLResource resource = new XMLResource(resourceManager, url); InputStream in = null; try { in = url.openStream(); ArrayList<Transformer> trList = null; Document doc = docbuilder.parse(in); for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) { if (n.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE && "xml-stylesheet".equals(n.getNodeName())) { ProcessingInstruction pi = (ProcessingInstruction) n; Map<String, String> attrs = DOMUtil.parseProcessingInstructionAttributes(pi); if ("text/xsl".equals(attrs.get("type"))) { String href = attrs.get("href"); if (href == null) throw new NAFException("Style sheet processing instructions must have an \"href\" attribute"); try { Transformer t = styleManager.createTransformer(new URL(url, href)); if (trList == null) trList = new ArrayList<Transformer>(); trList.add(t); } catch (Exception ex) { throw new NAFException("Error reading style sheet resource \"" + href + "\""); } } } } if (trList != null) { for (Transformer t : trList) { doc = (Document) styleManager.transform(t, doc); if (LOGGER_DUMP.isDebugEnabled()) { StringWriter swr = new StringWriter(); DOMUtil.dumpNode(doc, swr); LOGGER_DUMP.debug("Transformed instance:\n" + swr + "\n"); } } } Element rootE = doc.getDocumentElement(); if (!NAF_NAMESPACE_URI.equals(rootE.getNamespaceURI())) throw new NAFException("Root element does not use the NAF namespace"); Object comp = createComponent(rootE, resource, null); resource.setRootObject(comp); return resource; } catch (Exception ex) { throw new NAFException("Error reading NAF resource \"" + url.toExternalForm() + "\"", ex); } finally { if (in != null) try { in.close(); } catch (Exception ignored) { } } }
11
Code Sample 1: @Override protected IStatus runCancelableRunnable(IProgressMonitor monitor) { IStatus returnValue = Status.OK_STATUS; monitor.beginTask(NLS.bind(Messages.SaveFileOnDiskHandler_SavingFiles, open), informationUnitsFromExecutionEvent.size()); for (InformationUnit informationUnit : informationUnitsFromExecutionEvent) { if (!monitor.isCanceled()) { monitor.setTaskName(NLS.bind(Messages.SaveFileOnDiskHandler_Saving, informationUnit.getLabel())); InformationStructureRead read = InformationStructureRead.newSession(informationUnit); read.getValueByNodeId(Activator.FILENAME); IFile binaryReferenceFile = InformationUtil.getBinaryReferenceFile(informationUnit); FileWriter writer = null; try { if (binaryReferenceFile != null) { File file = new File(open, (String) read.getValueByNodeId(Activator.FILENAME)); InputStream contents = binaryReferenceFile.getContents(); writer = new FileWriter(file); IOUtils.copy(contents, writer); monitor.worked(1); } } catch (Exception e) { returnValue = StatusCreator.newStatus(NLS.bind(Messages.SaveFileOnDiskHandler_ErrorSaving, informationUnit.getLabel(), e)); break; } finally { if (writer != null) { try { writer.flush(); writer.close(); } catch (IOException e) { } } } } } return returnValue; } Code Sample 2: @Override public void run() { try { IOUtils.copy(getSource(), processStdIn); System.err.println("Copy done."); close(); } catch (IOException e) { e.printStackTrace(); IOUtils.closeQuietly(ExternalDecoder.this); } }
11
Code Sample 1: private Document saveFile(Document document, File file) throws Exception { List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { preference = preferences.get(0); } SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); String repo = preference.getRepository(); Calendar calendar = Calendar.getInstance(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(sdf.format(calendar.getTime())); sbFolder.append(File.separator).append(calendar.get(Calendar.HOUR_OF_DAY)); File folder = new File(sbRepo.append(sbFolder).toString()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()); StringBuffer fname = new StringBuffer(document.getId().toString()); fname.append(".").append(document.getExt()); sbFile.append(File.separator).append(fname); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } return document; } Code Sample 2: boolean createSessionArchive(String archiveFilename) { byte[] buffer = new byte[1024]; try { ZipOutputStream archive = new ZipOutputStream(new FileOutputStream(archiveFilename)); for (mAnnotationsCursor.moveToFirst(); !mAnnotationsCursor.isAfterLast(); mAnnotationsCursor.moveToNext()) { FileInputStream in = new FileInputStream(mAnnotationsCursor.getString(ANNOTATIONS_FILE_NAME)); archive.putNextEntry(new ZipEntry("audio" + (mAnnotationsCursor.getPosition() + 1) + ".3gpp")); int length; while ((length = in.read(buffer)) > 0) archive.write(buffer, 0, length); archive.closeEntry(); in.close(); } archive.close(); } catch (IOException e) { Toast.makeText(mActivity, mActivity.getString(R.string.error_zip) + " " + e.getMessage(), Toast.LENGTH_SHORT).show(); return false; } return true; }
11
Code Sample 1: public static void copyFile(File file, File dest_file) throws FileNotFoundException, IOException { DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest_file))); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) > 0) { out.write(buffer, 0, read); } in.close(); out.close(); } Code Sample 2: @Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { expected = new StringBuilder(); System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + (queryString = httpServletRequest.getQueryString())); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + (body = baos.toString())); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); expected.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); expected.append(value); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); }
11
Code Sample 1: @Override public void execute(JobExecutionContext context) throws JobExecutionException { super.execute(context); debug("Start execute job " + this.getClass().getName()); String dir = this.path_app_root + "/" + this.properties.get("dir") + "/"; try { File dir_f = new File(dir); if (!dir_f.exists()) { debug("(0) - make dir: " + dir_f + " - "); org.apache.commons.io.FileUtils.forceMkdir(dir_f); } } catch (IOException ex) { fatal("IOException", ex); } debug("Files:" + this.properties.get("url")); String[] url_to_download = properties.get("url").split(";"); for (String u : url_to_download) { if (StringUtil.isNullOrEmpty(u)) { continue; } u = StringUtil.trim(u); debug("(0) url: " + u); String f_name = u.substring(u.lastIndexOf("/"), u.length()); debug("(1) - start download: " + u + " to file name: " + new File(dir + "/" + f_name).toString()); com.utils.HttpUtil.downloadData(u, new File(dir + "/" + f_name).toString()); } try { conn_stats.setAutoCommit(false); } catch (SQLException e) { fatal("SQLException", e); } String[] query_delete = properties.get("query_delete").split(";"); for (String q : query_delete) { if (StringUtil.isNullOrEmpty(q)) { continue; } q = StringUtil.trim(q); debug("(2) - " + q); try { Statement stat = conn_stats.createStatement(); stat.executeUpdate(q); stat.close(); } catch (SQLException e) { try { conn_stats.rollback(); } catch (SQLException ex) { fatal("SQLException", ex); } fatal("SQLException", e); } } for (String u : url_to_download) { if (StringUtil.isNullOrEmpty(u)) { continue; } u = StringUtil.trim(u); try { Statement stat = conn_stats.createStatement(); String f_name = new File(dir + "/" + u.substring(u.lastIndexOf("/"), u.length())).toString(); debug("(3) - start import: " + f_name); BigFile lines = new BigFile(f_name); int n = 0; for (String l : lines) { String fields[] = l.split(","); String query = ""; if (f_name.indexOf("hip_countries.csv") != -1) { query = "insert into hip_countries values (" + fields[0] + ",'" + normalize(fields[1]) + "','" + normalize(fields[2]) + "')"; } else if (f_name.indexOf("hip_ip4_city_lat_lng.csv") != -1) { query = "insert into hip_ip4_city_lat_lng values (" + fields[0] + ",'" + normalize(fields[1]) + "'," + fields[2] + "," + fields[3] + ")"; } else if (f_name.indexOf("hip_ip4_country.csv") != -1) { query = "insert into hip_ip4_country values (" + fields[0] + "," + fields[1] + ")"; } debug(n + " - " + query); stat.executeUpdate(query); n++; } debug("(4) tot import per il file" + f_name + " : " + n); stat.close(); new File(f_name).delete(); } catch (SQLException ex) { fatal("SQLException", ex); try { conn_stats.rollback(); } catch (SQLException ex2) { fatal("SQLException", ex2); } } catch (IOException ex) { fatal("IOException", ex); } catch (Exception ex3) { fatal("Exception", ex3); } } try { conn_stats.commit(); } catch (SQLException e) { fatal("SQLException", e); } try { conn_stats.setAutoCommit(true); } catch (SQLException e) { fatal("SQLException", e); } try { debug("(6) Vacuum"); Statement stat = this.conn_stats.createStatement(); stat.executeUpdate("VACUUM"); stat.close(); } catch (SQLException e) { fatal("SQLException", e); } debug("End execute job " + this.getClass().getName()); } Code Sample 2: protected boolean store(Context context) throws DataStoreException, ServletException { Connection db = context.getConnection(); Statement st = null; String q = null; Integer subscriber = context.getValueAsInteger("subscriber"); int amount = 0; if (subscriber == null) { throw new DataAuthException("Don't know who moderator is"); } Object response = context.get("Response"); if (response == null) { throw new DataStoreException("Don't know what to moderate"); } else { Context scratch = (Context) context.clone(); TableDescriptor.getDescriptor("response", "response", scratch).fetch(scratch); Integer author = scratch.getValueAsInteger("author"); if (subscriber.equals(author)) { throw new SelfModerationException("You may not moderate your own responses"); } } context.put("moderator", subscriber); context.put("moderated", response); if (db != null) { try { st = db.createStatement(); q = "select mods from subscriber where subscriber = " + subscriber.toString(); ResultSet r = st.executeQuery(q); if (r.next()) { if (r.getInt("mods") < 1) { throw new DataAuthException("You have no moderation points left"); } } else { throw new DataAuthException("Don't know who moderator is"); } Object reason = context.get("reason"); q = "select score from modreason where modreason = " + reason; r = st.executeQuery(q); if (r.next()) { amount = r.getInt("score"); context.put("amount", new Integer(amount)); } else { throw new DataStoreException("Don't recognise reason (" + reason + ") to moderate"); } context.put(keyField, null); if (super.store(context, db)) { db.setAutoCommit(false); q = "update RESPONSE set Moderation = " + "( select sum( Amount) from MODERATION " + "where Moderated = " + response + ") " + "where Response = " + response; st.executeUpdate(q); q = "update subscriber set mods = mods - 1 " + "where subscriber = " + subscriber; st.executeUpdate(q); q = "select author from response " + "where response = " + response; r = st.executeQuery(q); if (r.next()) { int author = r.getInt("author"); if (author != 0) { int points = -1; if (amount > 0) { points = 1; } StringBuffer qb = new StringBuffer("update subscriber "); qb.append("set score = score + ").append(amount); qb.append(", mods = mods + ").append(points); qb.append(" where subscriber = ").append(author); st.executeUpdate(qb.toString()); } } db.commit(); } } catch (Exception e) { try { db.rollback(); } catch (Exception whoops) { throw new DataStoreException("Shouldn't happen: " + "failed to back out " + "failed insert: " + whoops.getMessage()); } throw new DataStoreException("Failed to store moderation: " + e.getMessage()); } finally { if (st != null) { try { st.close(); } catch (Exception noclose) { } context.releaseConnection(db); } } } return true; }
11
Code Sample 1: public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); } Code Sample 2: public void write(PDDocument doc) throws COSVisitorException { document = doc; SecurityHandler securityHandler = document.getSecurityHandler(); if (securityHandler != null) { try { securityHandler.prepareDocumentForEncryption(document); this.willEncrypt = true; } catch (IOException e) { throw new COSVisitorException(e); } catch (CryptographyException e) { throw new COSVisitorException(e); } } else { this.willEncrypt = false; } COSDocument cosDoc = document.getDocument(); COSDictionary trailer = cosDoc.getTrailer(); COSArray idArray = (COSArray) trailer.getDictionaryObject("ID"); if (idArray == null) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(Long.toString(System.currentTimeMillis()).getBytes()); COSDictionary info = (COSDictionary) trailer.getDictionaryObject("Info"); if (info != null) { Iterator values = info.getValues().iterator(); while (values.hasNext()) { md.update(values.next().toString().getBytes()); } } idArray = new COSArray(); COSString id = new COSString(md.digest()); idArray.add(id); idArray.add(id); trailer.setItem("ID", idArray); } catch (NoSuchAlgorithmException e) { throw new COSVisitorException(e); } } cosDoc.accept(this); }
00
Code Sample 1: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } Code Sample 2: public void connect() throws IOException { if (log.isDebugEnabled()) log.debug("Connecting to: " + HOST); ftpClient.connect(HOST); if (log.isDebugEnabled()) log.debug("\tReply: " + ftpClient.getReplyString()); if (log.isDebugEnabled()) log.debug("Login as anonymous"); ftpClient.login("anonymous", ""); if (log.isDebugEnabled()) log.debug("\tReply: " + ftpClient.getReplyString()); folder = INTACT_FOLDER; }
00
Code Sample 1: public void connect() throws FTPException { try { ftp = new FTPClient(); ftp.connect(host); if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.login(this.username, this.password); } else { ftp.disconnect(); throw new FTPException("Não foi possivel se conectar no servidor FTP"); } isConnected = true; } catch (Exception ex) { throw new FTPException(ex); } } Code Sample 2: public void addRegisterInfo(HttpServletRequest request) throws ApplicationException { String[] pids = request.getParameterValues("pid"); if (pids == null || pids.length <= 0) throw new ApplicationException("��ѡ��Ҫ���IJ�Ʒ"); RegisterDao registerDao = new RegisterDao(); Register register = registerDao.findPojoById(StrFun.getString(request, "rid"), Register.class); if (register.audit) throw new ApplicationException("��������Ѿ���ˣ��������µ���Ʒ"); DBConnect dbc = null; Connection conn = null; try { dbc = DBConnect.createDBConnect(); conn = dbc.getConnection(); conn.setAutoCommit(false); for (String pid : pids) { RegisterInfo pd = new RegisterInfo(); pd.rid = StrFun.getInt(request, "rid"); pd.pid = Integer.parseInt(pid); pd.productName = StrFun.getString(request, "productName_" + pid); pd.regAmount = StrFun.getInt(request, "regAmount_" + pid); pd.regPrice = StrFun.getInt(request, "regPrice_" + pid); pd.regSalePrice = StrFun.getInt(request, "regSalePrice_" + pid); pd.userNo = ServerUtil.getUserFromSession(request).userNo; if (pd.regAmount <= 0) throw new ApplicationException("�����������Ϊ��"); String sql = "insert into SS_RegisterInfo " + "(pid, rid, productName, regAmount, regPrice, regSalePrice, userNo) " + "values(" + "'" + pd.pid + "', " + "'" + pd.rid + "', " + "'" + pd.productName + "', " + "'" + pd.regAmount + "', " + "'" + pd.regPrice + "', " + "'" + pd.regSalePrice + "', " + "'" + pd.userNo + "' " + ")"; conn.createStatement().executeUpdate(sql); } conn.commit(); } catch (Exception e) { e.printStackTrace(); if (conn != null) { try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } throw new ApplicationException(e.getMessage(), e); } finally { if (dbc != null) try { dbc.close(); } catch (Exception e) { e.printStackTrace(); } } }
00
Code Sample 1: public static Image getPluginImage(final Object plugin, final String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; } Code Sample 2: public ProgramProfilingSymbol deleteProfilingSymbol(int id) throws AdaptationException { ProgramProfilingSymbol profilingSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProgramProfilingSymbols " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete program profiling " + "symbol failed."; log.error(msg); throw new AdaptationException(msg); } profilingSymbol = getProfilingSymbol(resultSet); query = "DELETE FROM ProgramProfilingSymbols " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProfilingSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return profilingSymbol; }
11
Code Sample 1: public static void copyFile(File srcFile, File destFolder) { try { File destFile = new File(destFolder, srcFile.getName()); if (destFile.exists()) { throw new BuildException("Could not copy " + srcFile + " to " + destFolder + " as " + destFile + " already exists"); } FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(srcFile).getChannel(); destChannel = new FileOutputStream(destFile).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) { srcChannel.close(); } if (destChannel != null) { destChannel.close(); } } destFile.setLastModified((srcFile.lastModified())); } catch (IOException e) { throw new BuildException("Could not copy " + srcFile + " to " + destFolder + ": " + e, e); } } Code Sample 2: public static void copyFile(File file, String pathExport) throws IOException { File out = new File(pathExport); FileChannel sourceChannel = new FileInputStream(file).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: public void putFile(CompoundName file, FileInputStream fileInput) throws IOException { File fullDir = new File(REMOTE_BASE_DIR.getCanonicalPath()); for (int i = 0; i < file.size() - 1; i++) fullDir = new File(fullDir, file.get(i)); fullDir.mkdirs(); File outputFile = new File(fullDir, file.get(file.size() - 1)); FileOutputStream outStream = new FileOutputStream(outputFile); for (int byteIn = fileInput.read(); byteIn != -1; byteIn = fileInput.read()) outStream.write(byteIn); fileInput.close(); outStream.close(); } Code Sample 2: public static void copyFile(File source, File dest) throws Exception { log.warn("File names are " + source.toString() + " and " + dest.toString()); if (!dest.getParentFile().exists()) dest.getParentFile().mkdir(); FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
00
Code Sample 1: public void createMessageBuffer(String messageBufferName, MessageBufferPolicy messageBufferPolicyObj) throws AppFabricException { String messageBufferPolicy = messageBufferPolicyObj.getMessageBufferPolicy(); if (messageBufferPolicy == null) { throw new AppFabricException("MessageBufferPolicy can not be null"); } MessageBufferUtil msgBufferUtilObj = new MessageBufferUtil(solutionName, TokenConstants.getSimpleAuthAuthenticationType()); String requestUri = msgBufferUtilObj.getRequestUri(); String messageBufferUri = msgBufferUtilObj.getCreateMessageBufferUri(messageBufferName); if (messageBufferUri == null) { throw new AppFabricException("MessageBufferUri can not be null"); } String authorizationToken = ""; try { ACSTokenProvider tp = new ACSTokenProvider(httpWebProxyServer_, httpWebProxyPort_, this.credentials); authorizationToken = tp.getACSToken(requestUri, messageBufferUri); } catch (AppFabricException e) { throw e; } 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("PUT"); connection.setRequestProperty("Content-type", MessageBufferConstants.getCONTENT_TYPE_PROPERTY_FOR_ATOM_XML()); connection.setRequestProperty("Content-Length", "" + messageBufferPolicy.length()); String authStr = TokenConstants.getWrapAuthenticationType() + " " + TokenConstants.getWrapAuthorizationHeaderKey() + "=\"" + authorizationToken + "\""; connection.setRequestProperty("Authorization", authStr); connection.setRequestProperty("Expect", "100-continue"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(messageBufferPolicy); wr.flush(); wr.close(); if (LoggerUtil.getIsLoggingOn()) SDKLoggerHelper.logRequest(connection, SDKLoggerHelper.RecordType.CreateMessageBuffer_REQUEST); String responseCode = "<responseCode>" + connection.getResponseCode() + "</responseCode>"; if ((connection.getResponseCode() == MessageBufferConstants.HTTP_STATUS_CODE_ACCEPTED) || (connection.getResponseCode() == MessageBufferConstants.HTTP_STATUS_CODE_CREATED) || (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(); if (LoggerUtil.getIsLoggingOn()) { StringBuilder responseXML = new StringBuilder(); responseXML.append(responseCode); responseXML.append(response.toString()); SDKLoggerHelper.logMessage(URLEncoder.encode(responseXML.toString(), "UTF-8"), SDKLoggerHelper.RecordType.CreateMessageBuffer_RESPONSE); } } else { if (LoggerUtil.getIsLoggingOn()) SDKLoggerHelper.logMessage(URLEncoder.encode(responseCode, "UTF-8"), SDKLoggerHelper.RecordType.CreateMessageBuffer_RESPONSE); throw new AppFabricException("MessageBuffer could not be created or updated. Error. Response code: " + connection.getResponseCode()); } } catch (Exception e) { throw new AppFabricException(e.getMessage()); } } Code Sample 2: protected void copy(File src, File dest) throws IOException { if (src.isDirectory() && dest.isFile()) throw new IOException("Cannot copy a directory to a file"); if (src.isDirectory()) { File newDir = new File(dest, src.getName()); if (!newDir.mkdirs()) throw new IOException("Cannot create a new Directory"); File[] entries = src.listFiles(); for (int i = 0; i < entries.length; ++i) copy(entries[i], newDir); return; } if (dest.isDirectory()) { File newFile = new File(dest, src.getName()); newFile.createNewFile(); copy(src, newFile); return; } try { if (src.length() == 0) { dest.createNewFile(); return; } FileChannel fc = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); long transfered = 0; long totalLength = src.length(); while (transfered < totalLength) { long num = fc.transferTo(transfered, totalLength - transfered, dstChannel); if (num == 0) throw new IOException("Error while copying"); transfered += num; } dstChannel.close(); fc.close(); } catch (IOException e) { if (os.equals("Unix")) { _logger.fine("Trying to use cp to copy file..."); File cp = new File("/usr/bin/cp"); if (!cp.exists()) cp = new File("/bin/cp"); if (!cp.exists()) cp = new File("/usr/local/bin/cp"); if (!cp.exists()) cp = new File("/sbin/cp"); if (!cp.exists()) cp = new File("/usr/sbin/cp"); if (!cp.exists()) cp = new File("/usr/local/sbin/cp"); if (cp.exists()) { Process cpProcess = Runtime.getRuntime().exec(cp.getAbsolutePath() + " '" + src.getAbsolutePath() + "' '" + dest.getAbsolutePath() + "'"); int errCode; try { errCode = cpProcess.waitFor(); } catch (java.lang.InterruptedException ie) { throw e; } return; } } throw e; } }
00
Code Sample 1: private String fetchURL(String url) { StringBuilder content = new StringBuilder(); String line; BufferedReader input = null; try { URL urlToFetch = new URL(url); input = new BufferedReader(new InputStreamReader(urlToFetch.openStream())); while ((line = input.readLine()) != null) { content.append(line); } input.close(); return content.toString(); } catch (java.io.IOException ex) { return null; } } Code Sample 2: private boolean downloadFile() { FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(this.server); ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Connected to " + this.server); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP server refused connection."); return false; } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { return false; } } ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP Could not connect to server."); ResourcePool.LogException(e, this); return false; } try { if (!ftp.login(this.user, this.password)) { ftp.logout(); ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP login failed."); return false; } ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Remote system is " + ftp.getSystemName()); if ((this.transferType != null) && (this.transferType.compareTo(FTPWorkerThread.ASCII) == 0)) { ftp.setFileType(FTP.ASCII_FILE_TYPE); } else { ftp.setFileType(FTP.BINARY_FILE_TYPE); } if ((this.passiveMode != null) && this.passiveMode.equalsIgnoreCase(FTPWorkerThread.FALSE)) { ftp.enterLocalActiveMode(); } else { ftp.enterLocalPassiveMode(); } } catch (FTPConnectionClosedException e) { ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "Server closed connection."); ResourcePool.LogException(e, this); return false; } catch (IOException e) { ResourcePool.LogException(e, this); return false; } OutputStream output; try { java.util.Date startDate = new java.util.Date(); output = new FileOutputStream(this.destFileName); ftp.retrieveFile(this.fileName, output); File f = new File(this.destFileName); if (f.exists() && (this.lastModifiedDate != null)) { f.setLastModified(this.lastModifiedDate.longValue()); } java.util.Date endDate = new java.util.Date(); this.downloadTime = endDate.getTime() - startDate.getTime(); double iDownLoadTime = ((this.downloadTime + 1) / 1000) + 1; ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Download Complete, Rate = " + (this.fileSize / (iDownLoadTime * 1024)) + " Kb/s, Seconds = " + iDownLoadTime); this.downloadTime = (this.downloadTime + 1) / 1000; if (ftp.isConnected()) { ftp.disconnect(); } } catch (FTPConnectionClosedException e) { ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, e.getMessage()); ResourcePool.LogException(e, this); return false; } catch (IOException e) { ResourcePool.LogException(e, this); return false; } return true; }
00
Code Sample 1: public static synchronized String getSequenceNumber(String SequenceName) { String result = "0"; Connection conn = null; Statement ps = null; ResultSet rs = null; try { conn = TPCW_Database.getConnection(); conn.setAutoCommit(false); String sql = "select num from sequence where name='" + SequenceName + "'"; ps = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); rs = ps.executeQuery(sql); long num = 0; while (rs.next()) { num = rs.getLong(1); result = new Long(num).toString(); } num++; sql = "update sequence set num=" + num + " where name='" + SequenceName + "'"; int res = ps.executeUpdate(sql); if (res == 1) { conn.commit(); } else conn.rollback(); } catch (Exception e) { System.out.println("Error Happens when trying to obtain the senquence number"); e.printStackTrace(); } finally { try { if (conn != null) conn.close(); if (rs != null) rs.close(); if (ps != null) ps.close(); } catch (SQLException se) { se.printStackTrace(); } } return result; } Code Sample 2: public XMLTreeView(JFrame frame, Web3DService web3DService) { frame.getContentPane().setLayout(new BorderLayout()); DefaultMutableTreeNode top = new DefaultMutableTreeNode(file); saxTree = new SAXTreeBuilder(top); InputStream urlIn = null; try { SAXParser saxParser = new SAXParser(); saxParser.setContentHandler(saxTree); String request = web3DService.getServiceEndPoint() + "?" + "SERVICE=" + web3DService.getService() + "&" + "REQUEST=GetCapabilities&" + "ACCEPTFORMATS=text/xml&" + "ACCEPTVERSIONS="; for (int i = 0; i < web3DService.getAcceptVersions().length; i++) { if (i > 0) request += ","; request += web3DService.getAcceptVersions()[i]; } System.out.println(request); URL url = new URL(request); URLConnection urlc = url.openConnection(); urlc.setReadTimeout(Navigator.TIME_OUT); if (web3DService.getEncoding() != null) { urlc.setRequestProperty("Authorization", "Basic " + web3DService.getEncoding()); } urlIn = urlc.getInputStream(); saxParser.parse(new InputSource(urlIn)); } catch (Exception ex) { top.add(new DefaultMutableTreeNode(ex.getMessage())); } try { urlIn.close(); } catch (Exception e) { } JTree tree = new JTree(saxTree.getTree()); JScrollPane scrollPane = new JScrollPane(tree); frame.getContentPane().add("Center", scrollPane); frame.setVisible(true); }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile) throws IOException { 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: protected File downloadUpdate(String resource) throws AgentException { RESTCall call = makeRESTCall(resource); call.invoke(); File tmpFile; try { tmpFile = File.createTempFile("controller-update-", ".war", new File(tmpPath)); } catch (IOException e) { throw new AgentException("Failed to create temporary file", e); } InputStream is; try { is = call.getInputStream(); } catch (IOException e) { throw new AgentException("Failed to open input stream", e); } try { FileOutputStream os; try { os = new FileOutputStream(tmpFile); } catch (FileNotFoundException e) { throw new AgentException("Failed to open temporary file for writing", e); } boolean success = false; try { IOUtils.copy(is, os); success = true; } catch (IOException e) { throw new AgentException("Failed to download update", e); } finally { try { os.flush(); os.close(); } catch (IOException e) { if (!success) throw new AgentException("Failed to flush to disk", e); } } } finally { try { is.close(); } catch (IOException e) { log.error("Failed to close input stream", e); } call.disconnect(); } return tmpFile; }
11
Code Sample 1: @Override public void execute() throws BuildException { final String GC_USERNAME = "google-code-username"; final String GC_PASSWORD = "google-code-password"; if (StringUtils.isBlank(this.projectName)) throw new BuildException("undefined project"); if (this.file == null) throw new BuildException("undefined file"); if (!this.file.exists()) throw new BuildException("file not found :" + file); if (!this.file.isFile()) throw new BuildException("not a file :" + file); if (this.config == null) throw new BuildException("undefined config"); if (!this.config.exists()) throw new BuildException("file not found :" + config); if (!this.config.isFile()) throw new BuildException("not a file :" + config); PostMethod post = null; try { Properties cfg = new Properties(); FileInputStream fin = new FileInputStream(this.config); cfg.loadFromXML(fin); fin.close(); if (!cfg.containsKey(GC_USERNAME)) throw new BuildException("undefined " + GC_USERNAME + " in " + this.config); if (!cfg.containsKey(GC_PASSWORD)) throw new BuildException("undefined " + GC_PASSWORD + " in " + this.config); HttpClient client = new HttpClient(); post = new PostMethod("https://" + projectName + ".googlecode.com/files"); post.addRequestHeader("User-Agent", getClass().getName()); post.addRequestHeader("Authorization", "Basic " + Base64.encode(cfg.getProperty(GC_USERNAME) + ":" + cfg.getProperty(GC_PASSWORD))); List<Part> parts = new ArrayList<Part>(); String s = this.summary; if (StringUtils.isBlank(s)) { s = this.file.getName() + " (" + TimeUtils.toYYYYMMDD() + ")"; } parts.add(new StringPart("summary", s)); for (String lbl : this.labels.split("[, \t\n]+")) { if (StringUtils.isBlank(lbl)) continue; parts.add(new StringPart("label", lbl.trim())); } parts.add(new FilePart("filename", this.file)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()); post.setRequestEntity(requestEntity); int status = client.executeMethod(post); if (status != 201) { throw new BuildException("http status !=201 : " + post.getResponseBodyAsString()); } else { IOUtils.copyTo(post.getResponseBodyAsStream(), new NullOutputStream()); } } catch (BuildException e) { throw e; } catch (Exception e) { throw new BuildException(e); } finally { if (post != null) post.releaseConnection(); } } Code Sample 2: @Override public void copyFile2File(final File src, final File dest, final boolean force) throws C4JException { if (dest.exists()) if (force && !dest.delete()) throw new C4JException(format("Copying ‘%s’ to ‘%s’ failed; cannot overwrite existing file.", src.getPath(), dest.getPath())); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(src).getChannel(); outChannel = new FileOutputStream(dest).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (src.canExecute()) dest.setExecutable(true, false); } catch (final IOException e) { throw new C4JException(format("Could not copy ‘%s’ to ‘%s’.", src.getPath(), dest.getPath()), e); } finally { if (inChannel != null) try { try { inChannel.close(); } catch (final IOException e) { throw new C4JException(format("Could not close input stream for ‘%s’.", src.getPath()), e); } } finally { if (outChannel != null) try { outChannel.close(); } catch (final IOException e) { throw new C4JException(format("Could not close output stream for ‘%s’.", dest.getPath()), e); } } } }
11
Code Sample 1: public void readMESHDescriptorFileIntoFiles(String outfiledir) { String inputLine, ins; String filename = getMESHdescriptorfilename(); String uid = ""; String name = ""; String description = ""; String element_of = ""; Vector treenr = new Vector(); Vector related = new Vector(); Vector synonyms = new Vector(); Vector actions = new Vector(); Vector chemicals = new Vector(); Vector allCASchemicals = new Vector(); Set CAS = new TreeSet(); Map treenr2uid = new TreeMap(); Map uid2name = new TreeMap(); String cut1, cut2; try { BufferedReader in = new BufferedReader(new FileReader(filename)); String outfile = outfiledir + "\\mesh"; BufferedWriter out_concept = new BufferedWriter(new FileWriter(outfile + "_concept.txt")); BufferedWriter out_concept_name = new BufferedWriter(new FileWriter(outfile + "_concept_name.txt")); BufferedWriter out_relation = new BufferedWriter(new FileWriter(outfile + "_relation.txt")); BufferedWriter cas_mapping = new BufferedWriter(new FileWriter(outfile + "to_cas_mapping.txt")); BufferedWriter ec_mapping = new BufferedWriter(new FileWriter(outfile + "to_ec_mapping.txt")); Connection db = tools.openDB("kb"); String query = "SELECT hierarchy_complete,uid FROM mesh_tree, mesh_graph_uid_name WHERE term=name"; ResultSet rs = tools.executeQuery(db, query); while (rs.next()) { String db_treenr = rs.getString("hierarchy_complete"); String db_uid = rs.getString("uid"); treenr2uid.put(db_treenr, db_uid); } db.close(); System.out.println("Reading in the DUIDs ..."); BufferedReader in_for_mapping = new BufferedReader(new FileReader(filename)); inputLine = getNextLine(in_for_mapping); boolean leave = false; while ((in_for_mapping != null) && (inputLine != null)) { if (inputLine.startsWith("<DescriptorRecord DescriptorClass")) { inputLine = getNextLine(in_for_mapping); cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String mesh_uid = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); if (mesh_uid.compareTo("D041441") == 0) leave = true; inputLine = getNextLine(in_for_mapping); inputLine = getNextLine(in_for_mapping); cut1 = "<String>"; cut2 = "</String>"; String mesh_name = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); uid2name.put(mesh_uid, mesh_name); } inputLine = getNextLine(in_for_mapping); } in_for_mapping.close(); BufferedReader in_ec_numbers = new BufferedReader(new FileReader("e:\\projects\\ondex\\ec_concept_acc.txt")); Set ec_numbers = new TreeSet(); String ec_line = in_ec_numbers.readLine(); while (in_ec_numbers.ready()) { StringTokenizer st = new StringTokenizer(ec_line); st.nextToken(); ec_numbers.add(st.nextToken()); ec_line = in_ec_numbers.readLine(); } in_ec_numbers.close(); tools.printDate(); inputLine = getNextLine(in); while (inputLine != null) { if (inputLine.startsWith("<DescriptorRecord DescriptorClass")) { treenr.clear(); related.clear(); synonyms.clear(); actions.clear(); chemicals.clear(); boolean id_ready = false; boolean line_read = false; while ((inputLine != null) && (!inputLine.startsWith("</DescriptorRecord>"))) { line_read = false; if ((inputLine.startsWith("<DescriptorUI>")) && (!id_ready)) { cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; uid = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); inputLine = getNextLine(in); inputLine = getNextLine(in); cut1 = "<String>"; cut2 = "</String>"; name = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); id_ready = true; } if (inputLine.compareTo("<SeeRelatedList>") == 0) { while ((inputLine != null) && (inputLine.indexOf("</SeeRelatedList>") == -1)) { if (inputLine.startsWith("<DescriptorUI>")) { cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String id = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); related.add(id); } inputLine = getNextLine(in); line_read = true; } } if (inputLine.compareTo("<TreeNumberList>") == 0) { while ((inputLine != null) && (inputLine.indexOf("</TreeNumberList>") == -1)) { if (inputLine.startsWith("<TreeNumber>")) { cut1 = "<TreeNumber>"; cut2 = "</TreeNumber>"; String id = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); treenr.add(id); } inputLine = getNextLine(in); line_read = true; } } if (inputLine.startsWith("<Concept PreferredConceptYN")) { boolean prefConcept = false; if (inputLine.compareTo("<Concept PreferredConceptYN=\"Y\">") == 0) prefConcept = true; while ((inputLine != null) && (inputLine.indexOf("</Concept>") == -1)) { if (inputLine.startsWith("<CASN1Name>") && prefConcept) { cut1 = "<CASN1Name>"; cut2 = "</CASN1Name>"; String casn1 = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); String chem_name = casn1; String chem_description = ""; if (casn1.length() > chem_name.length() + 2) chem_description = casn1.substring(chem_name.length() + 2, casn1.length()); String reg_number = ""; inputLine = getNextLine(in); if (inputLine.startsWith("<RegistryNumber>")) { cut1 = "<RegistryNumber>"; cut2 = "</RegistryNumber>"; reg_number = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); } Vector chemical = new Vector(); String type = ""; if (reg_number.startsWith("EC")) { type = "EC"; reg_number = reg_number.substring(3, reg_number.length()); } else { type = "CAS"; } chemical.add(type); chemical.add(reg_number); chemical.add(chem_name); chemical.add(chem_description); chemicals.add(chemical); if (type.compareTo("CAS") == 0) { if (!CAS.contains(reg_number)) { CAS.add(reg_number); allCASchemicals.add(chemical); } } } if (inputLine.startsWith("<ScopeNote>") && prefConcept) { cut1 = "<ScopeNote>"; description = inputLine.substring(cut1.length(), inputLine.length()); } if (inputLine.startsWith("<TermUI>")) { inputLine = getNextLine(in); cut1 = "<String>"; cut2 = "</String>"; String syn = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); if (syn.indexOf("&amp;") != -1) { String syn1 = syn.substring(0, syn.indexOf("&amp;")); String syn2 = syn.substring(syn.indexOf("amp;") + 4, syn.length()); syn = syn1 + " & " + syn2; } if (name.compareTo(syn) != 0) synonyms.add(syn); } if (inputLine.startsWith("<PharmacologicalAction>")) { inputLine = getNextLine(in); inputLine = getNextLine(in); cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String act_ui = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); actions.add(act_ui); } inputLine = getNextLine(in); line_read = true; } } if (!line_read) inputLine = getNextLine(in); } String pos_tag = ""; element_of = "MESHD"; String is_primary = "0"; out_concept.write(uid + "\t" + pos_tag + "\t" + description + "\t" + element_of + "\t"); out_concept.write(is_primary + "\n"); String name_stemmed = ""; String name_tagged = ""; element_of = "MESHD"; String is_unique = "0"; int is_preferred = 1; String original_name = name; String is_not_substring = "0"; out_concept_name.write(uid + "\t" + name + "\t" + name_stemmed + "\t"); out_concept_name.write(name_tagged + "\t" + element_of + "\t"); out_concept_name.write(is_unique + "\t" + is_preferred + "\t"); out_concept_name.write(original_name + "\t" + is_not_substring + "\n"); is_preferred = 0; for (int i = 0; i < synonyms.size(); i++) { name = (String) synonyms.get(i); original_name = name; out_concept_name.write(uid + "\t" + name + "\t" + name_stemmed + "\t"); out_concept_name.write(name_tagged + "\t" + element_of + "\t"); out_concept_name.write(is_unique + "\t" + is_preferred + "\t"); out_concept_name.write(original_name + "\t" + is_not_substring + "\n"); } String rel_type = "is_r"; element_of = "MESHD"; String from_name = name; for (int i = 0; i < related.size(); i++) { String to_uid = (String) related.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } rel_type = "is_a"; element_of = "MESHD"; related.clear(); for (int i = 0; i < treenr.size(); i++) { String tnr = (String) treenr.get(i); if (tnr.length() > 3) tnr = tnr.substring(0, tnr.lastIndexOf(".")); String rel_uid = (String) treenr2uid.get(tnr); if (rel_uid != null) related.add(rel_uid); else System.out.println(uid + ": No DUI found for " + tnr); } for (int i = 0; i < related.size(); i++) { String to_uid = (String) related.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } if (related.size() == 0) System.out.println(uid + ": No is_a relations"); rel_type = "act"; element_of = "MESHD"; for (int i = 0; i < actions.size(); i++) { String to_uid = (String) actions.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } String method = "IMPM"; String score = "1.0"; for (int i = 0; i < chemicals.size(); i++) { Vector chemical = (Vector) chemicals.get(i); String type = (String) chemical.get(0); String chem = (String) chemical.get(1); if (!ec_numbers.contains(chem) && (type.compareTo("EC") == 0)) { if (chem.compareTo("1.14.-") == 0) chem = "1.14.-.-"; else System.out.println("MISSING EC: " + chem); } String id = type + ":" + chem; String entry = uid + "\t" + id + "\t" + method + "\t" + score + "\n"; if (type.compareTo("CAS") == 0) cas_mapping.write(entry); else ec_mapping.write(entry); } } else inputLine = getNextLine(in); } System.out.println("End import descriptors"); tools.printDate(); in.close(); out_concept.close(); out_concept_name.close(); out_relation.close(); cas_mapping.close(); ec_mapping.close(); outfile = outfiledir + "\\cas"; out_concept = new BufferedWriter(new FileWriter(outfile + "_concept.txt")); out_concept_name = new BufferedWriter(new FileWriter(outfile + "_concept_name.txt")); BufferedWriter out_concept_acc = new BufferedWriter(new FileWriter(outfile + "_concept_acc.txt")); for (int i = 0; i < allCASchemicals.size(); i++) { Vector chemical = (Vector) allCASchemicals.get(i); String cas_id = "CAS:" + (String) chemical.get(1); String cas_name = (String) chemical.get(2); String cas_pos_tag = ""; String cas_description = (String) chemical.get(3); String cas_element_of = "CAS"; String cas_is_primary = "0"; out_concept.write(cas_id + "\t" + cas_pos_tag + "\t" + cas_description + "\t"); out_concept.write(cas_element_of + "\t" + cas_is_primary + "\n"); String cas_name_stemmed = ""; String cas_name_tagged = ""; String cas_is_unique = "0"; String cas_is_preferred = "0"; String cas_original_name = cas_name; String cas_is_not_substring = "0"; out_concept_name.write(cas_id + "\t" + cas_name + "\t" + cas_name_stemmed + "\t"); out_concept_name.write(cas_name_tagged + "\t" + cas_element_of + "\t"); out_concept_name.write(cas_is_unique + "\t" + cas_is_preferred + "\t"); out_concept_name.write(cas_original_name + "\t" + cas_is_not_substring + "\n"); out_concept_acc.write(cas_id + "\t" + (String) chemical.get(1) + "\t"); out_concept_acc.write(cas_element_of + "\n"); } out_concept.close(); out_concept_name.close(); out_concept_acc.close(); } catch (Exception e) { settings.writeLog("Error while reading MESH descriptor file: " + e.getMessage()); } } Code Sample 2: private boolean performModuleInstallation(Model m) { String seldir = directoryHandler.getSelectedDirectory(); if (seldir == null) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A target directory must be selected."); box.open(); return false; } String sjar = pathText.getText(); File fjar = new File(sjar); if (!fjar.exists()) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A non-existing jar file has been selected."); box.open(); return false; } int count = 0; try { URLClassLoader loader = new URLClassLoader(new URL[] { fjar.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(fjar)); JarEntry entry = jis.getNextJarEntry(); while (entry != null) { String name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); Class<?> cls = loader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && (cls.getModifiers() & Modifier.ABSTRACT) == 0) { if (!testAlgorithm(cls, m)) return false; count++; } } entry = jis.getNextJarEntry(); } } catch (Exception e1) { Application.logexcept("Could not load classes from jar file.", e1); return false; } if (count == 0) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("There don't seem to be any algorithms in the specified module."); box.open(); return false; } try { FileChannel ic = new FileInputStream(sjar).getChannel(); FileChannel oc = new FileOutputStream(seldir + File.separator + fjar.getName()).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (Exception e) { Application.logexcept("Could not install module", e); return false; } result = new Object(); return true; }
00
Code Sample 1: public static String encodePassword(String password) { try { MessageDigest messageDiegest = MessageDigest.getInstance("SHA-1"); messageDiegest.update(password.getBytes("UTF-8")); return Base64.encodeToString(messageDiegest.digest(), false); } catch (NoSuchAlgorithmException e) { log.error("Exception while encoding password"); throw new Error(e); } catch (UnsupportedEncodingException e) { log.error("Exception while encoding password"); throw new Error(e); } } Code Sample 2: public void setUrl(URL url) throws PDFException, PDFSecurityException, IOException { InputStream in = null; try { URLConnection urlConnection = url.openConnection(); in = urlConnection.getInputStream(); String pathOrURL = url.toString(); setInputStream(in, pathOrURL); } finally { if (in != null) { in.close(); } } }
00
Code Sample 1: private String getPage(String urlString) throws Exception { if (pageBuffer.containsKey(urlString)) return pageBuffer.get(urlString); URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); BufferedReader in = null; StringBuilder page = new StringBuilder(); try { in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { page.append(line); page.append("\n"); } } catch (IOException ioe) { logger.warn("Failed to read web page"); } finally { if (in != null) { in.close(); } } return page.toString(); } Code Sample 2: void setURLString(String path, boolean forceLoad) { if (path != null) { if (this.url != null || inputStream != null) throw new IllegalArgumentException(Ding3dI18N.getString("MediaContainer5")); try { URL url = new URL(path); InputStream stream; stream = url.openStream(); stream.close(); } catch (Exception e) { throw new SoundException(javax.media.ding3d.Ding3dI18N.getString("MediaContainer0")); } } this.urlString = path; if (forceLoad) dispatchMessage(); }
11
Code Sample 1: public static void copyFile(File sourceFile, File destinationFile) throws IOException { if (!destinationFile.exists()) { destinationFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: private boolean copyToFile(String folder, String fileName) throws StorageException { InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(folder + "/" + fileName); if (in == null) { return false; } FileOutputStream out = null; try { out = new FileOutputStream(new File(path, fileName)); IOUtils.copy(in, out); in.close(); out.flush(); } catch (Exception e) { throw new StorageException(e); } finally { if (in != null) { IOUtils.closeQuietly(in); } if (out != null) { IOUtils.closeQuietly(out); } } return true; }
11
Code Sample 1: public static String calculateHA2(String uri) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes("GET", ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(uri, ISO_8859_1)); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } } Code Sample 2: protected void innerProcess(ProcessorURI curi) throws InterruptedException { Pattern regexpr = curi.get(this, STRIP_REG_EXPR); ReplayCharSequence cs = null; try { cs = curi.getRecorder().getReplayCharSequence(); } catch (Exception e) { curi.getNonFatalFailures().add(e); 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 != null) { s = cs.toString(); } else { Matcher m = regexpr.matcher(cs); s = m.replaceAll(" "); } digest.update(s.getBytes()); byte[] newDigestValue = digest.digest(); curi.setContentDigest(SHA1, newDigestValue); } finally { if (cs != null) { try { cs.close(); } catch (IOException ioe) { logger.warning(TextUtils.exceptionToString("Failed close of ReplayCharSequence.", ioe)); } } } }
11
Code Sample 1: public void unzip(final File outDir) throws IOException { ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(this.bytes)); ZipEntry entry = input.getNextEntry(); while (entry != null) { entry = input.getNextEntry(); if (entry != null) { File file = this.createFile(outDir, entry.getName()); if (!entry.isDirectory()) { FileOutputStream output = new FileOutputStream(file); IOUtils.copy(input, output); output.close(); } } } input.close(); } Code Sample 2: 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"); }
11
Code Sample 1: public static int unzipFile(File file_input, File dir_output) { ZipInputStream zip_in_stream; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in); zip_in_stream = new ZipInputStream(source); } catch (IOException e) { return STATUS_IN_FAIL; } byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; do { try { ZipEntry zip_entry = zip_in_stream.getNextEntry(); if (zip_entry == null) break; File output_file = new File(dir_output, zip_entry.getName()); FileOutputStream out = new FileOutputStream(output_file); BufferedOutputStream destination = new BufferedOutputStream(out, BUF_SIZE); while ((len = zip_in_stream.read(input_buffer, 0, BUF_SIZE)) != -1) destination.write(input_buffer, 0, len); destination.flush(); out.close(); } catch (IOException e) { return STATUS_GUNZIP_FAIL; } } while (true); try { zip_in_stream.close(); } catch (IOException e) { } return STATUS_OK; } Code Sample 2: public void visit(BosMember member) throws BosException { String relative = AddressingUtil.getRelativePath(member.getDataSourceUri(), baseUri); URL resultUrl; try { resultUrl = new URL(outputUrl, relative); File resultFile = new File(resultUrl.toURI()); resultFile.getParentFile().mkdirs(); log.info("Creating result file \"" + resultFile.getAbsolutePath() + "\"..."); IOUtils.copy(member.getInputStream(), new FileOutputStream(resultFile)); } catch (Exception e) { throw new BosException(e); } }
11
Code Sample 1: protected void initGame() { try { for (File fonte : files) { String absolutePath = outputDir.getAbsolutePath(); String separator = System.getProperty("file.separator"); String name = fonte.getName(); String destName = name.substring(0, name.length() - 3); File destino = new File(absolutePath + separator + destName + "jme"); FileInputStream reader = new FileInputStream(fonte); OutputStream writer = new FileOutputStream(destino); conversor.setProperty("mtllib", fonte.toURL()); conversor.convert(reader, writer); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } super.finish(); } Code Sample 2: protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } }
00
Code Sample 1: private Document getXML(String artist) throws Exception { Document doc = null; URL url = new URL("http://" + disgogsUrl + "/artist/" + formatQuery(artist) + "?f=xml&api_key=" + apiKey[0]); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.addRequestProperty("Accept-Encoding", "gzip"); if (StaticObj.PROXY_ENABLED) { Properties systemSettings = System.getProperties(); systemSettings.put("http.proxyHost", StaticObj.PROXY_URL); systemSettings.put("http.proxyPort", StaticObj.PROXY_PORT); System.setProperties(systemSettings); sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder(); String encoded = new String(encoder.encode(new String(StaticObj.PROXY_USERNAME + ":" + StaticObj.PROXY_PASSWORD).getBytes())); uc.setRequestProperty("Proxy-Authorization", "Basic " + encoded); } BufferedReader ir = null; try { if (uc.getInputStream() != null) { InputStream _is = uc.getInputStream(); GZIPInputStream _gzipIs = new GZIPInputStream(_is); InputStreamReader _isReader = new InputStreamReader(_gzipIs); ir = new BufferedReader(_isReader); SAXBuilder builder = new SAXBuilder(); doc = builder.build(ir); } } catch (Exception e) { if (StaticObj.DEBUG) { LogManager.getInstance().getLogger().error(e); e.printStackTrace(); System.out.println("No Data found!"); } } return doc; } 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 static Bitmap[] getMaps(double lat, double lon, int zoom) throws MalformedURLException, IOException { int latitudeTileNumber = lat2tile(lat, zoom); int longitudeTileNumber = lon2tile(lon, zoom); Bitmap[] maps = new Bitmap[10]; int cpt = 0; for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { try { URL url = new URL(("http://tile.openstreetmap.org/" + zoom + "/" + (longitudeTileNumber + j) + "/" + (latitudeTileNumber + i) + ".png")); Bitmap bmImg = BitmapFactory.decodeStream(url.openStream()); maps[cpt] = bmImg; cpt++; } catch (IOException e) { e.printStackTrace(); } } } return maps; } Code Sample 2: @RequestMapping(value = "/privatefiles/{file_name}") public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response, Principal principal) { try { Boolean validUser = false; final String currentUser = principal.getName(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!auth.getPrincipal().equals(new String("anonymousUser"))) { MetabolightsUser metabolightsUser = (MetabolightsUser) auth.getPrincipal(); if (metabolightsUser != null && metabolightsUser.isCurator()) validUser = true; } if (currentUser != null) { Study study = studyService.getBiiStudy(fileName, true); Collection<User> users = study.getUsers(); Iterator<User> iter = users.iterator(); while (iter.hasNext()) { User user = iter.next(); if (user.getUserName().equals(currentUser)) { validUser = true; break; } } } if (!validUser) throw new RuntimeException(PropertyLookup.getMessage("Entry.notAuthorised")); try { InputStream is = new FileInputStream(privateFtpDirectory + fileName + ".zip"); response.setContentType("application/zip"); IOUtils.copy(is, response.getOutputStream()); } catch (Exception e) { throw new RuntimeException(PropertyLookup.getMessage("Entry.fileMissing")); } response.flushBuffer(); } catch (IOException ex) { logger.info("Error writing file to output stream. Filename was '" + fileName + "'"); throw new RuntimeException("IOError writing file to output stream"); } }
11
Code Sample 1: static void copyFile(File file, File file1) throws IOException { byte abyte0[] = new byte[512]; FileInputStream fileinputstream = new FileInputStream(file); FileOutputStream fileoutputstream = new FileOutputStream(file1); int i; while ((i = fileinputstream.read(abyte0)) > 0) fileoutputstream.write(abyte0, 0, i); fileinputstream.close(); fileoutputstream.close(); } Code Sample 2: public static File createTempFile(InputStream contentStream, String ext) throws IOException { ExceptionUtils.throwIfNull(contentStream, "contentStream"); File file = File.createTempFile("test", ext); FileOutputStream fos = new FileOutputStream(file); try { IOUtils.copy(contentStream, fos, false); } finally { fos.close(); } return file; }
00
Code Sample 1: public static double[][] getCurrency() throws IOException { URL url = new URL("http://hk.finance.yahoo.com/currency"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "big5")); double currency[][] = new double[11][11]; while (true) { String line = in.readLine(); String reg = "<td\\s((align=\"right\"\\sclass=\"yfnc_tabledata1\")" + "|(class=\"yfnc_tabledata1\"\\salign=\"right\"))>" + "([\\d|\\.]+)</td>"; Matcher m = Pattern.compile(reg).matcher(line); int i = 0, j = 0; boolean isfound = false; while (m.find()) { isfound = true; currency[i][j] = Double.parseDouble(m.group(4)); if (j == 10) { j = 0; i++; } else j++; } if (isfound) break; } return currency; } Code Sample 2: public void initForEncryption() throws CryptographyException, IOException { String ownerPassword = pdDocument.getOwnerPasswordForEncryption(); String userPassword = pdDocument.getUserPasswordForEncryption(); if (ownerPassword == null) { ownerPassword = ""; } if (userPassword == null) { userPassword = ""; } PDStandardEncryption encParameters = (PDStandardEncryption) pdDocument.getEncryptionDictionary(); int permissionInt = encParameters.getPermissions(); int revision = encParameters.getRevision(); int length = encParameters.getLength() / 8; COSArray idArray = document.getDocumentID(); if (idArray == null || idArray.size() < 2) { idArray = new COSArray(); try { MessageDigest md = MessageDigest.getInstance("MD5"); BigInteger time = BigInteger.valueOf(System.currentTimeMillis()); md.update(time.toByteArray()); md.update(ownerPassword.getBytes()); md.update(userPassword.getBytes()); md.update(document.toString().getBytes()); byte[] id = md.digest(this.toString().getBytes()); COSString idString = new COSString(); idString.append(id); idArray.add(idString); idArray.add(idString); document.setDocumentID(idArray); } catch (NoSuchAlgorithmException e) { throw new CryptographyException(e); } } COSString id = (COSString) idArray.getObject(0); encryption = new PDFEncryption(); byte[] o = encryption.computeOwnerPassword(ownerPassword.getBytes("ISO-8859-1"), userPassword.getBytes("ISO-8859-1"), revision, length); byte[] u = encryption.computeUserPassword(userPassword.getBytes("ISO-8859-1"), o, permissionInt, id.getBytes(), revision, length); encryptionKey = encryption.computeEncryptedKey(userPassword.getBytes("ISO-8859-1"), o, permissionInt, id.getBytes(), revision, length); encParameters.setOwnerKey(o); encParameters.setUserKey(u); document.setEncryptionDictionary(encParameters.getCOSDictionary()); }
11
Code Sample 1: public int update(BusinessObject o) throws DAOException { int update = 0; Item item = (Item) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("UPDATE_ITEM")); pst.setString(1, item.getDescription()); pst.setDouble(2, item.getUnit_price()); pst.setInt(3, item.getQuantity()); pst.setDouble(4, item.getVat()); pst.setInt(5, item.getIdProject()); if (item.getIdBill() == 0) pst.setNull(6, java.sql.Types.INTEGER); else pst.setInt(6, item.getIdBill()); pst.setInt(7, item.getIdCurrency()); pst.setInt(8, item.getId()); System.out.println("item => " + item.getDescription() + " " + item.getUnit_price() + " " + item.getQuantity() + " " + item.getVat() + " " + item.getIdProject() + " " + item.getIdBill() + " " + item.getIdCurrency() + " " + item.getId()); update = pst.executeUpdate(); if (update <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (update > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return update; } Code Sample 2: @Override public void excluir(Disciplina t) throws Exception { PreparedStatement stmt = null; String sql = "DELETE from disciplina where id_disciplina = ?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, t.getIdDisciplina()); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } finally { try { stmt.close(); conexao.close(); } catch (SQLException e) { throw e; } } }
00
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static String httpGet(URL url) throws Exception { URLConnection connection = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuffer content = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { content.append(line); } return content.toString(); }
00
Code Sample 1: private void loadImage(URL url) { ImageData imageData; Image artworkImage = null; InputStream artworkStream = null; try { artworkStream = new BufferedInputStream(url.openStream()); imageData = new ImageLoader().load(artworkStream)[0]; Image tmpImage = new Image(getDisplay(), imageData); artworkImage = ImageUtilities.scaleImageTo(tmpImage, 128, 128); tmpImage.dispose(); } catch (Exception e) { } finally { if (artworkStream != null) { try { artworkStream.close(); } catch (IOException e) { e.printStackTrace(); } } } loadImage(artworkImage, url); } Code Sample 2: public static String exchangeForSessionToken(String protocol, String domain, String onetimeUseToken, PrivateKey key) throws IOException, GeneralSecurityException, AuthenticationException { String sessionUrl = getSessionTokenUrl(protocol, domain); URL url = new URL(sessionUrl); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); String header = formAuthorizationHeader(onetimeUseToken, key, url, "GET"); httpConn.setRequestProperty("Authorization", header); if (httpConn.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new AuthenticationException(httpConn.getResponseCode() + ": " + httpConn.getResponseMessage()); } String body = IOUtils.toString(httpConn.getInputStream()); Map parsedTokens = StringUtils.string2Map(body, "\n", "=", true); parsedTokens = StringUtils.lowercaseKeys(parsedTokens); return (String) parsedTokens.get("token"); }
11
Code Sample 1: private void unpackBundle() throws IOException { File useJarPath = null; if (DownloadManager.isWindowsVista()) { useJarPath = lowJarPath; File jarDir = useJarPath.getParentFile(); if (jarDir != null) { jarDir.mkdirs(); } } else { useJarPath = jarPath; } DownloadManager.log("Unpacking " + this + " to " + useJarPath); InputStream rawStream = new FileInputStream(localPath); JarInputStream in = new JarInputStream(rawStream) { public void close() throws IOException { } }; try { File jarTmp = null; JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { String entryName = entry.getName(); if (entryName.equals("classes.pack")) { File packTmp = new File(useJarPath + ".pack"); packTmp.getParentFile().mkdirs(); DownloadManager.log("Writing temporary .pack file " + packTmp); OutputStream tmpOut = new FileOutputStream(packTmp); try { DownloadManager.send(in, tmpOut); } finally { tmpOut.close(); } jarTmp = new File(useJarPath + ".tmp"); DownloadManager.log("Writing temporary .jar file " + jarTmp); unpack(packTmp, jarTmp); packTmp.delete(); } else if (!entryName.startsWith("META-INF")) { File dest; if (DownloadManager.isWindowsVista()) { dest = new File(lowJavaPath, entryName.replace('/', File.separatorChar)); } else { dest = new File(DownloadManager.JAVA_HOME, entryName.replace('/', File.separatorChar)); } if (entryName.equals(BUNDLE_JAR_ENTRY_NAME)) dest = useJarPath; File destTmp = new File(dest + ".tmp"); boolean exists = dest.exists(); if (!exists) { DownloadManager.log(dest + ".mkdirs()"); dest.getParentFile().mkdirs(); } try { DownloadManager.log("Using temporary file " + destTmp); FileOutputStream out = new FileOutputStream(destTmp); try { byte[] buffer = new byte[2048]; int c; while ((c = in.read(buffer)) > 0) out.write(buffer, 0, c); } finally { out.close(); } if (exists) dest.delete(); DownloadManager.log("Renaming from " + destTmp + " to " + dest); if (!destTmp.renameTo(dest)) { throw new IOException("unable to rename " + destTmp + " to " + dest); } } catch (IOException e) { if (!exists) throw e; } } } if (jarTmp != null) { if (useJarPath.exists()) jarTmp.delete(); else if (!jarTmp.renameTo(useJarPath)) { throw new IOException("unable to rename " + jarTmp + " to " + useJarPath); } } if (DownloadManager.isWindowsVista()) { DownloadManager.log("Using broker to move " + name); if (!DownloadManager.moveDirWithBroker(DownloadManager.getKernelJREDir() + name)) { throw new IOException("unable to create " + name); } DownloadManager.log("Broker finished " + name); } DownloadManager.log("Finished unpacking " + this); } finally { rawStream.close(); } if (deleteOnInstall) { localPath.delete(); } } Code Sample 2: private static void copyFile(String from, String to) throws IOException { FileReader in = new FileReader(from); FileWriter out = new FileWriter(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
00
Code Sample 1: public void startElement(String uri, String tag, String qName, org.xml.sax.Attributes attributes) throws SAXException { wabclient.Attributes prop = new wabclient.Attributes(attributes); try { if (tag.equals("window")) { if (prop == null) { System.err.println("window without properties"); return; } int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); Color bgcolor = prop.getValue("bgcolor", Color.white); String caption = prop.getValue("caption", ""); layout = prop.getValue("layout", 0); boolean statusbar = prop.getValue("statusbar", false); if (sheet.opentype == WABSheet.LAYERED) { Point pos = frame.getNextMDIPos(); sheet.setBounds(pos.x, pos.y, 400, 200); sheet.setNormalBounds(new Rectangle(pos.x, pos.y, 400, 200)); } else { sheet.setBounds(x, y, width, height); sheet.setNormalBounds(new Rectangle(x, y, width, height)); } if (sheet.opentype == WABSheet.MAXIMIZED) sheet.setMaximum(true); else sheet.setMaximum(false); sheet.setTitle(caption); frame.addSheetToMenu(caption); sheet.setBackground(bgcolor); if (layout == 1) sheet.getContentPane().setLayout(new FlowLayout()); else if (layout == 2) sheet.getContentPane().setLayout(new BorderLayout()); else sheet.getContentPane().setLayout(null); } else if (tag.equals("menu")) { if (prop == null) { System.err.println("menu without properties"); return; } String id = prop.getValue("id", ""); String label = prop.getValue("label", ""); if ((id != null && id.equals("WINDOW_MENU") || label.equalsIgnoreCase("window"))) { windowMenu = new JMenu(); menu = windowMenu; sheet.setWindowMenu(menu); } else { menu = new JMenu(); } menu.setText(label); sheet.menubar.add(menu); } else if (tag.equals("menuitem")) { if (prop == null) { System.err.println("menuitem without properties"); return; } JMenuItem item; String action = prop.getValue("action", ""); String label = prop.getValue("label", ""); boolean visible = prop.getValue("visible", true); String icon = prop.getValue("icon", ""); if (action.equals("WINDOW_OVERLAPPED")) { item = windowMenuOverlapped = new JMenuItem(); item.setActionCommand("10001"); item.addActionListener(frame); } else if (action.equals("WINDOW_TILE_HORIZONTALLY")) { item = windowMenuTile = new JMenuItem(); item.setActionCommand("10002"); item.addActionListener(frame); } else if (action.equals("WINDOW_TILE_VERTICALLY")) { item = windowMenuArrange = new JMenuItem(); item.setActionCommand("10003"); item.addActionListener(frame); } else { item = new JMenuItem(); item.setActionCommand(action); item.addActionListener((WABClient) global); } item.setText(label); if (!visible) menu.setVisible(false); menu.add(item); if (frame.getToolBar() != null) { if (icon.length() > 0) { try { ImageIcon img = new ImageIcon(new URL(icon)); BufferedImage image = new BufferedImage(25, 25, BufferedImage.TYPE_4BYTE_ABGR); Graphics g = image.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, 25, 25); g.drawImage(img.getImage(), 4, 4, 16, 16, (ImageObserver) null); BufferedImage pressed = new BufferedImage(25, 25, BufferedImage.TYPE_4BYTE_ABGR); g = pressed.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, 25, 25); g.drawImage(img.getImage(), 5, 5, 16, 16, (ImageObserver) null); g.setColor(new Color(132, 132, 132)); g.drawLine(0, 0, 24, 0); g.drawLine(0, 0, 0, 24); g.setColor(new Color(255, 255, 255)); g.drawLine(24, 24, 24, 0); g.drawLine(24, 24, 0, 24); BufferedImage over = new BufferedImage(25, 25, BufferedImage.TYPE_4BYTE_ABGR); g = over.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, 25, 25); g.drawImage(img.getImage(), 4, 4, 16, 16, (ImageObserver) null); g.setColor(new Color(255, 255, 255)); g.drawLine(0, 0, 24, 0); g.drawLine(0, 0, 0, 24); g.setColor(new Color(132, 132, 132)); g.drawLine(24, 24, 24, 0); g.drawLine(24, 24, 0, 24); JButton b = new JButton(new ImageIcon(image)); b.setRolloverEnabled(true); b.setPressedIcon(new ImageIcon(pressed)); b.setRolloverIcon(new ImageIcon(over)); b.setToolTipText(label); b.setActionCommand(action); b.setFocusPainted(false); b.setBorderPainted(false); b.setContentAreaFilled(false); b.setMargin(new Insets(0, 0, 0, 0)); b.addActionListener(sheet); sheet.toolbar.add(b); } catch (Exception e) { } } } } else if (tag.equals("separator")) { menu.addSeparator(); } else if (tag.equals("choice")) { if (prop == null) { System.err.println("choice without properties"); return; } combo = new JComboBox(); list = null; int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); Object constraints = prop.getValue("constraints"); boolean editable = prop.getValue("editable", false); boolean visible = prop.getValue("visible", true); boolean enabled = prop.getValue("enabled", true); combo_text = prop.getValue("text", ""); combo.setBounds(x, y, width, height); combo.setName((String) id); if (editable) { combo.setEditable(editable); combo.setSelectedItem(combo_text); } if (!visible) combo.setVisible(false); if (!enabled) combo.setEnabled(false); if (layout == 0) sheet.getContentPane().add(combo); else sheet.getContentPane().add(combo, constraints); } else if (tag.equals("list")) { if (prop == null) { System.err.println("list without properties"); return; } list = new JList(); combo = null; listdata = new Vector(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); Object constraints = prop.getValue("constraints"); list.setName((String) id); list.setListData(listdata); JScrollPane sp = new JScrollPane(list); sp.setBounds(x, y, width, height); if (layout == 0) sheet.getContentPane().add(sp); else sheet.getContentPane().add(sp, constraints); } else if (tag.equals("option")) { if (prop == null) { System.err.println("choice.option without properties"); return; } String value = prop.getValue("value", ""); String text = prop.getValue("text", ""); if (list != null) listdata.addElement(new ComboOption(text, value)); if (combo != null) { ComboOption co = new ComboOption(text, value); combo.addItem(co); if (combo_text.equals(text.trim())) combo.setSelectedItem(co); } } else if (tag.equals("label")) { if (prop == null) { System.err.println("label without properties"); return; } JLabel label = new JLabel(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String text = prop.getValue("text", ""); Object constraints = prop.getValue("constraints"); boolean visible = prop.getValue("visible", true); label.setBounds(x, y, width, height); label.setText(text); if (!visible) label.setVisible(false); if (layout == 0) sheet.getContentPane().add(label); else sheet.getContentPane().add(label, constraints); } else if (tag.equals("button")) { if (prop == null) { System.err.println("button without properties"); return; } JButton btn = new JButton(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); String text = prop.getValue("text", ""); String onmouseup = prop.getValue("onmouseup", ""); Object constraints = prop.getValue("constraints"); btn.setBounds(x, y, width, height); btn.setText(text); btn.addActionListener(sheet); btn.setActionCommand(onmouseup); if (layout == 0) sheet.getContentPane().add(btn); else sheet.getContentPane().add(btn, constraints); } else if (tag.equals("radiobutton")) { if (prop == null) { System.err.println("radiobutton without properties"); return; } JRadioButton rb = new JRadioButton(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); String text = prop.getValue("text", ""); Object constraints = prop.getValue("constraints"); String checked = prop.getValue("checked", "false"); rb.setBounds(x, y, width, height); rb.setText(text); rb.setName((String) id); rb.addActionListener(sheet); rb.setSelected(checked.equalsIgnoreCase("true")); if (layout == 0) sheet.getContentPane().add(rb); else sheet.getContentPane().add(rb, constraints); } else if (tag.equals("checkbox")) { if (prop == null) { System.err.println("checkbox without properties"); return; } JCheckBox cb = new JCheckBox(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); String text = prop.getValue("text", ""); String onmouseup = prop.getValue("onmouseup", ""); Object constraints = prop.getValue("constraints"); String checked = prop.getValue("checked", "false"); cb.setBounds(x, y, width, height); cb.setText(text); cb.setName((String) id); cb.setSelected(checked.equalsIgnoreCase("true")); if (layout == 0) sheet.getContentPane().add(cb); else sheet.getContentPane().add(cb, constraints); } else if (tag.equals("image")) { if (prop == null) { System.err.println("image without properties"); return; } JLabel label = new JLabel(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String src = prop.getValue("src", ""); Object constraints = prop.getValue("constraints"); label.setIcon(new ImageIcon(new URL(src))); label.setBounds(x, y, width, height); if (layout == 0) sheet.getContentPane().add(label); else sheet.getContentPane().add(label, constraints); } else if (tag.equals("singlelineedit")) { if (prop == null) { System.err.println("singlelineedit without properties"); return; } String pwd = prop.getValue("password", ""); JTextField sle; if (pwd.equalsIgnoreCase("true")) sle = new JPasswordField(); else sle = new JTextField(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); Object id = prop.getValue("id"); String text = prop.getValue("text", ""); Object constraints = prop.getValue("constraints"); sle.setBounds(x, y, width, height); sle.setText(text); sle.setName((String) id); if (layout == 0) sheet.getContentPane().add(sle); else sheet.getContentPane().add(sle, constraints); } else if (tag.equals("treeview")) { if (prop == null) { System.err.println("treeview without properties"); return; } treeview_root = new DefaultMutableTreeNode("root"); treeview = new JTree(treeview_root); Object constraints = prop.getValue("constraints"); sheet.getContentPane().add(new JScrollPane(treeview), constraints); } else if (tag.equals("treeitem")) { if (prop == null) { System.err.println("treeview.treeitem without properties"); return; } String text = prop.getValue("text", ""); String value = prop.getValue("value", ""); DefaultMutableTreeNode node = new DefaultMutableTreeNode(text); treeview_root.add(node); } else if (tag.equals("table")) { if (prop == null) { System.err.println("table without properties"); return; } String id = prop.getValue("id", ""); table = new JTable(); model = new DefaultTableModel() { public boolean isCellEditable(int row, int col) { return false; } }; table.setModel(model); table.setName((String) id); Object constraints = prop.getValue("constraints"); sheet.getContentPane().add(new JScrollPane(table), constraints); rowNumber = 0; columnNumber = 0; headerWidths = new Vector(); } else if (tag.equals("header")) { if (prop == null) { System.err.println("table.header without properties"); return; } String text = prop.getValue("text", ""); int width = prop.getValue("width", 0); headerWidths.addElement(new Integer(width)); model.addColumn(text); } else if (tag.equals("row")) { rowNumber++; columnNumber = 0; model.setRowCount(rowNumber); } else if (tag.equals("column")) { columnNumber++; if (prop == null) { System.err.println("table.column without properties"); return; } String value = prop.getValue("value", ""); model.setValueAt(value, rowNumber - 1, columnNumber - 1); } else if (tag.equals("script")) { sheet.beginScript(); String url = prop.getValue("src"); if (url.length() > 0) { try { BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String buffer; while (true) { buffer = r.readLine(); if (buffer == null) break; sheet.script += buffer + "\n"; } r.close(); sheet.endScript(); } catch (IOException ioe) { System.err.println("[IOError] " + ioe.getMessage()); System.exit(0); } } } else System.err.println("[sheet] unparsed tag: " + tag); } catch (Exception e) { e.printStackTrace(System.err); } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: @LargeTest public void testThreadCheck() throws Exception { ContentResolver resolver = getContext().getContentResolver(); GoogleHttpClient client = new GoogleHttpClient(resolver, "Test", false); try { HttpGet method = new HttpGet(mServerUrl); AndroidHttpClient.setThreadBlocked(true); try { client.execute(method); fail("\"thread forbids HTTP requests\" exception expected"); } catch (RuntimeException e) { if (!e.toString().contains("forbids HTTP requests")) throw e; } finally { AndroidHttpClient.setThreadBlocked(false); } HttpResponse response = client.execute(method); assertEquals("/", EntityUtils.toString(response.getEntity())); } finally { client.close(); } } Code Sample 2: public void modify(String strName, String strNewPass) { String str = "update jb_user set V_PASSWORD =? where V_USERNAME =?"; Connection con = null; PreparedStatement pstmt = null; try { con = DbForumFactory.getConnection(); con.setAutoCommit(false); pstmt = con.prepareStatement(str); pstmt.setString(1, SecurityUtil.md5ByHex(strNewPass)); pstmt.setString(2, strName); pstmt.executeUpdate(); con.commit(); } catch (Exception e) { e.printStackTrace(); try { con.rollback(); } catch (SQLException e1) { } } finally { try { DbForumFactory.closeDB(null, pstmt, null, con); } catch (Exception e) { } } }
00
Code Sample 1: public String getScenarioData(String urlForSalesData) throws IOException, Exception { InputStream inputStream = null; BufferedReader bufferedReader = null; DataInputStream input = null; StringBuffer sBuf = new StringBuffer(); Proxy proxy; if (httpWebProxyServer != null && Integer.toString(httpWebProxyPort) != null) { SocketAddress address = new InetSocketAddress(httpWebProxyServer, httpWebProxyPort); proxy = new Proxy(Proxy.Type.HTTP, address); } else { proxy = null; } proxy = null; URL url; try { url = new URL(urlForSalesData); HttpURLConnection httpUrlConnection; if (proxy != null) httpUrlConnection = (HttpURLConnection) url.openConnection(proxy); else httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setDoInput(true); httpUrlConnection.setRequestMethod("GET"); String name = rb.getString("WRAP_NAME"); String password = rb.getString("WRAP_PASSWORD"); Credentials simpleAuthCrentials = new Credentials(TOKEN_TYPE.SimpleApiAuthToken, name, password); ACSTokenProvider tokenProvider = new ACSTokenProvider(httpWebProxyServer, httpWebProxyPort, simpleAuthCrentials); String requestUriStr1 = "https://" + solutionName + "." + acmHostName + "/" + serviceName; String appliesTo1 = rb.getString("SIMPLEAPI_APPLIES_TO"); String token = tokenProvider.getACSToken(requestUriStr1, appliesTo1); httpUrlConnection.addRequestProperty("token", "WRAPv0.9 " + token); httpUrlConnection.addRequestProperty("solutionName", solutionName); httpUrlConnection.connect(); if (httpUrlConnection.getResponseCode() == HttpServletResponse.SC_UNAUTHORIZED) { List<TestSalesOrderService> salesOrderServiceBean = new ArrayList<TestSalesOrderService>(); TestSalesOrderService response = new TestSalesOrderService(); response.setResponseCode(HttpServletResponse.SC_UNAUTHORIZED); response.setResponseMessage(httpUrlConnection.getResponseMessage()); salesOrderServiceBean.add(response); } inputStream = httpUrlConnection.getInputStream(); input = new DataInputStream(inputStream); bufferedReader = new BufferedReader(new InputStreamReader(input)); String str; while (null != ((str = bufferedReader.readLine()))) { sBuf.append(str); } String responseString = sBuf.toString(); return responseString; } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } } Code Sample 2: private void renameTo(File from, File to) { if (!from.exists()) return; if (to.exists()) to.delete(); boolean worked = false; try { worked = from.renameTo(to); } catch (Exception e) { database.logError(this, "" + e, null); } if (!worked) { database.logWarning(this, "Could not rename GEDCOM to " + to.getAbsolutePath(), null); try { to.delete(); final FileReader in = new FileReader(from); final FileWriter out = new FileWriter(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); from.delete(); } catch (Exception e) { database.logError(this, "" + e, null); } } }
11
Code Sample 1: public void copyFile(String source, String destination, String description, boolean recursive) throws Exception { File sourceFile = new File(source); File destinationFile = new File(destination); if (!sourceFile.exists()) { throw new Exception("source file (" + source + ") does not exist!"); } if (!sourceFile.isFile()) { throw new Exception("source file (" + source + ") is not a file!"); } if (!sourceFile.canRead()) { throw new Exception("source file (" + source + ") is not readable!"); } if (destinationFile.exists()) { m_out.print(" - " + destination + " exists, removing... "); if (destinationFile.delete()) { m_out.println("REMOVED"); } else { m_out.println("FAILED"); throw new Exception("unable to delete existing file: " + sourceFile); } } m_out.print(" - copying " + source + " to " + destination + "... "); if (!destinationFile.getParentFile().exists()) { if (!destinationFile.getParentFile().mkdirs()) { throw new Exception("unable to create directory: " + destinationFile.getParent()); } } if (!destinationFile.createNewFile()) { throw new Exception("unable to create file: " + destinationFile); } FileChannel from = null; FileChannel to = null; try { from = new FileInputStream(sourceFile).getChannel(); to = new FileOutputStream(destinationFile).getChannel(); to.transferFrom(from, 0, from.size()); } catch (FileNotFoundException e) { throw new Exception("unable to copy " + sourceFile + " to " + destinationFile, e); } finally { if (from != null) { from.close(); } if (to != null) { to.close(); } } m_out.println("DONE"); } Code Sample 2: private static Collection<String> createTopLevelFiles(Configuration configuration, Collections collections, Sets sets) throws FlickrException, SAXException, IOException, JDOMException, TransformerException { Collection<String> createdFiles = new HashSet<String>(); File toplevelXmlFilename = getToplevelXmlFilename(configuration.photosBaseDirectory); Logger.getLogger(FlickrDownload.class).info("Creating XML file " + toplevelXmlFilename.getAbsolutePath()); MediaIndexer indexer = new XmlMediaIndexer(configuration); Element toplevel = new Element("flickr").addContent(XmlUtils.createApplicationXml()).addContent(XmlUtils.createUserXml(configuration)).addContent(collections.createTopLevelXml()).addContent(sets.createTopLevelXml()).addContent(new Stats(sets).createStatsXml(indexer)); createdFiles.addAll(indexer.writeIndex()); XmlUtils.outputXmlFile(toplevelXmlFilename, toplevel); createdFiles.add(toplevelXmlFilename.getName()); Logger.getLogger(FlickrDownload.class).info("Copying support files and performing XSLT transformations"); IOUtils.copyToFileAndCloseStreams(XmlUtils.class.getResourceAsStream("xslt/" + PHOTOS_CSS_FILENAME), new File(configuration.photosBaseDirectory, PHOTOS_CSS_FILENAME)); createdFiles.add(PHOTOS_CSS_FILENAME); IOUtils.copyToFileAndCloseStreams(XmlUtils.class.getResourceAsStream("xslt/" + PLAY_ICON_FILENAME), new File(configuration.photosBaseDirectory, PLAY_ICON_FILENAME)); createdFiles.add(PLAY_ICON_FILENAME); XmlUtils.performXsltTransformation(configuration, "all_sets.xsl", toplevelXmlFilename, new File(configuration.photosBaseDirectory, ALL_SETS_HTML_FILENAME)); createdFiles.add(ALL_SETS_HTML_FILENAME); XmlUtils.performXsltTransformation(configuration, "all_collections.xsl", toplevelXmlFilename, new File(configuration.photosBaseDirectory, ALL_COLLECTIONS_HTML_FILENAME)); createdFiles.add(ALL_COLLECTIONS_HTML_FILENAME); createdFiles.add(Collections.COLLECTIONS_ICON_DIRECTORY); XmlUtils.performXsltTransformation(configuration, "stats.xsl", toplevelXmlFilename, new File(configuration.photosBaseDirectory, STATS_HTML_FILENAME)); createdFiles.add(STATS_HTML_FILENAME); sets.performXsltTransformation(); for (AbstractSet set : sets.getSets()) { createdFiles.add(set.getSetId()); } return createdFiles; }
00
Code Sample 1: public String generateKey(String className, String methodName, String text, String meaning) { if (text == null) { return null; } MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error initializing MD5", e); } try { md5.update(text.getBytes("UTF-8")); if (meaning != null) { md5.update(meaning.getBytes("UTF-8")); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 unsupported", e); } return StringUtils.toHexString(md5.digest()); } Code Sample 2: private String fetch(String urlstring) { String content = ""; try { URL url = new URL(urlstring); InputStream is = url.openStream(); BufferedReader d = new BufferedReader(new InputStreamReader(is)); String s; while (null != (s = d.readLine())) { content = content + s + "\n"; } is.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return content; }
00
Code Sample 1: private String getData(String requestUrl) throws AuthenticationException, IOException { URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); String header; try { header = oauthAuthenticator.getHttpAuthorizationHeader(url.toString(), "GET", profile.getOAuthToken(), profile.getOAuthTokenSecret()); } catch (OAuthException e) { throw new AuthenticationException(e); } conn.setRequestProperty("Authorization", header); if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new AuthenticationException(); } InputStreamReader reader = new InputStreamReader(conn.getInputStream()); char[] buffer = new char[1024]; int bytesRead = 0; StringBuilder data = new StringBuilder(); while ((bytesRead = reader.read(buffer)) != -1) { data.append(buffer, 0, bytesRead); } reader.close(); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException(conn.getResponseCode() + " " + conn.getResponseMessage() + "\n" + data); } return data.toString(); } Code Sample 2: private void processHelpFile() { InputStream in = null; if (line.hasOption("helpfile")) { OutputStream out = null; try { String filename = line.getOptionValue("helpfile"); in = new FileInputStream(filename); filename = filename.replace('\\', '/'); filename = filename.substring(filename.lastIndexOf('/') + 1); File outFile = new File(outputDir, filename); if (LOG.isInfoEnabled()) { LOG.info("Processing generated file " + outFile.getAbsolutePath()); } out = new FileOutputStream(outFile); baseProperties.setProperty("helpfile", filename); IOUtils.copy(in, out); } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } return; } Properties props = new Properties(baseProperties); ClassLoader cl = this.getClass().getClassLoader(); Document doc = null; try { in = cl.getResourceAsStream(RESOURCE_PKG + "/help-doc.xml"); doc = XmlUtils.parse(in); } catch (XmlException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } transformResource(doc, "help-doc.xsl", props, "help-doc.html"); baseProperties.setProperty("helpfile", "help-doc.html"); }
11
Code Sample 1: public int process(ProcessorContext context) throws InterruptedException, ProcessorException { logger.info("JAISaveTask:process"); final RenderedOp im = (RenderedOp) context.get("RenderedOp"); final String path = "s3://s3.amazonaws.com/rssfetch/" + (new Guid()); final PNGEncodeParam.RGB encPar = new PNGEncodeParam.RGB(); encPar.setTransparentRGB(new int[] { 0, 0, 0 }); File tmpFile = null; try { tmpFile = File.createTempFile("thmb", ".png"); OutputStream out = new FileOutputStream(tmpFile); final ParameterBlock pb = (new ParameterBlock()).addSource(im).add(out).add("png").add(encPar); JAI.create("encode", pb, null); out.flush(); out.close(); FileInputStream in = new FileInputStream(tmpFile); final XFile xfile = new XFile(path); final XFileOutputStream xout = new XFileOutputStream(xfile); final com.luzan.common.nfs.s3.XFileExtensionAccessor xfa = ((com.luzan.common.nfs.s3.XFileExtensionAccessor) xfile.getExtensionAccessor()); if (xfa != null) { xfa.setMimeType("image/png"); xfa.setContentLength(tmpFile.length()); } IOUtils.copy(in, xout); xout.flush(); xout.close(); in.close(); context.put("outputPath", path); } catch (IOException e) { logger.error(e); throw new ProcessorException(e); } catch (Throwable e) { logger.error(e); throw new ProcessorException(e); } finally { if (tmpFile != null && tmpFile.exists()) { tmpFile.delete(); } } return TaskState.STATE_MO_START + TaskState.STATE_ENCODE; } Code Sample 2: private void internalTransferComplete(File tmpfile) { System.out.println("transferComplete : " + tmpfile); try { File old = new File(m_destination.toString() + ".old"); old.delete(); File current = m_destination; current.renameTo(old); FileInputStream fis = new FileInputStream(tmpfile); FileOutputStream fos = new FileOutputStream(m_destination); BufferedInputStream in = new BufferedInputStream(fis); BufferedOutputStream out = new BufferedOutputStream(fos); for (int read = in.read(); read != -1; read = in.read()) { out.write(read); } out.flush(); in.close(); out.close(); fis.close(); fos.close(); tmpfile.delete(); setVisible(false); transferComplete(); } catch (Exception exc) { exc.printStackTrace(); JOptionPane.showMessageDialog(this, "An error occurred while downloading!", "ACLocator Error", JOptionPane.ERROR_MESSAGE); } }
11
Code Sample 1: protected static void writeFileToStream(FileWrapper file, String filename, ZipOutputStream zipStream) throws CausedIOException, IOException { InputStream in; try { in = file.getInputStream(); } catch (Exception e) { throw new CausedIOException("Could not obtain InputStream for " + filename, e); } try { IOUtils.copy(in, zipStream); } finally { IOUtils.closeQuietly(in); } } 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: private GmailContact convertContactToGmailContact(Contact contact) throws GmailManagerException { boolean homePhone = false, homePhone2 = false, homeFax = false, homeMobile = false, homePager = false; boolean businessPhone = false, businessPhone2 = false, businessFax = false, businessMobile = false, businessPager = false; boolean otherPhone = false, otherFax = false; if (log.isTraceEnabled()) log.trace("Converting Foundation contact to Gmail contact: Name:" + contact.getName().getFirstName().getPropertyValueAsString()); try { GmailContact gmailContact = new GmailContact(); gmailContact.setId(contact.getUid()); Name name = contact.getName(); if (name != null) if (name.getFirstName() != null && name.getFirstName().getPropertyValueAsString() != null) { StringBuffer buffer = new StringBuffer(); buffer.append(name.getFirstName().getPropertyValueAsString()).append(" "); if (name.getMiddleName() != null && name.getMiddleName().getPropertyValueAsString() != null) buffer.append(name.getMiddleName().getPropertyValueAsString()).append(" "); if (name.getLastName() != null && name.getLastName().getPropertyValueAsString() != null) buffer.append(name.getLastName().getPropertyValueAsString()).append(" "); if (log.isDebugEnabled()) log.debug("NAME: " + buffer.toString().trim()); gmailContact.setName(buffer.toString().trim()); } if (contact.getPersonalDetail() != null) { if (contact.getPersonalDetail().getEmails() != null && contact.getPersonalDetail().getEmails().size() > 0) { if (contact.getPersonalDetail().getEmails().get(0) != null) { Email email1 = (Email) contact.getPersonalDetail().getEmails().get(0); if (email1.getPropertyValueAsString() != null && email1.getPropertyValueAsString().equals("") == false) { if (log.isDebugEnabled()) log.debug("EMAIL1: " + email1.getPropertyValueAsString()); gmailContact.setEmail(email1.getPropertyValueAsString()); } } if (contact.getPersonalDetail().getEmails().size() > 1 && contact.getPersonalDetail().getEmails().get(1) != null) { Email email2 = (Email) contact.getPersonalDetail().getEmails().get(1); if (email2.getPropertyValueAsString() != null && email2.getPropertyValueAsString().equals("") == false) { if (log.isDebugEnabled()) log.debug("EMAIL2: " + email2.getPropertyValueAsString()); gmailContact.setEmail2(email2.getPropertyValueAsString()); } } } Address address = contact.getPersonalDetail().getAddress(); if (address != null) if (address.getStreet() != null) if (address.getStreet().getPropertyValueAsString() != null) { StringBuffer addressBuffer = new StringBuffer(); addressBuffer.append(address.getStreet().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getPostalCode().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getCity().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getState().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getCountry().getPropertyValueAsString()); if (log.isDebugEnabled()) log.debug("HOME_ADDRESS: " + addressBuffer.toString()); gmailContact.setHomeAddress(addressBuffer.toString()); } Address addressOther = contact.getPersonalDetail().getOtherAddress(); if (addressOther != null) if (addressOther.getStreet() != null) if (addressOther.getStreet().getPropertyValueAsString() != null) { StringBuffer addressBuffer = new StringBuffer(); addressBuffer.append(addressOther.getStreet().getPropertyValueAsString()).append(" "); addressBuffer.append(addressOther.getPostalCode().getPropertyValueAsString()).append(" "); addressBuffer.append(addressOther.getCity().getPropertyValueAsString()).append(" "); addressBuffer.append(addressOther.getState().getPropertyValueAsString()).append(" "); addressBuffer.append(addressOther.getCountry().getPropertyValueAsString()); if (log.isDebugEnabled()) log.debug("OTHER_ADDRESS: " + addressBuffer.toString()); gmailContact.setOtherAddress(addressBuffer.toString()); } if (contact.getPersonalDetail().getPhones() != null && contact.getPersonalDetail().getPhones().size() > 0) { for (int i = 0; i < contact.getPersonalDetail().getPhones().size(); i++) { Phone phone = (Phone) contact.getPersonalDetail().getPhones().get(i); if (log.isDebugEnabled()) log.debug("PERSONAL_PHONE: " + phone.getPropertyValueAsString() + " type:" + phone.getPhoneType()); if (phone.getPhoneType().equals(SIFC.HOME_TELEPHONE_NUMBER) && homePhone == false) { gmailContact.setHomePhone(phone.getPropertyValueAsString()); homePhone = true; } else if (phone.getPhoneType().equals(SIFC.HOME2_TELEPHONE_NUMBER) && homePhone2 == false) { gmailContact.setHomePhone2(phone.getPropertyValueAsString()); homePhone2 = true; } else if (phone.getPhoneType().equals(SIFC.HOME_FAX_NUMBER) && homeFax == false) { gmailContact.setHomeFax(phone.getPropertyValueAsString()); homeFax = true; } else if ((phone.getPhoneType().equals(SIFC.MOBILE_TELEPHONE_NUMBER) || phone.getPhoneType().equals(SIFC.MOBILE_HOME_TELEPHONE_NUMBER)) && homeMobile == false) { gmailContact.setMobilePhone(phone.getPropertyValueAsString()); homeMobile = true; } else if (phone.getPhoneType().equals(SIFC.PAGER_NUMBER) && homePager == false) { gmailContact.setPager(phone.getPropertyValueAsString()); homePager = true; } else if (phone.getPhoneType().equals(SIFC.OTHER_TELEPHONE_NUMBER) && otherPhone == false) { gmailContact.setOtherPhone(phone.getPropertyValueAsString()); otherPhone = true; } else if (phone.getPhoneType().equals(SIFC.OTHER_FAX_NUMBER) && otherFax == false) { gmailContact.setOtherFax(phone.getPropertyValueAsString()); otherFax = true; } else { if (log.isDebugEnabled()) log.debug("GOOGLE - Whoops - Personal Phones UNKNOWN TYPE:" + phone.getPhoneType() + " VALUE:" + phone.getPropertyValueAsString()); } } } } if (contact.getBusinessDetail() != null) { if (contact.getBusinessDetail().getEmails() != null && contact.getBusinessDetail().getEmails().size() > 0) { if (contact.getBusinessDetail().getEmails().get(0) != null) { Email email3 = (Email) contact.getBusinessDetail().getEmails().get(0); if (email3.getPropertyValueAsString() != null && email3.getPropertyValueAsString().equals("") == false) { if (log.isDebugEnabled()) log.debug("EMAIL3: " + email3.getPropertyValueAsString()); gmailContact.setEmail3(email3.getPropertyValueAsString()); } } } Address address = contact.getBusinessDetail().getAddress(); if (address != null) if (address.getStreet() != null) if (address.getStreet().getPropertyValueAsString() != null) { StringBuffer addressBuffer = new StringBuffer(); addressBuffer.append(address.getStreet().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getPostalCode().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getCity().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getState().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getCountry().getPropertyValueAsString()); if (log.isDebugEnabled()) log.debug("BUSINESS_ADDRESS: " + addressBuffer.toString()); gmailContact.setBusinessAddress(addressBuffer.toString()); } if (contact.getBusinessDetail().getPhones() != null && contact.getBusinessDetail().getPhones().size() > 0) { for (int i = 0; i < contact.getBusinessDetail().getPhones().size(); i++) { Phone phone = (Phone) contact.getBusinessDetail().getPhones().get(i); if (log.isDebugEnabled()) log.debug("BUSINESS_PHONE: " + phone.getPropertyValueAsString() + " type:" + phone.getPhoneType()); if (phone.getPhoneType().equals(SIFC.BUSINESS_TELEPHONE_NUMBER) && businessPhone == false) { gmailContact.setBusinessPhone(phone.getPropertyValueAsString()); businessPhone = true; } else if (phone.getPhoneType().equals(SIFC.BUSINESS2_TELEPHONE_NUMBER) && businessPhone2 == false) { gmailContact.setBusinessPhone2(phone.getPropertyValueAsString()); businessPhone2 = true; } else if (phone.getPhoneType().equals(SIFC.BUSINESS_FAX_NUMBER) && businessFax == false) { gmailContact.setBusinessFax(phone.getPropertyValueAsString()); businessFax = true; } else if (phone.getPhoneType().equals(SIFC.MOBILE_BUSINESS_TELEPHONE_NUMBER) && homeMobile == false && businessMobile == false) { gmailContact.setMobilePhone(phone.getPropertyValueAsString()); businessMobile = true; } else if (phone.getPhoneType().equals(SIFC.PAGER_NUMBER) && homePager == false && businessPager == false) { gmailContact.setPager(phone.getPropertyValueAsString()); businessPager = true; } else { if (log.isDebugEnabled()) log.debug("GOOGLE - Whoops - Business Phones UNKNOWN TYPE:" + phone.getPhoneType() + " VALUE:" + phone.getPropertyValueAsString()); } } } if (contact.getBusinessDetail().getCompany() != null) if (contact.getBusinessDetail().getCompany().getPropertyValueAsString() != null) { if (log.isDebugEnabled()) log.debug("COMPANY: " + contact.getBusinessDetail().getCompany().getPropertyValueAsString()); gmailContact.setCompany(contact.getBusinessDetail().getCompany().getPropertyValueAsString()); } if (contact.getBusinessDetail().getTitles() != null && contact.getBusinessDetail().getTitles().size() > 0) { if (contact.getBusinessDetail().getTitles().get(0) != null) { Title title = (Title) contact.getBusinessDetail().getTitles().get(0); if (log.isDebugEnabled()) log.debug("TITLE: " + title.getPropertyValueAsString()); gmailContact.setJobTitle(title.getPropertyValueAsString()); } } } if (contact.getNotes() != null && contact.getNotes().size() > 0) { if (contact.getNotes().get(0) != null) { Note notes = (Note) contact.getNotes().get(0); if (notes.getPropertyValueAsString() != null && notes.getPropertyValueAsString().equals("") == false) { if (log.isDebugEnabled()) log.debug("NOTES: " + notes.getPropertyValueAsString()); gmailContact.setNotes(notes.getPropertyValueAsString()); } } } MessageDigest m = MessageDigest.getInstance("MD5"); m.update(contact.toString().getBytes()); gmailContact.setMd5Hash(new BigInteger(m.digest()).toString()); return gmailContact; } catch (Exception e) { throw new GmailManagerException("GOOGLE Gmail - convertContactToGmailContact error: " + e.getMessage()); } } Code Sample 2: public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel source = null; FileChannel destination = null; try { source = (inStream = new FileInputStream(sourceFile)).getChannel(); destination = (outStream = new FileOutputStream(destFile)).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { closeIO(source); closeIO(inStream); closeIO(destination); closeIO(outStream); } }