label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
11
|
Code Sample 1:
private static void recurseFiles(File root, File file, TarArchiveOutputStream taos, boolean absolute) throws IOException { if (file.isDirectory()) { File[] files = file.listFiles(); for (File file2 : files) { recurseFiles(root, file2, taos, absolute); } } else if ((!file.getName().endsWith(".tar")) && (!file.getName().endsWith(".TAR"))) { String filename = null; if (absolute) { filename = file.getAbsolutePath().substring(root.getAbsolutePath().length()); } else { filename = file.getName(); } TarArchiveEntry tae = new TarArchiveEntry(filename); tae.setSize(file.length()); taos.putArchiveEntry(tae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, taos); taos.closeArchiveEntry(); } }
Code Sample 2:
public static void copyFile(String target, String source) { try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { ExceptionHelper.showErrorDialog(e); } }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private void copyFile(File from, File to) throws IOException { FileUtils.ensureParentDirectoryExists(to); byte[] buffer = new byte[1024]; int read; FileInputStream is = new FileInputStream(from); FileOutputStream os = new FileOutputStream(to); while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } is.close(); os.close(); }
|
11
|
Code Sample 1:
private byte[] getMD5(String string) throws IMException { byte[] buffer = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(string.getBytes("utf-8")); buffer = md.digest(); buffer = getHexString(buffer); } catch (NoSuchAlgorithmException e) { throw new IMException(e); } catch (UnsupportedEncodingException ue) { throw new IMException(ue); } return buffer; }
Code Sample 2:
public static String md5(String word) { MessageDigest alg = null; try { alg = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ServletUtils.class.getName()).log(Level.SEVERE, null, ex); } alg.reset(); alg.update(word.getBytes()); byte[] digest = alg.digest(); StringBuilder hashedWord = new StringBuilder(); String hx; for (int i = 0; i < digest.length; i++) { hx = Integer.toHexString(0xFF & digest[i]); if (hx.length() == 1) { hx = "0" + hx; } hashedWord.append(hx); } return hashedWord.toString(); }
|
11
|
Code Sample 1:
public static void decompressGZIP(File gzip, File to, long skip) throws IOException { GZIPInputStream gis = null; BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(to)); FileInputStream fis = new FileInputStream(gzip); fis.skip(skip); gis = new GZIPInputStream(fis); final byte[] buffer = new byte[IO_BUFFER]; int read = -1; while ((read = gis.read(buffer)) != -1) { bos.write(buffer, 0, read); } } finally { try { gis.close(); } catch (Exception nope) { } try { bos.flush(); } catch (Exception nope) { } try { bos.close(); } catch (Exception nope) { } } }
Code Sample 2:
public void handleEvent(Event event) { if (fileDialog == null) { fileDialog = new FileDialog(getShell(), SWT.OPEN); fileDialog.setText("Open device profile file..."); fileDialog.setFilterNames(new String[] { "Device profile (*.jar)" }); fileDialog.setFilterExtensions(new String[] { "*.jar" }); } fileDialog.open(); if (fileDialog.getFileName() != null) { File file; String manifestDeviceName = null; URL[] urls = new URL[1]; ArrayList descriptorEntries = new ArrayList(); try { file = new File(fileDialog.getFilterPath(), fileDialog.getFileName()); JarFile jar = new JarFile(file); Manifest manifest = jar.getManifest(); if (manifest != null) { Attributes attrs = manifest.getMainAttributes(); manifestDeviceName = attrs.getValue("Device-Name"); } for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorEntries.add(entry); } } jar.close(); urls[0] = file.toURL(); } catch (IOException ex) { Message.error("Error reading file: " + fileDialog.getFileName() + ", " + Message.getCauseMessage(ex), ex); return; } if (descriptorEntries.size() == 0) { Message.error("Cannot find any device profile in file: " + fileDialog.getFileName()); return; } if (descriptorEntries.size() > 1) { manifestDeviceName = null; } ClassLoader classLoader = Common.createExtensionsClassLoader(urls); HashMap devices = new HashMap(); for (Iterator it = descriptorEntries.iterator(); it.hasNext(); ) { JarEntry entry = (JarEntry) it.next(); try { devices.put(entry.getName(), DeviceImpl.create(emulatorContext, classLoader, entry.getName(), SwtDevice.class)); } catch (IOException ex) { Message.error("Error parsing device profile, " + Message.getCauseMessage(ex), ex); return; } } for (int i = 0; i < deviceModel.size(); i++) { DeviceEntry entry = (DeviceEntry) deviceModel.elementAt(i); if (devices.containsKey(entry.getDescriptorLocation())) { devices.remove(entry.getDescriptorLocation()); } } if (devices.size() == 0) { Message.info("Device profile already added"); return; } try { File deviceFile = new File(Config.getConfigPath(), file.getName()); if (deviceFile.exists()) { deviceFile = File.createTempFile("device", ".jar", Config.getConfigPath()); } IOUtils.copyFile(file, deviceFile); DeviceEntry entry = null; for (Iterator it = devices.keySet().iterator(); it.hasNext(); ) { String descriptorLocation = (String) it.next(); Device device = (Device) devices.get(descriptorLocation); if (manifestDeviceName != null) { entry = new DeviceEntry(manifestDeviceName, deviceFile.getName(), descriptorLocation, false); } else { entry = new DeviceEntry(device.getName(), deviceFile.getName(), descriptorLocation, false); } deviceModel.addElement(entry); for (int i = 0; i < deviceModel.size(); i++) { if (deviceModel.elementAt(i) == entry) { lsDevices.add(entry.getName()); lsDevices.select(i); } } Config.addDeviceEntry(entry); } lsDevicesListener.widgetSelected(null); } catch (IOException ex) { Message.error("Error adding device profile, " + Message.getCauseMessage(ex), ex); return; } } }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dst) throws IOException { if (T.t) T.info("Copying " + src + " -> " + dst + "..."); FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dst); byte buf[] = new byte[40 * KB]; int read; while ((read = in.read(buf)) != -1) { out.write(buf, 0, read); } out.flush(); out.close(); in.close(); if (T.t) T.info("File copied."); }
Code Sample 2:
protected String decrypt(final String data, final String key) throws CryptographicFailureException { Validate.notNull(data, "Provided data cannot be null."); Validate.notNull(key, "Provided key name cannot be null."); final PrivateKey pk = getPrivateKey(key); if (pk == null) { throw new CryptographicFailureException("PrivateKeyNotFound", String.format("Cannot find private key '%s'", key)); } try { final Cipher cipher = Cipher.getInstance(pk.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, pk); final ByteArrayInputStream bin = new ByteArrayInputStream(Base64.decodeBase64(data.getBytes())); final CipherInputStream cin = new CipherInputStream(bin, cipher); final ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(cin, bout); return new String(bout.toByteArray()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(String.format("Cannot find instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (NoSuchPaddingException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (InvalidKeyException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (IOException e) { throw new IllegalStateException("Cannot build in-memory cipher copy", e); } }
|
00
|
Code Sample 1:
public String addShare2(String appid, String appkey, String oauth_token, String oauth_token_secret, String openid, String format, Webpage webpage) throws Exception { String shareUrl = "http://openapi.qzone.qq.com/share/add_share"; String oauth_signature = ""; long oauth_timestamp = new Date().getTime() / 1000; String oauth_nonce = (Math.random() + "").replaceFirst("^0.", ""); List<NameValuePair> shareParameters = new ArrayList<NameValuePair>(); shareParameters.add(new BasicNameValuePair("format", format)); shareParameters.add(new BasicNameValuePair("images", webpage.images)); shareParameters.add(new BasicNameValuePair("oauth_consumer_key", appid)); shareParameters.add(new BasicNameValuePair("oauth_nonce", oauth_nonce)); shareParameters.add(new BasicNameValuePair("oauth_signature_method", "HMAC-SHA1")); shareParameters.add(new BasicNameValuePair("oauth_timestamp", oauth_timestamp + "")); shareParameters.add(new BasicNameValuePair("oauth_token", oauth_token)); shareParameters.add(new BasicNameValuePair("oauth_version", "1.0")); shareParameters.add(new BasicNameValuePair("openid", openid)); shareParameters.add(new BasicNameValuePair("title", webpage.title)); shareParameters.add(new BasicNameValuePair("url", webpage.url)); String stepA1 = "POST"; String stepA2 = URLEncoder.encode(shareUrl, "UTF-8"); String stepA3 = ""; for (int i = 0; i < shareParameters.size(); i++) { NameValuePair item = shareParameters.get(i); stepA3 += item.getName() + "=" + item.getValue(); if (i < shareParameters.size() - 1) { stepA3 += "&"; } } stepA3 = URLEncoder.encode(stepA3, "UTF-8"); String stepA = stepA1 + "&" + stepA2 + "&" + stepA3; String stepB = appkey + "&" + oauth_token_secret; Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec spec = new SecretKeySpec(stepB.getBytes("US-ASCII"), "HmacSHA1"); mac.init(spec); byte[] oauthSignature = mac.doFinal(stepA.getBytes("US-ASCII")); oauth_signature = Base64Encoder.encode(oauthSignature); shareParameters.add(new BasicNameValuePair("oauth_signature", oauth_signature)); HttpPost sharePost = new HttpPost(shareUrl); sharePost.setHeader("Referer", "http://openapi.qzone.qq.com"); sharePost.setHeader("Host", "openapi.qzone.qq.com"); sharePost.setHeader("Accept-Language", "zh-cn"); sharePost.setHeader("Content-Type", "application/x-www-form-urlencoded"); sharePost.setEntity(new UrlEncodedFormEntity(shareParameters, "UTF-8")); DefaultHttpClient httpclient = HttpClientUtils.getHttpClient(); HttpResponse loginPostRes = httpclient.execute(sharePost); String shareHtml = HttpClientUtils.getHtml(loginPostRes, "UTF-8", false); return shareHtml; }
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 void execute(HttpResponse response) throws HttpException, IOException { StringBuffer content = new StringBuffer(); NodeSet allNodes = membershipRegistry.listAllMembers(); for (Node node : allNodes) { content.append(node.getId().toString()); content.append(SystemUtils.LINE_SEPARATOR); } StringEntity body = new StringEntity(content.toString()); body.setContentType(PLAIN_TEXT_RESPONSE_CONTENT_TYPE); response.setEntity(body); }
Code Sample 2:
public byte[] authClient(String host, String user, String passwd, String realm, String serverChallenge) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); OutputStream b64os = new BASE64EncoderStream(bos, Integer.MAX_VALUE); SecureRandom random; try { random = new SecureRandom(); md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { if (debugout != null) debugout.println("DEBUG DIGEST-MD5: " + ex); throw new IOException(ex.toString()); } StringBuffer result = new StringBuffer(); uri = "smtp/" + host; String nc = "00000001"; String qop = "auth"; byte[] bytes = new byte[32]; int resp; if (debugout != null) debugout.println("DEBUG DIGEST-MD5: Begin authentication ..."); Hashtable map = tokenize(serverChallenge); if (realm == null) { String text = (String) map.get("realm"); realm = text != null ? new StringTokenizer(text, ",").nextToken() : host; } String nonce = (String) map.get("nonce"); random.nextBytes(bytes); b64os.write(bytes); b64os.flush(); String cnonce = bos.toString(); bos.reset(); md5.update(md5.digest(ASCIIUtility.getBytes(user + ":" + realm + ":" + passwd))); md5.update(ASCIIUtility.getBytes(":" + nonce + ":" + cnonce)); clientResponse = toHex(md5.digest()) + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":"; md5.update(ASCIIUtility.getBytes("AUTHENTICATE:" + uri)); md5.update(ASCIIUtility.getBytes(clientResponse + toHex(md5.digest()))); result.append("username=\"" + user + "\""); result.append(",realm=\"" + realm + "\""); result.append(",qop=" + qop); result.append(",nc=" + nc); result.append(",nonce=\"" + nonce + "\""); result.append(",cnonce=\"" + cnonce + "\""); result.append(",digest-uri=\"" + uri + "\""); result.append(",response=" + toHex(md5.digest())); if (debugout != null) debugout.println("DEBUG DIGEST-MD5: Response => " + result.toString()); b64os.write(ASCIIUtility.getBytes(result.toString())); b64os.flush(); return bos.toByteArray(); }
|
00
|
Code Sample 1:
private static void initMagicRules() { InputStream in = null; try { String fname = System.getProperty("magic-mime"); if (fname != null && fname.length() != 0) { in = new FileInputStream(fname); if (in != null) { parse("-Dmagic-mime=" + fname, new InputStreamReader(in)); } } } catch (Exception e) { log.error("Failed to parse custom magic mime file defined by system property -Dmagic-mime [" + System.getProperty("magic-mime") + "]. File will be ignored.", e); } finally { in = closeStream(in); } try { Enumeration en = MimeUtil.class.getClassLoader().getResources("magic.mime"); while (en.hasMoreElements()) { URL url = (URL) en.nextElement(); in = url.openStream(); if (in != null) { try { parse("classpath:[" + url + "]", new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse magic.mime rule file [" + url + "] on the classpath. File will be ignored.", ex); } } } } catch (Exception e) { log.error("Problem while processing magic.mime files from classpath. Files will be ignored.", e); } finally { in = closeStream(in); } try { File f = new File(System.getProperty("user.home") + File.separator + ".magic.mime"); if (f.exists()) { in = new FileInputStream(f); if (in != null) { try { parse(f.getAbsolutePath(), new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse .magic.mime file from the users home directory. File will be ignored.", ex); } } } } catch (Exception e) { log.error("Problem while processing .magic.mime file from the users home directory. File will be ignored.", e); } finally { in = closeStream(in); } try { String name = System.getProperty("MAGIC"); if (name != null && name.length() != 0) { if (name.indexOf('.') < 0) { name = name + ".mime"; } else { name = name.substring(0, name.indexOf('.') - 1) + "mime"; } File f = new File(name); if (f.exists()) { in = new FileInputStream(f); if (in != null) { try { parse(f.getAbsolutePath(), new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse magic.mime file from directory located by environment variable MAGIC. File will be ignored.", ex); } } } } } catch (Exception e) { log.error("Problem while processing magic.mime file from directory located by environment variable MAGIC. File will be ignored.", e); } finally { in = closeStream(in); } int mMagicMimeEntriesSizeBeforeReadingOS = mMagicMimeEntries.size(); Iterator it = magicMimeFileLocations.iterator(); while (it.hasNext()) { parseMagicMimeFileLocation((String) it.next()); } if (mMagicMimeEntriesSizeBeforeReadingOS == mMagicMimeEntries.size()) { try { String resource = "eu/medsea/mimeutil/magic.mime"; in = MimeUtil.class.getClassLoader().getResourceAsStream(resource); if (in != null) { try { parse("resource:" + resource, new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse internal magic.mime file.", ex); } } } catch (Exception e) { log.error("Problem while processing internal magic.mime file.", e); } finally { in = closeStream(in); } } }
Code Sample 2:
private void copyOutResource(String dstPath, InputStream in) throws FileNotFoundException, IOException { FileOutputStream out = null; try { dstPath = this.outputDir + dstPath; File file = new File(dstPath); file.getParentFile().mkdirs(); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } } }
|
00
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String 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 FTPClient connect() throws FTPException { try { FTPClient ftp = new FTPClient(); ftp.connect(host, port); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); } ftp.login(userName, password); ftp.setFileType(FTP.BINARY_FILE_TYPE); return ftp; } catch (SocketException e) { throw new FTPException("Failed to connect to server", e); } catch (IOException e) { throw new FTPException("Failed to connect to server", e); } }
|
00
|
Code Sample 1:
private static void sentRequest() { try { URLConnection urlConn; URL url = new URL(gatewayURL); urlConn = url.openConnection(); urlConn.setRequestProperty("Content-Type", "text/xml"); urlConn.setDoOutput(true); OutputStream ostream = urlConn.getOutputStream(); PrintWriter out = new PrintWriter(ostream); out.print(request); out.close(); ostream.close(); InputStream inStream = urlConn.getInputStream(); File myFile = new File(styleSheetLocation); if (type.equals("A") && myFile.exists()) { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new StreamSource(styleSheetLocation)); transformer.transform(new StreamSource(inStream), new StreamResult(System.out)); } else { BufferedReader in = new BufferedReader(new InputStreamReader(inStream)); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public static void createBackup() { String workspacePath = Workspace.INSTANCE.getWorkspace(); if (workspacePath.length() == 0) return; workspacePath += "/"; String backupPath = workspacePath + "Backup"; File directory = new File(backupPath); if (!directory.exists()) directory.mkdirs(); String dateString = DataUtils.DateAndTimeOfNowAsLocalString(); dateString = dateString.replace(" ", "_"); dateString = dateString.replace(":", ""); backupPath += "/Backup_" + dateString + ".zip"; ArrayList<String> backupedFiles = new ArrayList<String>(); backupedFiles.add("Database/Database.properties"); backupedFiles.add("Database/Database.script"); FileInputStream in; byte[] data = new byte[1024]; int read = 0; try { ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(backupPath)); zip.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < backupedFiles.size(); i++) { String backupedFile = backupedFiles.get(i); try { File inFile = new File(workspacePath + backupedFile); if (inFile.exists()) { in = new FileInputStream(workspacePath + backupedFile); if (in != null) { ZipEntry entry = new ZipEntry(backupedFile); zip.putNextEntry(entry); while ((read = in.read(data, 0, 1024)) != -1) zip.write(data, 0, read); zip.closeEntry(); in.close(); } } } catch (Exception e) { Logger.logError(e, "Error during file backup:" + backupedFile); } } zip.close(); } catch (IOException ex) { Logger.logError(ex, "Error during backup"); } }
|
11
|
Code Sample 1:
public static int copy(File src, int amount, File dst) { final int BUFFER_SIZE = 1024; int amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { if (in != null) try { in.close(); } catch (IOException e) { } if (out != null) { try { out.flush(); } catch (IOException e) { } try { out.close(); } catch (IOException e) { } } } return amount - amountToRead; }
Code Sample 2:
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object msg = e.getMessage(); if (!(msg instanceof HttpMessage) && !(msg instanceof HttpChunk)) { ctx.sendUpstream(e); return; } HttpMessage currentMessage = this.currentMessage; File localFile = this.file; if (currentMessage == null) { HttpMessage m = (HttpMessage) msg; if (m.isChunked()) { final String localName = UUID.randomUUID().toString(); List<String> encodings = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING); encodings.remove(HttpHeaders.Values.CHUNKED); if (encodings.isEmpty()) { m.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING); } this.currentMessage = m; this.file = new File(Play.tmpDir, localName); this.out = new FileOutputStream(file, true); } else { ctx.sendUpstream(e); } } else { final HttpChunk chunk = (HttpChunk) msg; if (maxContentLength != -1 && (localFile.length() > (maxContentLength - chunk.getContent().readableBytes()))) { currentMessage.setHeader(HttpHeaders.Names.WARNING, "play.netty.content.length.exceeded"); } else { IOUtils.copyLarge(new ChannelBufferInputStream(chunk.getContent()), this.out); if (chunk.isLast()) { this.out.flush(); this.out.close(); currentMessage.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(localFile.length())); currentMessage.setContent(new FileChannelBuffer(localFile)); this.out = null; this.currentMessage = null; this.file = null; Channels.fireMessageReceived(ctx, currentMessage, e.getRemoteAddress()); } } } }
|
00
|
Code Sample 1:
private void importUrl(String str) throws Exception { URL url = new URL(str); InputStream xmlStream = url.openStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); MessageHolder messages = MessageHolder.getInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(xmlStream); Element rootElement = document.getDocumentElement(); EntrySetParser entrySetParser = new EntrySetParser(); EntrySetTag entrySet = entrySetParser.process(rootElement); UpdateProteinsI proteinFactory = new UpdateProteins(); BioSourceFactory bioSourceFactory = new BioSourceFactory(); ControlledVocabularyRepository.check(); EntrySetChecker.check(entrySet, proteinFactory, bioSourceFactory); if (messages.checkerMessageExists()) { MessageHolder.getInstance().printCheckerReport(System.err); } else { EntrySetPersister.persist(entrySet); if (messages.checkerMessageExists()) { MessageHolder.getInstance().printPersisterReport(System.err); } else { System.out.println("The data have been successfully saved in your Intact node."); } } }
Code Sample 2:
public void markAsCachedHelper(Item item, Date from, Date to, Map<String, Boolean> properties) { if (properties.size() == 0) { return; } Connection conn = null; Iterable<Integer> props = representer.getInternalReps(properties.keySet()); Integer hostIndex = representer.lookUpInternalRep(item.getResolved().getHost()); HashMap<Integer, long[]> periods = new HashMap<Integer, long[]>(); for (Map.Entry<String, Boolean> e : properties.entrySet()) { periods.put(representer.lookUpInternalRep(e.getKey()), new long[] { from.getTime(), to.getTime(), e.getValue() ? 1 : 0 }); } try { conn = getConnection(); conn.setAutoCommit(false); conn.setSavepoint(); PreparedStatement stmt = null; try { stmt = conn.prepareStatement("SELECT MIN(starttime), MAX(endtime), MAX(hasvalues) FROM cachedperiods WHERE " + "id = ? AND host = ? AND prop = ? AND " + "starttime <= ? AND endtime >= ?"); stmt.setString(1, item.getResolved().getId()); stmt.setInt(2, hostIndex); stmt.setLong(4, to.getTime()); stmt.setLong(5, from.getTime()); for (Map.Entry<Integer, long[]> e1 : periods.entrySet()) { stmt.setInt(3, e1.getKey()); ResultSet rs = stmt.executeQuery(); if (rs.next()) { e1.getValue()[0] = Math.min(rs.getLong(1), e1.getValue()[0]); e1.getValue()[1] = Math.max(rs.getLong(2), e1.getValue()[1]); e1.getValue()[2] = Math.max(rs.getInt(3), e1.getValue()[2]); } StorageUtils.close(rs); } StorageUtils.close(stmt); stmt = conn.prepareStatement("DELETE FROM cachedperiods WHERE " + "id = ? AND host = ? AND " + "starttime <= ? AND endtime >= ? AND " + "prop IN (" + StringUtils.join(props.iterator(), ",") + ")"); stmt.setString(1, item.getResolved().getId()); stmt.setInt(2, hostIndex); stmt.setLong(3, to.getTime()); stmt.setLong(4, from.getTime()); stmt.executeUpdate(); StorageUtils.close(stmt); stmt = conn.prepareStatement("INSERT INTO cachedperiods (id, host, prop, starttime, endtime, hasvalues) VALUES (?, ?, ?, ?, ?, ?)"); stmt.setString(1, item.getResolved().getId()); stmt.setInt(2, hostIndex); for (Map.Entry<Integer, long[]> e2 : periods.entrySet()) { stmt.setInt(3, e2.getKey()); stmt.setLong(4, e2.getValue()[0]); stmt.setLong(5, e2.getValue()[1]); stmt.setInt(6, (int) e2.getValue()[2]); stmt.executeUpdate(); } } finally { StorageUtils.close(stmt); } conn.commit(); } catch (SQLException ex) { Logger.getLogger(MetaDataStoragerImpl.class.getName()).log(Level.SEVERE, "Cannot update cachedperiods table.", ex); try { conn.rollback(); } catch (SQLException ex1) { Logger.getLogger(MetaDataStoragerImpl.class.getName()).log(Level.SEVERE, "Could not roll back database, please consult system administrator.", ex1); } } finally { StorageUtils.close(conn); } }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public void writeConfigurationFile() throws IOException, ComponentException { SystemConfig config = parent.getParentSystem().getConfiguration(); File original = config.getLocation(); File backup = new File(original.getParentFile(), original.getName() + "." + System.currentTimeMillis()); FileInputStream in = new FileInputStream(original); FileOutputStream out = new FileOutputStream(backup); byte[] buffer = new byte[2048]; try { int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy backup of configuration file"); throw e; } finally { in.close(); out.close(); } FileWriter replace = new FileWriter(original); replace.write(config.toFileFormat()); replace.close(); logger.info("Re-wrote configuration file " + original.getPath()); }
|
11
|
Code Sample 1:
@Deprecated public boolean backupLuceneIndex(int indexLocation, int backupLocation) { boolean result = false; try { System.out.println("lucene backup started"); String indexPath = this.getIndexFolderPath(indexLocation); String backupPath = this.getIndexFolderPath(backupLocation); File inDir = new File(indexPath); boolean flag = true; if (inDir.exists() && inDir.isDirectory()) { File filesList[] = inDir.listFiles(); if (filesList != null) { File parDirBackup = new File(backupPath); if (!parDirBackup.exists()) parDirBackup.mkdir(); String date = this.getDate(); backupPath += "/" + date; File dirBackup = new File(backupPath); if (!dirBackup.exists()) dirBackup.mkdir(); else { File files[] = dirBackup.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i] != null) { files[i].delete(); } } } dirBackup.delete(); dirBackup.mkdir(); } for (int i = 0; i < filesList.length; i++) { if (filesList[i].isFile()) { try { File destFile = new File(backupPath + "/" + filesList[i].getName()); if (!destFile.exists()) destFile.createNewFile(); FileInputStream in = new FileInputStream(filesList[i]); FileOutputStream out = new FileOutputStream(destFile); FileChannel fcIn = in.getChannel(); FileChannel fcOut = out.getChannel(); fcIn.transferTo(0, fcIn.size(), fcOut); } catch (FileNotFoundException ex) { System.out.println("FileNotFoundException ---->" + ex); flag = false; } catch (IOException excIO) { System.out.println("IOException ---->" + excIO); flag = false; } } } } } System.out.println("lucene backup finished"); System.out.println("flag ========= " + flag); if (flag) { result = true; } } catch (Exception e) { System.out.println("Exception in backupLuceneIndex Method : " + e); e.printStackTrace(); } return result; }
Code Sample 2:
public static void copyFile(String src, String target) throws IOException { FileChannel ic = new FileInputStream(src).getChannel(); FileChannel oc = new FileOutputStream(target).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
|
00
|
Code Sample 1:
static Object executeMethod(HttpMethod method, int timeout, boolean array) throws HttpRequestFailureException, HttpException, IOException, HttpRequestTimeoutException { try { method.getParams().setSoTimeout(timeout * 1000); int status = -1; Object result = null; System.out.println("Execute method: " + method.getPath() + " " + method.getQueryString()); TwitterclipseConfig config = TwitterclipsePlugin.getDefault().getTwitterclipseConfiguration(); HttpClient httpClient = HttpClientUtils.createHttpClient(TWITTER_BASE_URL, config.getUserId(), config.getPassword()); status = httpClient.executeMethod(method); System.out.println("Received response. status = " + status); if (status == HttpStatus.SC_OK) { InputStream inputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(inputStream, baos); String response = new String(baos.toByteArray(), "UTF-8"); System.out.println(response); if (array) result = JSONArray.fromString(response); else result = JSONObject.fromString(response); } else { throw new HttpRequestFailureException(status); } return result; } catch (SocketTimeoutException e) { throw new HttpRequestTimeoutException(e); } finally { method.releaseConnection(); } }
Code Sample 2:
static void sort(int[] a) { int i = 0; while (i < a.length - 1) { int j = 0; while (j < (a.length - i) - 1) { if (a[j] > a[j + 1]) { int aux = a[j]; a[j] = a[j + 1]; a[j + 1] = aux; } j = j + 1; } i = i + 1; } }
|
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:
public static void copyFile(File sourceFile, File targetFile) throws IOException { FileInputStream iStream = new FileInputStream(sourceFile); FileOutputStream oStream = new FileOutputStream(targetFile); FileChannel inChannel = iStream.getChannel(); FileChannel outChannel = oStream.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { buffer.clear(); int readCount = inChannel.read(buffer); if (readCount == -1) { break; } buffer.flip(); outChannel.write(buffer); } iStream.close(); oStream.close(); }
|
11
|
Code Sample 1:
public static void copyFiles(String strPath, String dstPath) throws IOException { File src = new File(strPath); File dest = new File(dstPath); if (src.isDirectory()) { dest.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { if (list[i].lastIndexOf(SVN) != -1) { if (!SVN.equalsIgnoreCase(list[i].substring(list[i].length() - 4, list[i].length()))) { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFiles(src1, dest1); } } else { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFiles(src1, dest1); } } } else { FileInputStream fin = new FileInputStream(src); FileOutputStream fout = new FileOutputStream(dest); int c; while ((c = fin.read()) >= 0) fout.write(c); fin.close(); fout.close(); } }
Code Sample 2:
public static void copyFile(File src, File dst) throws ResourceNotFoundException, ParseErrorException, Exception { if (src.getAbsolutePath().endsWith(".vm")) { copyVMFile(src, dst.getAbsolutePath().substring(0, dst.getAbsolutePath().lastIndexOf(".vm"))); } else { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; fIn = new FileInputStream(src); fOut = new FileOutputStream(dst); fIChan = fIn.getChannel(); fOChan = fOut.getChannel(); fSize = fIChan.size(); mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); fOChan.write(mBuf); fIChan.close(); fIn.close(); fOChan.close(); fOut.close(); } }
|
00
|
Code Sample 1:
public void load(String fileName) { BufferedReader bufReader; loaded = false; vector.removeAllElements(); try { if (fileName.startsWith("http:")) { URL url = new URL(fileName); bufReader = new BufferedReader(new InputStreamReader(url.openStream())); } else bufReader = new BufferedReader(new FileReader(fileName)); String inputLine; while ((inputLine = bufReader.readLine()) != null) { if (listener != null) listener.handleLine(inputLine); else vector.add(inputLine); } bufReader.close(); loaded = true; } catch (IOException e) { errorMsg = e.getMessage(); } }
Code Sample 2:
private String digest(String message) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(message.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); String hpassword = hash.toString(16); return hpassword; } catch (Exception e) { } return null; }
|
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:
public synchronized void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CacheEntry entry = null; Tenant tenant = null; if (!tenantInfo.getTenants().isEmpty()) { tenant = tenantInfo.getMatchingTenant(request); if (tenant == null) { tenant = tenantInfo.getTenants().get(0); } entry = tenantToCacheEntry.get(tenant.getName()); } else { entry = cacheEntry; } if (entry == null) { File tempDir = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); tempDir = new File(tempDir, "pustefix-sitemap-cache"); if (!tempDir.exists()) { tempDir.mkdirs(); } entry = new CacheEntry(); entry.file = new File(tempDir, "sitemap" + (tenant == null ? "" : "-" + tenant.getName()) + ".xml"); try { String host = AbstractPustefixRequestHandler.getServerName(request); Document doc = getSearchEngineSitemap(tenant, host); Transformer trf = TransformerFactory.newInstance().newTransformer(); trf.setOutputProperty(OutputKeys.INDENT, "yes"); FileOutputStream out = new FileOutputStream(entry.file); MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException x) { throw new RuntimeException("Can't create message digest", x); } DigestOutputStream digestOutput = new DigestOutputStream(out, digest); trf.transform(new DOMSource(doc), new StreamResult(digestOutput)); digestOutput.close(); byte[] digestBytes = digest.digest(); entry.etag = MD5Utils.byteToHex(digestBytes); } catch (Exception x) { throw new ServletException("Error creating sitemap", x); } } String reqETag = request.getHeader("If-None-Match"); if (reqETag != null) { if (entry.etag.equals(reqETag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.flushBuffer(); return; } } long reqMod = request.getDateHeader("If-Modified-Since"); if (reqMod != -1) { if (entry.file.lastModified() < reqMod + 1000) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.flushBuffer(); return; } } response.setContentType("application/xml"); response.setContentLength((int) entry.file.length()); response.setDateHeader("Last-Modified", entry.file.lastModified()); response.setHeader("ETag", entry.etag); OutputStream out = new BufferedOutputStream(response.getOutputStream()); InputStream in = new FileInputStream(entry.file); int bytes_read; byte[] buffer = new byte[8]; while ((bytes_read = in.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } out.flush(); in.close(); out.close(); }
|
11
|
Code Sample 1:
public static void joinFiles(FileValidator validator, File target, File[] sources) { FileOutputStream fos = null; try { if (!validator.verifyFile(target)) return; fos = new FileOutputStream(target); FileInputStream fis = null; byte[] bytes = new byte[512]; for (int i = 0; i < sources.length; i++) { fis = new FileInputStream(sources[i]); int nbread = 0; try { while ((nbread = fis.read(bytes)) > -1) { fos.write(bytes, 0, nbread); } } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { fis.close(); } } } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } }
Code Sample 2:
public String getResourceAsString(String name) throws IOException { String content = null; InputStream stream = aClass.getResourceAsStream(name); if (stream != null) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copyAndClose(stream, buffer); content = buffer.toString(); } else { Assert.fail("Resource not available: " + name); } return content; }
|
11
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
private static void loadCommandList() { final URL url; try { url = IOUtils.getResource(null, PYTHON_MENU_FILE); } catch (final FileNotFoundException ex) { log.error("File '" + PYTHON_MENU_FILE + "': " + ex.getMessage()); return; } final List<String> cmdList = new ArrayList<String>(); try { final InputStream inputStream = url.openStream(); try { final Reader reader = new InputStreamReader(inputStream, IOUtils.MAP_ENCODING); try { final BufferedReader bufferedReader = new BufferedReader(reader); try { while (true) { final String inputLine = bufferedReader.readLine(); if (inputLine == null) { break; } final String line = inputLine.trim(); if (line.length() > 0 && !line.startsWith("#")) { final int k = line.indexOf('('); if (k > 0) { cmdList.add(line.substring(0, k) + "()"); } else { log.error("Parse error in " + url + ":"); log.error(" \"" + line + "\" missing '()'"); cmdList.add(line + "()"); } } } Collections.sort(cmdList, String.CASE_INSENSITIVE_ORDER); if (!cmdList.isEmpty()) { menuEntries = cmdList.toArray(new String[cmdList.size()]); } } finally { bufferedReader.close(); } } finally { reader.close(); } } finally { inputStream.close(); } } catch (final FileNotFoundException ex) { log.error("File '" + url + "' not found: " + ex.getMessage()); } catch (final EOFException ignored) { } catch (final UnsupportedEncodingException ex) { log.error("Cannot decode file '" + url + "': " + ex.getMessage()); } catch (final IOException ex) { log.error("Cannot read file '" + url + "': " + ex.getMessage()); } }
|
11
|
Code Sample 1:
public void writeTo(OutputStream out) throws IOException { if (!closed) { throw new IOException("Stream not closed"); } if (isInMemory()) { memoryOutputStream.writeTo(out); } else { FileInputStream fis = new FileInputStream(outputFile); try { IOUtils.copy(fis, out); } finally { IOUtils.closeQuietly(fis); } } }
Code Sample 2:
private static void writeBinaryFile(String filename, String target) throws IOException { File outputFile = new File(target); AgentFilesystem.forceDir(outputFile.getParent()); FileOutputStream output = new FileOutputStream(new File(target)); FileInputStream inputStream = new FileInputStream(filename); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) > -1) output.write(buffer, 0, bytesRead); inputStream.close(); output.close(); }
|
11
|
Code Sample 1:
public void xtest2() throws Exception { InputStream input1 = new FileInputStream("C:/Documentos/j931_01.pdf"); InputStream input2 = new FileInputStream("C:/Documentos/j931_02.pdf"); InputStream tmp = new ITextManager().merge(new InputStream[] { input1, input2 }); FileOutputStream output = new FileOutputStream("C:/temp/split.pdf"); IOUtils.copy(tmp, output); input1.close(); input2.close(); tmp.close(); output.close(); }
Code Sample 2:
public void compressImage(InputStream input, OutputStream output, DjatokaEncodeParam params) throws DjatokaException { if (params == null) params = new DjatokaEncodeParam(); File inputFile = null; try { inputFile = File.createTempFile("tmp", ".tif"); IOUtils.copyStream(input, new FileOutputStream(inputFile)); if (params.getLevels() == 0) { ImageRecord dim = ImageRecordUtils.getImageDimensions(inputFile.getAbsolutePath()); params.setLevels(ImageProcessingUtils.getLevelCount(dim.getWidth(), dim.getHeight())); dim = null; } } catch (IOException e1) { logger.error("Unexpected file format; expecting uncompressed TIFF", e1); throw new DjatokaException("Unexpected file format; expecting uncompressed TIFF"); } String out = STDOUT; File winOut = null; if (isWindows) { try { winOut = File.createTempFile("pipe_", ".jp2"); } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } out = winOut.getAbsolutePath(); } String command = getKduCompressCommand(inputFile.getAbsolutePath(), out, params); logger.debug("compressCommand: " + command); Runtime rt = Runtime.getRuntime(); try { final Process process = rt.exec(command, envParams, new File(env)); if (out.equals(STDOUT)) { IOUtils.copyStream(process.getInputStream(), output); } else if (isWindows) { FileInputStream fis = new FileInputStream(out); IOUtils.copyStream(fis, output); fis.close(); } process.waitFor(); if (process != null) { String errorCheck = null; try { errorCheck = new String(IOUtils.getByteArray(process.getErrorStream())); } catch (Exception e1) { logger.error(e1, e1); } process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); process.destroy(); if (errorCheck != null) throw new DjatokaException(errorCheck); } } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } catch (InterruptedException e) { logger.error(e, e); throw new DjatokaException(e); } if (inputFile != null) inputFile.delete(); if (winOut != null) winOut.delete(); }
|
11
|
Code Sample 1:
public static void main(String[] args) { paraProc(args); CanonicalGFF cgff = new CanonicalGFF(gffFilename); CanonicalGFF geneModel = new CanonicalGFF(modelFilename); CanonicalGFF transcriptGff = new CanonicalGFF(transcriptFilename); TreeMap ksTable1 = getKsTable(ksTable1Filename); TreeMap ksTable2 = getKsTable(ksTable2Filename); Map intronReadCntMap = new TreeMap(); Map intronSplicingPosMap = new TreeMap(); try { BufferedReader fr = new BufferedReader(new FileReader(inFilename)); while (fr.ready()) { String line = fr.readLine(); if (line.startsWith("#")) continue; String tokens[] = line.split("\t"); String chr = tokens[0]; int start = Integer.parseInt(tokens[1]); int stop = Integer.parseInt(tokens[2]); GenomeInterval intron = new GenomeInterval(chr, start, stop); int readCnt = Integer.parseInt(tokens[3]); intronReadCntMap.put(intron, readCnt); String splicingMapStr = tokens[4]; Map splicingMap = getSplicingMap(splicingMapStr); intronSplicingPosMap.put(intron, splicingMap); } fr.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } double[] hdCDF = getHdCdf(readLength, minimumOverlap); try { FileWriter fw = new FileWriter(outFilename); for (Iterator intronIterator = intronReadCntMap.keySet().iterator(); intronIterator.hasNext(); ) { GenomeInterval intron = (GenomeInterval) intronIterator.next(); int readCnt = ((Integer) intronReadCntMap.get(intron)).intValue(); TreeMap splicingMap = (TreeMap) intronSplicingPosMap.get(intron); Object ksInfoArray[] = distributionAccepter((TreeMap) splicingMap.clone(), readCnt, hdCDF, ksTable1, ksTable2); boolean ksAccepted = (Boolean) ksInfoArray[0]; double testK = (Double) ksInfoArray[1]; double standardK1 = (Double) ksInfoArray[2]; double standardK2 = (Double) ksInfoArray[3]; int positionCnt = splicingMap.size(); Object modelInfoArray[] = getModelAgreedSiteCnt(intron, cgff, geneModel, transcriptGff); int modelAgreedSiteCnt = (Integer) modelInfoArray[0]; int maxAgreedTransSiteCnt = (Integer) modelInfoArray[1]; boolean containedBySomeGene = (Boolean) modelInfoArray[2]; int numIntersectingGenes = (Integer) modelInfoArray[3]; int distance = intron.getStop() - intron.getStart(); fw.write(intron.getChr() + ":" + intron.getStart() + ".." + intron.getStop() + "\t" + distance + "\t" + readCnt + "\t" + splicingMap + "\t" + probabilityEvaluation(readLength, distance, readCnt, splicingMap, positionCnt) + "\t" + ksAccepted + "\t" + testK + "\t" + standardK1 + "\t" + standardK2 + "\t" + positionCnt + "\t" + modelAgreedSiteCnt + "\t" + maxAgreedTransSiteCnt + "\t" + containedBySomeGene + "\t" + numIntersectingGenes + "\n"); } fw.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } }
Code Sample 2:
public static URL toFileUrl(URL location) throws IOException { String protocol = location.getProtocol().intern(); if (protocol != "jar") throw new IOException("cannot explode " + location); JarURLConnection juc = (JarURLConnection) location.openConnection(); String path = juc.getEntryName(); String parentPath = parentPathOf(path); File tempDir = createTempDir("jartemp"); JarFile jarFile = juc.getJarFile(); for (Enumeration<JarEntry> en = jarFile.entries(); en.hasMoreElements(); ) { ZipEntry entry = en.nextElement(); if (entry.isDirectory()) continue; String entryPath = entry.getName(); if (entryPath.startsWith(parentPath)) { File dest = new File(tempDir, entryPath); dest.getParentFile().mkdirs(); InputStream in = jarFile.getInputStream(entry); OutputStream out = new FileOutputStream(dest); IOUtils.copy(in, out); dest.deleteOnExit(); } } File realFile = new File(tempDir, path); return realFile.toURL(); }
|
00
|
Code Sample 1:
public boolean loadURL(URL url) { try { propertyBundle.load(url.openStream()); LOG.info("Configuration loaded from " + url + "\n"); return true; } catch (Exception e) { if (canComplain) { LOG.warn("Unable to load configuration " + url + "\n"); } canComplain = false; return false; } }
Code Sample 2:
public static void copyFile(File source, File dest) throws Exception { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { throw new Exception("Cannot copy file " + source.getAbsolutePath() + " to " + dest.getAbsolutePath(), e); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (Exception e) { throw new Exception("Cannot close streams.", e); } } }
|
00
|
Code Sample 1:
public static String sha1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("UTF-8"), 0, text.length()); byte[] sha1hash = md.digest(); return convertToHex(sha1hash); }
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:
protected static boolean copyFile(File src, File dest) { try { if (!dest.exists()) { dest.createNewFile(); } FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); byte[] temp = new byte[1024 * 8]; int readSize = 0; do { readSize = fis.read(temp); fos.write(temp, 0, readSize); } while (readSize == temp.length); temp = null; fis.close(); fos.flush(); fos.close(); } catch (Exception e) { return false; } return true; }
Code Sample 2:
private static File copyFileTo(File file, File directory) throws IOException { File newFile = new File(directory, file.getName()); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(file); fos = new FileOutputStream(newFile); byte buff[] = new byte[1024]; int val; while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val); } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } return newFile; }
|
00
|
Code Sample 1:
@Override public void send() { BufferedReader in = null; StringBuffer result = new StringBuffer(); try { URL url = new URL(getUrl()); in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { result.append(str); } } catch (ConnectException ce) { logger.error("MockupExecutableCommand excute fail: " + ce.getMessage()); } catch (Exception e) { logger.error("MockupExecutableCommand excute fail: " + e.getMessage()); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("BufferedReader could not be closed", e); } } } }
Code Sample 2:
private File copyFile(String fileInClassPath, String systemPath) throws Exception { InputStream is = getClass().getResourceAsStream(fileInClassPath); OutputStream os = new FileOutputStream(systemPath); IOUtils.copy(is, os); is.close(); os.close(); return new File(systemPath); }
|
00
|
Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
private Map getBlackHoleData() throws Exception { File dataFile = new File(Kit.getDataDir() + BLACK_HOLE); if (dataFile.exists() && daysOld(dataFile) < 1) { return getStoredData(dataFile); } InputStream stream = null; try { String bh_url = "http://www.critique.org/users/critters/blackholes/sightdata.html"; URL url = new URL(bh_url); stream = url.openStream(); } catch (IOException e) { return getStoredData(dataFile); } BufferedReader br = new BufferedReader(new InputStreamReader(stream)); StringBuffer data = new StringBuffer(); String line; while ((line = br.readLine()) != null) { data.append(line); } br.close(); Pattern p = Pattern.compile(regexp); Matcher m = p.matcher(data); Map map = new THashMap(); while (m.find()) { map.put(m.group(1).trim(), new ReplyTimeDatum(Integer.parseInt(m.group(3)), Integer.parseInt(m.group(4)), 0, Integer.parseInt(m.group(2)))); } ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(dataFile)); oos.writeObject(map); oos.close(); return map; }
|
00
|
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:
private HashSet<String> loadSupportedAnnotationTypes(VannitationType baseVannitationType) { Enumeration<URL> urls = null; try { urls = this.getClass().getClassLoader().getResources("META-INF/" + baseVannitationType); } catch (IOException e) { throw new RuntimeException("Failed to load the annotations we support", e); } supportedAnnotationTypes.put(baseVannitationType, new HashSet<String>()); while (urls.hasMoreElements()) { URL url = urls.nextElement(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { supportedAnnotationTypes.get(baseVannitationType).add(line.trim()); } reader.close(); } catch (Exception e) { throw new RuntimeException("Could not open " + url); } } return supportedAnnotationTypes.get(baseVannitationType); }
|
00
|
Code Sample 1:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
Code Sample 2:
public static String uploadArticleMedia(String localPath, String articleImageName, String year, String month, String day, DataStore db, HttpSession session) { CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user"); if (!localPath.endsWith(File.separator)) { localPath += File.separator; } FTPClient ftp = new FTPClient(); String liveFTPLogin = (String) user.workingPubConfigElementsHash.get("LIVEFTPLOGIN"); String liveFTPPassword = (String) user.workingPubConfigElementsHash.get("LIVEFTPPASSWORD"); String liveImagesServer = (String) user.workingPubConfigElementsHash.get("LIVEFTPSERVER"); String liveImagesFolder = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESFOLDER"); if (!liveImagesFolder.endsWith("/")) { liveImagesFolder = liveImagesFolder + "/"; } String liveImagesYearFolder = ""; String liveImagesMonthFolder = ""; String fileLocation = ""; fileLocation += "/" + year + "/" + month + "/" + day; liveImagesYearFolder = liveImagesFolder + year; liveImagesMonthFolder = (liveImagesYearFolder + "/" + month); liveImagesFolder = (liveImagesMonthFolder + "/" + day); CofaxToolsUtil.log("CofaxToolsFTP: liveImagesServer: " + liveImagesServer); CofaxToolsUtil.log("CofaxToolsFTP: liveImagesFolder: " + liveImagesFolder); boolean stored = false; ArrayList servers = splitServers(liveImagesServer); for (int count = 0; count < servers.size(); count++) { String server = (String) servers.get(count); try { int reply; ftp.connect(server); CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia connecting to server : " + server); CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia results: " + ftp.getReplyString()); CofaxToolsUtil.log(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return ("CofaxToolsFTP uploadArticleMedia ERROR: FTP server refused connection."); } else { ftp.login(liveFTPLogin, liveFTPPassword); } try { ftp.setFileType(FTP.IMAGE_FILE_TYPE); InputStream input; CofaxToolsUtil.log("CofaxToolsFTP: opening file stream: " + localPath + articleImageName); input = new FileInputStream(localPath + articleImageName); CofaxToolsUtil.log("CofaxToolsFTP: attempting to change working directory to: " + liveImagesFolder); boolean changed = ftp.changeWorkingDirectory(liveImagesFolder); CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia results: " + changed); if (changed == false) { CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia attempting to create directory :" + liveImagesFolder); boolean newDirYear = ftp.makeDirectory(liveImagesYearFolder); boolean newDirMonth = ftp.makeDirectory(liveImagesMonthFolder); boolean newDir = ftp.makeDirectory(liveImagesFolder); CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia results: YearDir: " + newDirYear + " MonthDir: " + newDirMonth + " finalDir: " + newDir); changed = ftp.changeWorkingDirectory(liveImagesFolder); } if (changed) { CofaxToolsUtil.log("CofaxToolsFTP: storing " + articleImageName + " to " + liveImagesFolder); stored = ftp.storeFile(articleImageName, input); } else { CofaxToolsUtil.log("CofaxToolsFTP: failed changing: " + liveImagesFolder); } if (stored) { CofaxToolsUtil.log("CofaxToolsFTP: Successfully ftped file."); } else { CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file."); } input.close(); ftp.logout(); ftp.disconnect(); } catch (org.apache.commons.net.io.CopyStreamException e) { CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file." + e.toString()); CofaxToolsUtil.log("CofaxToolsFTP: " + e.getIOException().toString()); return ("Cannot upload file " + liveImagesFolder + "/" + articleImageName); } catch (IOException e) { CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file." + e.toString()); return ("Cannot upload file " + liveImagesFolder + "/" + articleImageName); } catch (Exception e) { CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file." + e.toString()); return ("Cannot upload file " + liveImagesFolder + "/" + articleImageName); } } catch (IOException e) { return ("Could not connect to server: " + e); } } return (""); }
|
11
|
Code Sample 1:
public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_name); System.out.print("Overwrite existing file " + to_name + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("FileCopy: existing file was not overwritten."); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
|
11
|
Code Sample 1:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } }
|
11
|
Code Sample 1:
public void testQueryForBinary() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource source = (JCRNodeSource) resolveSource(BASE_URL + "images/photo.png"); assertNotNull(source); assertEquals(false, source.exists()); OutputStream os = source.getOutputStream(); assertNotNull(os); String content = "foo is a bar"; os.write(content.getBytes()); os.flush(); os.close(); QueryResultSource qResult = (QueryResultSource) resolveSource(BASE_URL + "images?/*[contains(local-name(), 'photo.png')]"); assertNotNull(qResult); Collection results = qResult.getChildren(); assertEquals(1, results.size()); Iterator it = results.iterator(); JCRNodeSource rSrc = (JCRNodeSource) it.next(); InputStream rSrcIn = rSrc.getInputStream(); ByteArrayOutputStream actualOut = new ByteArrayOutputStream(); IOUtils.copy(rSrcIn, actualOut); rSrcIn.close(); assertEquals(content, actualOut.toString()); actualOut.close(); rSrc.delete(); }
Code Sample 2:
public long copyFileWithPaths(String userBaseDir, String sourcePath, String destinPath) throws Exception { if (userBaseDir.endsWith(sep)) { userBaseDir = userBaseDir.substring(0, userBaseDir.length() - sep.length()); } String file1FullPath = new String(); if (sourcePath.startsWith(sep)) { file1FullPath = new String(userBaseDir + sourcePath); } else { file1FullPath = new String(userBaseDir + sep + sourcePath); } String file2FullPath = new String(); if (destinPath.startsWith(sep)) { file2FullPath = new String(userBaseDir + destinPath); } else { file2FullPath = new String(userBaseDir + sep + destinPath); } long plussQuotaSize = 0; BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File fileordir = new File(file1FullPath); if (fileordir.exists()) { if (fileordir.isFile()) { File file2 = new File(file2FullPath); if (file2.exists()) { plussQuotaSize -= file2.length(); file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(file1FullPath), bufferSize); out = new BufferedOutputStream(new FileOutputStream(file2FullPath), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } if (fileordir.isDirectory()) { String[] entryList = fileordir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String file1FullPathEntry = new String(file1FullPath.concat(entryList[pos])); String file2FullPathEntry = new String(file2FullPath.concat(entryList[pos])); File file2 = new File(file2FullPathEntry); if (file2.exists()) { plussQuotaSize -= file2.length(); file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(file1FullPathEntry), bufferSize); out = new BufferedOutputStream(new FileOutputStream(file2FullPathEntry), 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("Source file or dir not exist ! file1FullPath = (" + file1FullPath + ")"); } return plussQuotaSize; }
|
11
|
Code Sample 1:
public static byte[] SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return sha1hash; }
Code Sample 2:
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnClear) { passwordField.setText(""); } for (int i = 0; i < 10; i++) { if (e.getSource() == btnNumber[i]) { String password = new String((passwordField.getPassword())); passwordField.setText(password + i); } } if (e.getSource() == btnOK) { String password = new String((passwordField.getPassword())); ResultSet rs; Statement stmt; String sql; String result = ""; boolean checkPassword = false; sql = "select password from Senhas_De_Unica_Vez where login='" + login + "'" + " and key=" + key + " "; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result = rs.getString("password"); } rs.close(); stmt.close(); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String output = bigInt.toString(16); if (output.compareTo(result) == 0) checkPassword = true; else checkPassword = false; } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } if (checkPassword == true) { JOptionPane.showMessageDialog(null, "senha correta!"); sql = "delete from Senhas_De_Unica_Vez where login='" + login + "'" + " and key=" + key + " "; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } setVisible(false); setTries(0); Error.log(4003, "Senha de uso �nico verificada positivamente."); Error.log(4002, "Autentica��o etapa 3 encerrada."); ManagerWindow mw = new ManagerWindow(login); mw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } else { JOptionPane.showMessageDialog(null, "senha incorreta!"); int tries = getTries(); if (tries == 0) { Error.log(4004, "Primeiro erro da senha de uso �nico contabilizado."); } else if (tries == 1) { Error.log(4005, "Segundo erro da senha de uso �nico contabilizado."); } else if (tries == 2) { Error.log(4006, "Terceiro erro da senha de uso �nico contabilizado."); Error.log(4007, "Acesso do usuario " + login + " bloqueado pela autentica��o etapa 3."); Error.log(4002, "Autentica��o etapa 3 encerrada."); Error.log(1002, "Sistema encerrado."); setTries(++tries); System.exit(1); } setTries(++tries); } } }
|
11
|
Code Sample 1:
private void copyDirContent(String fromDir, String toDir) throws Exception { String fs = System.getProperty("file.separator"); File[] files = new File(fromDir).listFiles(); if (files == null) { throw new FileNotFoundException("Sourcepath: " + fromDir + " not found!"); } for (int i = 0; i < files.length; i++) { File dir = new File(toDir); dir.mkdirs(); if (files[i].isFile()) { try { FileChannel srcChannel = new FileInputStream(files[i]).getChannel(); FileChannel dstChannel = new FileOutputStream(toDir + fs + files[i].getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { Logger.ERROR("Error during file copy: " + e.getMessage()); throw e; } } } }
Code Sample 2:
@Test public void testCopy_inputStreamToWriter() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); }
|
00
|
Code Sample 1:
public static String MD5_hex(String p) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); md.update(p.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); String ret = hash.toString(16); return ret; } catch (NoSuchAlgorithmException e) { logger.error("can not create confirmation key", e); throw new TechException(e); } }
Code Sample 2:
protected InputSource getInputSource(String pReferencingSystemId, String pURI) throws SAXException { URL url = null; if (pReferencingSystemId != null) { try { url = new URL(new URL(pReferencingSystemId), pURI); } catch (MalformedURLException e) { } if (url == null) { try { url = new File(new File(pReferencingSystemId).getParentFile(), pURI).toURL(); } catch (MalformedURLException e) { } } } if (url == null) { try { url = new URL(pURI); } catch (MalformedURLException e) { try { url = new File(pURI).toURL(); } catch (MalformedURLException f) { throw new SAXException("Failed to parse the URI " + pURI); } } } try { InputSource isource = new InputSource(url.openStream()); isource.setSystemId(url.toString()); return isource; } catch (IOException e) { throw new SAXException("Failed to open the URL " + url, e); } }
|
11
|
Code Sample 1:
private void write(File src, File dst, byte id3v1Tag[], byte id3v2HeadTag[], byte id3v2TailTag[]) throws IOException { if (src == null || !src.exists()) throw new IOException(Debug.getDebug("missing src", src)); if (!src.getName().toLowerCase().endsWith(".mp3")) throw new IOException(Debug.getDebug("src not mp3", src)); if (dst == null) throw new IOException(Debug.getDebug("missing dst", dst)); if (dst.exists()) { dst.delete(); if (dst.exists()) throw new IOException(Debug.getDebug("could not delete dst", dst)); } boolean hasId3v1 = new MyID3v1().hasID3v1(src); long id3v1Length = hasId3v1 ? ID3_V1_TAG_LENGTH : 0; long id3v2HeadLength = new MyID3v2().findID3v2HeadLength(src); long id3v2TailLength = new MyID3v2().findID3v2TailLength(src, hasId3v1); OutputStream os = null; InputStream is = null; try { dst.getParentFile().mkdirs(); os = new FileOutputStream(dst); os = new BufferedOutputStream(os); if (!skipId3v2Head && !skipId3v2 && id3v2HeadTag != null) os.write(id3v2HeadTag); is = new FileInputStream(src); is = new BufferedInputStream(is); is.skip(id3v2HeadLength); long total_to_read = src.length(); total_to_read -= id3v1Length; total_to_read -= id3v2HeadLength; total_to_read -= id3v2TailLength; byte buffer[] = new byte[1024]; long total_read = 0; while (total_read < total_to_read) { int remainder = (int) (total_to_read - total_read); int readSize = Math.min(buffer.length, remainder); int read = is.read(buffer, 0, readSize); if (read <= 0) throw new IOException("unexpected EOF"); os.write(buffer, 0, read); total_read += read; } if (!skipId3v2Tail && !skipId3v2 && id3v2TailTag != null) os.write(id3v2TailTag); if (!skipId3v1 && id3v1Tag != null) os.write(id3v1Tag); } finally { try { if (is != null) is.close(); } catch (Throwable e) { Debug.debug(e); } try { if (os != null) os.close(); } catch (Throwable e) { Debug.debug(e); } } }
Code Sample 2:
@Test public void testEncryptDecrypt() throws IOException { BlockCipher cipher = new SerpentEngine(); Random rnd = new Random(); byte[] key = new byte[256 / 8]; rnd.nextBytes(key); byte[] iv = new byte[cipher.getBlockSize()]; rnd.nextBytes(iv); byte[] data = new byte[1230000]; new Random().nextBytes(data); ByteArrayOutputStream bout = new ByteArrayOutputStream(); CryptOutputStream eout = new CryptOutputStream(bout, cipher, key); eout.write(data); eout.close(); byte[] eData = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(eData); CryptInputStream din = new CryptInputStream(bin, cipher, key); bout = new ByteArrayOutputStream(); IOUtils.copy(din, bout); eData = bout.toByteArray(); Assert.assertTrue(Arrays.areEqual(data, eData)); }
|
00
|
Code Sample 1:
public static String calculateHash(String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); md.reset(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } md.update(password.getBytes()); return byteToBase64(md.digest()); }
Code Sample 2:
public boolean saveLecturerecordingsXMLOnWebserver() { boolean error = false; FTPClient ftp = new FTPClient(); String lecture = ""; try { URL url = new URL("http://localhost:8080/virtPresenterVerwalter/lecturerecordings.jsp?seminarid=" + this.getSeminarID()); HttpURLConnection http = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream())); String zeile = ""; while ((zeile = in.readLine()) != null) { lecture += zeile + "\n"; } in.close(); http.disconnect(); } catch (Exception e) { System.err.println("Konnte lecturerecordings.xml nicht lesen."); } try { int reply; ftp.connect(this.getWebserver().getUrl()); System.out.println("Connected to " + this.getWebserver().getUrl() + "."); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); return false; } if (!ftp.login(this.getWebserver().getFtpBenutzer(), this.getWebserver().getFtpPasswort())) { System.err.println("FTP server: Login incorrect"); } String tmpSeminarID = this.getSeminarID(); if (tmpSeminarID == null) tmpSeminarID = "unbekannt"; try { ftp.changeWorkingDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/"); } catch (Exception e) { ftp.makeDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/"); ftp.changeWorkingDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ByteArrayInputStream lectureIn = new ByteArrayInputStream(lecture.getBytes()); System.err.println("FTP Verzeichnis: " + ftp.printWorkingDirectory()); ftp.storeFile("lecturerecordings.xml", lectureIn); lectureIn.close(); ftp.logout(); ftp.disconnect(); } catch (IOException e) { System.err.println("Job " + this.getId() + ": Datei lecturerecordings.xml konnte nicht auf Webserver kopiert werden."); error = true; e.printStackTrace(); } catch (NullPointerException e) { System.err.println("Job " + this.getId() + ": Datei lecturerecordings.xml konnte nicht auf Webserver kopiert werden. (Kein Webserver zugewiesen)"); error = true; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return error; }
|
11
|
Code Sample 1:
public static void main(String[] args) { paraProc(args); CanonicalGFF cgff = new CanonicalGFF(gffFilename); CanonicalGFF geneModel = new CanonicalGFF(modelFilename); CanonicalGFF transcriptGff = new CanonicalGFF(transcriptFilename); TreeMap ksTable1 = getKsTable(ksTable1Filename); TreeMap ksTable2 = getKsTable(ksTable2Filename); Map intronReadCntMap = new TreeMap(); Map intronSplicingPosMap = new TreeMap(); try { BufferedReader fr = new BufferedReader(new FileReader(inFilename)); while (fr.ready()) { String line = fr.readLine(); if (line.startsWith("#")) continue; String tokens[] = line.split("\t"); String chr = tokens[0]; int start = Integer.parseInt(tokens[1]); int stop = Integer.parseInt(tokens[2]); GenomeInterval intron = new GenomeInterval(chr, start, stop); int readCnt = Integer.parseInt(tokens[3]); intronReadCntMap.put(intron, readCnt); String splicingMapStr = tokens[4]; Map splicingMap = getSplicingMap(splicingMapStr); intronSplicingPosMap.put(intron, splicingMap); } fr.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } double[] hdCDF = getHdCdf(readLength, minimumOverlap); try { FileWriter fw = new FileWriter(outFilename); for (Iterator intronIterator = intronReadCntMap.keySet().iterator(); intronIterator.hasNext(); ) { GenomeInterval intron = (GenomeInterval) intronIterator.next(); int readCnt = ((Integer) intronReadCntMap.get(intron)).intValue(); TreeMap splicingMap = (TreeMap) intronSplicingPosMap.get(intron); Object ksInfoArray[] = distributionAccepter((TreeMap) splicingMap.clone(), readCnt, hdCDF, ksTable1, ksTable2); boolean ksAccepted = (Boolean) ksInfoArray[0]; double testK = (Double) ksInfoArray[1]; double standardK1 = (Double) ksInfoArray[2]; double standardK2 = (Double) ksInfoArray[3]; int positionCnt = splicingMap.size(); Object modelInfoArray[] = getModelAgreedSiteCnt(intron, cgff, geneModel, transcriptGff); int modelAgreedSiteCnt = (Integer) modelInfoArray[0]; int maxAgreedTransSiteCnt = (Integer) modelInfoArray[1]; boolean containedBySomeGene = (Boolean) modelInfoArray[2]; int numIntersectingGenes = (Integer) modelInfoArray[3]; int distance = intron.getStop() - intron.getStart(); fw.write(intron.getChr() + ":" + intron.getStart() + ".." + intron.getStop() + "\t" + distance + "\t" + readCnt + "\t" + splicingMap + "\t" + probabilityEvaluation(readLength, distance, readCnt, splicingMap, positionCnt) + "\t" + ksAccepted + "\t" + testK + "\t" + standardK1 + "\t" + standardK2 + "\t" + positionCnt + "\t" + modelAgreedSiteCnt + "\t" + maxAgreedTransSiteCnt + "\t" + containedBySomeGene + "\t" + numIntersectingGenes + "\n"); } fw.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } }
Code Sample 2:
public static void parseString(String str, String name) { BufferedReader reader; String zeile = null; boolean firstL = true; int lambda; float intens; int l_b = 0; int l_e = 0; HashMap<Integer, Float> curve = new HashMap<Integer, Float>(); String[] temp; try { File f = File.createTempFile("tempFile", null); URL url = new URL(str); InputStream is = url.openStream(); FileOutputStream os = new FileOutputStream(f); byte[] buffer = new byte[0xFFFF]; for (int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len); is.close(); os.close(); reader = new BufferedReader(new FileReader(f)); zeile = reader.readLine(); lambda = 0; while (zeile != null) { if (!(zeile.length() > 0 && zeile.charAt(0) == '#')) { zeile = reader.readLine(); break; } zeile = reader.readLine(); } while (zeile != null) { if (zeile.length() > 0) { temp = zeile.split(" "); lambda = Integer.parseInt(temp[0]); intens = Float.parseFloat(temp[1]); if (firstL) { firstL = false; l_b = lambda; } curve.put(lambda, intens); } zeile = reader.readLine(); } l_e = lambda; } catch (IOException e) { System.err.println("Error2 :" + e); } try { String tempV; File file = new File("C:/spectralColors/" + name + ".sd"); FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); bw.write("# COLOR: " + name + " Auto generated File: 02/09/2009; From " + l_b + " to " + l_e); bw.newLine(); bw.write(l_b + ""); bw.newLine(); for (int i = l_b; i <= l_e; i++) { if (curve.containsKey(i)) { tempV = i + " " + curve.get(i); bw.write(tempV); bw.newLine(); } } bw.close(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public void criarTopicoQuestao(Questao q, Integer idTopico) throws SQLException { PreparedStatement stmt = null; String sql = "INSERT INTO questao_topico (id_questao, id_disciplina, id_topico) VALUES (?,?,?)"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.setInt(2, q.getDisciplina().getIdDisciplina()); stmt.setInt(3, idTopico); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } }
Code Sample 2:
public boolean ReadFile() { boolean ret = false; FilenameFilter FileFilter = null; File dir = new File(fDir); String[] FeeFiles; int Lines = 0; BufferedReader FeeFile = null; PreparedStatement DelSt = null, InsSt = null; String Line = null, Term = null, CurTerm = null, TermType = null, Code = null; double[] Fee = new double[US_D + 1]; double FeeAm = 0; String UpdateSt = "INSERT INTO reporter.term_fee (TERM, TERM_TYPE, THEM_VC, THEM_VE, THEM_EC, THEM_EE, THEM_D," + "BA_VC, BA_VE, BA_EC, BA_EE, BA_D," + "US_VC, US_VE, US_EC, US_EE, US_D)" + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; try { FileFilter = new FilenameFilter() { public boolean accept(File dir, String name) { if ((new File(dir, name)).isDirectory()) return false; else return (name.matches(fFileMask)); } }; FeeFiles = dir.list(FileFilter); java.util.Arrays.sort(FeeFiles); System.out.println(FeeFiles[FeeFiles.length - 1] + " " + (new SimpleDateFormat("dd.MM.yy HH:mm:ss")).format(new Date())); Log.info(String.format("Load = %1s", fDir + FeeFiles[FeeFiles.length - 1])); FeeFile = new BufferedReader(new FileReader(fDir + FeeFiles[FeeFiles.length - 1])); FeeZero(Fee); DelSt = cnProd.prepareStatement("delete from reporter.term_fee"); DelSt.executeUpdate(); InsSt = cnProd.prepareStatement(UpdateSt); WriteTerm(FeeFiles[FeeFiles.length - 1] + " " + (new SimpleDateFormat("dd.MM.yy HH:mm:ss")).format(new Date()), "XXX", Fee, InsSt); while ((Line = FeeFile.readLine()) != null) { Lines++; if (!Line.matches("\\d{15}\\s+��������.+")) continue; Term = Line.substring(7, 15); if ((CurTerm == null) || !Term.equals(CurTerm)) { if (CurTerm != null) { WriteTerm(CurTerm, TermType, Fee, InsSt); } CurTerm = Term; if (Line.indexOf("���") > 0) TermType = "���"; else TermType = "���"; FeeZero(Fee); } Code = Line.substring(64, 68).trim().toUpperCase(); if (Code.equals("ST") || Code.equals("AC") || Code.equals("8110") || Code.equals("8160")) continue; FeeAm = new Double(Line.substring(140, 160)).doubleValue(); if (Line.indexOf("�� ����� ������") > 0) SetFee(Fee, CARD_THEM, Code, FeeAm); else if (Line.indexOf("�� ������ �����") > 0) SetFee(Fee, CARD_BA, Code, FeeAm); else if (Line.indexOf("�� ������ ��") > 0) SetFee(Fee, CARD_US, Code, FeeAm); else throw new Exception("������ ���� ����.:" + Line); } WriteTerm(CurTerm, TermType, Fee, InsSt); cnProd.commit(); ret = true; } catch (Exception e) { System.out.printf("Err = %1s\r\n", e.getMessage()); Log.error(String.format("Err = %1s", e.getMessage())); Log.error(String.format("Line = %1s", Line)); try { cnProd.rollback(); } catch (Exception ee) { } ; } finally { try { if (FeeFile != null) FeeFile.close(); } catch (Exception ee) { } } try { if (DelSt != null) DelSt.close(); if (InsSt != null) InsSt.close(); cnProd.setAutoCommit(true); } catch (Exception ee) { } Log.info(String.format("Lines = %1d", Lines)); return (ret); }
|
00
|
Code Sample 1:
@SuppressWarnings({ "ProhibitedExceptionDeclared" }) public int run(@NotNull final List<String> args) throws Exception { int returnCode = 0; if (args.size() == 0) { log(Level.SEVERE, "noarguments"); returnCode++; } final byte[] buf = new byte[BUF_SIZE]; for (final String arg : args) { try { final URL url = new URL(arg); final URLConnection con = url.openConnection(); final InputStream in = con.getInputStream(); try { final String location = con.getHeaderField("Content-Location"); final String outputFilename = new File((location != null ? new URL(url, location) : url).getFile()).getName(); log(Level.INFO, "writing", arg, outputFilename); final OutputStream out = new FileOutputStream(outputFilename); try { for (int bytesRead; (bytesRead = in.read(buf)) != -1; ) { out.write(buf, 0, bytesRead); } } finally { out.close(); } } finally { in.close(); } } catch (final IOException e) { log(Level.WARNING, "cannotopen", arg, e); returnCode++; } } return returnCode; }
Code Sample 2:
public static String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
|
00
|
Code Sample 1:
private Source getStylesheetSource(String stylesheetResource) throws ApplicationContextException { if (LOG.isDebugEnabled()) { LOG.debug("Loading XSLT stylesheet from " + stylesheetResource); } try { URL url = this.getClass().getClassLoader().getResource(stylesheetResource); String urlPath = url.toString(); String systemId = urlPath.substring(0, urlPath.lastIndexOf('/') + 1); return new StreamSource(url.openStream(), systemId); } catch (IOException e) { throw new RuntimeException("Can't load XSLT stylesheet from " + stylesheetResource, e); } }
Code Sample 2:
public static String getURLContent(String href) throws BuildException { URL url = null; String content; try { URL context = new URL("file:" + System.getProperty("user.dir") + "/"); url = new URL(context, href); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); StringBuffer stringBuffer = new StringBuffer(); char[] buffer = new char[1024]; int len; while ((len = isr.read(buffer, 0, 1024)) > 0) stringBuffer.append(buffer, 0, len); content = stringBuffer.toString(); isr.close(); } catch (Exception ex) { throw new BuildException("Cannot get content of URL " + href + ": " + ex); } return content; }
|
11
|
Code Sample 1:
public OutputStream getAsOutputStream() throws IOException { OutputStream out; if (contentStream != null) { File tmp = File.createTempFile(getId(), null); out = new FileOutputStream(tmp); IOUtils.copy(contentStream, out); } else { out = new ByteArrayOutputStream(); out.write(getContent()); } return out; }
Code Sample 2:
public void update() { if (!updatable) { Main.fenetre().erreur(Fenetre.OLD_VERSION); return; } try { Main.fenetre().update(); Element remoteRoot = new SAXBuilder().build(xml).getRootElement(); addPackages = new HashMap<Integer, PackageVersion>(); Iterator<?> iterElem = remoteRoot.getChildren().iterator(); while (iterElem.hasNext()) { PackageVersion pack = new PackageVersion((Element) iterElem.next()); addPackages.put(pack.id(), pack); } removePackages = new HashMap<Integer, PackageVersion>(); iterElem = root.getChildren("package").iterator(); while (iterElem.hasNext()) { PackageVersion pack = new PackageVersion((Element) iterElem.next()); int id = pack.id(); if (!addPackages.containsKey(id)) { removePackages.put(id, pack); } else if (addPackages.get(id).version().equals(pack.version())) { addPackages.remove(id); } else { addPackages.get(id).ecrase(); } } Iterator<PackageVersion> iterPack = addPackages.values().iterator(); while (iterPack.hasNext()) { install(iterPack.next()); } iterPack = removePackages.values().iterator(); while (iterPack.hasNext()) { remove(iterPack.next()); } if (offline) { Runtime.getRuntime().addShutdownHook(new AddPackage(xml, "versions.xml")); Main.fenetre().erreur(Fenetre.UPDATE_TERMINE_RESTART); } else { File oldXML = new File("versions.xml"); oldXML.delete(); oldXML.createNewFile(); FileChannel out = new FileOutputStream(oldXML).getChannel(); FileChannel in = new FileInputStream(xml).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); xml.delete(); if (restart) { Main.fenetre().erreur(Fenetre.UPDATE_TERMINE_RESTART); } else { Main.updateVersion(); } } } catch (Exception e) { Main.fenetre().erreur(Fenetre.ERREUR_UPDATE, e); } }
|
11
|
Code Sample 1:
public void testCodingCompletedFromFile() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 5); encoder.write(wrap("stuff")); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("more stuff"); wrtout.flush(); wrtout.close(); try { FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 10); fail("IllegalStateException should have been thrown"); } catch (IllegalStateException ex) { } finally { tmpFile.delete(); } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
private void fileCopy(File filename) throws IOException { if (this.stdOut) { this.fileDump(filename); return; } File source_file = new File(spoolPath + "/" + filename); File destination_file = new File(copyPath + "/" + filename); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("no such source file: " + source_file); if (!source_file.canRead()) throw new FileCopyException("source file is unreadable: " + source_file); if (destination_file.exists()) { if (destination_file.isFile()) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); if (!destination_file.canWrite()) throw new FileCopyException("destination file is unwriteable: " + destination_file); if (!this.overwrite) { System.out.print("File " + destination_file + " already exists. Overwrite? (Y/N): "); System.out.flush(); if (!in.readLine().toUpperCase().equals("Y")) throw new FileCopyException("copy cancelled."); } } else throw new FileCopyException("destination is not a file: " + destination_file); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("destination directory doesn't exist: " + destination_file); if (!parentdir.canWrite()) throw new FileCopyException("destination directory is unwriteable: " + destination_file); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while ((bytes_read = source.read(buffer)) != -1) { destination.write(buffer, 0, bytes_read); } System.out.println("File " + filename + " successfull copied to " + destination_file); if (this.keep == false && source_file.isFile()) { try { source.close(); } catch (Exception e) { } if (source_file.delete()) { new File(this.spoolPath + "/info/" + filename + ".desc").delete(); } } } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.flush(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } }
Code Sample 2:
public void Copy() throws IOException { if (!FileDestination.exists()) { FileDestination.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(FileSource).getChannel(); destination = new FileOutputStream(FileDestination).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
00
|
Code Sample 1:
protected byte[] getBytesForWebPageUsingHTTPClient(String urlString) throws ClientProtocolException, IOException { log("Retrieving url: " + urlString); DefaultHttpClient httpclient = new DefaultHttpClient(); if (this.archiveAccessSpecification.getUserID() != null) { httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(this.archiveAccessSpecification.getUserID(), this.archiveAccessSpecification.getUserPassword())); } HttpGet httpget = new HttpGet(urlString); log("about to do request: " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); log("-------------- Request results --------------"); log("Status line: " + response.getStatusLine()); if (entity != null) { log("Response content length: " + entity.getContentLength()); } log("contents"); byte[] bytes = null; if (entity != null) { bytes = getBytesFromInputStream(entity.getContent()); entity.consumeContent(); } log("Status code :" + response.getStatusLine().getStatusCode()); log(response.getStatusLine().getReasonPhrase()); if (response.getStatusLine().getStatusCode() != 200) return null; return bytes; }
Code Sample 2:
protected InputStream callApiMethod(String apiUrl, String xmlContent, String contentType, String method, int expected) { try { URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); if (ApplicationConstants.CONNECT_TIMEOUT > -1) { request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT); } if (ApplicationConstants.READ_TIMEOUT > -1) { request.setReadTimeout(ApplicationConstants.READ_TIMEOUT); } for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.setRequestMethod(method); request.setDoOutput(true); if (contentType != null) { request.setRequestProperty("Content-Type", contentType); } if (xmlContent != null) { PrintStream out = new PrintStream(new BufferedOutputStream(request.getOutputStream())); out.print(xmlContent); out.flush(); out.close(); } request.connect(); if (request.getResponseCode() != expected) { throw new BingMapsException(convertStreamToString(request.getErrorStream())); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new BingMapsException(e); } }
|
00
|
Code Sample 1:
public void anular() throws SQLException, ClassNotFoundException, Exception { Connection conn = null; PreparedStatement ms = null; try { conn = ToolsBD.getConn(); conn.setAutoCommit(false); String sentencia_delete = "DELETE FROM BZOFRENT " + " WHERE REN_OFANY=? AND REN_OFOFI=? AND REN_OFNUM=?"; ms = conn.prepareStatement(sentencia_delete); ms.setInt(1, anoOficio != null ? Integer.parseInt(anoOficio) : 0); ms.setInt(2, oficinaOficio != null ? Integer.parseInt(oficinaOficio) : 0); ms.setInt(3, numeroOficio != null ? Integer.parseInt(numeroOficio) : 0); int afectados = ms.executeUpdate(); if (afectados > 0) { registroActualizado = true; } else { registroActualizado = false; } conn.commit(); } catch (Exception ex) { System.out.println("Error inesperat, no s'ha desat el registre: " + ex.getMessage()); ex.printStackTrace(); registroActualizado = false; errores.put("", "Error inesperat, no s'ha desat el registre" + ": " + ex.getClass() + "->" + ex.getMessage()); try { if (conn != null) conn.rollback(); } catch (SQLException sqle) { throw new RemoteException("S'ha produït un error i no s'han pogut tornar enrere els canvis efectuats", sqle); } throw new RemoteException("Error inesperat, no s'ha modifcat el registre", ex); } finally { ToolsBD.closeConn(conn, ms, null); } }
Code Sample 2:
private boolean loadSymbol(QuoteCache quoteCache, Symbol symbol, TradingDate startDate, TradingDate endDate) { boolean success = true; String URLString = constructURL(symbol, startDate, endDate); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url; url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line; while ((line = bufferedInput.readLine()) != null) { Class cl = null; Constructor cnst = null; QuoteFilter filter = null; try { cl = Class.forName("org.mov.quote." + name + "QuoteFilter"); try { cnst = cl.getConstructor(new Class[] { Symbol.class }); } catch (SecurityException e2) { e2.printStackTrace(); } catch (NoSuchMethodException e2) { e2.printStackTrace(); } try { filter = (QuoteFilter) cnst.newInstance(new Object[] { symbol }); } catch (IllegalArgumentException e3) { e3.printStackTrace(); } catch (InstantiationException e3) { e3.printStackTrace(); } catch (IllegalAccessException e3) { e3.printStackTrace(); } catch (InvocationTargetException e3) { e3.printStackTrace(); } } catch (ClassNotFoundException e1) { e1.printStackTrace(); } Quote quote = filter.toQuote(line); if (quote != null) quoteCache.load(quote); } bufferedInput.close(); } catch (BindException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); success = false; } catch (ConnectException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); success = false; } catch (UnknownHostException e) { DesktopManager.showErrorMessage(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); success = false; } catch (NoRouteToHostException e) { DesktopManager.showErrorMessage(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); success = false; } catch (MalformedURLException e) { DesktopManager.showErrorMessage(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); success = false; } catch (FileNotFoundException e) { } catch (IOException e) { DesktopManager.showErrorMessage(Locale.getString("ERROR_DOWNLOADING_QUOTES")); success = false; } return success; }
|
11
|
Code Sample 1:
@Override protected void doFetch(HttpServletRequest request, HttpServletResponse response) throws IOException, GadgetException { if (request.getHeader("If-Modified-Since") != null) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } String host = request.getHeader("Host"); if (!lockedDomainService.isSafeForOpenProxy(host)) { String msg = "Embed request for url " + getParameter(request, URL_PARAM, "") + " made to wrong domain " + host; logger.info(msg); throw new GadgetException(GadgetException.Code.INVALID_PARAMETER, msg); } HttpRequest rcr = buildHttpRequest(request, URL_PARAM); HttpResponse results = requestPipeline.execute(rcr); if (results.isError()) { HttpRequest fallbackRcr = buildHttpRequest(request, FALLBACK_URL_PARAM); if (fallbackRcr != null) { results = requestPipeline.execute(fallbackRcr); } } if (contentRewriterRegistry != null) { try { results = contentRewriterRegistry.rewriteHttpResponse(rcr, results); } catch (RewritingException e) { throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e); } } for (Map.Entry<String, String> entry : results.getHeaders().entries()) { String name = entry.getKey(); if (!DISALLOWED_RESPONSE_HEADERS.contains(name.toLowerCase())) { response.addHeader(name, entry.getValue()); } } String responseType = results.getHeader("Content-Type"); if (!StringUtils.isEmpty(rcr.getRewriteMimeType())) { String requiredType = rcr.getRewriteMimeType(); if (requiredType.endsWith("/*") && !StringUtils.isEmpty(responseType)) { requiredType = requiredType.substring(0, requiredType.length() - 2); if (!responseType.toLowerCase().startsWith(requiredType.toLowerCase())) { response.setContentType(requiredType); responseType = requiredType; } } else { response.setContentType(requiredType); responseType = requiredType; } } setResponseHeaders(request, response, results); if (results.getHttpStatusCode() != HttpResponse.SC_OK) { response.sendError(results.getHttpStatusCode()); } IOUtils.copy(results.getResponse(), response.getOutputStream()); }
Code Sample 2:
public boolean validateZipFile(File zipFile) { String tempdir = Config.CONTEXT.getRealPath(getBackupTempFilePath()); try { deleteTempFiles(); File ftempDir = new File(tempdir); ftempDir.mkdirs(); File tempZip = new File(tempdir + File.separator + zipFile.getName()); tempZip.createNewFile(); FileChannel ic = new FileInputStream(zipFile).getChannel(); FileChannel oc = new FileOutputStream(tempZip).getChannel(); for (long i = 0; i <= ic.size(); i++) { ic.transferTo(0, 1000000, oc); i = i + 999999; } ic.close(); oc.close(); if (zipFile != null && zipFile.getName().toLowerCase().endsWith(".zip")) { ZipFile z = new ZipFile(zipFile); ZipUtil.extract(z, new File(Config.CONTEXT.getRealPath(backupTempFilePath))); } return true; } catch (Exception e) { Logger.error(this, "Error with file", e); return false; } }
|
11
|
Code Sample 1:
public void testCodingFromFileSmaller() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff;"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); }
Code Sample 2:
private boolean saveLOBDataToFileSystem() { if ("".equals(m_attachmentPathRoot)) { log.severe("no attachmentPath defined"); return false; } if (m_items == null || m_items.size() == 0) { setBinaryData(null); return true; } final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.newDocument(); final Element root = document.createElement("attachments"); document.appendChild(root); document.setXmlStandalone(true); for (int i = 0; i < m_items.size(); i++) { log.fine(m_items.get(i).toString()); File entryFile = m_items.get(i).getFile(); final String path = entryFile.getAbsolutePath(); log.fine(path + " - " + m_attachmentPathRoot); if (!path.startsWith(m_attachmentPathRoot)) { log.fine("move file: " + path); FileChannel in = null; FileChannel out = null; try { final File destFolder = new File(m_attachmentPathRoot + File.separator + getAttachmentPathSnippet()); if (!destFolder.exists()) { if (!destFolder.mkdirs()) { log.warning("unable to create folder: " + destFolder.getPath()); } } final File destFile = new File(m_attachmentPathRoot + File.separator + getAttachmentPathSnippet() + File.separator + entryFile.getName()); in = new FileInputStream(entryFile).getChannel(); out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); if (entryFile.exists()) { if (!entryFile.delete()) { entryFile.deleteOnExit(); } } entryFile = destFile; } catch (IOException e) { e.printStackTrace(); log.severe("unable to copy file " + entryFile.getAbsolutePath() + " to " + m_attachmentPathRoot + File.separator + getAttachmentPathSnippet() + File.separator + entryFile.getName()); } finally { if (in != null && in.isOpen()) { in.close(); } if (out != null && out.isOpen()) { out.close(); } } } final Element entry = document.createElement("entry"); entry.setAttribute("name", getEntryName(i)); String filePathToStore = entryFile.getAbsolutePath(); filePathToStore = filePathToStore.replaceFirst(m_attachmentPathRoot.replaceAll("\\\\", "\\\\\\\\"), ATTACHMENT_FOLDER_PLACEHOLDER); log.fine(filePathToStore); entry.setAttribute("file", filePathToStore); root.appendChild(entry); } final Source source = new DOMSource(document); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final Result result = new StreamResult(bos); final Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(source, result); final byte[] xmlData = bos.toByteArray(); log.fine(bos.toString()); setBinaryData(xmlData); return true; } catch (Exception e) { log.log(Level.SEVERE, "saveLOBData", e); } setBinaryData(null); return false; }
|
00
|
Code Sample 1:
public String postData(String result, DefaultHttpClient httpclient) { try { HttpPost post = new HttpPost("http://3dforandroid.appspot.com/api/v1/note/create"); StringEntity se = new StringEntity(result); se.setContentEncoding(HTTP.UTF_8); se.setContentType("application/json"); post.setEntity(se); post.setHeader("Content-Type", "application/json"); post.setHeader("Accept", "*/*"); HttpResponse response = httpclient.execute(post); HttpEntity entity = response.getEntity(); InputStream instream; instream = entity.getContent(); responseMessage = read(instream); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return responseMessage; }
Code Sample 2:
public static User authenticate(final String username, final String password) throws LoginException { Object result = doPriviledgedAction(new PrivilegedAction() { public Object run() { List correctUsers = (List) JsonPath.query("select * from ? where name=?", usersTable(), username); if (correctUsers.size() == 0) { return new LoginException("user " + username + " not found"); } Persistable userObject = (Persistable) correctUsers.get(0); boolean alreadyHashed = false; boolean passwordMatch = password.equals(userObject.get(PASSWORD_FIELD)); if (!passwordMatch) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(((String) userObject.get(PASSWORD_FIELD)).getBytes()); passwordMatch = password.equals(new String(new Base64().encode(md.digest()))); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } alreadyHashed = true; } if (passwordMatch) { Logger.getLogger(User.class.toString()).info("User " + username + " has been authenticated"); User user = (User) userObject; try { if (alreadyHashed) user.currentTicket = password; else { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); user.currentTicket = new String(new Base64().encode(md.digest())); } } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return user; } else { Logger.getLogger(User.class.toString()).info("The password was incorrect for " + username); return new LoginException("The password was incorrect for user " + username + ". "); } } }); if (result instanceof LoginException) throw (LoginException) result; return (User) result; }
|
11
|
Code Sample 1:
private void copyFileNFS(String sSource, String sTarget) throws Exception { FileInputStream fis = new FileInputStream(sSource); FileOutputStream fos = new FileOutputStream(sTarget); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buf = new byte[2048]; int i = 0; while ((i = bis.read(buf)) != -1) bos.write(buf, 0, i); bis.close(); bos.close(); fis.close(); fos.close(); }
Code Sample 2:
public void testRevcounter() throws ServiceException, IOException { JCRNodeSource emptySource = loadTestSource(); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } System.out.println(emptySource.getLatestSourceRevision()); } String testSourceUri = BASE_URL + "users/lars.trieloff?revision=1.1"; JCRNodeSource secondSource = (JCRNodeSource) resolveSource(testSourceUri); System.out.println("Created at: " + secondSource.getSourceRevision()); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } System.out.println(emptySource.getLatestSourceRevision()); } System.out.println("Read again at:" + secondSource.getSourceRevision()); assertNotNull(emptySource.getSourceRevision()); }
|
00
|
Code Sample 1:
public String getLastVersion() { try { String server = icescrum2Properties.get("check.url").toString(); Boolean useProxy = new Boolean(icescrum2Properties.get("proxy.active").toString()); Boolean authProxy = new Boolean(icescrum2Properties.get("proxy.auth.active").toString()); URL url = new URL(server); if (useProxy) { String proxy = icescrum2Properties.get("proxy.url").toString(); String port = icescrum2Properties.get("proxy.port").toString(); Properties systemProperties = System.getProperties(); systemProperties.setProperty("http.proxyHost", proxy); systemProperties.setProperty("http.proxyPort", port); } URLConnection connection = url.openConnection(); if (authProxy) { String username = icescrum2Properties.get("proxy.auth.username").toString(); String password = icescrum2Properties.get("proxy.auth.password").toString(); String login = username + ":" + password; String encodedLogin = Base64.base64Encode(login); connection.setRequestProperty("Proxy-Authorization", "Basic " + encodedLogin); } connection.setConnectTimeout(Integer.parseInt(icescrum2Properties.get("check.timeout").toString())); InputStream input = connection.getInputStream(); StringWriter writer = new StringWriter(); InputStreamReader streamReader = new InputStreamReader(input); BufferedReader buffer = new BufferedReader(streamReader); String value = ""; while (null != (value = buffer.readLine())) { writer.write(value); } return writer.toString(); } catch (IOException e) { } return null; }
Code Sample 2:
private void copy(String url, File toDir) throws IOException { System.err.println("url=" + url + " dir=" + toDir); if (url.endsWith("/")) { String basename = url.substring(url.lastIndexOf("/", url.length() - 2) + 1); File directory = new File(toDir, basename); directory.mkdir(); LineNumberReader reader = new LineNumberReader(new InputStreamReader(new URL(url).openStream(), "utf-8")); String line; while ((line = reader.readLine()) != null) { System.err.println(line.replace('\t', '|')); int tab = line.lastIndexOf('\t', line.lastIndexOf('\t', line.lastIndexOf('\t') - 1) - 1); System.err.println(tab); char type = line.charAt(tab + 1); String file = line.substring(0, tab); copy(url + URIUtil.encodePath(file) + (type == 'd' ? "/" : ""), directory); } } else { String basename = url.substring(url.lastIndexOf("/") + 1); File file = new File(toDir, basename); System.err.println("copy " + url + " --> " + file); IO.copy(new URL(url).openStream(), new FileOutputStream(file)); } }
|
11
|
Code Sample 1:
private void createPolicy(String policyName) throws SPLException { URL url = getClass().getResource(policyName + ".spl"); StringBuffer contents = new StringBuffer(); try { BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = input.readLine()) != null) { contents.append(line); contents.append(System.getProperty("line.separator")); } input.close(); System.out.println(policyName); System.out.println(contents.toString()); boolean createReturn = jspl.createPolicy(policyName, contents.toString()); System.out.println("Policy Created : " + policyName + " - " + createReturn); System.out.println(""); } catch (IOException ex) { ex.printStackTrace(); } }
Code Sample 2:
public String htmlContentSimple(String urlStr, String charset) { StringBuffer html = new StringBuffer(); URL url = null; BufferedReader reader = null; try { url = new URL(urlStr); reader = new BufferedReader(new InputStreamReader(url.openStream(), charset)); String line; while ((line = reader.readLine()) != null) { html.append(line).append("\r\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return html.toString(); }
|
00
|
Code Sample 1:
public static void main(String[] args) { String url = "jdbc:mysql://localhost/test"; String user = "root"; String password = "password"; String imageLocation = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\01100002.tif"; String imageLocation2 = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\011000022.tif"; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } try { File f = new File(imageLocation); InputStream fis = new FileInputStream(f); Connection c = DriverManager.getConnection(url, user, password); ResultSet rs = c.createStatement().executeQuery("SELECT Image FROM ImageTable WHERE ImageID=12345678"); new File(imageLocation2).createNewFile(); rs.first(); System.out.println("GotFirst"); InputStream is = rs.getAsciiStream("Image"); System.out.println("gotStream"); FileOutputStream fos = new FileOutputStream(new File(imageLocation2)); int readInt; int i = 0; while (true) { readInt = is.read(); if (readInt == -1) { System.out.println("ReadInt == -1"); break; } i++; if (i % 1000000 == 0) System.out.println(i + " / " + is.available()); fos.write(readInt); } c.close(); } catch (SQLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
Code Sample 2:
private Object[] retrieveSecondURL(URL url, RSLink link) { link.setStatus(RSLink.STATUS_WAITING); Object[] result = new Object[2]; HttpURLConnection httpConn = null; BufferedReader inr = null; DataOutputStream outs = null; Pattern mirrorLinePattern = Pattern.compile("'<input.+checked.+type=\"radio\".+name=\"mirror\".+\\\\'.+\\\\'"); Pattern mirrorUrlPattern = Pattern.compile("\\\\'.+\\\\'"); Pattern counterPattern = Pattern.compile("var c=[0-9]+;"); Pattern counterIntPattern = Pattern.compile("[0-9]+"); try { String line = null; String urlLine = null; Integer counter = null; String postData = URLEncoder.encode("dl.start", "UTF-8") + "=" + URLEncoder.encode("Free", "UTF-8"); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length)); httpConn.setRequestProperty("Content-Language", "en-US"); httpConn.setDoOutput(true); httpConn.setDoInput(true); outs = new DataOutputStream(httpConn.getOutputStream()); outs.writeBytes(postData); outs.flush(); inr = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); Matcher matcher = null; while ((line = inr.readLine()) != null) { matcher = mirrorLinePattern.matcher(line); if (matcher.find()) { matcher = mirrorUrlPattern.matcher(line); if (matcher.find()) { urlLine = matcher.group().substring(2, matcher.group().length() - 2); result[0] = new URL(urlLine); } } matcher = counterPattern.matcher(line); if (matcher.find()) { matcher = counterIntPattern.matcher(line); if (matcher.find()) { counter = new Integer(matcher.group()); result[1] = counter; } } } } catch (IOException ex) { log("I/O Exception!"); } finally { try { if (outs != null) outs.close(); if (inr != null) inr.close(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Can not close some connections:\n" + ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE); } if (httpConn != null) httpConn.disconnect(); link.setStatus(RSLink.STATUS_NOTHING); return result; } }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void testGetOldVersion() throws ServiceException, IOException, SAXException, ParserConfigurationException { JCRNodeSource emptySource = loadTestSource(); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } } String testSourceUri = BASE_URL + "users/lars.trieloff?revision=1.1"; JCRNodeSource secondSource = (JCRNodeSource) resolveSource(testSourceUri); System.out.println("Read again at:" + secondSource.getSourceRevision()); InputStream expected = emptySource.getInputStream(); InputStream actual = secondSource.getInputStream(); assertTrue(isXmlEqual(expected, actual)); }
|
11
|
Code Sample 1:
public static void translateTableAttributes(String baseDir, String tableName, NameSpaceDefinition nsDefinition) throws Exception { setVosiNS(baseDir, "table_att", nsDefinition); String filename = baseDir + "table_att.xsl"; Scanner s = new Scanner(new File(filename)); PrintWriter fw = new PrintWriter(new File(baseDir + tableName + "_att.xsl")); while (s.hasNextLine()) { fw.println(s.nextLine().replaceAll("TABLENAME", tableName)); } s.close(); fw.close(); applyStyle(baseDir + "tables.xml", baseDir + tableName + "_att.json", baseDir + tableName + "_att.xsl"); }
Code Sample 2:
public static String backupFile(File source) { File backup = new File(source.getParent() + "/~" + source.getName()); try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(source))); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(backup))); return FileUtil.backupFile(reader, writer, source.getAbsolutePath()); } catch (FileNotFoundException fe) { String msg = "Failed to find file for backup [" + source.getAbsolutePath() + "]."; _log.error(msg, fe); throw new InvalidImplementationException(msg, fe); } }
|
11
|
Code Sample 1:
public void test() throws Exception { StringDocument doc = new StringDocument("Test", "UTF-8"); doc.open(); try { assertEquals("UTF-8", doc.getCharacterEncoding()); assertEquals("Test", doc.getText()); InputStream input = doc.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { writer.close(); } assertEquals("Test", writer.toString()); } finally { doc.close(); } }
Code Sample 2:
void write() throws IOException { if (!allowUnlimitedArgs && args != null && args.length > 1) throw new IllegalArgumentException("Only one argument allowed unless allowUnlimitedArgs is enabled"); String shebang = "#!" + interpretter; for (int i = 0; i < args.length; i++) { shebang += " " + args[i]; } shebang += '\n'; IOUtils.copy(new StringReader(shebang), outputStream); }
|
11
|
Code Sample 1:
private final void copyTargetFileToSourceFile(File sourceFile, File targetFile) throws MJProcessorException { if (!targetFile.exists()) { targetFile.getParentFile().mkdirs(); try { if (!targetFile.exists()) { targetFile.createNewFile(); } } catch (IOException e) { throw new MJProcessorException(e.getMessage(), e); } } FileChannel in = null, out = null; try { in = new FileInputStream(sourceFile).getChannel(); out = new FileOutputStream(targetFile).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (IOException e) { log.error(e); } finally { if (in != null) try { in.close(); } catch (IOException e) { log.error(e); } if (out != null) try { out.close(); } catch (IOException e) { log.error(e); } } }
Code Sample 2:
private void doProcess(HttpServletRequest request, HttpServletResponse resp) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { Analyzer analyzer = new Analyzer(); ServletContext context = getServletContext(); String xml = context.getRealPath("data\\log.xml"); String xsd = context.getRealPath("data\\log.xsd"); String grs = context.getRealPath("reports\\" + request.getParameter("type") + ".grs"); String pdf = context.getRealPath("html\\report.pdf"); System.out.println("omg: " + request.getParameter("type")); System.out.println("omg: " + request.getParameter("pc")); int pcount = Integer.parseInt(request.getParameter("pc")); String[] params = new String[pcount]; for (int i = 0; i < pcount; i++) { params[i] = request.getParameter("p" + i); } try { analyzer.generateReport(xml, xsd, grs, pdf, params); } catch (Exception e) { e.printStackTrace(); } File file = new File(pdf); byte[] bs = tryLoadFile(pdf); if (bs == null) throw new NullPointerException(); resp.setHeader("Content-Disposition", " filename=\"" + file.getName() + "\";"); resp.setContentLength(bs.length); InputStream is = new ByteArrayInputStream(bs); IOUtils.copy(is, resp.getOutputStream()); }
|
00
|
Code Sample 1:
@SuppressWarnings("static-access") public void run() { while (true) { try { thisThread.sleep(10000); } catch (InterruptedException e) { System.out.print("no connection"); } ++i; umat.flush(); umat = null; try { base = getDocumentBase(); username = getParameter("username"); } catch (Exception e) { } String userdat = "data/" + username + "_l.cod"; URL url = null; try { url = new URL(base, userdat); } catch (MalformedURLException e1) { } InputStream in = null; try { in = url.openStream(); } catch (IOException e1) { } BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(in)); } catch (Exception r) { } try { String line = reader.readLine(); StringTokenizer tokenizer = new StringTokenizer(line, " "); int dim = Integer.parseInt(tokenizer.nextToken().trim().toLowerCase()); this.topol = tokenizer.nextToken().trim().toLowerCase(); xunit = Integer.parseInt(tokenizer.nextToken().trim().toLowerCase()); yunit = Integer.parseInt(tokenizer.nextToken().trim().toLowerCase()); @SuppressWarnings("unused") String neigh = tokenizer.nextToken().trim().toLowerCase(); String label = null; labels = new String[xunit][yunit]; for (int e = 0; e < yunit; e++) { for (int r = 0; r < xunit; r++) { line = reader.readLine(); StringTokenizer tokenizer2 = new StringTokenizer(line, " "); for (int w = 0; w < dim; w++) { if (tokenizer2.countTokens() > 0) tokenizer2.nextToken(); } while (tokenizer2.countTokens() > 0) { label = tokenizer2.nextToken() + " "; } if (label == null) { labels[r][e] = "none"; } else { labels[r][e] = label; } label = null; } } reader.close(); if (topol.equals("hexa")) { xposit = new int[xunit][yunit]; yposit = new int[xunit][yunit]; double divisor1 = xunit; double divisor2 = yunit; for (int p = 0; p < xunit; p++) { for (int q = 0; q < yunit; q++) { if (q % 2 == 0) { double nenner = (p * width); xposit[p][q] = (int) Math.round(nenner / divisor1); } if (q % 2 != 0) { double nenner = (width * 0.5) + (p * width); xposit[p][q] = (int) Math.round(nenner / divisor1); } yposit[p][q] = (int) Math.round(((height * 0.5) + q * height) / divisor2); } } } if (topol.equals("rect")) { xposit = new int[xunit][yunit]; yposit = new int[xunit][yunit]; double divisor1 = xunit; double divisor2 = yunit; for (int p = 0; p < xunit; p++) { for (int q = 0; q < yunit; q++) { double nenner = (width * 0.5) + (p * width); xposit[p][q] = (int) Math.round((nenner / divisor1)); yposit[p][q] = (int) Math.round(((height * 0.5) + q * height) / divisor2); } } } } catch (IOException o) { } String userpng = "images/" + username + ".png"; mt.removeImage(umat); umat = getImage(base, userpng); mt.addImage(umat, 0); try { mt.waitForID(0); } catch (InterruptedException i) { showStatus("Interrupted"); } repaint(); } }
Code Sample 2:
public void testAutoCommit() throws Exception { Connection con = getConnectionOverrideProperties(new Properties()); try { Statement stmt = con.createStatement(); assertEquals(0, stmt.executeUpdate("create table #testAutoCommit (i int)")); con.setAutoCommit(false); assertEquals(1, stmt.executeUpdate("insert into #testAutoCommit (i) values (0)")); con.setAutoCommit(false); con.rollback(); assertEquals(1, stmt.executeUpdate("insert into #testAutoCommit (i) values (1)")); con.setAutoCommit(true); con.setAutoCommit(false); con.rollback(); con.setAutoCommit(true); ResultSet rs = stmt.executeQuery("select i from #testAutoCommit"); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); rs.close(); stmt.close(); } finally { con.close(); } }
|
00
|
Code Sample 1:
@Override public void alterar(QuestaoDiscursiva q) throws Exception { System.out.println("ALTERAR " + q.getIdQuestao()); PreparedStatement stmt = null; String sql = "UPDATE questao SET id_disciplina=?, enunciado=?, grau_dificuldade=? WHERE id_questao=?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getDisciplina().getIdDisciplina()); stmt.setString(2, q.getEnunciado()); stmt.setString(3, q.getDificuldade().name()); stmt.setInt(4, q.getIdQuestao()); stmt.executeUpdate(); conexao.commit(); alterarQuestaoDiscursiva(q); } catch (SQLException e) { conexao.rollback(); throw e; } }
Code Sample 2:
static void getGroupMember(String groupname) { try { URL url = new URL("http://www.lastfm.de/group/" + groupname + "/members"); URLConnection con = url.openConnection(); BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); HTMLEditorKit editorKit = new HTMLEditorKit(); HTMLDocument htmlDoc = new HTMLDocument(); htmlDoc.putProperty("IgnoreCharsetDirective", Boolean.TRUE); editorKit.read(br, htmlDoc, 0); Vector<String> a_tags = new Vector<String>(); HTMLDocument.Iterator iter = htmlDoc.getIterator(HTML.Tag.A); while (iter.isValid()) { a_tags.add((String) iter.getAttributes().getAttribute(HTML.Attribute.HREF)); iter.next(); } Vector<String> members = new Vector<String>(); for (int i = 0; i < a_tags.size(); i++) { String element = (String) a_tags.get(i); if (!members.contains(element)) { if (element.contains("/user/")) { members.add(element); } } } for (int a = 0; a < members.size(); a++) { String gruppe = members.elementAt(a).toString().substring(6); int b = gruppe.length() - 1; String membername = gruppe.toString().substring(0, b); DB_Groups.addGroupRelation(membername, groupname); User.getUserProfile_Stop(membername); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (BadLocationException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static String encrypt(String txt) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(txt.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
protected InputStream makeSignedRequestAndGetJSONData(String url) { try { if (consumer == null) loginOAuth(); } catch (Exception e) { consumer = null; e.printStackTrace(); } DefaultHttpClient httpClient = new DefaultHttpClient(); URI uri; InputStream data = null; try { uri = new URI(url); HttpGet method = new HttpGet(uri); consumer.sign(method); HttpResponse response = httpClient.execute(method); data = response.getEntity().getContent(); } catch (Exception e) { e.printStackTrace(); } return data; }
|
00
|
Code Sample 1:
public final void propertyChange(final PropertyChangeEvent event) { if (fChecker != null && event.getProperty().equals(ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY)) { if (fUserDictionary != null) { fChecker.removeDictionary(fUserDictionary); fUserDictionary = null; } final String file = (String) event.getNewValue(); if (file.length() > 0) { try { final URL url = new URL("file", null, file); InputStream stream = url.openStream(); if (stream != null) { try { fUserDictionary = new PersistentSpellDictionary(url); fChecker.addDictionary(fUserDictionary); } finally { stream.close(); } } } catch (MalformedURLException exception) { } catch (IOException exception) { } } } }
Code Sample 2:
public static void writeToFile(final File file, final InputStream in) throws IOException { IOUtils.createFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copyStream(in, fos); } finally { IOUtils.closeIO(fos); } }
|
11
|
Code Sample 1:
public void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; Closer c = new Closer(); try { source = c.register(new FileInputStream(sourceFile).getChannel()); destination = c.register(new FileOutputStream(destFile).getChannel()); destination.transferFrom(source, 0, source.size()); } catch (IOException e) { c.doNotThrow(); throw e; } finally { c.closeAll(); } }
Code Sample 2:
public void handleMessage(Message message) throws Fault { InputStream is = message.getContent(InputStream.class); if (is == null) { return; } CachedOutputStream bos = new CachedOutputStream(); try { IOUtils.copy(is, bos); is.close(); bos.close(); sendMsg("Inbound Message \n" + "--------------" + bos.getOut().toString() + "\n--------------"); message.setContent(InputStream.class, bos.getInputStream()); } catch (IOException e) { throw new Fault(e); } }
|
00
|
Code Sample 1:
public QueryResult doSearch(String searchTerm, Integer searchInReceivedItems, Integer searchInSentItems, Integer searchInSupervisedItems, Integer startRow, Integer resultCount, Boolean searchArchived, Boolean searchInItemsNeededAttentionOnly) throws UnsupportedEncodingException, IOException { String sessionId = (String) RuntimeAccess.getInstance().getSession().getAttribute("SESSION_ID"); DefaultHttpClient httpclient = new DefaultHttpClient(); QueryResult queryResult = new QueryResult(); SearchRequest request = new SearchRequest(); SearchItemsQuery query = new SearchItemsQuery(); query.setArchiveIncluded(searchArchived); log(INFO, "searchTerm=" + searchTerm); log(INFO, "search in received=" + searchInReceivedItems); log(INFO, "search in sent=" + searchInSentItems); log(INFO, "search in supervised=" + searchInSupervisedItems); List<String> filters = new ArrayList<String>(); if (searchInItemsNeededAttentionOnly == false) { if (searchInReceivedItems != null) { filters.add("ALL_RECEIVED_ITEMS"); } if (searchInSentItems != null) { filters.add("ALL_SENT_ITEMS"); } if (searchInSupervisedItems != null) { filters.add("ALL_SUPERVISED_ITEMS"); } } else { if (searchInReceivedItems != null) { filters.add("RECEIVED_ITEMS_NEEDED_ATTENTION"); } if (searchInSentItems != null) { filters.add("SENT_ITEMS_NEEDED_ATTENTION"); } } query.setFilters(filters); query.setId("1234"); query.setOwner(sessionId); query.setReferenceOnly(false); query.setSearchTerm(searchTerm); query.setUseOR(false); request.setStartRow(startRow); request.setResultCount(resultCount); request.setQuery(query); request.setSessionId(sessionId); XStream writer = new XStream(); writer.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); writer.alias("SearchRequest", SearchRequest.class); XStream reader = new XStream(); reader.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); reader.alias("SearchResponse", SearchResponse.class); String strRequest = URLEncoder.encode(reader.toXML(request), "UTF-8"); HttpGet httpget = new HttpGet(MewitProperties.getMewitUrl() + "/resources/search?REQUEST=" + strRequest); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { String result = URLDecoder.decode(EntityUtils.toString(entity), "UTF-8"); SearchResponse searchResponse = (SearchResponse) reader.fromXML(result); List<Item> items = searchResponse.getItems(); queryResult.setItems(items); queryResult.setTotal(searchResponse.getTotalResultCount()); queryResult.setStartRow(searchResponse.getStartRow()); } return queryResult; }
Code Sample 2:
public void run() { if (saveAsDialog == null) { saveAsDialog = new FileDialog(window.getShell(), SWT.SAVE); saveAsDialog.setFilterExtensions(saveAsTypes); } String outputFile = saveAsDialog.open(); if (outputFile != null) { Object inputFile = DataSourceSingleton.getInstance().getContainer().getWrapped(); InputStream in; try { if (inputFile instanceof URL) in = ((URL) inputFile).openStream(); else in = new FileInputStream((File) inputFile); OutputStream out = new FileOutputStream(outputFile); if (outputFile.endsWith("xml")) { int c; while ((c = in.read()) != -1) out.write(c); } else { PrintWriter pw = new PrintWriter(out); Element data = DataSourceSingleton.getInstance().getRawData(); writeTextFile(data, pw, -1); pw.close(); } in.close(); out.close(); } catch (MalformedURLException e1) { } catch (IOException e) { } } }
|
11
|
Code Sample 1:
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()); } }
Code Sample 2:
protected HttpResponseImpl makeRequest(final HttpMethod m, final String requestId) { try { HttpResponseImpl ri = new HttpResponseImpl(); ri.setRequestMethod(m); ri.setResponseCode(_client.executeMethod(m)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(m.getResponseBodyAsStream(), bos); ri.setResponseBody(bos.toByteArray()); notifyOfRequestSuccess(requestId, m, ri); return ri; } catch (HttpException ex) { notifyOfRequestFailure(requestId, m, ex); } catch (IOException ex) { notifyOfRequestFailure(requestId, m, ex); } return null; }
|
00
|
Code Sample 1:
protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { ChallengeAction challengeAction; ManagerResponse challengeResponse; String challenge; String key; LoginAction loginAction; ManagerResponse loginResponse; if (socket == null) { connect(); } synchronized (protocolIdentifier) { if (protocolIdentifier.value == null) { try { protocolIdentifier.wait(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (protocolIdentifier.value == null) { disconnect(); if (reader != null && reader.getTerminationException() != null) { throw reader.getTerminationException(); } else { throw new TimeoutException("Timeout waiting for protocol identifier"); } } } challengeAction = new ChallengeAction("MD5"); try { challengeResponse = sendAction(challengeAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send challenge action", e); } if (challengeResponse instanceof ChallengeResponse) { challenge = ((ChallengeResponse) challengeResponse).getChallenge(); } else { disconnect(); throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + challengeResponse.getMessage()); } try { MessageDigest md; md = MessageDigest.getInstance("MD5"); if (challenge != null) { md.update(challenge.getBytes()); } if (password != null) { md.update(password.getBytes()); } key = ManagerUtil.toHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { disconnect(); throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } loginAction = new LoginAction(username, "MD5", key, eventMask); try { loginResponse = sendAction(loginAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send login action", e); } if (loginResponse instanceof ManagerError) { disconnect(); throw new AuthenticationFailedException(loginResponse.getMessage()); } state = CONNECTED; logger.info("Successfully logged in"); version = determineVersion(); writer.setTargetVersion(version); logger.info("Determined Asterisk version: " + version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); }
Code Sample 2:
public void run() { try { URL url = new URL("http://mydiversite.appspot.com/version.html"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static void getResponseAsStream(String _url, Object _stringOrStream, OutputStream _stream, Map<String, String> _headers, Map<String, String> _params, String _contentType, int _timeout) throws IOException { if (_url == null || _url.length() <= 0) throw new IllegalArgumentException("Url can not be null."); String temp = _url.toLowerCase(); if (!temp.startsWith("http://") && !temp.startsWith("https://")) _url = "http://" + _url; _url = encodeURL(_url); HttpMethod method = null; if (_stringOrStream == null && (_params == null || _params.size() <= 0)) method = new GetMethod(_url); else method = new PostMethod(_url); HttpMethodParams methodParams = ((HttpMethodBase) method).getParams(); if (methodParams == null) { methodParams = new HttpMethodParams(); ((HttpMethodBase) method).setParams(methodParams); } if (_timeout < 0) methodParams.setSoTimeout(0); else methodParams.setSoTimeout(_timeout); if (_contentType != null && _contentType.length() > 0) { if (_headers == null) _headers = new HashMap<String, String>(); _headers.put("Content-Type", _contentType); } if (_headers == null || !_headers.containsKey("User-Agent")) { if (_headers == null) _headers = new HashMap<String, String>(); _headers.put("User-Agent", DEFAULT_USERAGENT); } if (_headers != null) { Iterator<Map.Entry<String, String>> iter = _headers.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); method.setRequestHeader((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof PostMethod && (_params != null && _params.size() > 0)) { Iterator<Map.Entry<String, String>> iter = _params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); ((PostMethod) method).addParameter((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof EntityEnclosingMethod && _stringOrStream != null) { if (_stringOrStream instanceof InputStream) { RequestEntity entity = new InputStreamRequestEntity((InputStream) _stringOrStream); ((EntityEnclosingMethod) method).setRequestEntity(entity); } else { RequestEntity entity = new StringRequestEntity(_stringOrStream.toString(), _contentType, null); ((EntityEnclosingMethod) method).setRequestEntity(entity); } } HttpClient httpClient = new HttpClient(new org.apache.commons.httpclient.SimpleHttpConnectionManager()); httpClient.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); InputStream instream = null; try { int status = httpClient.executeMethod(method); if (status != HttpStatus.SC_OK) { LOG.warn("Http Satus:" + status + ",Url:" + _url); if (status >= 500 && status < 600) throw new IOException("Remote service<" + _url + "> respose a error, status:" + status); } instream = method.getResponseBodyAsStream(); IOUtils.copy(instream, _stream); } catch (IOException err) { LOG.error("Failed to access " + _url, err); throw err; } finally { IOUtils.closeQuietly(instream); if (method != null) method.releaseConnection(); } }
|
11
|
Code Sample 1:
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; } }
Code Sample 2:
public byte[] getResponseContent() throws IOException { if (responseContent == null) { InputStream is = getResponseStream(); if (is == null) { responseContent = new byte[0]; } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); IOUtils.copy(is, baos); responseContent = baos.toByteArray(); } } return responseContent; }
|
11
|
Code Sample 1:
public void testAllowClosingInputStreamTwice() throws IOException { OutputStream outputStream = fileSystem.createOutputStream(_("hello"), OutputMode.OVERWRITE); outputStream.write(new byte[] { 1, 2, 3 }); outputStream.close(); InputStream inputStream = fileSystem.createInputStream(_("hello")); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copy(inputStream, buffer); inputStream.close(); inputStream.close(); }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
00
|
Code Sample 1:
List<String> options(String path) throws TwinException { try { BasicHttpRequest request = new BasicHttpRequest("OPTIONS", url + path); HttpClient client = getClient(); HttpResponse response = client.execute(new HttpHost(url.getHost(), url.getPort()), request); Header hdr = response.getFirstHeader("Allow"); if (hdr == null || hdr.getValue().isEmpty()) return Collections.emptyList(); return Arrays.asList(hdr.getValue().split("\\s*,\\s*")); } catch (IOException e) { throw TwinError.UnknownError.create("IOException when accessing RC", e); } }
Code Sample 2:
public void readURL(URL url) throws IOException, ParserConfigurationException, SAXException { URLConnection connection; if (proxy == null) { connection = url.openConnection(); } else { connection = url.openConnection(proxy); } connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(readTimeout); connection.connect(); InputStream in = connection.getInputStream(); readInputStream(in); }
|
00
|
Code Sample 1:
public Boolean compress(String sSourceDir, ArrayList<String> aFiles, String sDestinationFilename) { logger.debug("compress(%s, %s, %s)", sSourceDir, aFiles, sDestinationFilename); BufferedInputStream oOrigin = null; FileOutputStream oDestination; ZipOutputStream oOutput = null; Iterator<String> oIterator; byte[] aData; try { oDestination = new FileOutputStream(sDestinationFilename); oOutput = new ZipOutputStream(new BufferedOutputStream(oDestination)); aData = new byte[BUFFER_SIZE]; oIterator = aFiles.iterator(); while (oIterator.hasNext()) { try { String sFilename = (String) oIterator.next(); FileInputStream fisInput = new FileInputStream(sSourceDir + File.separator + sFilename); oOrigin = new BufferedInputStream(fisInput, BUFFER_SIZE); ZipEntry oEntry = new ZipEntry(sFilename.replace('\\', '/')); oOutput.putNextEntry(oEntry); int iCount; while ((iCount = oOrigin.read(aData, 0, BUFFER_SIZE)) != -1) oOutput.write(aData, 0, iCount); } finally { StreamHelper.close(oOrigin); } } } catch (Exception oException) { logger.error(oException.getMessage(), oException); return false; } finally { StreamHelper.close(oOutput); } return true; }
Code Sample 2:
public String calcMD5(String sequence) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md5.update(sequence.toString().toUpperCase().getBytes()); BigInteger md5hash = new BigInteger(1, md5.digest()); String sequence_md5 = md5hash.toString(16); while (sequence_md5.length() < 32) { sequence_md5 = "0" + sequence_md5; } return sequence_md5; }
|
11
|
Code Sample 1:
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(); }
Code Sample 2:
private void addMaintainerScripts(TarOutputStream tar, PackageInfo info) throws IOException, ScriptDataTooLargeException { for (final MaintainerScript script : info.getMaintainerScripts().values()) { if (script.getSize() > Integer.MAX_VALUE) { throw new ScriptDataTooLargeException("The script data is too large for the tar file. script=[" + script.getType().getFilename() + "]."); } final TarEntry entry = standardEntry(script.getType().getFilename(), UnixStandardPermissions.EXECUTABLE_FILE_MODE, (int) script.getSize()); tar.putNextEntry(entry); IOUtils.copy(script.getStream(), tar); tar.closeEntry(); } }
|
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 BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
|
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:
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 digest(String text, String algorithm, String charsetName) { try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(text.getBytes(charsetName), 0, text.length()); return convertToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("unexpected exception: " + e, e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("unexpected exception: " + e, e); } }
Code Sample 2:
public 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"); }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
private JButton getButtonImagen() { if (buttonImagen == null) { buttonImagen = new JButton(); buttonImagen.setText(Messages.getString("gui.AdministracionResorces.6")); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetree.png"))); buttonImagen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } } }); } return buttonImagen; }
|
00
|
Code Sample 1:
public void run() { date = DateUtil.addMonth(-1); List list = bo.getDao().getHibernateTemplate().find("from MailAffixPojo where upload_time <'" + date + "' and to_number(sized) >" + size); if (null != list && list.size() > 0) { try { FTPClient ftp = new FTPClient(); ftp.connect(config.getHostUrl(), config.getFtpPort()); ftp.login(config.getUname(), config.getUpass()); int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { ftp.disconnect(); return; } for (int i = 0; i < list.size(); i++) { MailAffixPojo pojo = (MailAffixPojo) list.get(i); ftp.changeWorkingDirectory(pojo.getUploadTime().substring(0, 7)); ftp.deleteFile(pojo.getAffixSaveName()); ftp.changeToParentDirectory(); bo.delete(MailAffixPojo.class, new Long(pojo.getId())); } } catch (Exception e) { e.printStackTrace(); } } }
Code Sample 2:
public void testStorageByteArray() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); { OutputStream output = r.getOutputStream(); output.write("This is an example".getBytes("UTF-8")); output.write(" and another one.".getBytes("UTF-8")); assertEquals("This is an example and another one.", r.getText()); } { InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); } { OutputStream output = r.getOutputStream(); output.write(" and another line".getBytes("UTF-8")); assertEquals("This is an example and another one. and another line", r.getText()); } { Writer output = r.getWriter(); output.write(" and write some more"); assertEquals("This is an example and another one. and another line and write some more", r.getText()); } { r.addText(" and even more."); assertEquals("This is an example and another one. and another line and write some more and even more.", r.getText()); } assertFalse(r.hasEnded()); r.setEndState(ResponseStateOk.getInstance()); assertTrue(r.hasEnded()); try { r.getOutputStream(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } try { r.getWriter(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } }
|
00
|
Code Sample 1:
private void downloadFtp(File file, URL jurl) throws SocketException, IOException { System.out.println("downloadFtp(" + file + ", " + jurl + ")"); FTPClient client = new FTPClient(); client.addProtocolCommandListener(new ProtocolCommandListener() { public void protocolCommandSent(ProtocolCommandEvent event) { System.out.println("downloadFtp: " + event.getMessage()); } public void protocolReplyReceived(ProtocolCommandEvent event) { System.out.println("downloadFtp: " + event.getMessage()); } }); try { client.connect(jurl.getHost(), -1 == jurl.getPort() ? FTP.DEFAULT_PORT : jurl.getPort()); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { client.disconnect(); throw new IOException("FTP server refused connection."); } if (!client.login("anonymous", "anonymous")) { client.logout(); throw new IOException("Authentication failure."); } client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); FileOutputStream out = new FileOutputStream(file); boolean ok = client.retrieveFile(jurl.getPath(), out); out.close(); client.logout(); if (!ok) { throw new IOException("File transfer failure."); } } catch (IOException e) { throw e; } finally { if (client.isConnected()) { try { client.disconnect(); } catch (IOException e) { } } } }
Code Sample 2:
public static void main(String argv[]) { try { if (argv.length != 1 && argv.length != 3) { usage(); System.exit(1); } URL url = new URL(argv[0]); URLConnection conn; conn = url.openConnection(); if (conn.getHeaderField("WWW-Authenticate") != null) { auth(conn, argv[1], argv[2]); } else { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) System.out.println(line); } } catch (Exception ex) { ex.printStackTrace(); } }
|
00
|
Code Sample 1:
String fetch_m3u(String m3u) { InputStream pstream = null; if (m3u.startsWith("http://")) { try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), m3u); else url = new URL(m3u); URLConnection urlc = url.openConnection(); pstream = urlc.getInputStream(); } catch (Exception ee) { System.err.println(ee); return null; } } if (pstream == null && !running_as_applet) { try { pstream = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + m3u); } catch (Exception ee) { System.err.println(ee); return null; } } String line = null; while (true) { try { line = readline(pstream); } catch (Exception e) { } if (line == null) break; return line; } return null; }
Code Sample 2:
private static void compressZip(String source, String dest) throws Exception { File baseFolder = new File(source); if (baseFolder.exists()) { if (baseFolder.isDirectory()) { List<File> fileList = getSubFiles(new File(source)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest)); zos.setEncoding("GBK"); ZipEntry entry = null; byte[] buf = new byte[2048]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { File file = fileList.get(i); if (file.isDirectory()) { entry = new ZipEntry(getAbsFileName(source, file) + "/"); } else { entry = new ZipEntry(getAbsFileName(source, file)); } entry.setSize(file.length()); entry.setTime(file.lastModified()); zos.putNextEntry(entry); if (file.isFile()) { InputStream in = new BufferedInputStream(new FileInputStream(file)); while ((readLen = in.read(buf, 0, 1024)) != -1) { zos.write(buf, 0, readLen); } in.close(); } } zos.close(); } else { throw new Exception("Can not do this operation!."); } } else { baseFolder.mkdirs(); compressZip(source, dest); } }
|
00
|
Code Sample 1:
public static String hashPassword(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); byte result[] = md5.digest("InTeRlOgY".getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < result.length; i++) { String s = Integer.toHexString(result[i]); int length = s.length(); if (length >= 2) { sb.append(s.substring(length - 2, length)); } else { sb.append("0"); sb.append(s); } } return "{md5}" + sb.toString(); } catch (NoSuchAlgorithmException e) { return password; } }
Code Sample 2:
private Document parseResponse(String url) throws IOException, MalformedURLException, ParserConfigurationException, SAXException { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputStream stream = null; try { stream = new URL(url).openStream(); return db.parse(stream); } finally { PetstoreUtil.closeIgnoringException(stream); } }
|
00
|
Code Sample 1:
public static String encrypt(String value) { MessageDigest messageDigest; byte[] raw = null; try { messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(((String) value).getBytes("UTF-8")); raw = messageDigest.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return (new BASE64Encoder()).encode(raw); }
Code Sample 2:
public void test() throws Exception { StorageString s = new StorageString("UTF-8"); s.addText("Test"); try { s.getOutputStream(); fail("Should throw IOException as method not supported."); } catch (IOException e) { } try { s.getWriter(); fail("Should throw IOException as method not supported."); } catch (IOException e) { } s.addText("ing is important"); s.close(ResponseStateOk.getInstance()); assertEquals("Testing is important", s.getText()); InputStream input = s.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer, "UTF-8"); assertEquals("Testing is important", writer.toString()); }
|
00
|
Code Sample 1:
private static void download(String urlString) throws IOException { URL url = new URL(urlString); url = handleRedirectUrl(url); URLConnection cn = url.openConnection(); Utils.setHeader(cn); long fileLength = cn.getContentLength(); Statics.getInstance().setFileLength(fileLength); long packageLength = fileLength / THREAD_COUNT; long leftLength = fileLength % THREAD_COUNT; String fileName = Utils.decodeURLFileName(url); RandomAccessFile file = new RandomAccessFile(fileName, "rw"); System.out.println("File: " + fileName + ", Size: " + Utils.calSize(fileLength)); CountDownLatch latch = new CountDownLatch(THREAD_COUNT + 1); long pos = 0; for (int i = 0; i < THREAD_COUNT; i++) { long endPos = pos + packageLength; if (leftLength > 0) { endPos++; leftLength--; } new Thread(new DownloadThread(latch, url, file, pos, endPos)).start(); pos = endPos; } new Thread(new MoniterThread(latch)).start(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } }
Code Sample 2:
protected String getPageText(final String url) { StringBuilder b = new StringBuilder(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String line = null; while ((line = reader.readLine()) != null) { b.append(line).append('\n'); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { ex.printStackTrace(); } } } return b.toString(); }
|
00
|
Code Sample 1:
public synchronized void readModels(Project p, URL url) throws IOException { _proj = p; Argo.log.info("======================================="); Argo.log.info("== READING MODEL " + url); try { XMIReader reader = new XMIReader(); InputSource source = new InputSource(url.openStream()); source.setSystemId(url.toString()); _curModel = reader.parse(source); if (reader.getErrors()) { throw new IOException("XMI file " + url.toString() + " could not be parsed."); } _UUIDRefs = new HashMap(reader.getXMIUUIDToObjectMap()); } catch (SAXException saxEx) { Exception ex = saxEx.getException(); if (ex == null) { saxEx.printStackTrace(); } else { ex.printStackTrace(); } } catch (Exception ex) { ex.printStackTrace(); } Argo.log.info("======================================="); try { _proj.addModel((ru.novosoft.uml.foundation.core.MNamespace) _curModel); } catch (PropertyVetoException ex) { System.err.println("An error occurred adding the model to the project!"); ex.printStackTrace(); } Collection ownedElements = _curModel.getOwnedElements(); Iterator oeIterator = ownedElements.iterator(); while (oeIterator.hasNext()) { MModelElement me = (MModelElement) oeIterator.next(); if (me instanceof MClass) { _proj.defineType((MClass) me); } else if (me instanceof MDataType) { _proj.defineType((MDataType) me); } } }
Code Sample 2:
public void insert() throws Exception { Connection con = DbUtil.connectToDb(); PreparedStatement pStmt = null; try { pStmt = con.prepareStatement("INSERT INTO " + Constants.TABLENAME + " (name,phone,address)" + " values(?,?,?)"); con.setAutoCommit(false); pStmt.setString(1, name); pStmt.setString(2, phone); pStmt.setString(3, address); int j = pStmt.executeUpdate(); con.commit(); } catch (Exception ex) { try { con.rollback(); } catch (SQLException sqlex) { sqlex.printStackTrace(System.out); } throw ex; } finally { try { pStmt.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } } }
|
00
|
Code Sample 1:
private static InputStream connect(final String url) throws IOException { InputStream in = null; try { final URLConnection conn = new URL(url).openConnection(); conn.setConnectTimeout(YahooGeocoding.connectTimeOut); conn.setReadTimeout(YahooGeocoding.readTimeOut); conn.setRequestProperty("User-Agent", YahooGeocoding.USER_AGENT); in = conn.getInputStream(); return in; } catch (final IOException e) { Util.d("problems connecting to geonames url " + url + "Exception:" + e); } return in; }
Code Sample 2:
public static List<PluginInfo> getPluginInfos(String urlRepo) throws MalformedURLException, IOException { XStream xStream = new XStream(); xStream.alias("plugin", PluginInfo.class); xStream.alias("plugins", List.class); List<PluginInfo> infos = null; URL url; BufferedReader in = null; StringBuilder buffer = new StringBuilder(); try { url = new URL(urlRepo); in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { buffer.append(inputLine); } } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { Logger.getLogger(RemotePluginsManager.class.getName()).log(Level.SEVERE, null, ex); } } infos = (List<PluginInfo>) xStream.fromXML(buffer.toString()); return infos; }
|
11
|
Code Sample 1:
public static boolean writeFileByBinary(InputStream pIs, File pFile, boolean pAppend) { boolean flag = false; try { FileOutputStream fos = new FileOutputStream(pFile, pAppend); IOUtils.copy(pIs, fos); fos.flush(); fos.close(); pIs.close(); flag = true; } catch (Exception e) { LOG.error("将字节流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; }
Code Sample 2:
@Override public RServiceResponse execute(final NexusServiceRequest inData) throws NexusServiceException { final RServiceRequest data = (RServiceRequest) inData; final RServiceResponse retval = new RServiceResponse(); final StringBuilder result = new StringBuilder("R service call results:\n"); RSession session; RConnection connection = null; try { result.append("Session Attachment: \n"); final byte[] sessionBytes = data.getSession(); if (sessionBytes != null && sessionBytes.length > 0) { session = RUtils.getInstance().bytesToSession(sessionBytes); result.append(" attaching to " + session + "\n"); connection = session.attach(); } else { result.append(" creating new session\n"); connection = new RConnection(data.getServerAddress()); } result.append("Input Parameters: \n"); for (String attributeName : data.getInputVariables().keySet()) { final Object parameter = data.getInputVariables().get(attributeName); if (parameter instanceof URI) { final FileObject file = VFS.getManager().resolveFile(((URI) parameter).toString()); final RFileOutputStream ros = connection.createFile(file.getName().getBaseName()); IOUtils.copy(file.getContent().getInputStream(), ros); connection.assign(attributeName, file.getName().getBaseName()); } else { connection.assign(attributeName, RUtils.getInstance().convertToREXP(parameter)); } result.append(" " + parameter.getClass().getSimpleName() + " " + attributeName + "=" + parameter + "\n"); } final REXP rExpression = connection.eval(RUtils.getInstance().wrapCode(data.getCode().replace('\r', '\n'))); result.append("Execution results:\n" + rExpression.asString() + "\n"); if (rExpression.isNull() || rExpression.asString().startsWith("Error")) { retval.setErr(rExpression.asString()); throw new NexusServiceException("R error: " + rExpression.asString()); } result.append("Output Parameters:\n"); final String[] rVariables = connection.eval("ls();").asStrings(); for (String varname : rVariables) { final String[] rVariable = connection.eval("class(" + varname + ")").asStrings(); if (rVariable.length == 2 && "file".equals(rVariable[0]) && "connection".equals(rVariable[1])) { final String rFileName = connection.eval("showConnections(TRUE)[" + varname + "]").asString(); result.append(" R File ").append(varname).append('=').append(rFileName).append('\n'); final RFileInputStream rInputStream = connection.openFile(rFileName); final File file = File.createTempFile("nexus-" + data.getRequestId(), ".dat"); IOUtils.copy(rInputStream, new FileOutputStream(file)); retval.getOutputVariables().put(varname, file.getCanonicalFile().toURI()); } else { final Object varvalue = RUtils.getInstance().convertREXP(connection.eval(varname)); retval.getOutputVariables().put(varname, varvalue); final String printValue = varvalue == null ? "null" : varvalue.getClass().isArray() ? Arrays.asList(varvalue).toString() : varvalue.toString(); result.append(" ").append(varvalue == null ? "" : varvalue.getClass().getSimpleName()).append(' ').append(varname).append('=').append(printValue).append('\n'); } } } catch (ClassNotFoundException cnfe) { retval.setErr(cnfe.getMessage()); LOGGER.error("Rserve Exception", cnfe); } catch (RserveException rse) { retval.setErr(rse.getMessage()); LOGGER.error("Rserve Exception", rse); } catch (REXPMismatchException rme) { retval.setErr(rme.getMessage()); LOGGER.error("REXP Mismatch Exception", rme); } catch (IOException rme) { retval.setErr(rme.getMessage()); LOGGER.error("IO Exception copying file ", rme); } finally { result.append("Session Detachment:\n"); if (connection != null) { RSession outSession; if (retval.isKeepSession()) { try { outSession = connection.detach(); } catch (RserveException e) { LOGGER.debug("Error detaching R session", e); outSession = null; } } else { outSession = null; } final boolean close = outSession == null; if (!close) { retval.setSession(RUtils.getInstance().sessionToBytes(outSession)); result.append(" suspended session for later use\n"); } connection.close(); retval.setSession(null); result.append(" session closed.\n"); } } retval.setOut(result.toString()); return retval; }
|
11
|
Code Sample 1:
private void exportJar(File root, List<File> list, Manifest manifest) throws Exception { JarOutputStream jarOut = null; FileInputStream fin = null; try { jarOut = new JarOutputStream(new FileOutputStream(jarFile), manifest); for (int i = 0; i < list.size(); i++) { String filename = list.get(i).getAbsolutePath(); filename = filename.substring(root.getAbsolutePath().length() + 1); fin = new FileInputStream(list.get(i)); JarEntry entry = new JarEntry(filename.replace('\\', '/')); jarOut.putNextEntry(entry); byte[] buf = new byte[4096]; int read; while ((read = fin.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); jarOut.flush(); } } finally { if (fin != null) { try { fin.close(); } catch (Exception e) { ExceptionOperation.operate(e); } } if (jarOut != null) { try { jarOut.close(); } catch (Exception e) { } } } }
Code Sample 2:
public static void copyFile(File sourceFile, File destFile) throws IOException { log.info("Copying file '" + sourceFile + "' to '" + destFile + "'"); if (!sourceFile.isFile()) { throw new IllegalArgumentException("The sourceFile '" + sourceFile + "' does not exist or is not a normal file."); } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); long numberOfBytes = destination.transferFrom(source, 0, source.size()); log.debug("Transferred " + numberOfBytes + " bytes from '" + sourceFile + "' to '" + destFile + "'."); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
00
|
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:
private void doDissemTest(String what, boolean redirectOK) throws Exception { final int num = 30; System.out.println("Getting " + what + " " + num + " times..."); int i = 0; try { URL url = new URL(BASE_URL + "/get/" + what); for (i = 0; i < num; i++) { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream in = conn.getInputStream(); in.read(); in.close(); conn.disconnect(); } } catch (Exception e) { fail("Dissemination of " + what + " failed on iter " + i + ": " + e.getMessage()); } }
|
00
|
Code Sample 1:
public void run() { LogPrinter.log(Level.FINEST, "Started Download at : {0, date, long}", new Date()); if (!PipeConnected) { throw new IllegalStateException("You should connect the pipe before with getInputStream()"); } InputStream ins = null; if (IsAlreadyDownloaded) { LogPrinter.log(Level.FINEST, "The file already Exists open and foward the byte"); try { ContentLength = (int) TheAskedFile.length(); ContentType = URLConnection.getFileNameMap().getContentTypeFor(TheAskedFile.getName()); ins = new FileInputStream(TheAskedFile); byte[] buffer = new byte[BUFFER_SIZE]; int read = ins.read(buffer); while (read >= 0) { Pipe.write(buffer, 0, read); read = ins.read(buffer); } } catch (IOException e) { e.printStackTrace(); } finally { if (ins != null) { try { ins.close(); } catch (IOException e) { } } } } else { LogPrinter.log(Level.FINEST, "the file does not exist locally so we try to download the thing"); File theDir = TheAskedFile.getParentFile(); if (!theDir.exists()) { theDir.mkdirs(); } for (URL url : ListFastest) { FileOutputStream fout = null; boolean OnError = false; long timestart = System.currentTimeMillis(); long bytecount = 0; try { URL newUrl = new URL(url.toString() + RequestedFile); LogPrinter.log(Level.FINEST, "the download URL = {0}", newUrl); URLConnection conn = newUrl.openConnection(); ContentType = conn.getContentType(); ContentLength = conn.getContentLength(); ins = conn.getInputStream(); fout = new FileOutputStream(TheAskedFile); byte[] buffer = new byte[BUFFER_SIZE]; int read = ins.read(buffer); while (read >= 0) { fout.write(buffer, 0, read); Pipe.write(buffer, 0, read); read = ins.read(buffer); bytecount += read; } Pipe.flush(); } catch (IOException e) { OnError = true; } finally { if (ins != null) { try { ins.close(); } catch (IOException e) { } } if (fout != null) { try { fout.close(); } catch (IOException e) { } } } long timeend = System.currentTimeMillis(); if (OnError) { continue; } else { long timetook = timeend - timestart; BigDecimal speed = new BigDecimal(bytecount).multiply(new BigDecimal(1000)).divide(new BigDecimal(timetook), MathContext.DECIMAL32); for (ReportCalculatedStatistique report : Listener) { report.reportUrlStat(url, speed, timetook); } break; } } } LogPrinter.log(Level.FINEST, "download finished at {0,date,long}", new Date()); if (Pipe != null) { try { Pipe.close(); } catch (IOException e) { e.printStackTrace(); } } }
Code Sample 2:
public void removeRoom(int thisRoom) { DBConnection con = null; try { con = DBServiceManager.allocateConnection(); con.setAutoCommit(false); String query = "DELETE FROM cafe_Chat_Category WHERE cafe_Chat_Category_id=? "; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, thisRoom); ps.executeUpdate(); query = "DELETE FROM cafe_Chatroom WHERE cafe_chatroom_category=? "; ps = con.prepareStatement(query); ps.setInt(1, thisRoom); ps.executeUpdate(); con.commit(); con.setAutoCommit(true); } catch (SQLException e) { try { con.rollback(); } catch (SQLException sqle) { } } finally { if (con != null) con.release(); } }
|
00
|
Code Sample 1:
private HttpURLConnection getHttpURLConnection(String bizDocToExecute) { StringBuffer servletURL = new StringBuffer(); servletURL.append(getBaseServletURL()); servletURL.append("?_BIZVIEW=").append(bizDocToExecute); Map<String, Object> inputParms = getInputParams(); if (inputParms != null) { Set<Entry<String, Object>> entrySet = inputParms.entrySet(); for (Entry<String, Object> entry : entrySet) { String name = entry.getKey(); String value = entry.getValue().toString(); servletURL.append("&").append(name).append("=").append(value); } } HttpURLConnection connection = null; try { URL url = new URL(servletURL.toString()); connection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { Assert.fail("Failed to connect to the test servlet: " + e); } return connection; }
Code Sample 2:
public synchronized String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { log().error("failed to encrypt the password.", e); throw new RuntimeException("failed to encrypt the password.", e); } catch (UnsupportedEncodingException e) { log().error("failed to encrypt the password.", e); throw new RuntimeException("failed to encrypt the password.", e); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
|
11
|
Code Sample 1:
private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { GTLogger.getInstance().error(e); } } catch (FileNotFoundException e) { GTLogger.getInstance().error(e); } }
Code Sample 2:
public static boolean copyFile(String fromfile, String tofile) { File from = new File(fromfile); File to = new File(tofile); if (!from.exists()) return false; if (to.exists()) { log.error(tofile + "exists already"); return false; } BufferedInputStream in = null; BufferedOutputStream out = null; FileInputStream fis = null; FileOutputStream ois = null; boolean flag = true; try { to.createNewFile(); fis = new FileInputStream(from); ois = new FileOutputStream(to); in = new BufferedInputStream(fis); out = new BufferedOutputStream(ois); byte[] buf = new byte[2048]; int readBytes = 0; while ((readBytes = in.read(buf, 0, buf.length)) != -1) { out.write(buf, 0, readBytes); } } catch (IOException e) { log.error(e); flag = false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { log.error(e); flag = false; } } return flag; }
|
11
|
Code Sample 1:
public boolean executeUpdate(String strSql) throws SQLException { getConnection(); boolean flag = false; stmt = con.createStatement(); logger.info("###############::执行SQL语句操作(更新数据 无参数):" + strSql); try { if (0 < stmt.executeUpdate(strSql)) { close_DB_Object(); flag = true; con.commit(); } } catch (SQLException ex) { logger.info("###############Error DBManager Line126::执行SQL语句操作(更新数据 无参数):" + strSql + "失败!"); flag = false; con.rollback(); throw ex; } return flag; }
Code Sample 2:
public synchronized void insertMessage(FrostUnsentMessageObject mo) throws SQLException { AttachmentList files = mo.getAttachmentsOfType(Attachment.FILE); AttachmentList boards = mo.getAttachmentsOfType(Attachment.BOARD); Connection conn = AppLayerDatabase.getInstance().getPooledConnection(); try { conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("INSERT INTO UNSENDMESSAGES (" + "primkey,messageid,inreplyto,board,sendafter,idlinepos,idlinelen,fromname,subject,recipient,msgcontent," + "hasfileattachment,hasboardattachment,timeAdded" + ") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); Long identity = null; Statement stmt = AppLayerDatabase.getInstance().createStatement(); ResultSet rs = stmt.executeQuery("select UNIQUEKEY('UNSENDMESSAGES')"); if (rs.next()) { identity = new Long(rs.getLong(1)); } else { logger.log(Level.SEVERE, "Could not retrieve a new unique key!"); } rs.close(); stmt.close(); mo.setMsgIdentity(identity.longValue()); int i = 1; ps.setLong(i++, mo.getMsgIdentity()); ps.setString(i++, mo.getMessageId()); ps.setString(i++, mo.getInReplyTo()); ps.setInt(i++, mo.getBoard().getPrimaryKey().intValue()); ps.setLong(i++, 0); ps.setInt(i++, mo.getIdLinePos()); ps.setInt(i++, mo.getIdLineLen()); ps.setString(i++, mo.getFromName()); ps.setString(i++, mo.getSubject()); ps.setString(i++, mo.getRecipientName()); ps.setString(i++, mo.getContent()); ps.setBoolean(i++, (files.size() > 0)); ps.setBoolean(i++, (boards.size() > 0)); ps.setLong(i++, mo.getTimeAdded()); int inserted = 0; try { inserted = ps.executeUpdate(); } finally { ps.close(); } if (inserted == 0) { logger.log(Level.SEVERE, "message insert returned 0 !!!"); return; } mo.setMsgIdentity(identity.longValue()); if (files.size() > 0) { PreparedStatement p = conn.prepareStatement("INSERT INTO UNSENDFILEATTACHMENTS" + " (msgref,filename,filesize,filekey)" + " VALUES (?,?,?,?)"); for (Iterator it = files.iterator(); it.hasNext(); ) { FileAttachment fa = (FileAttachment) it.next(); int ix = 1; p.setLong(ix++, mo.getMsgIdentity()); p.setString(ix++, fa.getInternalFile().getPath()); p.setLong(ix++, fa.getFileSize()); p.setString(ix++, fa.getKey()); int ins = p.executeUpdate(); if (ins == 0) { logger.log(Level.SEVERE, "fileattachment insert returned 0 !!!"); } } p.close(); } if (boards.size() > 0) { PreparedStatement p = conn.prepareStatement("INSERT INTO UNSENDBOARDATTACHMENTS" + " (msgref,boardname,boardpublickey,boardprivatekey,boarddescription)" + " VALUES (?,?,?,?,?)"); for (Iterator it = boards.iterator(); it.hasNext(); ) { BoardAttachment ba = (BoardAttachment) it.next(); Board b = ba.getBoardObj(); int ix = 1; p.setLong(ix++, mo.getMsgIdentity()); p.setString(ix++, b.getNameLowerCase()); p.setString(ix++, b.getPublicKey()); p.setString(ix++, b.getPrivateKey()); p.setString(ix++, b.getDescription()); int ins = p.executeUpdate(); if (ins == 0) { logger.log(Level.SEVERE, "boardattachment insert returned 0 !!!"); } } p.close(); } conn.commit(); conn.setAutoCommit(true); } catch (Throwable t) { logger.log(Level.SEVERE, "Exception during insert of unsent message", t); try { conn.rollback(); } catch (Throwable t1) { logger.log(Level.SEVERE, "Exception during rollback", t1); } try { conn.setAutoCommit(true); } catch (Throwable t1) { } } finally { AppLayerDatabase.getInstance().givePooledConnection(conn); } }
|
11
|
Code Sample 1:
private static void loadFromZip() { InputStream in = Resources.class.getResourceAsStream("data.zip"); if (in == null) { return; } ZipInputStream zipIn = new ZipInputStream(in); try { while (true) { ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { break; } String entryName = entry.getName(); if (!entryName.startsWith("/")) { entryName = "/" + entryName; } ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(zipIn, out); zipIn.closeEntry(); FILES.put(entryName, out.toByteArray()); } zipIn.close(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
11
|
Code Sample 1:
@SuppressWarnings("unchecked") public static void zip(String input, OutputStream out) { File file = new File(input); ZipOutputStream zip = null; FileInputStream in = null; try { if (file.exists()) { Collection<File> items = new ArrayList(); if (file.isDirectory()) { items = FileUtils.listFiles(file, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); zip = new ZipOutputStream(out); zip.putNextEntry(new ZipEntry(file.getName() + "/")); Iterator iter = items.iterator(); while (iter.hasNext()) { File item = (File) iter.next(); in = new FileInputStream(item); zip.putNextEntry(new ZipEntry(file.getName() + "/" + item.getName())); IOUtils.copy(in, zip); IOUtils.closeQuietly(in); zip.closeEntry(); } IOUtils.closeQuietly(zip); } } else { log.info("-->>���ļ���û���ļ�"); } } catch (Exception e) { log.error("����ѹ��" + input + "�������", e); throw new RuntimeException("����ѹ��" + input + "�������", e); } finally { try { if (null != zip) { zip.close(); zip = null; } if (null != in) { in.close(); in = null; } } catch (Exception e) { log.error("�ر��ļ�������"); } } }
Code Sample 2:
public static long copy(File src, File dest) throws UtilException { FileChannel srcFc = null; FileChannel destFc = null; try { srcFc = new FileInputStream(src).getChannel(); destFc = new FileOutputStream(dest).getChannel(); long srcLength = srcFc.size(); srcFc.transferTo(0, srcLength, destFc); return srcLength; } catch (IOException e) { throw new UtilException(e); } finally { try { if (srcFc != null) srcFc.close(); srcFc = null; } catch (IOException e) { } try { if (destFc != null) destFc.close(); destFc = null; } catch (IOException e) { } } }
|
11
|
Code Sample 1:
public void run(Preprocessor pp) throws SijappException { for (int i = 0; i < this.filenames.length; i++) { File srcFile = new File(this.srcDir, this.filenames[i]); BufferedReader reader; try { InputStreamReader isr = new InputStreamReader(new FileInputStream(srcFile), "CP1251"); reader = new BufferedReader(isr); } catch (Exception e) { throw (new SijappException("File " + srcFile.getPath() + " could not be read")); } File destFile = new File(this.destDir, this.filenames[i]); BufferedWriter writer; try { (new File(destFile.getParent())).mkdirs(); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(destFile), "CP1251"); writer = new BufferedWriter(osw); } catch (Exception e) { throw (new SijappException("File " + destFile.getPath() + " could not be written")); } try { pp.run(reader, writer); } catch (SijappException e) { try { reader.close(); } catch (IOException f) { } try { writer.close(); } catch (IOException f) { } try { destFile.delete(); } catch (SecurityException f) { } throw (new SijappException(srcFile.getPath() + ":" + e.getMessage())); } try { reader.close(); } catch (IOException e) { } try { writer.close(); } catch (IOException e) { } } }
Code Sample 2:
@Override public void render(Output output) throws IOException { output.setStatus(headersFile.getStatusCode(), headersFile.getStatusMessage()); for (Entry<String, Set<String>> header : headersFile.getHeadersMap().entrySet()) { Set<String> values = header.getValue(); for (String value : values) { output.addHeader(header.getKey(), value); } } if (file != null) { InputStream inputStream = new FileInputStream(file); try { output.open(); OutputStream out = output.getOutputStream(); IOUtils.copy(inputStream, out); } finally { inputStream.close(); output.close(); } } }
|
11
|
Code Sample 1:
public void writeFile(OutputStream outputStream) throws IOException { InputStream inputStream = null; if (file != null) { try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, outputStream); } finally { if (inputStream != null) { IOUtils.closeQuietly(inputStream); } } } }
Code Sample 2:
public List<SuspectFileProcessingStatus> retrieve() throws Exception { BufferedOutputStream bos = null; try { String listFilePath = GeneralUtils.generateAbsolutePath(getDownloadDirectoryPath(), getListName(), "/"); listFilePath = listFilePath.concat(".xml"); if (!new File(getDownloadDirectoryPath()).exists()) { FileUtils.forceMkdir(new File(getDownloadDirectoryPath())); } FileOutputStream listFileOutputStream = new FileOutputStream(listFilePath); bos = new BufferedOutputStream(listFileOutputStream); InputStream is = null; if (getUseProxy()) { is = URLUtils.getResponse(getUrl(), getUserName(), getPassword(), URLUtils.HTTP_GET_METHOD, getProxyHost(), getProxyPort()); IOUtils.copyLarge(is, bos); } else { URLUtils.getResponse(getUrl(), getUserName(), getPassword(), bos, null); } bos.flush(); bos.close(); File listFile = new File(listFilePath); if (!listFile.exists()) { throw new IllegalStateException("The list file did not get created"); } if (isLoggingInfo()) { logInfo("Downloaded list file : " + listFile); } List<SuspectFileProcessingStatus> sfpsList = new ArrayList<SuspectFileProcessingStatus>(); String loadType = GeneralConstants.LOAD_TYPE_FULL; String feedType = GeneralConstants.EMPTY_TOKEN; String listName = getListName(); String errorCode = ""; String description = ""; SuspectFileProcessingStatus sfps = getSuspectsLoaderService().storeFileIntoListIncomingDir(listFile, loadType, feedType, listName, errorCode, description); sfpsList.add(sfps); if (isLoggingInfo()) { logInfo("Retrieved list file with SuspectFileProcessingStatus: " + sfps); } return sfpsList; } finally { if (null != bos) { bos.close(); } } }
|
11
|
Code Sample 1:
private static byte[] sha2(String... data) { byte[] digest = new byte[32]; StringBuilder buffer = new StringBuilder(); for (String s : data) { buffer.append(s); } MessageDigest sha256 = null; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException ex) { assert false; } sha256.update(buffer.toString().getBytes()); try { sha256.digest(digest, 0, digest.length); } catch (DigestException ex) { assert false; } return digest; }
Code Sample 2:
public boolean verifySignature() { try { byte[] data = readFile(name + ".tmp1.bin"); if (data == null) return false; if (data[data.length - 0x104] != 'N' || data[data.length - 0x103] != 'G' || data[data.length - 0x102] != 'I' || data[data.length - 0x101] != 'S') return false; byte[] signature = new byte[0x100]; byte[] module = new byte[data.length - 0x104]; System.arraycopy(data, data.length - 0x100, signature, 0, 0x100); System.arraycopy(data, 0, module, 0, data.length - 0x104); BigIntegerEx power = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { 0x01, 0x00, 0x01, 0x00 }); BigIntegerEx mod = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { (byte) 0x6B, (byte) 0xCE, (byte) 0xF5, (byte) 0x2D, (byte) 0x2A, (byte) 0x7D, (byte) 0x7A, (byte) 0x67, (byte) 0x21, (byte) 0x21, (byte) 0x84, (byte) 0xC9, (byte) 0xBC, (byte) 0x25, (byte) 0xC7, (byte) 0xBC, (byte) 0xDF, (byte) 0x3D, (byte) 0x8F, (byte) 0xD9, (byte) 0x47, (byte) 0xBC, (byte) 0x45, (byte) 0x48, (byte) 0x8B, (byte) 0x22, (byte) 0x85, (byte) 0x3B, (byte) 0xC5, (byte) 0xC1, (byte) 0xF4, (byte) 0xF5, (byte) 0x3C, (byte) 0x0C, (byte) 0x49, (byte) 0xBB, (byte) 0x56, (byte) 0xE0, (byte) 0x3D, (byte) 0xBC, (byte) 0xA2, (byte) 0xD2, (byte) 0x35, (byte) 0xC1, (byte) 0xF0, (byte) 0x74, (byte) 0x2E, (byte) 0x15, (byte) 0x5A, (byte) 0x06, (byte) 0x8A, (byte) 0x68, (byte) 0x01, (byte) 0x9E, (byte) 0x60, (byte) 0x17, (byte) 0x70, (byte) 0x8B, (byte) 0xBD, (byte) 0xF8, (byte) 0xD5, (byte) 0xF9, (byte) 0x3A, (byte) 0xD3, (byte) 0x25, (byte) 0xB2, (byte) 0x66, (byte) 0x92, (byte) 0xBA, (byte) 0x43, (byte) 0x8A, (byte) 0x81, (byte) 0x52, (byte) 0x0F, (byte) 0x64, (byte) 0x98, (byte) 0xFF, (byte) 0x60, (byte) 0x37, (byte) 0xAF, (byte) 0xB4, (byte) 0x11, (byte) 0x8C, (byte) 0xF9, (byte) 0x2E, (byte) 0xC5, (byte) 0xEE, (byte) 0xCA, (byte) 0xB4, (byte) 0x41, (byte) 0x60, (byte) 0x3C, (byte) 0x7D, (byte) 0x02, (byte) 0xAF, (byte) 0xA1, (byte) 0x2B, (byte) 0x9B, (byte) 0x22, (byte) 0x4B, (byte) 0x3B, (byte) 0xFC, (byte) 0xD2, (byte) 0x5D, (byte) 0x73, (byte) 0xE9, (byte) 0x29, (byte) 0x34, (byte) 0x91, (byte) 0x85, (byte) 0x93, (byte) 0x4C, (byte) 0xBE, (byte) 0xBE, (byte) 0x73, (byte) 0xA9, (byte) 0xD2, (byte) 0x3B, (byte) 0x27, (byte) 0x7A, (byte) 0x47, (byte) 0x76, (byte) 0xEC, (byte) 0xB0, (byte) 0x28, (byte) 0xC9, (byte) 0xC1, (byte) 0xDA, (byte) 0xEE, (byte) 0xAA, (byte) 0xB3, (byte) 0x96, (byte) 0x9C, (byte) 0x1E, (byte) 0xF5, (byte) 0x6B, (byte) 0xF6, (byte) 0x64, (byte) 0xD8, (byte) 0x94, (byte) 0x2E, (byte) 0xF1, (byte) 0xF7, (byte) 0x14, (byte) 0x5F, (byte) 0xA0, (byte) 0xF1, (byte) 0xA3, (byte) 0xB9, (byte) 0xB1, (byte) 0xAA, (byte) 0x58, (byte) 0x97, (byte) 0xDC, (byte) 0x09, (byte) 0x17, (byte) 0x0C, (byte) 0x04, (byte) 0xD3, (byte) 0x8E, (byte) 0x02, (byte) 0x2C, (byte) 0x83, (byte) 0x8A, (byte) 0xD6, (byte) 0xAF, (byte) 0x7C, (byte) 0xFE, (byte) 0x83, (byte) 0x33, (byte) 0xC6, (byte) 0xA8, (byte) 0xC3, (byte) 0x84, (byte) 0xEF, (byte) 0x29, (byte) 0x06, (byte) 0xA9, (byte) 0xB7, (byte) 0x2D, (byte) 0x06, (byte) 0x0B, (byte) 0x0D, (byte) 0x6F, (byte) 0x70, (byte) 0x9E, (byte) 0x34, (byte) 0xA6, (byte) 0xC7, (byte) 0x31, (byte) 0xBE, (byte) 0x56, (byte) 0xDE, (byte) 0xDD, (byte) 0x02, (byte) 0x92, (byte) 0xF8, (byte) 0xA0, (byte) 0x58, (byte) 0x0B, (byte) 0xFC, (byte) 0xFA, (byte) 0xBA, (byte) 0x49, (byte) 0xB4, (byte) 0x48, (byte) 0xDB, (byte) 0xEC, (byte) 0x25, (byte) 0xF3, (byte) 0x18, (byte) 0x8F, (byte) 0x2D, (byte) 0xB3, (byte) 0xC0, (byte) 0xB8, (byte) 0xDD, (byte) 0xBC, (byte) 0xD6, (byte) 0xAA, (byte) 0xA6, (byte) 0xDB, (byte) 0x6F, (byte) 0x7D, (byte) 0x7D, (byte) 0x25, (byte) 0xA6, (byte) 0xCD, (byte) 0x39, (byte) 0x6D, (byte) 0xDA, (byte) 0x76, (byte) 0x0C, (byte) 0x79, (byte) 0xBF, (byte) 0x48, (byte) 0x25, (byte) 0xFC, (byte) 0x2D, (byte) 0xC5, (byte) 0xFA, (byte) 0x53, (byte) 0x9B, (byte) 0x4D, (byte) 0x60, (byte) 0xF4, (byte) 0xEF, (byte) 0xC7, (byte) 0xEA, (byte) 0xAC, (byte) 0xA1, (byte) 0x7B, (byte) 0x03, (byte) 0xF4, (byte) 0xAF, (byte) 0xC7 }); byte[] result = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, signature).modPow(power, mod).toByteArray(); byte[] digest; byte[] properResult = new byte[0x100]; for (int i = 0; i < properResult.length; i++) properResult[i] = (byte) 0xBB; MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(module); md.update("MAIEV.MOD".getBytes()); digest = md.digest(); System.arraycopy(digest, 0, properResult, 0, digest.length); for (int i = 0; i < result.length; i++) if (result[i] != properResult[i]) return false; return true; } catch (Exception e) { System.out.println("Failed to verify signature: " + e.toString()); } return false; }
|
11
|
Code Sample 1:
public static String generateMessageId(String plain) { byte[] cipher = new byte[35]; String messageId = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(plain.getBytes()); cipher = md5.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < cipher.length; i++) { String hex = Integer.toHexString(0xff & cipher[i]); if (hex.length() == 1) sb.append('0'); sb.append(hex); } StringBuffer pass = new StringBuffer(); pass.append(sb.substring(0, 6)); pass.append("H"); pass.append(sb.substring(6, 11)); pass.append("H"); pass.append(sb.substring(11, 21)); pass.append("H"); pass.append(sb.substring(21)); messageId = new String(pass); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return messageId; }
Code Sample 2:
private byte[] szyfrujKlucz(byte[] kluczSesyjny) { byte[] zaszyfrowanyKlucz = null; byte[] klucz = null; try { MessageDigest skrot = MessageDigest.getInstance("SHA-1"); skrot.update(haslo.getBytes()); byte[] skrotHasla = skrot.digest(); Object kluczDoKlucza = MARS_Algorithm.makeKey(skrotHasla); int resztaKlucza = this.dlugoscKlucza % ROZMIAR_BLOKU; if (resztaKlucza == 0) { klucz = kluczSesyjny; zaszyfrowanyKlucz = new byte[this.dlugoscKlucza]; } else { int liczbaBlokow = this.dlugoscKlucza / ROZMIAR_BLOKU + 1; int nowyRozmiar = liczbaBlokow * ROZMIAR_BLOKU; zaszyfrowanyKlucz = new byte[nowyRozmiar]; klucz = new byte[nowyRozmiar]; byte roznica = (byte) (ROZMIAR_BLOKU - resztaKlucza); System.arraycopy(kluczSesyjny, 0, klucz, 0, kluczSesyjny.length); for (int i = kluczSesyjny.length; i < nowyRozmiar; i++) klucz[i] = (byte) roznica; } byte[] szyfrogram = null; int liczbaBlokow = klucz.length / ROZMIAR_BLOKU; int offset = 0; for (offset = 0; offset < liczbaBlokow; offset++) { szyfrogram = MARS_Algorithm.blockEncrypt(klucz, offset * ROZMIAR_BLOKU, kluczDoKlucza); System.arraycopy(szyfrogram, 0, zaszyfrowanyKlucz, offset * ROZMIAR_BLOKU, szyfrogram.length); } } catch (InvalidKeyException ex) { Logger.getLogger(SzyfrowaniePliku.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return zaszyfrowanyKlucz; }
|
00
|
Code Sample 1:
@Override public Class<?> loadClass(final String name) throws ClassNotFoundException { final String baseName = StringUtils.substringBefore(name, "$"); if (baseName.startsWith("java") && !whitelist.contains(baseName) && !additionalWhitelist.contains(baseName)) { throw new NoClassDefFoundError(name + " is a restricted class for GAE"); } if (!name.startsWith("com.gargoylesoftware")) { return super.loadClass(name); } super.loadClass(name); final InputStream is = getResourceAsStream(name.replaceAll("\\.", "/") + ".class"); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { IOUtils.copy(is, bos); final byte[] bytes = bos.toByteArray(); return defineClass(name, bytes, 0, bytes.length); } catch (final IOException e) { throw new RuntimeException(e); } }
Code Sample 2:
public void check() { statusBar.setStatusText(Labels.getLabel("state.retrievingVersion")); Runnable checkVersionCode = new Runnable() { public void run() { BufferedReader reader = null; String message = null; int messageStyle = SWT.ICON_WARNING; try { URL url = new URL(Version.LATEST_VERSION_URL); URLConnection conn = url.openConnection(); reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String latestVersion = reader.readLine(); latestVersion = latestVersion.substring(latestVersion.indexOf(' ') + 1); if (!Version.getVersion().equals(latestVersion)) { message = Labels.getLabel("text.version.old"); message = message.replaceFirst("%LATEST", latestVersion); message = message.replaceFirst("%VERSION", Version.getVersion()); messageStyle = SWT.ICON_QUESTION | SWT.YES | SWT.NO; } else { message = Labels.getLabel("text.version.latest"); messageStyle = SWT.ICON_INFORMATION; } } catch (Exception e) { message = Labels.getLabel("exception.UserErrorException.version.latestFailed"); Logger.getLogger(getClass().getName()).log(Level.WARNING, message, e); } finally { try { if (reader != null) reader.close(); } catch (IOException e) { } final String messageToShow = message; final int messageStyleToShow = messageStyle; Display.getDefault().asyncExec(new Runnable() { public void run() { statusBar.setStatusText(null); MessageBox messageBox = new MessageBox(statusBar.getShell(), messageStyleToShow); messageBox.setText(Version.getFullName()); messageBox.setMessage(messageToShow); if (messageBox.open() == SWT.YES) { BrowserLauncher.openURL(Version.DOWNLOAD_URL); } } }); } } }; new Thread(checkVersionCode).start(); }
|
11
|
Code Sample 1:
private void sendData(HttpServletResponse response, MediaBean mediaBean) throws IOException { if (logger.isInfoEnabled()) logger.info("sendData[" + mediaBean + "]"); response.setContentLength(mediaBean.getContentLength()); response.setContentType(mediaBean.getContentType()); response.addHeader("Last-Modified", mediaBean.getLastMod()); response.addHeader("Cache-Control", "must-revalidate"); response.addHeader("content-disposition", "attachment, filename=" + (new Date()).getTime() + "_" + mediaBean.getFileName()); byte[] content = mediaBean.getContent(); InputStream is = null; OutputStream os = null; try { os = response.getOutputStream(); is = new ByteArrayInputStream(content); IOUtils.copy(is, os); } catch (IOException e) { logger.error(e, e); } finally { if (is != null) try { is.close(); } catch (IOException e) { } if (os != null) try { os.close(); } catch (IOException e) { } } }
Code Sample 2:
public static void nioJoinFiles(FileLib.FileValidator validator, File target, File[] sources) { boolean big_files = false; for (int i = 0; i < sources.length; i++) { if (sources[i].length() > Integer.MAX_VALUE) { big_files = true; break; } } if (big_files) { joinFiles(validator, target, sources); } else { System.out.println(i18n.getString("jdk14_comment")); FileOutputStream fos = null; try { fos = new FileOutputStream(target); FileChannel fco = fos.getChannel(); FileInputStream fis = null; for (int i = 0; i < sources.length; i++) { fis = new FileInputStream(sources[i]); FileChannel fci = fis.getChannel(); java.nio.MappedByteBuffer map; try { map = fci.map(FileChannel.MapMode.READ_ONLY, 0, (int) sources[i].length()); fco.write(map); fci.close(); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); try { fis.close(); fos.close(); } catch (IOException e) { } } finally { fis.close(); } } fco.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.