label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public static int deleteHedgeCustTrade() { Connection conn = null; PreparedStatement psmt = null; StringBuffer SQL = new StringBuffer(200); int deleted = 0; SQL.append(" DELETE FROM JHF_HEDGE_CUSTTRADE "); try { conn = JdbcConnectionPool.mainConnection(); conn.setAutoCommit(false); conn.setReadOnly(false); psmt = conn.prepareStatement(SQL.toString()); deleted = psmt.executeUpdate(); conn.commit(); } catch (SQLException e) { if (null != conn) { try { conn.rollback(); } catch (SQLException e1) { System.out.println(" error when roll back !"); } } } finally { try { if (null != psmt) { psmt.close(); psmt = null; } if (null != conn) { conn.close(); conn = null; } } catch (SQLException e) { System.out.println(" error when psmt close or conn close ."); } } return deleted; } Code Sample 2: public static void entering(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.readClass(new BufferedInputStream(new FileInputStream(args[0]))); int constantIndex = writer.getStringConstantIndex("Entering "); int fieldRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;"); int printlnRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); int printRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "print", "(Ljava/lang/String;)V"); for (Iterator i = writer.getMethods().iterator(); i.hasNext(); ) { MethodInfo method = (MethodInfo) i.next(); if (method.getName().equals("readConstant")) continue; CodeAttribute attribute = method.getCodeAttribute(); ArrayList instructions = new ArrayList(10); byte[] operands; operands = new byte[2]; NetByte.intToPair(fieldRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("getstatic"), 0, operands, false)); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("dup"), 0, null, false)); instructions.add(Instruction.appropriateLdc(constantIndex, false)); operands = new byte[2]; NetByte.intToPair(printRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); instructions.add(Instruction.appropriateLdc(writer.getStringConstantIndex(method.getName()), false)); operands = new byte[2]; NetByte.intToPair(printlnRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); attribute.insertInstructions(0, 0, instructions); attribute.codeCheck(); } BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(args[1])); writer.writeClass(outStream); outStream.close(); }
11
Code Sample 1: protected boolean loadJarLibrary(final String jarLib) { final String tempLib = System.getProperty("java.io.tmpdir") + File.separator + jarLib; boolean copied = IOUtils.copyFile(jarLib, tempLib); if (!copied) { return false; } System.load(tempLib); return true; } Code Sample 2: 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: protected void doDownload(S3Bucket bucket, S3Object s3object) throws Exception { String key = s3object.getKey(); key = trimPrefix(key); String[] path = key.split("/"); String fileName = path[path.length - 1]; String dirPath = ""; for (int i = 0; i < path.length - 1; i++) { dirPath += path[i] + "/"; } File outputDir = new File(downloadFileOutputDir + "/" + dirPath); if (outputDir.exists() == false) { outputDir.mkdirs(); } File outputFile = new File(outputDir, fileName); long size = s3object.getContentLength(); if (outputFile.exists() && outputFile.length() == size) { return; } long startTime = System.currentTimeMillis(); log.info("Download start.S3 file=" + s3object.getKey() + " local file=" + outputFile.getAbsolutePath()); FileOutputStream fout = null; S3Object dataObject = null; try { fout = new FileOutputStream(outputFile); dataObject = s3.getObject(bucket, s3object.getKey()); InputStream is = dataObject.getDataInputStream(); IOUtils.copyStream(is, fout); downloadedFileList.add(key); long downloadTime = System.currentTimeMillis() - startTime; log.info("Download complete.Estimete time=" + downloadTime + "ms " + IOUtils.toBPSText(downloadTime, size)); } catch (Exception e) { log.error("Download fail. s3 file=" + key, e); outputFile.delete(); throw e; } finally { IOUtils.closeNoException(fout); if (dataObject != null) { dataObject.closeDataInputStream(); } } } Code Sample 2: public void load(URL urlin) throws IOException { index = hs.getDoIndex(); loaded = false; url = urlin; int c, i; htmlDocLength = 0; HtmlReader in = new HtmlReader(new InputStreamReader(url.openStream(), charset)); try { if (debug >= 2) System.out.print("Loading " + urlin.toString() + " ... "); while ((c = in.read()) >= 0) { htmlDoc[htmlDocLength++] = (char) (c); if (htmlDocLength == htmlDocMaxLength) { char[] newHtmlDoc = new char[2 * htmlDocMaxLength]; System.arraycopy(htmlDoc, 0, newHtmlDoc, 0, htmlDocMaxLength); htmlDocMaxLength = 2 * htmlDocMaxLength; htmlDoc = newHtmlDoc; } } if (debug >= 2) System.out.println("done."); } catch (ArrayIndexOutOfBoundsException aioobe) { if (debug >= 1) System.out.println("Error, reading file into memory (too big) - skipping " + urlin.toString()); loaded = false; return; } in.close(); fetchURLpos = 0; dumpPos = 0; dumpLastChar = SPACE; loaded = true; frameset = false; titledone = false; headdone = false; checkhead = false; checkbody = false; }
11
Code Sample 1: private boolean copy(File in, File out) { try { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); FileChannel readableChannel = fis.getChannel(); FileChannel writableChannel = fos.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); fis.close(); fos.close(); return true; } catch (IOException ioe) { System.out.println("Copy Error: IOException during copy\r\n" + ioe.getMessage()); return false; } } Code Sample 2: protected void copyFile(final String sourceFileName, final File path) throws IOException { final File source = new File(sourceFileName); final File destination = new File(path, source.getName()); FileChannel srcChannel = null; FileChannel dstChannel = null; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); srcChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(destination); dstChannel = fileOutputStream.getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { try { if (dstChannel != null) { dstChannel.close(); } } catch (Exception exception) { } try { if (srcChannel != null) { srcChannel.close(); } } catch (Exception exception) { } try { fileInputStream.close(); } catch (Exception exception) { } try { fileOutputStream.close(); } catch (Exception exception) { } } }
00
Code Sample 1: @SuppressWarnings("unchecked") public static void createInstance(ExternProtoDeclare externProtoDeclare) { ExternProtoDeclareImport epdi = new ExternProtoDeclareImport(); HashMap<String, ProtoDeclareImport> protoMap = X3DImport.getTheImport().getCurrentParser().getProtoMap(); boolean loadedFromWeb = false; File f = null; URL url = null; List<String> urls = externProtoDeclare.getUrl(); String tmpUrls = urls.toString(); urls = Util.splitStringToListOfStrings(tmpUrls); String protoName = null; int urlCount = urls.size(); for (int urlIndex = 0; urlIndex < urlCount; urlIndex++) { try { String path = urls.get(urlIndex); if (path.startsWith("\"") && path.endsWith("\"")) path = path.substring(1, path.length() - 1); int hashMarkPos = path.indexOf("#"); int urlLength = path.length(); if (hashMarkPos == -1) path = path.substring(0, urlLength); else { protoName = path.substring(hashMarkPos + 1, urlLength); path = path.substring(0, hashMarkPos); } if (path.toLowerCase().startsWith("http://")) { String filename = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf(".")); String fileext = path.substring(path.lastIndexOf("."), path.length()); f = File.createTempFile(filename, fileext); url = new URL(path); 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(); url = f.toURI().toURL(); loadedFromWeb = true; } else { if (path.startsWith("/") || (path.charAt(1) == ':')) { } else { File x3dfile = X3DImport.getTheImport().getCurrentParser().getFile(); path = Util.getRealPath(x3dfile) + path; } f = new File(path); url = f.toURI().toURL(); Object testContent = url.getContent(); if (testContent == null) continue; loadedFromWeb = false; } X3DDocument x3dDocument = null; try { x3dDocument = X3DDocument.Factory.parse(f); } catch (XmlException e) { e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } Scene scene = x3dDocument.getX3D().getScene(); ProtoDeclare[] protos = scene.getProtoDeclareArray(); ProtoDeclare protoDeclare = null; if (protoName == null) { protoDeclare = protos[0]; } else { for (ProtoDeclare proto : protos) { if (proto.getName().equals(protoName)) { protoDeclare = proto; break; } } } if (protoDeclare == null) continue; ProtoBody protoBody = protoDeclare.getProtoBody(); epdi.protoBody = protoBody; protoMap.put(externProtoDeclare.getName(), epdi); break; } catch (MalformedURLException e) { } catch (IOException e) { } finally { if (loadedFromWeb && f != null) { f.delete(); } } } } Code Sample 2: public void delete(String fileToDelete) throws IOException { FTPClient ftp = new FTPClient(); try { int reply = 0; ftp.connect(this.endpointURL, this.endpointPort); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("Ftp delete server refused connection."); } if (!ftp.login("anonymous", "")) { ftp.logout(); throw new IOException("FTP: server wrong passwd"); } ftp.enterLocalPassiveMode(); log.debug("Deleted: " + ftp.deleteFile(fileToDelete)); ftp.logout(); } catch (Exception e) { throw new IOException(e.getMessage()); } }
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(); } if (!socket.isConnected()) { 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()); } version = determineVersion(); writer.setTargetVersion(version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); } Code Sample 2: public static boolean isDicom(URL url) { assert url != null; boolean isDicom = false; BufferedInputStream is = null; try { is = new BufferedInputStream(url.openStream()); is.skip(DICOM_PREAMBLE_SIZE); byte[] buf = new byte[DICM.length]; is.read(buf); if (buf[0] == DICM[0] && buf[1] == DICM[1] && buf[2] == DICM[2] && buf[3] == DICM[3]) { isDicom = true; } } catch (Exception exc) { System.out.println("ImageFactory::isDicom(): exc=" + exc); } finally { if (is != null) { try { is.close(); } catch (Exception exc) { } } } return isDicom; }
11
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: public String hash(String text) { try { MessageDigest md = MessageDigest.getInstance(hashFunction); md.update(text.getBytes(charset)); byte[] raw = md.digest(); return new String(encodeHex(raw)); } catch (Exception e) { throw new RuntimeException(e); } }
11
Code Sample 1: public boolean copy(File src, File dest, byte[] b) { if (src.isDirectory()) { String[] ss = src.list(); for (int i = 0; i < ss.length; i++) if (!copy(new File(src, ss[i]), new File(dest, ss[i]), b)) return false; return true; } delete(dest); dest.getParentFile().mkdirs(); try { FileInputStream fis = new FileInputStream(src); try { FileOutputStream fos = new FileOutputStream(dest); try { int read; while ((read = fis.read(b)) != -1) fos.write(b, 0, read); } finally { try { fos.close(); } catch (IOException ignore) { } register(dest); } } finally { fis.close(); } if (log.isDebugEnabled()) log.debug("Success: M-COPY " + src + " -> " + dest); return true; } catch (IOException e) { log.error("Failed: M-COPY " + src + " -> " + dest, e); return false; } } Code Sample 2: public static void copyFile(String pathOrig, String pathDst) throws FileNotFoundException, IOException { InputStream in; OutputStream out; if (pathOrig == null || pathDst == null) { System.err.println("Error en path"); return; } File orig = new File(pathOrig); if (!orig.exists() || !orig.isFile() || !orig.canRead()) { System.err.println("Error en fichero de origen"); return; } File dest = new File(pathDst); String file = new File(pathOrig).getName(); if (dest.isDirectory()) pathDst += file; in = new FileInputStream(pathOrig); out = new FileOutputStream(pathDst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
00
Code Sample 1: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public synchronized FTPClient getFTPClient(String User, String Password) throws IOException { if (logger.isDebugEnabled()) { logger.debug("getFTPClient(String, String) - start"); } while ((counter >= maxClients)) { try { wait(); } catch (InterruptedException e) { logger.error("getFTPClient(String, String)", e); e.printStackTrace(); } } FTPClient result = null; String key = User.concat(Password); logger.debug("versuche vorhandenen FTPClient aus Liste zu lesen"); if (Clients != null) { if (Clients.containsKey(key)) { LinkedList ClientList = (LinkedList) Clients.get(key); if (!ClientList.isEmpty()) do { result = (FTPClient) ClientList.getLast(); logger.debug("-- hole einen Client aus der Liste: " + result.toString()); ClientList.removeLast(); if (!result.isConnected()) { logger.debug("---- nicht mehr verbunden."); result = null; } else { try { result.changeWorkingDirectory("/"); } catch (IOException e) { logger.debug("---- schmei�t Exception bei Zugriff."); result = null; } } } while (result == null && !ClientList.isEmpty()); if (ClientList.isEmpty()) { Clients.remove(key); } } else { } } else logger.debug("-- keine Liste vorhanden."); if (result == null) { logger.debug("Kein FTPCLient verf�gbar, erstelle einen neuen."); result = new FTPClient(); logger.debug("-- Versuche Connect"); result.connect(Host); logger.debug("-- Versuche Login"); result.login(User, Password); result.setFileType(FTPClient.BINARY_FILE_TYPE); if (counter == maxClients - 1) { RemoveBufferedClient(); } } logger.debug("OK: neuer FTPClient ist " + result.toString()); ; counter++; if (logger.isDebugEnabled()) { logger.debug("getFTPClient(String, String) - end"); } return result; }
00
Code Sample 1: public String getWebPage(String url) { String content = ""; URL urlObj = null; try { urlObj = new URL(url); } catch (MalformedURLException urlEx) { urlEx.printStackTrace(); throw new Error("URL creation failed."); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(urlObj.openStream())); String line; while ((line = reader.readLine()) != null) { content += line; } } catch (IOException e) { e.printStackTrace(); throw new Error("Page retrieval failed."); } return content; } Code Sample 2: public static JSONObject update(String name, String uid, double lat, double lon, boolean online) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpPost post = new HttpPost(UPDATE_URI); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("name", name)); parameters.add(new BasicNameValuePair("uid", uid)); parameters.add(new BasicNameValuePair("latitude", Double.toString(lat))); parameters.add(new BasicNameValuePair("longitude", Double.toString(lon))); parameters.add(new BasicNameValuePair("online", Boolean.toString(online))); post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8)); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); return new JSONObject(res); } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); }
11
Code Sample 1: public synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new MyException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: public String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
11
Code Sample 1: private static void readAndWriteFile(File source, File target) { try { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { } } Code Sample 2: private boolean copy(File in, File out) { try { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); FileChannel readableChannel = fis.getChannel(); FileChannel writableChannel = fos.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); fis.close(); fos.close(); return true; } catch (IOException ioe) { System.out.println("Copy Error: IOException during copy\r\n" + ioe.getMessage()); return false; } }
00
Code Sample 1: private int getCountFromUrl(String url) { HttpGet request = new HttpGet(url); try { HttpResponse response = httpClient.execute(request); int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { ByteArrayOutputStream ostream = new ByteArrayOutputStream(); response.getEntity().writeTo(ostream); Log.e(TAG, ostream.toString()); } else { InputStream content = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content), 10); String count = reader.readLine(); content.close(); return Integer.parseInt(count); } } catch (IOException e) { Log.e(TAG, Log.getStackTraceString(e)); } return -1; } Code Sample 2: public int doEndTag() throws JspException { JspWriter saida = pageContext.getOut(); HttpURLConnection urlConnection = null; try { URL requisicao = new URL(((HttpServletRequest) pageContext.getRequest()).getRequestURL().toString()); URL link = new URL(requisicao, url); urlConnection = (HttpURLConnection) link.openConnection(); BufferedReader entrada = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "ISO-8859-1")); String linha = entrada.readLine(); while (linha != null) { saida.write(linha + "\n"); linha = entrada.readLine(); } entrada.close(); } catch (Exception e) { try { saida.write("Erro ao incluir o conte�do da URL \"" + url + "\""); } catch (IOException e1) { } } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return super.doEndTag(); }
11
Code Sample 1: @Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException { String context = request.getContextPath(); String resource = request.getRequestURI().replace(context, ""); resource = resource.replaceAll("^/\\w*/", ""); if ((StringUtils.isEmpty(resource)) || (resource.endsWith("/"))) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } URL url = ClassLoaderUtils.getResource(resource); if (url == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } if ((this.deny != null) && (this.deny.length > 0)) { for (String s : this.deny) { s = s.trim(); if (s.indexOf('*') != -1) { s = s.replaceAll("\\*", ".*"); } if (Pattern.matches(s, resource)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } } } InputStream input = url.openStream(); OutputStream output = response.getOutputStream(); URLConnection connection = url.openConnection(); String contentEncoding = connection.getContentEncoding(); int contentLength = connection.getContentLength(); String contentType = connection.getContentType(); if (contentEncoding != null) { response.setCharacterEncoding(contentEncoding); } response.setContentLength(contentLength); response.setContentType(contentType); IOUtils.copy(input, output, true); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public void encryptPassword() { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.out.print(e); } try { digest.update(passwordIn.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.out.println("cannot find char set for getBytes"); } byte digestBytes[] = digest.digest(); passwordHash = (new BASE64Encoder()).encode(digestBytes); } Code Sample 2: public static String getSHA1(String s) { try { MessageDigest sha1 = MessageDigest.getInstance("SHA1"); sha1.update(s.toLowerCase().getBytes()); return HexString.bufferToHex(sha1.digest()); } catch (NoSuchAlgorithmException e) { System.err.println("Error grave al inicializar SHA1"); e.printStackTrace(); return "!!"; } }
11
Code Sample 1: @Transactional(readOnly = false) public void saveOrUpdateProduct(Product product, File[] doc, String[] docFileName, String[] docContentType) throws IOException { logger.info("addOrUpdateProduct()"); List<Images> imgList = new ArrayList<Images>(); InputStream in = null; OutputStream out = null; String saveDirectory = ServletActionContext.getServletContext().getRealPath("common/userfiles/image/"); if (doc != null && doc.length > 0) { File uploadPath = new File(saveDirectory); if (!uploadPath.exists()) uploadPath.mkdirs(); for (int i = 0; i < doc.length; i++) { Images img = new Images(); in = new FileInputStream(doc[i]); img.setName(docFileName[i].substring(0, docFileName[i].lastIndexOf("."))); img.setRenameAs(docFileName[i]); imgList.add(img); out = new FileOutputStream(saveDirectory + "/" + img.getRenameAs()); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.flush(); } } product.setImagesCollection(imgList); productDao.saveOrUpdateProduct(product); if (null != in) { try { in.close(); } catch (Exception e) { e.printStackTrace(); } } if (null != out) { try { out.close(); } catch (Exception e) { logger.info("addOrUpdateProduct() **********" + e.getStackTrace()); e.printStackTrace(); } } } Code Sample 2: public static void main(String[] args) throws Exception { System.out.println("Opening destination cbrout.jizz"); OutputStream out = new BufferedOutputStream(new FileOutputStream("cbrout.jizz")); System.out.println("Opening source output.jizz"); InputStream in = new CbrLiveStream(new BufferedInputStream(new FileInputStream("output.jizz")), System.currentTimeMillis() + 10000, 128); System.out.println("Starting read/write loop"); boolean started = false; int len; byte[] buf = new byte[4 * 1024]; while ((len = in.read(buf)) > -1) { if (!started) { System.out.println("Starting at " + new Date()); started = true; } out.write(buf, 0, len); } System.out.println("Finished at " + new Date()); out.close(); in.close(); }
11
Code Sample 1: public void deleteGroupInstruction(int id, int rank) throws FidoDatabaseException, InstructionNotFoundException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); String sql = "delete from InstructionGroups " + "where InstructionId = " + id + " and Rank = " + rank; stmt.executeUpdate(sql); bumpAllRowsUp(stmt, id, rank); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
00
Code Sample 1: public String setContent(URL url, String inputdata) { String content = ""; try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.connect(); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(inputdata); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String strLine = ""; while ((strLine = in.readLine()) != null) { content = content + strLine; } in.close(); out.close(); } catch (IOException e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Problem writing to " + url + " content " + inputdata, e); } return content; } Code Sample 2: private File writeResourceToFile(String resource) throws IOException { File tmp = File.createTempFile("zfppt" + resource, null); InputStream res = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); OutputStream out = new FileOutputStream(tmp); IOUtils.copy(res, out); out.close(); return tmp; }
11
Code Sample 1: public static void downloadJars(IProject project, String repositoryUrl, String jarDirectory, String[] jars) { try { File tmpFile = null; for (String jar : jars) { try { tmpFile = File.createTempFile("tmpPlugin_", ".zip"); URL url = new URL(repositoryUrl + jarDirectory + jar); String destFilename = new File(url.getFile()).getName(); File destFile = new File(project.getLocation().append("lib").append(jarDirectory).toFile(), destFilename); InputStream inputStream = null; FileOutputStream outputStream = null; try { URLConnection urlConnection = url.openConnection(); inputStream = urlConnection.getInputStream(); outputStream = new FileOutputStream(tmpFile); IOUtils.copy(inputStream, outputStream); } finally { if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } } } catch (Exception ex) { ex.printStackTrace(); } } Code Sample 2: private byte[] getBytes(String resource) throws IOException { InputStream is = HttpServletFileDownloadTest.class.getResourceAsStream(resource); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); IOUtils.closeQuietly(is); return out.toByteArray(); }
11
Code Sample 1: public static int fileUpload(long lngFileSize, InputStream inputStream, String strFilePath, String strFileName) throws IOException { String SEPARATOR = System.getProperty("file.separator"); if (lngFileSize > (10 * 1024 * 1024)) { return -1; } InputStream is = null; FileOutputStream fos = null; try { File dir = new File(strFilePath); if (!dir.exists()) dir.mkdirs(); is = inputStream; fos = new FileOutputStream(new File(strFilePath + SEPARATOR + strFileName)); IOUtils.copy(is, fos); } catch (Exception ex) { return -2; } finally { try { fos.close(); is.close(); } catch (Exception ex2) { } } return 0; } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); long count = 0; long size = source.size(); while ((count += destination.transferFrom(source, 0, size - count)) < size) ; } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
11
Code Sample 1: @Override public void run() { try { File[] inputFiles = new File[this.previousFiles != null ? this.previousFiles.length + 1 : 1]; File copiedInput = new File(this.randomFolder, this.inputFile.getName()); IOUtils.copyFile(this.inputFile, copiedInput); inputFiles[inputFiles.length - 1] = copiedInput; if (previousFiles != null) { for (int i = 0; i < this.previousFiles.length; i++) { File prev = this.previousFiles[i]; File copiedPrev = new File(this.randomFolder, prev.getName()); IOUtils.copyFile(prev, copiedPrev); inputFiles[i] = copiedPrev; } } org.happycomp.radiog.Activator activator = org.happycomp.radiog.Activator.getDefault(); if (this.exportedMP3File != null) { EncodingUtils.encodeToWavAndThenMP3(inputFiles, this.exportedWavFile, this.exportedMP3File, this.deleteOnExit, this.randomFolder, activator.getCommandsMap()); } else { EncodingUtils.encodeToWav(inputFiles, this.exportedWavFile, randomFolder, activator.getCommandsMap()); } if (encodeMonitor != null) { encodeMonitor.setEncodingFinished(true); } } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } Code Sample 2: public static void copy(File from_file, File to_file) throws IOException { if (!from_file.exists()) abort("FileCopy: no such source file: " + from_file.getName()); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_file.getName()); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_file.getName()); 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_file.getName()); } 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) { e.printStackTrace(); } } if (to != null) { try { to.close(); } catch (IOException e) { e.printStackTrace(); } } } }
11
Code Sample 1: public static String encodeMD5(String value) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); BASE64Encoder encoder = new BASE64Encoder(); md.update(value.getBytes()); byte[] raw = md.digest(); result = encoder.encode(raw); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; } Code Sample 2: public static String buildUserPassword(String password) { String result = ""; MessageDigest md; try { md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF8")); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { int hexValue = hash[i] & 0xFF; if (hexValue < 16) { result = result + "0"; } result = result + Integer.toString(hexValue, 16); } logger.debug("Users'password MD5 Digest: " + result); } catch (NoSuchAlgorithmException ex) { logger.error(ex.getMessage()); ex.printStackTrace(); } catch (UnsupportedEncodingException ex) { logger.error(ex.getMessage()); ex.printStackTrace(); } return result; }
00
Code Sample 1: @Override protected Metadata doGet(final String url) throws WebServiceException, MbXMLException { final HttpGet method = new HttpGet(url); this.log.debug(url); Metadata metadata = null; try { final HttpResponse response = this.httpClient.execute(method); final int statusCode = response.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK == statusCode) { final InputStream responseStream = response.getEntity().getContent(); metadata = this.getParser().parse(responseStream); } else { final String responseString = response.getEntity() != null ? EntityUtils.toString(response.getEntity()) : ""; switch(statusCode) { case HttpStatus.SC_NOT_FOUND: throw new ResourceNotFoundException(responseString); case HttpStatus.SC_BAD_REQUEST: throw new RequestException(responseString); case HttpStatus.SC_FORBIDDEN: throw new AuthorizationException(responseString); case HttpStatus.SC_UNAUTHORIZED: throw new AuthorizationException(responseString); default: String em = "web service returned unknown status '" + statusCode + "', response was: " + responseString; this.log.error(em); throw new WebServiceException(em); } } } catch (IOException e) { this.log.error("Fatal transport error: " + e.getMessage()); throw new WebServiceException(e.getMessage(), e); } return metadata; } Code Sample 2: public void zipFile(String baseDir, String fileName, boolean encrypt) throws Exception { List fileList = getSubFiles(new File(baseDir)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fileName + ".temp")); ZipEntry ze = null; byte[] buf = new byte[BUFFER]; byte[] encrypByte = new byte[encrypLength]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { if (stopZipFile) { zos.close(); File zipFile = new File(fileName + ".temp"); if (zipFile.exists()) zipFile.delete(); break; } File f = (File) fileList.get(i); if (f.getAbsoluteFile().equals(fileName + ".temp")) continue; ze = new ZipEntry(getAbsFileName(baseDir, f)); ze.setSize(f.length()); ze.setTime(f.lastModified()); zos.putNextEntry(ze); InputStream is = new BufferedInputStream(new FileInputStream(f)); readLen = is.read(buf, 0, BUFFER); if (encrypt) { if (readLen >= encrypLength) { System.arraycopy(buf, 0, encrypByte, 0, encrypLength); } else if (readLen > 0) { Arrays.fill(encrypByte, (byte) 0); System.arraycopy(buf, 0, encrypByte, 0, readLen); readLen = encrypLength; } byte[] temp = CryptionControl.getInstance().encryptoECB(encrypByte, rootKey); System.arraycopy(temp, 0, buf, 0, encrypLength); } while (readLen != -1) { zos.write(buf, 0, readLen); readLen = is.read(buf, 0, BUFFER); } is.close(); } zos.close(); File zipFile = new File(fileName + ".temp"); if (zipFile.exists()) zipFile.renameTo(new File(fileName + ".zip")); }
11
Code Sample 1: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { 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); } Code Sample 2: public static String analyze(List<String> stackLines) { final MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return null; } final Iterator<String> iterator = stackLines.iterator(); if (!iterator.hasNext()) { return null; } try { final String messageLine = iterator.next(); final String exceptionClass = getExceptionClass(messageLine); messageDigest.update(exceptionClass.getBytes("UTF-8")); analyze(exceptionClass, iterator, messageDigest); final byte[] bytes = messageDigest.digest(); final BigInteger bigInt = new BigInteger(1, bytes); final String ret = bigInt.toString(36); return ret; } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e.getMessage(), e); } }
11
Code Sample 1: public void jsFunction_addFile(ScriptableFile infile) throws IOException { if (!infile.jsFunction_exists()) throw new IllegalArgumentException("Cannot add a file that doesn't exists to an archive"); ZipArchiveEntry entry = new ZipArchiveEntry(infile.getName()); entry.setSize(infile.jsFunction_getSize()); out.putArchiveEntry(entry); try { InputStream inStream = infile.jsFunction_createInputStream(); IOUtils.copy(inStream, out); inStream.close(); } finally { out.closeArchiveEntry(); } } Code Sample 2: public static long writePropertiesInOpenXMLDocument(String ext, InputStream in, OutputStreamProvider outProvider, Map<String, String> properties) { in = new BufferedInputStream(in); try { File tempPptx = null; POIXMLDocument doc; if (ext.toLowerCase().equals("docx")) { doc = new XWPFDocument(in); } else if (ext.toLowerCase().equals("xlsx")) { doc = new XSSFWorkbook(in); } else if (ext.toLowerCase().equals("pptx")) { tempPptx = File.createTempFile("temp", "pptx"); OutputStream tempPptxOut = new FileOutputStream(tempPptx); tempPptxOut = new BufferedOutputStream(tempPptxOut); IOUtils.copy(in, tempPptxOut); tempPptxOut.close(); doc = new XSLFSlideShow(tempPptx.getAbsolutePath()); } else { throw new IllegalArgumentException("Writing properties for a " + ext + " file is not supported"); } for (Map.Entry<String, String> property : properties.entrySet()) { CoreProperties coreProperties = doc.getProperties().getCoreProperties(); if (property.getKey().equals(Metadata.TITLE)) { coreProperties.setTitle(property.getValue()); } else if (property.getKey().equals(Metadata.AUTHOR)) { coreProperties.setCreator(property.getValue()); } else if (property.getKey().equals(Metadata.KEYWORDS)) { coreProperties.getUnderlyingProperties().setKeywordsProperty(property.getValue()); } else if (property.getKey().equals(Metadata.COMMENTS)) { coreProperties.setDescription(property.getValue()); } else if (property.getKey().equals(Metadata.SUBJECT)) { coreProperties.setSubjectProperty(property.getValue()); } else if (property.getKey().equals(Metadata.COMPANY)) { doc.getProperties().getExtendedProperties().getUnderlyingProperties().setCompany(property.getValue()); } else { org.apache.poi.POIXMLProperties.CustomProperties customProperties = doc.getProperties().getCustomProperties(); if (customProperties.contains(property.getKey())) { int index = 0; for (CTProperty prop : customProperties.getUnderlyingProperties().getPropertyArray()) { if (prop.getName().equals(property.getKey())) { customProperties.getUnderlyingProperties().removeProperty(index); break; } index++; } } customProperties.addProperty(property.getKey(), property.getValue()); } } in.close(); File tempOpenXMLDocumentFile = File.createTempFile("temp", "tmp"); OutputStream tempOpenXMLDocumentOut = new FileOutputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentOut = new BufferedOutputStream(tempOpenXMLDocumentOut); doc.write(tempOpenXMLDocumentOut); tempOpenXMLDocumentOut.close(); long length = tempOpenXMLDocumentFile.length(); InputStream tempOpenXMLDocumentIn = new FileInputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentIn = new BufferedInputStream(tempOpenXMLDocumentIn); OutputStream out = null; try { out = outProvider.getOutputStream(); out = new BufferedOutputStream(out); IOUtils.copy(tempOpenXMLDocumentIn, out); out.flush(); } finally { IOUtils.closeQuietly(out); } if (!FileUtils.deleteQuietly(tempOpenXMLDocumentFile)) { tempOpenXMLDocumentFile.deleteOnExit(); } if (tempPptx != null && !FileUtils.deleteQuietly(tempPptx)) { tempPptx.deleteOnExit(); } return length; } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidFormatException e) { throw new RuntimeException(e); } catch (OpenXML4JException e) { throw new RuntimeException(e); } catch (XmlException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(in); } }
00
Code Sample 1: private String getStoreName() { try { final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(protectionDomain.getBytes()); final byte[] bs = digest.digest(); final StringBuffer sb = new StringBuffer(bs.length * 2); for (int i = 0; i < bs.length; i++) { final String s = Integer.toHexString(bs[i] & 0xff); if (s.length() < 2) sb.append('0'); sb.append(s); } return sb.toString(); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Can't save credentials: digest method MD5 unavailable."); } } Code Sample 2: public static String[] check() throws Exception { if (currentVersion == null) throw new Exception(); URL url = new URL(versionURL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); String str = ""; BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); while (br.ready()) { str = str + br.readLine(); } br.close(); Document document = DocumentHelper.parseText(str); Node node = document.selectSingleNode("//root/version"); String latestVersion = node.valueOf("@id"); Double latest = Double.parseDouble(latestVersion); Double current = Double.parseDouble(currentVersion.substring(0, currentVersion.indexOf("-"))); if (latest > current) { String[] a = { latestVersion, node.valueOf("@url"), node.valueOf("@description") }; return a; } return null; }
11
Code Sample 1: @Override public String fetchURL(String urlString) throws ServiceException { try { URL url = new URL(urlString); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String content = ""; String line; while ((line = reader.readLine()) != null) { content += line + "\n"; } reader.close(); return content; } catch (MalformedURLException e) { throw new ServiceException(e.getMessage()); } catch (IOException e) { throw new ServiceException(e.getMessage()); } } Code Sample 2: protected InputSource getInputSource(URL url, AtomicReference<Date> checkModifiedDate) throws IOException { String proto = url.getProtocol().toLowerCase(Locale.ENGLISH); if (!("http".equals(proto) || "https".equals(proto))) throw new IllegalArgumentException("OAI only allows HTTP(S) as network protocol!"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(timeout * 1000); conn.setReadTimeout(timeout * 1000); StringBuilder ua = new StringBuilder("Java/").append(System.getProperty("java.version")).append(" (").append(de.pangaea.metadataportal.Package.getProductName()).append('/').append(de.pangaea.metadataportal.Package.getVersion()).append("; OAI downloader)"); conn.setRequestProperty("User-Agent", ua.toString()); conn.setRequestProperty("Accept-Encoding", "gzip, deflate, identity;q=0.3, *;q=0"); conn.setRequestProperty("Accept-Charset", "utf-8, *;q=0.1"); conn.setRequestProperty("Accept", "text/xml, application/xml, *;q=0.1"); if (checkModifiedDate != null && checkModifiedDate.get() != null) conn.setIfModifiedSince(checkModifiedDate.get().getTime()); conn.setUseCaches(false); conn.setFollowRedirects(true); log.debug("Opening connection..."); InputStream in = null; try { conn.connect(); in = conn.getInputStream(); } catch (IOException ioe) { int after, code; try { after = conn.getHeaderFieldInt("Retry-After", -1); code = conn.getResponseCode(); } catch (IOException ioe2) { after = -1; code = -1; } if (code == HttpURLConnection.HTTP_UNAVAILABLE && after > 0) throw new RetryAfterIOException(after, ioe); throw ioe; } if (checkModifiedDate != null) { if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { log.debug("File not modified since " + checkModifiedDate.get()); if (in != null) in.close(); return null; } long d = conn.getLastModified(); checkModifiedDate.set((d == 0L) ? null : new Date(d)); } String encoding = conn.getContentEncoding(); if (encoding == null) encoding = "identity"; encoding = encoding.toLowerCase(Locale.ENGLISH); log.debug("HTTP server uses " + encoding + " content encoding."); if ("gzip".equals(encoding)) in = new GZIPInputStream(in); else if ("deflate".equals(encoding)) in = new InflaterInputStream(in); else if (!"identity".equals(encoding)) throw new IOException("Server uses an invalid content encoding: " + encoding); String contentType = conn.getContentType(); String charset = null; if (contentType != null) { contentType = contentType.toLowerCase(Locale.ENGLISH); int charsetStart = contentType.indexOf("charset="); if (charsetStart >= 0) { int charsetEnd = contentType.indexOf(";", charsetStart); if (charsetEnd == -1) charsetEnd = contentType.length(); charsetStart += "charset=".length(); charset = contentType.substring(charsetStart, charsetEnd).trim(); } } log.debug("Charset from Content-Type: '" + charset + "'"); InputSource src = new InputSource(in); src.setSystemId(url.toString()); src.setEncoding(charset); return src; }
00
Code Sample 1: protected String parseAction() throws ChangesOnServerException, ConnectionException, RequestCancelledException { GetPageRequest request = getHttpClient().createGetPageRequest(); request.setUrl("http://www.zippyshare.com/index_old.jsp"); HttpResponse response = executeRequest(request); try { Parser p = new Parser(response.getResponseBody()); String action = p.parseOne("enctype=\"multipart/form-data\" action=\"(.*)\">"); return action; } catch (ParsingException ex) { throw new ChangesOnServerException(); } catch (IOException ex) { throw new ChangesOnServerException(); } } Code Sample 2: private void dumpFile(File repository, File copy) { try { if (copy.exists() && !copy.delete()) { throw new RuntimeException("can't delete copy: " + copy); } printFile("Real Archive File", repository); new ZipArchive(repository.getPath()); IOUtils.copyFiles(repository, copy); printFile("Copy Archive File", copy); new ZipArchive(copy.getPath()); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static int fileCopy(String strSourceFilePath, String strDestinationFilePath, String strFileName) throws IOException { String SEPARATOR = System.getProperty("file.separator"); File dir = new File(strSourceFilePath); if (!dir.exists()) dir.mkdirs(); File realDir = new File(strDestinationFilePath); if (!realDir.exists()) realDir.mkdirs(); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(new File(strSourceFilePath + SEPARATOR + strFileName)); fos = new FileOutputStream(new File(strDestinationFilePath + SEPARATOR + strFileName)); IOUtils.copy(fis, fos); } catch (Exception ex) { return -1; } finally { try { fos.close(); fis.close(); } catch (Exception ex2) { } } return 0; } Code Sample 2: private static void copy(File source, File target) throws IOException { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(source); to = new FileOutputStream(target); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { } if (to != null) try { to.close(); } catch (IOException e) { } } }
00
Code Sample 1: public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { if (text == null || text.length() < 1) { return null; } MessageDigest md = MessageDigest.getInstance(TYPE_SHA); md.update(text.getBytes(ENCODE), 0, text.length()); byte[] sha1hash = new byte[40]; sha1hash = md.digest(); return convertToHexFormat(sha1hash); } Code Sample 2: public void login() { loginsuccessful = false; try { cookies = new StringBuilder(); HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); NULogger.getLogger().info("Trying to log in to crocko.com"); HttpPost httppost = new HttpPost("https://www.crocko.com/accounts/login"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("login", getUsername())); formparams.add(new BasicNameValuePair("password", getPassword())); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); NULogger.getLogger().info("Getting cookies........"); NULogger.getLogger().info(EntityUtils.toString(httpresponse.getEntity())); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); cookies.append(escookie.getName()).append("=").append(escookie.getValue()).append(";"); if (escookie.getName().equals("PHPSESSID")) { sessionid = escookie.getValue(); NULogger.getLogger().info(sessionid); } } if (cookies.toString().contains("logacc")) { NULogger.getLogger().info(cookies.toString()); loginsuccessful = true; username = getUsername(); password = getPassword(); NULogger.getLogger().info("Crocko login successful :)"); } if (!loginsuccessful) { NULogger.getLogger().info("Crocko.com Login failed :("); loginsuccessful = false; username = ""; password = ""; JOptionPane.showMessageDialog(NeembuuUploader.getInstance(), "<html><b>" + HOSTNAME + "</b> " + TranslationProvider.get("neembuuuploader.accounts.loginerror") + "</html>", HOSTNAME, JOptionPane.WARNING_MESSAGE); AccountsManager.getInstance().setVisible(true); } httpclient.getConnectionManager().shutdown(); } catch (Exception e) { NULogger.getLogger().log(Level.SEVERE, "{0}: {1}", new Object[] { getClass().getName(), e.toString() }); System.err.println(e); } }
11
Code Sample 1: public void copy(String sourcePath, String targetPath) throws IOException { File sourceFile = new File(sourcePath); File targetFile = new File(targetPath); FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(sourceFile); fileOutputStream = new FileOutputStream(targetFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) fileOutputStream.write(buffer, 0, bytesRead); } finally { if (fileInputStream != null) try { fileInputStream.close(); } catch (IOException exception) { JOptionPane.showMessageDialog(null, AcideLanguageManager.getInstance().getLabels().getString("s265") + sourcePath, AcideLanguageManager.getInstance().getLabels().getString("s266"), JOptionPane.ERROR_MESSAGE); AcideLog.getLog().error(exception.getMessage()); } if (fileOutputStream != null) try { fileOutputStream.close(); } catch (IOException exception) { JOptionPane.showMessageDialog(null, AcideLanguageManager.getInstance().getLabels().getString("s267") + targetPath, AcideLanguageManager.getInstance().getLabels().getString("268"), JOptionPane.ERROR_MESSAGE); AcideLog.getLog().error(exception.getMessage()); } } } Code Sample 2: public static void exportDB(String input, String output) { try { Class.forName("org.sqlite.JDBC"); String fileName = input + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero DB", "Error", JOptionPane.ERROR_MESSAGE); } else { G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); HashMap<Integer, String> languageIDs = new HashMap<Integer, String>(); HashMap<Integer, String> typeIDs = new HashMap<Integer, String>(); long tiempoInicio = System.currentTimeMillis(); Element dataBaseXML = new Element("database"); Element languages = new Element("languages"); Statement stat = G.conn.createStatement(); ResultSet rs = stat.executeQuery("select * from language order by id"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); languageIDs.put(id, name); Element language = new Element("language"); language.setText(name); languages.addContent(language); } dataBaseXML.addContent(languages); rs = stat.executeQuery("select * from type order by id"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); typeIDs.put(id, name); } rs = stat.executeQuery("select distinct name from main order by name"); while (rs.next()) { String name = rs.getString("name"); Element image = new Element("image"); image.setAttribute("id", name); Statement stat2 = G.conn.createStatement(); ResultSet rs2 = stat2.executeQuery("select distinct idL from main where name = \"" + name + "\" order by idL"); while (rs2.next()) { int idL = rs2.getInt("idL"); Element language = new Element("language"); language.setAttribute("id", languageIDs.get(idL)); Statement stat3 = G.conn.createStatement(); ResultSet rs3 = stat3.executeQuery("select * from main where name = \"" + name + "\" and idL = " + idL + " order by idT"); while (rs3.next()) { int idT = rs3.getInt("idT"); String word = rs3.getString("word"); Element wordE = new Element("word"); wordE.setAttribute("type", typeIDs.get(idT)); wordE.setText(word); language.addContent(wordE); String pathSrc = input + File.separator + name.substring(0, 1).toUpperCase() + File.separator + name; String pathDst = output + File.separator + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } rs3.close(); stat3.close(); image.addContent(language); } rs2.close(); stat2.close(); dataBaseXML.addContent(image); } rs.close(); stat.close(); XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); FileOutputStream f = new FileOutputStream(output + File.separator + G.imagesName); out.output(dataBaseXML, f); f.flush(); f.close(); long totalTiempo = System.currentTimeMillis() - tiempoInicio; System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos"); } } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: protected File getFile(NameCategory category) throws IOException { File home = new File(System.getProperty("user.dir")); String fileName = String.format("%s.txt", category); File file = new File(home, fileName); if (file.exists()) { return file; } else { URL url = LocalNameGenerator.class.getResource("/" + fileName); if (url == null) { throw new IllegalStateException(String.format("Cannot find resource at %s", fileName)); } else { InputStream in = url.openStream(); try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); try { IOUtils.copy(in, out); } finally { out.close(); } } finally { in.close(); } return file; } } } Code Sample 2: private static void cut() { File inputFile = new File(inputFileName); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), inputCharSet)); } catch (FileNotFoundException e) { System.err.print("Invalid File Name!"); System.err.flush(); System.exit(1); } catch (UnsupportedEncodingException e) { System.err.print("Invalid Char Set Name!"); System.err.flush(); System.exit(1); } switch(cutMode) { case charMode: { int outputFileIndex = 1; char[] readBuf = new char[charPerFile]; while (true) { int readCount = 0; try { readCount = in.read(readBuf); } catch (IOException e) { System.err.println("Read IO Error!"); System.err.flush(); System.exit(1); } if (-1 == readCount) break; else { try { int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = "html"; DecimalFormat outputFileIndexFormat = new DecimalFormat("0000"); File outputFile = new File(prefixInputFileName + "-" + outputFileIndexFormat.format(outputFileIndex) + "." + postfixInputFileName); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), outputCharSet)); out.write(readBuf, 0, readCount); out.flush(); out.close(); outputFileIndex++; } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } } } break; } case lineMode: { boolean isFileEnd = false; int outputFileIndex = 1; while (!isFileEnd) { try { int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = inputFileName.substring(ppos + 1); DecimalFormat outputFileIndexFormat = new DecimalFormat("0000"); File outputFile = new File(prefixInputFileName + outputFileIndexFormat.format(outputFileIndex) + "." + postfixInputFileName); PrintStream out = new PrintStream(new FileOutputStream(outputFile), false, outputCharSet); int p = 0; while (p < linePerFile) { String line = in.readLine(); if (null == line) { isFileEnd = true; break; } out.println(line); ++p; } out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } ++outputFileIndex; } break; } case htmlMode: { boolean isFileEnd = false; int outputFileIndex = 1; int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = "html"; DecimalFormat df = new DecimalFormat("0000"); while (!isFileEnd) { try { File outputFile = new File(prefixInputFileName + "-" + df.format(outputFileIndex) + "." + postfixInputFileName); PrintStream out = new PrintStream(new FileOutputStream(outputFile), false, outputCharSet); out.println("<html><head><title>" + prefixInputFileName + "-" + df.format(outputFileIndex) + "</title>" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; " + "charset=" + outputCharSet + "\" />" + "<link rel =\"stylesheet\" " + "type=\"text/css\" " + "href=\"stylesheet.css\" />" + "</head><body><div id=\"content\">"); int p = 0; while (p < pPerFile) { String line = in.readLine(); if (null == line) { isFileEnd = true; break; } if (line.length() > 0) out.println("<p>" + line + "</p>"); ++p; } out.println("</div><a href=\"" + prefixInputFileName + "-" + df.format(outputFileIndex + 1) + "." + postfixInputFileName + "\">NEXT</a></body></html>"); out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } ++outputFileIndex; } try { File indexFile = new File("index.html"); PrintStream out = new PrintStream(new FileOutputStream(indexFile), false, outputCharSet); out.println("<html><head><title>" + "Index" + "</title>" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; " + "charset=" + outputCharSet + "\" />" + "<link rel =\"stylesheet\" " + "type=\"text/css\" " + "href=\"stylesheet.css\" />" + "</head><body><h2>" + htmlTitle + "</h2><div id=\"content\"><ul>"); for (int i = 1; i < outputFileIndex; i++) { out.println("<li><a href=\"" + prefixInputFileName + "-" + df.format(i) + "." + postfixInputFileName + "\">" + df.format(i) + "</a></li>"); } out.println("</ul></body></html>"); out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } break; } } }
11
Code Sample 1: @Override public void copy(final String fileName) throws FileIOException { final long savedCurrentPositionInFile = currentPositionInFile; if (opened) { closeImpl(); } final FileInputStream fis; try { fis = new FileInputStream(file); } catch (FileNotFoundException exception) { throw HELPER_FILE_UTIL.fileIOException(FAILED_OPEN + file, file, exception); } final File destinationFile = new File(fileName); final FileOutputStream fos; try { fos = new FileOutputStream(destinationFile); } catch (FileNotFoundException exception) { throw HELPER_FILE_UTIL.fileIOException(FAILED_OPEN + destinationFile, destinationFile, exception); } try { final byte[] buf = new byte[1024]; int readLength = 0; while ((readLength = fis.read(buf)) != -1) { fos.write(buf, 0, readLength); } } catch (IOException exception) { throw HELPER_FILE_UTIL.fileIOException("failed copy from " + file + " to " + destinationFile, null, exception); } finally { try { if (fis != null) { fis.close(); } } catch (Exception exception) { } try { if (fos != null) { fos.close(); } } catch (Exception exception) { } } if (opened) { openImpl(); seek(savedCurrentPositionInFile); } } Code Sample 2: private void copyFile(File source, File target) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
11
Code Sample 1: @Override public void run() { File file = new File(LogHandler.path); FileFilter filter = new FileFilter() { @Override public boolean accept(File file) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date()); cal.add(GregorianCalendar.DAY_OF_YEAR, -1); String oldTime = LogHandler.dateFormat.format(cal.getTime()); return file.getName().toLowerCase().startsWith(oldTime); } }; File[] list = file.listFiles(filter); if (list.length > 0) { FileInputStream in; int read = 0; byte[] data = new byte[1024]; for (int i = 0; i < list.length; i++) { try { in = new FileInputStream(LogHandler.path + list[i].getName()); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(LogHandler.path + list[i].getName() + ".temp")); while ((read = in.read(data, 0, 1024)) != -1) out.write(data, 0, read); in.close(); out.close(); new File(LogHandler.path + list[i].getName() + ".temp").renameTo(new File(LogHandler.path + list[i].getName() + ".gz")); list[i].delete(); } catch (FileNotFoundException e) { TrackingServer.incExceptionCounter(); e.printStackTrace(); } catch (IOException ioe) { } } } } Code Sample 2: protected void copyFile(final String sourceFileName, final File path) throws IOException { final File source = new File(sourceFileName); final File destination = new File(path, source.getName()); FileChannel srcChannel = null; FileChannel dstChannel = null; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); srcChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(destination); dstChannel = fileOutputStream.getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { try { if (dstChannel != null) { dstChannel.close(); } } catch (Exception exception) { } try { if (srcChannel != null) { srcChannel.close(); } } catch (Exception exception) { } try { fileInputStream.close(); } catch (Exception exception) { } try { fileOutputStream.close(); } catch (Exception exception) { } } }
00
Code Sample 1: public ProgramMessageSymbol deleteProgramMessageSymbol(int id) throws AdaptationException { ProgramMessageSymbol pmt = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProgramMessageSymbols " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { String msg = "Attempt to delete program message type " + "failed."; log.error(msg); ; throw new AdaptationException(msg); } pmt = getProgramMessageSymbol(resultSet); query = "DELETE FROM ProgramMessageSymbols " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProgramMessageSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return pmt; } Code Sample 2: @Test public void test_lookupType_NonExistingName() throws Exception { URL url = new URL(baseUrl + "/lookupType/blah-blah"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("[]")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/json; charset=utf-8")); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><rowset/>")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/xml; charset=utf-8")); }
00
Code Sample 1: public void setTableBraille(String tableBraille, boolean sys) { fiConf.setProperty(OptNames.fi_braille_table, tableBraille); fiConf.setProperty(OptNames.fi_is_sys_braille_table, Boolean.toString(sys)); FileChannel in = null; FileChannel out = null; try { String fichTable; if (!(tableBraille.endsWith(".ent"))) { tableBraille = tableBraille + ".ent"; } if (sys) { fichTable = ConfigNat.getInstallFolder() + "xsl/tablesBraille/" + tableBraille; } else { fichTable = ConfigNat.getUserBrailleTableFolder() + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(getUserBrailleTableFolder() + "Brltab.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } try { String fichTable; if (sys) { fichTable = ConfigNat.getInstallFolder() + "/xsl/tablesEmbosseuse/" + tableBraille; } else { fichTable = ConfigNat.getUserEmbossTableFolder() + "/" + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(ConfigNat.getUserTempFolder() + "Table_pour_chaines.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public String getMD5String(String par1Str) { try { String s = (new StringBuilder()).append(field_27370_a).append(par1Str).toString(); MessageDigest messagedigest = MessageDigest.getInstance("MD5"); messagedigest.update(s.getBytes(), 0, s.length()); return (new BigInteger(1, messagedigest.digest())).toString(16); } catch (NoSuchAlgorithmException nosuchalgorithmexception) { throw new RuntimeException(nosuchalgorithmexception); } }
00
Code Sample 1: public static boolean insert(final Departamento ObjDepartamento) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into departamento " + "(nome, sala, telefone, id_orgao)" + " values (?, ?, ?, ?)"; pst = c.prepareStatement(sql); pst.setString(1, ObjDepartamento.getNome()); pst.setString(2, ObjDepartamento.getSala()); pst.setString(3, ObjDepartamento.getTelefone()); pst.setInt(4, (ObjDepartamento.getOrgao()).getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { e1.printStackTrace(); } System.out.println("[DepartamentoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } } Code Sample 2: public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { System.err.println("Failed to load the SHA-1 MessageDigest. " + "Jive will be unable to function normally."); } } try { digest.update(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e); } return encodeHex(digest.digest()); }
11
Code Sample 1: public static java.io.ByteArrayOutputStream getFileByteStream(URL _url) { java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream(); try { InputStream input = _url.openStream(); IOUtils.copy(input, buffer); IOUtils.closeQuietly(input); } catch (Exception err) { throw new RuntimeException(err); } return buffer; } Code Sample 2: private void writeToFile(Body b, File mime4jFile) throws FileNotFoundException, IOException { if (b instanceof TextBody) { String charset = CharsetUtil.toJavaCharset(b.getParent().getCharset()); if (charset == null) { charset = "ISO8859-1"; } OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((TextBody) b).getReader(), out, charset); } else { OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((BinaryBody) b).getInputStream(), out); } }
00
Code Sample 1: public ArrayList<Jane16Results> callExternalService(ServiceType type, HashMap<String, String> params) throws Exception { URL url = initURL(type, params); XMLParser parser = initParser(type); InputStream in = url.openStream(); ArrayList<Jane16Results> results = new ArrayList<Jane16Results>(); byte[] buf = new byte[1024]; ArrayList<Byte> arrByte = new ArrayList<Byte>(); int len; while ((len = in.read(buf)) > 0) { for (int i = 0; i < len; i++) { arrByte.add(buf[i]); } } in.close(); byte[] data = new byte[arrByte.size()]; int i = 0; for (Byte b : arrByte) { data[i++] = b; } results = parser.parse(data); return results; } Code Sample 2: 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) { } } }
00
Code Sample 1: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { 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); } Code Sample 2: public static void main(String[] args) { if (args.length <= 0) { System.out.println(" *** SQL script generator and executor ***"); System.out.println(" You must specify name of the file with SQL script data"); System.out.println(" Fisrt rows of this file must be:"); System.out.println(" 1) JDBC driver class for your DBMS"); System.out.println(" 2) URL for your database instance"); System.out.println(" 3) user in that database (with administrator priviliges)"); System.out.println(" 4) password of that user"); System.out.println(" Next rows can have: '@' before schema to create,"); System.out.println(" '#' before table to create, '&' before table to insert,"); System.out.println(" '$' before trigger (inverse 'FK on delete cascade') to create,"); System.out.println(" '>' before table to drop, '<' before schema to drop."); System.out.println(" Other rows contain parameters of these actions:"); System.out.println(" for & action each parameter is a list of values,"); System.out.println(" for @ -//- is # acrion, for # -//- is column/constraint "); System.out.println(" definition or $ action. $ syntax to delete from table:"); System.out.println(" fullNameOfTable:itsColInWhereClause=matchingColOfThisTable"); System.out.println(" '!' before row means that it is a comment."); System.out.println(" If some exception is occured, all script is rolled back."); System.out.println(" If you specify 2nd command line argument - file name too -"); System.out.println(" connection will be established but all statements will"); System.out.println(" be saved in that output file and not transmitted to DB"); System.out.println(" If you specify 3nd command line argument - connect_string -"); System.out.println(" connect information will be added to output file"); System.out.println(" in the form 'connect user/password@connect_string'"); System.exit(0); } try { String[] info = new String[4]; BufferedReader reader = new BufferedReader(new FileReader(new File(args[0]))); Writer writer = null; try { for (int i = 0; i < 4; i++) info[i] = reader.readLine(); try { Class.forName(info[0]); Connection connection = DriverManager.getConnection(info[1], info[2], info[3]); SQLScript script = new SQLScript(connection); if (args.length > 1) { writer = new FileWriter(args[1]); if (args.length > 2) writer.write("connect " + info[2] + "/" + info[3] + "@" + args[2] + script.statementTerminator); } try { System.out.println(script.executeScript(reader, writer) + " updates has been performed during script execution"); } catch (SQLException e4) { reader.close(); if (writer != null) writer.close(); System.out.println(" Script execution error: " + e4); } connection.close(); } catch (Exception e3) { reader.close(); if (writer != null) writer.close(); System.out.println(" Connection error: " + e3); } } catch (IOException e2) { System.out.println("Error in file " + args[0]); } } catch (FileNotFoundException e1) { System.out.println("File " + args[0] + " not found"); } }
11
Code Sample 1: public XmldbURI createFile(String newName, InputStream is, Long length, String contentType) throws IOException, PermissionDeniedException, CollectionDoesNotExistException { if (LOG.isDebugEnabled()) LOG.debug("Create '" + newName + "' in '" + xmldbUri + "'"); XmldbURI newNameUri = XmldbURI.create(newName); MimeType mime = MimeTable.getInstance().getContentTypeFor(newName); if (mime == null) { mime = MimeType.BINARY_TYPE; } DBBroker broker = null; Collection collection = null; BufferedInputStream bis = new BufferedInputStream(is); VirtualTempFile vtf = new VirtualTempFile(); BufferedOutputStream bos = new BufferedOutputStream(vtf); IOUtils.copy(bis, bos); bis.close(); bos.close(); vtf.close(); if (mime.isXMLType() && vtf.length() == 0L) { if (LOG.isDebugEnabled()) LOG.debug("Creating dummy XML file for null resource lock '" + newNameUri + "'"); vtf = new VirtualTempFile(); IOUtils.write("<null_resource/>", vtf); vtf.close(); } TransactionManager transact = brokerPool.getTransactionManager(); Txn txn = transact.beginTransaction(); try { broker = brokerPool.get(subject); collection = broker.openCollection(xmldbUri, Lock.WRITE_LOCK); if (collection == null) { LOG.debug("Collection " + xmldbUri + " does not exist"); transact.abort(txn); throw new CollectionDoesNotExistException(xmldbUri + ""); } if (mime.isXMLType()) { if (LOG.isDebugEnabled()) LOG.debug("Inserting XML document '" + mime.getName() + "'"); VirtualTempFileInputSource vtfis = new VirtualTempFileInputSource(vtf); IndexInfo info = collection.validateXMLResource(txn, broker, newNameUri, vtfis); DocumentImpl doc = info.getDocument(); doc.getMetadata().setMimeType(mime.getName()); collection.store(txn, broker, info, vtfis, false); } else { if (LOG.isDebugEnabled()) LOG.debug("Inserting BINARY document '" + mime.getName() + "'"); InputStream fis = vtf.getByteStream(); bis = new BufferedInputStream(fis); DocumentImpl doc = collection.addBinaryResource(txn, broker, newNameUri, bis, mime.getName(), length.longValue()); bis.close(); } transact.commit(txn); if (LOG.isDebugEnabled()) LOG.debug("Document created sucessfully"); } catch (EXistException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (TriggerException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (SAXException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (LockException e) { LOG.error(e); transact.abort(txn); throw new PermissionDeniedException(xmldbUri + ""); } catch (IOException e) { LOG.error(e); transact.abort(txn); throw e; } catch (PermissionDeniedException e) { LOG.error(e); transact.abort(txn); throw e; } finally { if (vtf != null) { vtf.delete(); } if (collection != null) { collection.release(Lock.WRITE_LOCK); } brokerPool.release(broker); if (LOG.isDebugEnabled()) LOG.debug("Finished creation"); } XmldbURI newResource = xmldbUri.append(newName); return newResource; } 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()); }
11
Code Sample 1: public static boolean filecopy(final File source, final File target) { boolean out = false; if (source.isDirectory() || !source.exists() || target.isDirectory() || source.equals(target)) return false; try { target.getParentFile().mkdirs(); target.createNewFile(); FileChannel sourceChannel = new FileInputStream(source).getChannel(); try { FileChannel targetChannel = new FileOutputStream(target).getChannel(); try { targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); out = true; } finally { targetChannel.close(); } } finally { sourceChannel.close(); } } catch (IOException e) { out = false; } return out; } 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(); }
00
Code Sample 1: public void copy(File s, File t) throws IOException { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); } Code Sample 2: public void testReleaseOnAbort() throws Exception { HttpParams params = defaultParams.copy(); ConnManagerParams.setMaxTotalConnections(params, 1); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1)); ThreadSafeClientConnManager mgr = createTSCCM(params, null); assertEquals(0, mgr.getConnectionsInPool()); DefaultHttpClient client = new DefaultHttpClient(mgr, params); HttpGet httpget = new HttpGet("/random/20000"); HttpHost target = getServerHttp(); HttpResponse response = client.execute(target, httpget); ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null); try { connreq.getConnection(250, TimeUnit.MILLISECONDS); fail("ConnectionPoolTimeoutException should have been thrown"); } catch (ConnectionPoolTimeoutException expected) { } HttpEntity e = response.getEntity(); assertNotNull(e); httpget.abort(); assertEquals(0, mgr.getConnectionsInPool()); connreq = mgr.requestConnection(new HttpRoute(target), null); ManagedClientConnection conn = connreq.getConnection(250, TimeUnit.MILLISECONDS); mgr.releaseConnection(conn, -1, null); mgr.shutdown(); }
00
Code Sample 1: public static Coordinate getCoordenadas(String RCoURL) { Coordinate coord = new Coordinate(); String pURL; String iniPC1 = "<pc1>"; String iniPC2 = "<pc2>"; String finPC1 = "</pc1>"; String finPC2 = "</pc2>"; String iniX = "<xcen>"; String iniY = "<ycen>"; String finX = "</xcen>"; String finY = "</ycen>"; String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; boolean error = false; int ini, fin; if (RCoURL.contains("/") || RCoURL.contains("\\") || RCoURL.contains(".")) pURL = RCoURL; else { if (RCoURL.length() > 14) pURL = baseURL[1].replace("<RC>", RCoURL.substring(0, 14)); else pURL = baseURL[1].replace("<RC>", RCoURL); } try { URL url = new URL(pURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { if (str.contains(iniCuerr)) { ini = str.indexOf(iniCuerr) + iniCuerr.length(); fin = str.indexOf(finCuerr); if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true; } if (error) { if (str.contains(iniDesErr)) { ini = str.indexOf(iniDesErr) + iniDesErr.length(); fin = str.indexOf(finDesErr); throw (new Exception(str.substring(ini, fin))); } } else { if (str.contains(iniPC1)) { ini = str.indexOf(iniPC1) + iniPC1.length(); fin = str.indexOf(finPC1); coord.setDescription(str.substring(ini, fin)); } if (str.contains(iniPC2)) { ini = str.indexOf(iniPC2) + iniPC2.length(); fin = str.indexOf(finPC2); coord.setDescription(coord.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniX)) { ini = str.indexOf(iniX) + iniX.length(); fin = str.indexOf(finX); coord.setLongitude(Double.parseDouble(str.substring(ini, fin))); } if (str.contains(iniY)) { ini = str.indexOf(iniY) + iniY.length(); fin = str.indexOf(finY); coord.setLatitude(Double.parseDouble(str.substring(ini, fin))); } } } in.close(); } catch (Exception e) { System.err.println(e); } return coord; } Code Sample 2: public static Book GetReviewsForBook(String bookId, int page, int rating) throws Exception { Uri.Builder builder = new Uri.Builder(); builder.scheme("http"); builder.authority("www.goodreads.com"); builder.path("book/show"); builder.appendQueryParameter("key", _ConsumerKey); builder.appendQueryParameter("page", Integer.toString(page)); builder.appendQueryParameter("rating", Integer.toString(rating)); builder.appendQueryParameter("id", bookId); HttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(builder.build().toString()); if (get_IsAuthenticated()) { _Consumer.sign(getRequest); } HttpResponse response = httpClient.execute(getRequest); Response responseData = ResponseParser.parse(response.getEntity().getContent()); return responseData.get_Book(); }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public boolean copier(String source, String nomFichierSource, java.io.File destination) { boolean resultat = false; OutputStream tmpOut; try { tmpOut = new BufferedOutputStream(new FileOutputStream(nomFichierSource + "001.tmp")); InputStream is = getClass().getResourceAsStream(source + nomFichierSource); int i; while ((i = is.read()) != -1) tmpOut.write(i); tmpOut.close(); is.close(); } catch (IOException ex) { ex.printStackTrace(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(new File(nomFichierSource + "001.tmp")).getChannel(); out = new FileOutputStream(destination).getChannel(); in.transferTo(0, in.size(), out); resultat = true; } catch (java.io.FileNotFoundException f) { } catch (java.io.IOException e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } new File(nomFichierSource + "001.tmp").delete(); return (resultat); }
11
Code Sample 1: private void processData(InputStream raw) { String fileName = remoteName; if (localName != null) { fileName = localName; } try { FileOutputStream fos = new FileOutputStream(new File(fileName), true); IOUtils.copy(raw, fos); LOG.info("ok"); } catch (IOException e) { LOG.error("error writing file", e); } } Code Sample 2: private Map<String, DomAttr> getAttributesFor(final BaseFrame frame) throws IOException { final Map<String, DomAttr> map = createAttributesCopyWithClonedAttribute(frame, "src"); final DomAttr srcAttr = map.get("src"); if (srcAttr == null) { return map; } final Page enclosedPage = frame.getEnclosedPage(); final String suffix = getFileExtension(enclosedPage); final File file = createFile(srcAttr.getValue(), "." + suffix); if (enclosedPage instanceof HtmlPage) { file.delete(); ((HtmlPage) enclosedPage).save(file); } else { final InputStream is = enclosedPage.getWebResponse().getContentAsStream(); final FileOutputStream fos = new FileOutputStream(file); IOUtils.copyLarge(is, fos); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } srcAttr.setValue(file.getParentFile().getName() + FILE_SEPARATOR + file.getName()); return map; }
00
Code Sample 1: protected String loadPage(String url_string) { try { URL url = new URL(url_string); HttpURLConnection connection = null; InputStream is = null; try { connection = (HttpURLConnection) url.openConnection(); int response = connection.getResponseCode(); if (response == HttpURLConnection.HTTP_ACCEPTED || response == HttpURLConnection.HTTP_OK) { is = connection.getInputStream(); String page = ""; while (page.length() < MAX_PAGE_SIZE) { byte[] buffer = new byte[2048]; int len = is.read(buffer); if (len < 0) { break; } page += new String(buffer, 0, len); } return (page); } else { informFailure("httpinvalidresponse", "" + response); return (null); } } finally { try { if (is != null) { is.close(); } if (connection != null) { connection.disconnect(); } } catch (Throwable e) { Debug.printStackTrace(e); } } } catch (Throwable e) { informFailure("httploadfail", e.toString()); return (null); } } Code Sample 2: @Override public boolean validatePublisher(Object object, String... dbSettingParams) { DBConnectionListener listener = (DBConnectionListener) object; String host = dbSettingParams[0]; String port = dbSettingParams[1]; String driver = dbSettingParams[2]; String type = dbSettingParams[3]; String dbHost = dbSettingParams[4]; String dbName = dbSettingParams[5]; String dbUser = dbSettingParams[6]; String dbPassword = dbSettingParams[7]; boolean validPublisher = false; String url = "http://" + host + ":" + port + "/reports"; try { URL _url = new URL(url); _url.openConnection().connect(); validPublisher = true; } catch (Exception e) { log.log(Level.FINE, "Failed validating url " + url, e); } if (validPublisher) { Connection conn; try { if (driver != null) { conn = DBProperties.getInstance().getConnection(driver, dbHost, dbName, type, dbUser, dbPassword); } else { conn = DBProperties.getInstance().getConnection(); } } catch (Exception e) { conn = null; listener.connectionIsOk(false, null); validPublisher = false; } if (validPublisher) { if (!allNecessaryTablesCreated(conn)) { conn = null; listener.connectionIsOk(false, null); validPublisher = false; } listener.connectionIsOk(true, conn); } } else { listener.connectionIsOk(false, null); } return validPublisher; }
11
Code Sample 1: public void setContentAsStream(final InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { output.close(); } this.content = output.toByteArray(); } Code Sample 2: public static void copyFile(File src, File dest, boolean preserveFileDate) throws IOException { if (src.exists() && src.isDirectory()) { throw new IOException("source file exists but is a directory"); } if (dest.exists() && dest.isDirectory()) { dest = new File(dest, src.getName()); } if (!dest.exists()) { dest.createNewFile(); } FileChannel srcCH = null; FileChannel destCH = null; try { srcCH = new FileInputStream(src).getChannel(); destCH = new FileOutputStream(dest).getChannel(); destCH.transferFrom(srcCH, 0, srcCH.size()); } finally { closeQuietly(srcCH); closeQuietly(destCH); } if (src.length() != dest.length()) { throw new IOException("Failed to copy full contents from '" + src + "' to '" + dest + "'"); } if (preserveFileDate) { dest.setLastModified(src.lastModified()); } }
11
Code Sample 1: public static void s_copy(FileInputStream fis, FileOutputStream fos) throws Exception { FileChannel in = fis.getChannel(); FileChannel out = fos.getChannel(); in.transferTo(0, in.size(), out); if (in != null) in.close(); if (out != null) out.close(); } Code Sample 2: protected byte[] readGZippedBytes(TupleInput in) { final boolean is_compressed = in.readBoolean(); byte array[] = readBytes(in); if (array == null) return null; if (!is_compressed) { return array; } try { ByteArrayInputStream bais = new ByteArrayInputStream(array); GZIPInputStream gzin = new GZIPInputStream(bais); ByteArrayOutputStream baos = new ByteArrayOutputStream(array.length); IOUtils.copyTo(gzin, baos); gzin.close(); bais.close(); return baos.toByteArray(); } catch (IOException err) { throw new RuntimeException(err); } }
11
Code Sample 1: static final String md5(String text) throws RtmApiException { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("UTF-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException e) { throw new RtmApiException("Md5 error: NoSuchAlgorithmException - " + e.getMessage()); } catch (UnsupportedEncodingException e) { throw new RtmApiException("Md5 error: UnsupportedEncodingException - " + e.getMessage()); } } Code Sample 2: public static String hashURL(String url) { if (url == null) { throw new IllegalArgumentException("URL may not be null. "); } String result = null; try { MessageDigest md = MessageDigest.getInstance("SHA-1"); if (md != null) { md.reset(); md.update(url.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); result = hash.toString(16); } md = null; } catch (NoSuchAlgorithmException ex) { result = null; } return result; }
11
Code Sample 1: public void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static Object fetchCached(String address, int hours) throws MalformedURLException, IOException { String cacheName = md5(address); checkAndCreateDirectoryIfNeeded(); File r = new File(CACHELOCATION + cacheName); Date d = new Date(); long limit = d.getTime() - (1000 * 60 * 60 * hours); if (!r.exists() || (hours != -1 && r.lastModified() < limit)) { InputStream is = (InputStream) fetch(address); FileOutputStream fos = new FileOutputStream(CACHELOCATION + cacheName); int nextChar; while ((nextChar = is.read()) != -1) fos.write((char) nextChar); fos.flush(); } FileInputStream fis = new FileInputStream(CACHELOCATION + cacheName); return fis; }
11
Code Sample 1: @Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { expected = new StringBuilder(); System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + (queryString = httpServletRequest.getQueryString())); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + (body = baos.toString())); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); expected.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); expected.append(value); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); } Code Sample 2: public void writeData(String name, int items, int mznum, int mzscale, long tstart, long tdelta, int[] peaks) { PrintWriter file = getWriter(name + ".txt"); file.println("999 9999"); file.println("Doe, John"); file.println("TEST Lab"); if (mzscale == 1) file.println("PALMS Positive Ion Data"); else if (mzscale == -1) file.println("PALMS Negative Ion Data"); else file.println("PALMS GJIFJIGJ Ion Data"); file.println("TEST Mission"); file.println("1 1"); file.println("1970 01 01 2008 07 09"); file.println("0"); file.println("TIME (UT SECONDS)"); file.println(mznum + 4); for (int i = 0; i < mznum + 4; i++) file.println("1.0"); for (int i = 0; i < mznum + 4; i++) file.println("9.9E29"); file.println("TOTION total MCP signal (electron units)"); file.println("HMASS high mass integral (fraction)"); file.println("UNLIST (unlisted low mass peaks (fraction)"); file.println("UFO unidentified peaks (fraction)"); for (int i = 1; i <= mznum; i++) file.println("MS" + i + " (fraction)"); int header2length = 13; file.println(header2length); for (int i = 0; i < header2length; i++) file.println("1.0"); for (int i = 0; i < header2length; i++) file.println("9.9E29"); file.println("AirCraftTime aircraft time (s)"); file.println("INDEX index ()"); file.println("SCAT scatter (V)"); file.println("JMETER joule meter ()"); file.println("ND neutral density (fraction)"); file.println("SCALEA Mass scale intercept (us)"); file.println("SCALEB mass scale slope (us)"); file.println("NUMPKS number of peaks ()"); file.println("CONF confidence (coded)"); file.println("CAT preliminary category ()"); file.println("AeroDiam aerodynamic diameter (um)"); file.println("AeroDiam1p7 aero diam if density=1.7 (um)"); file.println("TOTBACK total background subtracted (electron units)"); file.println("0"); file.println("0"); String nothing = "0.000000"; for (int i = 0; i < items; i++) { file.println(tstart + (tdelta * i)); file.println(tstart + (tdelta * i) - 3); file.println(i + 1); for (int j = 0; j < 15; j++) file.println(Math.random()); boolean peaked = false; for (int k = 1; k <= mznum; k++) { for (int j = 0; j < peaks.length && !peaked; j++) if (k == peaks[j]) { double randData = (int) (1000000 * (j + 1)); file.println(randData / 1000000); peaked = true; } if (!peaked) file.println(nothing); peaked = false; } } try { Scanner test = new Scanner(f); while (test.hasNext()) { System.out.println(test.nextLine()); } System.out.println("test"); } catch (Exception e) { } file.close(); }
11
Code Sample 1: @Test public void testWriteModel() { Model model = new Model(); model.setName("MY_MODEL1"); Stereotype st1 = new Stereotype(); st1.setName("Pirulito1"); PackageObject p1 = new PackageObject("p1"); ClassType type1 = new ClassType("Class1"); type1.setStereotype(st1); type1.addMethod(new Method("doSomething")); p1.add(type1); ClassType type2 = new ClassType("Class2"); Method m2 = new Method("doSomethingElse"); m2.setType(type1); type2.addMethod(m2); p1.add(type2); Generalization g = new Generalization(); g.setSource(type1); g.setTarget(type1); p1.add(g); model.add(p1); ModelWriter writer = new ModelWriter(); try { File modelFile = new File("target", "test.model"); writer.write(model, modelFile); File xmlFile = new File("target", "test.xml"); xmlFile.createNewFile(); IOUtils.copy(new GZIPInputStream(new FileInputStream(modelFile)), new FileOutputStream(xmlFile)); } catch (IOException e) { log.error(e.getMessage(), e); Assert.fail(e.getMessage()); } } Code Sample 2: @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, final HttpServletResponse response) throws Exception { final String id = request.getParameter("id"); if (id == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } try { jaxrTemplate.execute(new JAXRCallback<Object>() { public Object execute(Connection connection) throws JAXRException { RegistryObject registryObject = connection.getRegistryService().getBusinessQueryManager().getRegistryObject(id); if (registryObject instanceof ExtrinsicObject) { ExtrinsicObject extrinsicObject = (ExtrinsicObject) registryObject; DataHandler dataHandler = extrinsicObject.getRepositoryItem(); if (dataHandler != null) { response.setContentType("text/html"); try { PrintWriter out = response.getWriter(); InputStream is = dataHandler.getInputStream(); try { final XMLStreamWriter xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(out); xmlStreamWriter.writeStartDocument(); xmlStreamWriter.writeStartElement("div"); xmlStreamWriter.writeStartElement("textarea"); xmlStreamWriter.writeAttribute("name", "repositoryItem"); xmlStreamWriter.writeAttribute("class", "xml"); xmlStreamWriter.writeAttribute("style", "display:none"); IOUtils.copy(new XmlInputStreamReader(is), new XmlStreamTextWriter(xmlStreamWriter)); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeStartElement("script"); xmlStreamWriter.writeAttribute("class", "javascript"); xmlStreamWriter.writeCharacters("dp.SyntaxHighlighter.HighlightAll('repositoryItem');"); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndDocument(); xmlStreamWriter.flush(); } finally { is.close(); } } catch (Throwable ex) { log.error("Error while trying to format repository item " + id, ex); } } else { } } else { } return null; } }); } catch (JAXRException ex) { throw new ServletException(ex); } return null; }
11
Code Sample 1: public static String MD5(String text) { MessageDigest md; try { 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 (NoSuchAlgorithmException ex) { ex.printStackTrace(); return text; } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); return text; } } Code Sample 2: public static String encrypt(String text) throws NoSuchAlgorithmException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; try { md.update(text.getBytes("iso-8859-1"), 0, text.length()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: public static final String getUniqueKey() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; ; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { println("Warn: getUniqueKey(), Error trying to get localhost" + e.getMessage()); } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { println("Warn: getUniqueKey() " + e); } return digest; } Code Sample 2: private static File createTempWebXml(Class portletClass, File portletDir, String appName, String portletName) throws IOException, FileNotFoundException { File pathToWebInf = new File(portletDir, "WEB-INF"); File tempWebXml = File.createTempFile("web", ".xml", pathToWebInf); tempWebXml.deleteOnExit(); OutputStream webOutputStream = new FileOutputStream(tempWebXml); PortletUnitWebXmlStream streamSource = WEB_XML_STREAM_FACTORY; IOUtils.copy(streamSource.createStream(portletClass, appName, portletName), webOutputStream); webOutputStream.close(); return tempWebXml; }
11
Code Sample 1: private Image retrievePdsImage(double lat, double lon) { imageDone = false; try { StringBuffer urlBuff = new StringBuffer(psdUrl + psdCgi + "?"); urlBuff.append("DATA_SET_NAME=" + dataSet); urlBuff.append("&VERSION=" + version); urlBuff.append("&PIXEL_TYPE=" + pixelType); urlBuff.append("&PROJECTION=" + projection); urlBuff.append("&STRETCH=" + stretch); urlBuff.append("&GRIDLINE_FREQUENCY=" + gridlineFrequency); urlBuff.append("&SCALE=" + URLEncoder.encode(scale)); urlBuff.append("&RESOLUTION=" + resolution); urlBuff.append("&LATBOX=" + latbox); urlBuff.append("&LONBOX=" + lonbox); urlBuff.append("&BANDS_SELECTED=" + bandsSelected); urlBuff.append("&LAT=" + lat); urlBuff.append("&LON=" + lon); URL url = new URL(urlBuff.toString()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String result = null; String line; String imageSrc; int count = 0; while ((line = in.readLine()) != null) { if (count == 6) result = line; count++; } int startIndex = result.indexOf("<TH COLSPAN=2 ROWSPAN=2><IMG SRC = \"") + 36; int endIndex = result.indexOf("\"", startIndex); imageSrc = result.substring(startIndex, endIndex); URL imageUrl = new URL(imageSrc); return (Toolkit.getDefaultToolkit().getImage(imageUrl)); } catch (MalformedURLException e) { } catch (IOException e) { } return null; } Code Sample 2: private void readVersion() { URL url = ClassLoader.getSystemResource("version"); if (url == null) { return; } BufferedReader reader = null; String line = null; try { reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { if (line.startsWith("Version=")) { version = (line.split("="))[1]; } if (line.startsWith("Revision=")) { revision = (line.split("="))[1]; } if (line.startsWith("Date=")) { String sSec = (line.split("="))[1]; Long lSec = Long.valueOf(sSec); compileDate = new Date(lSec); } } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return; }
00
Code Sample 1: public static Image getPluginImage(Object plugin, String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; } Code Sample 2: public IUserProfile getUserProfile(String profileID) throws MM4UUserProfileNotFoundException { SimpleUserProfile tempProfile = null; String tempProfileString = this.profileURI + profileID + FILE_SUFFIX; try { URL url = new URL(tempProfileString); Debug.println("Retrieve profile with ID: " + url); tempProfile = new SimpleUserProfile(); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); String tempLine = null; tempProfile.add("id", profileID); while ((tempLine = input.readLine()) != null) { Property tempProperty = PropertyList.splitStringIntoKeyAndValue(tempLine); if (tempProperty != null) { tempProfile.addIfNotNull(tempProperty.getKey(), tempProperty.getValue()); } } input.close(); } catch (MalformedURLException exception) { throw new MM4UUserProfileNotFoundException(this, "getProfile", "Profile '" + tempProfileString + "' not found."); } catch (IOException exception) { throw new MM4UUserProfileNotFoundException(this, "getProfile", "Profile '" + tempProfileString + "' not found."); } return tempProfile; }
00
Code Sample 1: private void setup() { env = new EnvAdvanced(); try { URL url = Sysutil.getURL("world.env"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null) { String[] fields = line.split(","); if (fields[0].equalsIgnoreCase("skybox")) { env.setRoom(new EnvSkyRoom(fields[1])); } else if (fields[0].equalsIgnoreCase("camera")) { env.setCameraXYZ(Double.parseDouble(fields[1]), Double.parseDouble(fields[2]), Double.parseDouble(fields[3])); env.setCameraYaw(Double.parseDouble(fields[4])); env.setCameraPitch(Double.parseDouble(fields[5])); } else if (fields[0].equalsIgnoreCase("terrain")) { terrain = new EnvTerrain(fields[1]); terrain.setTexture(fields[2]); env.addObject(terrain); } else if (fields[0].equalsIgnoreCase("object")) { GameObject n = (GameObject) Class.forName(fields[10]).newInstance(); n.setX(Double.parseDouble(fields[1])); n.setY(Double.parseDouble(fields[2])); n.setZ(Double.parseDouble(fields[3])); n.setScale(Double.parseDouble(fields[4])); n.setRotateX(Double.parseDouble(fields[5])); n.setRotateY(Double.parseDouble(fields[6])); n.setRotateZ(Double.parseDouble(fields[7])); n.setTexture(fields[9]); n.setModel(fields[8]); n.setEnv(env); env.addObject(n); } } } catch (Exception e) { e.printStackTrace(); } } 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: @Override protected void writeFile() { super.writeFile(); try { String tagListFilePath = file.toURI().toASCIIString(); tagListFilePath = tagListFilePath.substring(0, tagListFilePath.lastIndexOf(FileManager.GLIPS_VIEW_EXTENSION)) + FileManager.TAG_LIST_FILE_EXTENSION; File tagListFile = new File(new URI(tagListFilePath)); StringBuffer buffer = new StringBuffer(""); for (String tagName : tags) { buffer.append(tagName + "\n"); } ByteBuffer byteBuffer = ByteBuffer.wrap(buffer.toString().getBytes("UTF-8")); FileOutputStream out = new FileOutputStream(tagListFile); FileChannel channel = out.getChannel(); channel.write(byteBuffer); channel.close(); } catch (Exception ex) { } try { String parentPath = file.getParentFile().toURI().toASCIIString(); if (!parentPath.endsWith("/")) { parentPath += "/"; } File srcFile = null, destFile = null; byte[] tab = new byte[1000]; int nb = 0; InputStream in = null; OutputStream out = null; for (String destinationName : dataBaseFiles.keySet()) { srcFile = dataBaseFiles.get(destinationName); if (srcFile != null) { destFile = new File(new URI(parentPath + destinationName)); in = new BufferedInputStream(new FileInputStream(srcFile)); out = new BufferedOutputStream(new FileOutputStream(destFile)); while (in.available() > 0) { nb = in.read(tab); if (nb > 0) { out.write(tab, 0, nb); } } in.close(); out.flush(); out.close(); } } } catch (Exception ex) { ex.printStackTrace(); } } Code Sample 2: private void copyFile(File srcFile, File destFile) throws IOException { if (!(srcFile.exists() && srcFile.isFile())) throw new IllegalArgumentException("Source file doesn't exist: " + srcFile.getAbsolutePath()); if (destFile.exists() && destFile.isDirectory()) throw new IllegalArgumentException("Destination file is directory: " + destFile.getAbsolutePath()); FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[4096]; int no = 0; try { while ((no = in.read(buffer)) != -1) out.write(buffer, 0, no); } finally { in.close(); out.close(); } }
00
Code Sample 1: @Override public void execute() throws BuildException { final String GC_USERNAME = "google-code-username"; final String GC_PASSWORD = "google-code-password"; if (StringUtils.isBlank(this.projectName)) throw new BuildException("undefined project"); if (this.file == null) throw new BuildException("undefined file"); if (!this.file.exists()) throw new BuildException("file not found :" + file); if (!this.file.isFile()) throw new BuildException("not a file :" + file); if (this.config == null) throw new BuildException("undefined config"); if (!this.config.exists()) throw new BuildException("file not found :" + config); if (!this.config.isFile()) throw new BuildException("not a file :" + config); PostMethod post = null; try { Properties cfg = new Properties(); FileInputStream fin = new FileInputStream(this.config); cfg.loadFromXML(fin); fin.close(); if (!cfg.containsKey(GC_USERNAME)) throw new BuildException("undefined " + GC_USERNAME + " in " + this.config); if (!cfg.containsKey(GC_PASSWORD)) throw new BuildException("undefined " + GC_PASSWORD + " in " + this.config); HttpClient client = new HttpClient(); post = new PostMethod("https://" + projectName + ".googlecode.com/files"); post.addRequestHeader("User-Agent", getClass().getName()); post.addRequestHeader("Authorization", "Basic " + Base64.encode(cfg.getProperty(GC_USERNAME) + ":" + cfg.getProperty(GC_PASSWORD))); List<Part> parts = new ArrayList<Part>(); String s = this.summary; if (StringUtils.isBlank(s)) { s = this.file.getName() + " (" + TimeUtils.toYYYYMMDD() + ")"; } parts.add(new StringPart("summary", s)); for (String lbl : this.labels.split("[, \t\n]+")) { if (StringUtils.isBlank(lbl)) continue; parts.add(new StringPart("label", lbl.trim())); } parts.add(new FilePart("filename", this.file)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()); post.setRequestEntity(requestEntity); int status = client.executeMethod(post); if (status != 201) { throw new BuildException("http status !=201 : " + post.getResponseBodyAsString()); } else { IOUtils.copyTo(post.getResponseBodyAsStream(), new NullOutputStream()); } } catch (BuildException e) { throw e; } catch (Exception e) { throw new BuildException(e); } finally { if (post != null) post.releaseConnection(); } } Code Sample 2: public synchronized void readConfiguration() throws IOException, SecurityException { String path; InputStream inputStream; path = System.getProperty("java.util.logging.config.file"); if ((path == null) || (path.length() == 0)) { String url = (System.getProperty("gnu.classpath.home.url") + "/logging.properties"); inputStream = new URL(url).openStream(); } else inputStream = new java.io.FileInputStream(path); try { readConfiguration(inputStream); } finally { inputStream.close(); } }
00
Code Sample 1: 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(); } } Code Sample 2: void loadImage(Frame frame, URL url) throws Exception { URLConnection conn = url.openConnection(); String mimeType = conn.getContentType(); long length = conn.getContentLength(); InputStream is = conn.getInputStream(); loadImage(frame, is, length, mimeType); }
00
Code Sample 1: public static SpeciesTree create(String url) throws IOException { SpeciesTree tree = new SpeciesTree(); tree.setUrl(url); System.out.println("Fetching URL: " + url); BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String toParse = null; Properties properties = new Properties(); properties.load(in); String line = properties.getProperty("TREE"); if (line == null) return null; int end = line.indexOf(';'); if (end < 0) end = line.length(); toParse = line.substring(0, end).trim(); System.out.print("Parsing... "); parse(tree, toParse, properties); return tree; } Code Sample 2: public boolean uploadFromServlet(InputStream is, String serverFileName, String serverPath, String serverUrl, int serverPort, String userName, String passWord) throws IOException { FTPClient ftp = new FTPClient(); FTPClientConfig conf = new FTPClientConfig(); conf.setServerLanguageCode("zh_CN"); conf.setServerTimeZoneId("Asia/Chongqing"); try { ftp.configure(conf); int reply; ftp.setDefaultPort(serverPort); ftp.connect(serverUrl); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("FTP server refused connection."); } } catch (IOException e) { disconnectFtp(ftp); } try { if (!ftp.login(userName, passWord)) { throw new IOException("Can not log in with given username and password."); } if (!ftp.changeWorkingDirectory(serverPath)) { throw new IOException("Can not change to working directory."); } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (!ftp.storeFile(serverFileName, is)) { throw new IOException("Can not store file to FTP server."); } is.close(); } catch (SocketException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (ftp != null && ftp.isConnected()) { try { ftp.logout(); ftp.disconnect(); } catch (IOException e) { e.printStackTrace(); return false; } } } return true; }
00
Code Sample 1: private Attachment setupSimpleAttachment(Context context, long messageId, boolean withBody) throws IOException { Attachment attachment = new Attachment(); attachment.mFileName = "the file.jpg"; attachment.mMimeType = "image/jpg"; attachment.mSize = 0; attachment.mContentId = null; attachment.mContentUri = "content://com.android.email/1/1"; attachment.mMessageKey = messageId; attachment.mLocation = null; attachment.mEncoding = null; if (withBody) { InputStream inStream = new ByteArrayInputStream(TEST_STRING.getBytes()); File cacheDir = context.getCacheDir(); File tmpFile = File.createTempFile("setupSimpleAttachment", "tmp", cacheDir); OutputStream outStream = new FileOutputStream(tmpFile); IOUtils.copy(inStream, outStream); attachment.mContentUri = "file://" + tmpFile.getAbsolutePath(); } return attachment; } Code Sample 2: public static void storePolicy(DBBroker broker, XmldbURI docPath) throws EXistException, IOException { XmldbURI docName = docPath.lastSegment(); URL url = XACMLUtil.class.getResource(docPath.toString()); if (url == null) return; String content = toString(url.openStream()); if (content == null) return; Collection collection = getPolicyCollection(broker); if (collection == null) return; TransactionManager transact = broker.getBrokerPool().getTransactionManager(); Txn txn = transact.beginTransaction(); try { IndexInfo info = collection.validateXMLResource(txn, broker, docName, content); collection.store(txn, broker, info, content, false); transact.commit(txn); } catch (Exception e) { transact.abort(txn); if (e instanceof EXistException) throw (EXistException) e; throw new EXistException("Error storing policy '" + docPath + "'", 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: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public String expandTemplate(String target) throws IOException, HttpException { connect(); try { HttpGet request = new HttpGet(contextPath + target); HttpResponse response = httpexecutor.execute(request, conn); TolvenLogger.info("Response: " + response.getStatusLine(), TemplateGen.class); disconnect(); return EntityUtils.toString(response.getEntity()); } finally { disconnect(); } } Code Sample 2: public static File copy(String inFileName, String outFileName) throws IOException { File inputFile = new File(inFileName); File outputFile = new File(outFileName); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return outputFile; }
00
Code Sample 1: public void init() { String inputLine = ""; String registeredLine = ""; println("Insert RSS link:"); String urlString = sc.nextLine(); if (urlString.length() == 0) init(); println("Working..."); BufferedReader in = null; URL url = null; try { url = new URL(urlString); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = in.readLine()) != null) registeredLine += inputLine; in.close(); } catch (MalformedURLException e2) { e2.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } File elenco = new File("elenco.txt"); PrintWriter pout = null; try { pout = new PrintWriter(elenco); } catch (FileNotFoundException e1) { e1.printStackTrace(); } Vector<String> vector = new Vector<String>(); int endIndex = 0; int numeroFoto = 0; while ((registeredLine = registeredLine.substring(endIndex)).length() > 10) { int startIndex = registeredLine.indexOf("<media:content url='"); if (startIndex == -1) break; registeredLine = registeredLine.substring(startIndex); String address = ""; startIndex = registeredLine.indexOf("http://"); endIndex = registeredLine.indexOf("' height"); address = registeredLine.substring(startIndex, endIndex); println(address); pout.println(address); vector.add(address); numeroFoto++; } if (pout.checkError()) println("ERROR"); println("Images number: " + numeroFoto); if (numeroFoto == 0) { println("No photos found, WebAlbum is empty or the RSS link is incorrect."); sc.nextLine(); System.exit(0); } println("Start downloading? (y/n)"); if (!sc.nextLine().equalsIgnoreCase("y")) System.exit(0); SimpleDateFormat data = new SimpleDateFormat("dd-MM-yy_HH.mm"); Calendar oggi = Calendar.getInstance(); String cartella = data.format(oggi.getTime()); boolean success = new File(cartella).mkdir(); if (success) println("Sub-directory created..."); println("downloading...\npress ctrl-C to stop"); BufferedInputStream bin = null; BufferedOutputStream bout = null; URL photoAddr = null; int len = 0; for (int x = 0; x < vector.size(); x++) { println("file " + (x + 1) + " of " + numeroFoto); try { photoAddr = new URL(vector.get(x)); bin = new BufferedInputStream(photoAddr.openStream()); bout = new BufferedOutputStream(new FileOutputStream(cartella + "/" + (x + 1) + ".jpg")); while ((len = bin.read()) != -1) bout.write(len); bout.flush(); bout.close(); bin.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } println("Done!"); } Code Sample 2: @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "getPeerPrincipal", args = { }) public final void test_getPeerPrincipal() throws Exception { try { URL url = new URL("https://localhost:55555"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); try { connection.getPeerPrincipal(); fail("IllegalStateException wasn't thrown"); } catch (IllegalStateException ise) { } } catch (Exception e) { fail("Unexpected exception " + e + " for exception case"); } HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508"); try { Principal p = con.getPeerPrincipal(); fail("SSLPeerUnverifiedException wasn't thrown"); } catch (SSLPeerUnverifiedException e) { } con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509"); try { Principal p = con.getPeerPrincipal(); assertNotNull(p); } catch (Exception e) { fail("Unexpected exception " + e); } }
11
Code Sample 1: public static void copyFile(String inputFile, String outputFile) throws IOException { FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); for (int b = fis.read(); b != -1; b = fis.read()) fos.write(b); fos.close(); fis.close(); } 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: 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: public String 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 convertToHex(sha1hash); }
00
Code Sample 1: private String hashMD5(String strToHash) throws Exception { try { byte[] bHash = new byte[strToHash.length() * 2]; MessageDigest md = MessageDigest.getInstance("MD5"); md.update(strToHash.getBytes("UTF-16LE")); bHash = md.digest(); StringBuffer hexString = new StringBuffer(); for (byte element : bHash) { String strTemp = Integer.toHexString(element); hexString.append(strTemp.replaceAll("f", "")); } return hexString.toString(); } catch (NoSuchAlgorithmException duu) { throw new Exception("NoSuchAlgorithmException: " + duu.getMessage()); } } Code Sample 2: @Override public void run() { EventType type = event.getEventType(); IBaseObject field = event.getField(); log.info("select----->" + field.getAttribute(IDatafield.URL)); try { IParent parent = field.getParent(); String name = field.getName(); if (type == EventType.ON_BTN_CLICK) { invoke(parent, "eventRule_" + name); Object value = event.get(Event.ARG_VALUE); if (value != null && value instanceof String[]) { String[] args = (String[]) value; for (String arg : args) log.info("argument data: " + arg); } } else if (type == EventType.ON_BEFORE_DOWNLOAD) invoke(parent, "eventRule_" + name); else if (type == EventType.ON_VALUE_CHANGE) { String pattern = (String) event.get(Event.ARG_PATTERN); Object value = event.get(Event.ARG_VALUE); Class cls = field.getDataType(); if (cls == null || value == null || value.getClass().equals(cls)) field.setValue(value); else if (pattern == null) field.setValue(ConvertUtils.convert(value.toString(), cls)); else if (Date.class.isAssignableFrom(cls)) field.setValue(new SimpleDateFormat(pattern).parse((String) value)); else if (Number.class.isAssignableFrom(cls)) field.setValue(new DecimalFormat(pattern).parse((String) value)); else field.setValue(new MessageFormat(pattern).parse((String) value)); invoke(parent, "checkRule_" + name); invoke(parent, "defaultRule_" + name); } else if (type == EventType.ON_ROW_SELECTED) { log.info("table row selected."); Object selected = event.get(Event.ARG_ROW_INDEX); if (selected instanceof Integer) presentation.setSelectedRowIndex((IModuleList) field, (Integer) selected); else if (selected instanceof List) { String s = ""; String conn = ""; for (Integer item : (List<Integer>) selected) { s = s + conn + item; conn = ","; } log.info("row " + s + " line(s) been selected."); } } else if (type == EventType.ON_ROW_DBLCLICK) { log.info("table row double-clicked."); presentation.setSelectedRowIndex((IModuleList) field, (Integer) event.get(Event.ARG_ROW_INDEX)); } else if (type == EventType.ON_ROW_INSERT) { log.info("table row inserted."); listAdd((IModuleList) field, (Integer) event.get(Event.ARG_ROW_INDEX)); } else if (type == EventType.ON_ROW_REMOVE) { log.info("table row removed."); listRemove((IModuleList) field, (Integer) event.get(Event.ARG_ROW_INDEX)); } else if (type == EventType.ON_FILE_UPLOAD) { log.info("file uploaded."); InputStream is = (InputStream) event.get(Event.ARG_VALUE); String uploadFileName = (String) event.get(Event.ARG_FILE_NAME); log.info("<-----file name:" + uploadFileName); OutputStream os = (OutputStream) field.getValue(); IOUtils.copy(is, os); is.close(); os.close(); } } catch (Exception e) { if (field != null) log.info("field type is :" + field.getDataType().getName()); log.info("select", e); } }
00
Code Sample 1: public static String upload_file(String sessionid, String localFilePath, String remoteTagPath) { String jsonstring = "If you see this message, there is some problem inside the function:upload_file()"; String srcPath = localFilePath; String uploadUrl = "https://s2.cloud.cm/rpc/json/?session_id=" + sessionid + "&c=Storage&m=upload_file&tag=" + remoteTagPath; String end = "\r\n"; String twoHyphens = "--"; String boundary = "******"; try { URL url = new URL(uploadUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Connection", "Keep-Alive"); httpURLConnection.setRequestProperty("Charset", "UTF-8"); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream()); dos.writeBytes(twoHyphens + boundary + end); dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + srcPath.substring(srcPath.lastIndexOf("/") + 1) + "\"" + end); dos.writeBytes(end); FileInputStream fis = new FileInputStream(srcPath); byte[] buffer = new byte[8192]; int count = 0; while ((count = fis.read(buffer)) != -1) { dos.write(buffer, 0, count); } fis.close(); dos.writeBytes(end); dos.writeBytes(twoHyphens + boundary + twoHyphens + end); dos.flush(); InputStream is = httpURLConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); jsonstring = br.readLine(); dos.close(); is.close(); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; } Code Sample 2: public InputStream open() { try { if ("file".equals(url.getProtocol())) { if (new File(url.toURI()).exists()) { inputStream = url.openStream(); } } else { con = url.openConnection(); if (con instanceof JarURLConnection) { JarURLConnection jarCon = (JarURLConnection) con; jarCon.setUseCaches(false); jarFile = jarCon.getJarFile(); } inputStream = con.getInputStream(); } } catch (Exception e) { } return inputStream; }
00
Code Sample 1: @Override public void run() { try { long pos = begin; byte[] buf = new byte[1024]; URLConnection cn = url.openConnection(); Utils.setHeader(cn); cn.setRequestProperty("Range", "bytes=" + begin + "-" + end); BufferedInputStream bis = new BufferedInputStream(cn.getInputStream()); int len; while ((len = bis.read(buf)) > 0) { synchronized (file) { file.seek(pos); file.write(buf, 0, len); } pos += len; Statics.getInstance().addComleted(len); } } catch (Exception e) { e.printStackTrace(); } latch.countDown(); } Code Sample 2: private MapProperties readProperties(URL url) { @SuppressWarnings("unchecked") MapProperties properties = new MapProperties(new LinkedHashMap()); InputStream is = null; try { is = url.openStream(); properties.load(is); } catch (IOException ex) { throw new RuntimeException(ex); } finally { StreamUtils.close(is); } return properties; }
00
Code Sample 1: private static void zip(ZipOutputStream aOutputStream, final File[] aFiles, final String sArchive, final URI aRootURI, final String sFilter) throws FileError { boolean closeStream = false; if (aOutputStream == null) try { aOutputStream = new ZipOutputStream(new FileOutputStream(sArchive)); closeStream = true; } catch (final FileNotFoundException e) { throw new FileError("Can't create ODF file!", e); } try { try { for (final File curFile : aFiles) { aOutputStream.putNextEntry(new ZipEntry(URLDecoder.decode(aRootURI.relativize(curFile.toURI()).toASCIIString(), "UTF-8"))); if (curFile.isDirectory()) { aOutputStream.closeEntry(); FileUtils.zip(aOutputStream, FileUtils.getFiles(curFile, sFilter), sArchive, aRootURI, sFilter); continue; } final FileInputStream inputStream = new FileInputStream(curFile); for (int i; (i = inputStream.read(FileUtils.BUFFER)) != -1; ) aOutputStream.write(FileUtils.BUFFER, 0, i); inputStream.close(); aOutputStream.closeEntry(); } } finally { if (closeStream && aOutputStream != null) aOutputStream.close(); } } catch (final IOException e) { throw new FileError("Can't zip file to archive!", e); } if (closeStream) DocumentController.getStaticLogger().fine(aFiles.length + " files and folders zipped as " + sArchive); } Code Sample 2: public InputStream open(String filename) throws IOException { URL url = TemplateLoader.resolveURL("cms/" + filename); if (url != null) return url.openStream(); url = TemplateLoader.resolveURL(filename); if (url != null) return url.openStream(); return null; }
11
Code Sample 1: 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)); } Code Sample 2: private WikiSiteContentInfo createInfoIndexSite(Long domainId) { final UserInfo user = getSecurityService().getCurrentUser(); final Locale locale = new Locale(user.getLocale()); final String country = locale.getLanguage(); InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("wiki_index_" + country + ".xhtml"); if (inStream == null) { inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("wiki_index.xhtml"); } if (inStream == null) { inStream = new ByteArrayInputStream(DEFAULT_WIKI_INDEX_SITE_TEXT.getBytes()); } if (inStream != null) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copyLarge(inStream, out); return createIndexVersion(domainId, out.toString(), user); } catch (IOException exception) { LOGGER.error("Error creating info page.", exception); } finally { try { inStream.close(); out.close(); } catch (IOException exception) { LOGGER.error("Error reading wiki_index.xhtml", exception); } } } return null; }
11
Code Sample 1: public static String SHA1(String string) throws XLWrapException { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new XLWrapException("SHA-1 message digest is not available."); } byte[] data = new byte[40]; md.update(string.getBytes()); data = md.digest(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); } Code Sample 2: private static String scramble(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (byte b : md.digest()) sb.append(Integer.toString(b & 0xFF, 16)); return sb.toString(); } catch (UnsupportedEncodingException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } }
11
Code Sample 1: 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()); } Code Sample 2: public static void copyFile(String oldPath, String newPath) throws IOException { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } inStream.close(); } }
00
Code Sample 1: private static final String getResult(String url, String postData) throws MalformedURLException, IOException { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); if (!postData.equals("null")) { postData = postData.substring(1, postData.length() - 1); connection.setDoOutput(true); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); writer.write(postData); writer.flush(); } InputStreamReader reader = new InputStreamReader(connection.getInputStream()); int i; StringBuffer buffer = new StringBuffer(); while ((i = reader.read()) != -1) { buffer.append((char) i); } reader.close(); String response = buffer.toString().trim(); response = StringUtilities.replaceAll(response, "\r\n", "\\r\\n"); response = StringUtilities.replaceAll(response, "\"", "\\\""); return "\"" + response + "\""; } Code Sample 2: protected String getRequestContent(String urlText) throws Exception { URL url = new URL(urlText); HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); String line = null; try { urlcon.setUseCaches(false); urlcon.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream())); line = reader.readLine(); reader.close(); } finally { urlcon.disconnect(); } return line; }
11
Code Sample 1: public String doUpload(@ParamName(name = "file") MultipartFile file, @ParamName(name = "uploadDirectory") String _uploadDirectory) throws IOException { String sessionId = (String) RuntimeAccess.getInstance().getSession().getAttribute("SESSION_ID"); String tempUploadDir = MewitProperties.getTemporaryUploadDirectory(); if (!tempUploadDir.endsWith("/") && !tempUploadDir.endsWith("\\")) { tempUploadDir += "\\"; } String fileName = null; int position = file.getOriginalFilename().lastIndexOf("."); if (position <= 0) { fileName = java.util.UUID.randomUUID().toString(); } else { fileName = java.util.UUID.randomUUID().toString() + file.getOriginalFilename().substring(position); } File outputFile = new File(tempUploadDir, fileName); log(INFO, "writing the content of uploaded file to: " + outputFile); FileOutputStream fos = new FileOutputStream(outputFile); IOUtils.copy(file.getInputStream(), fos); file.getInputStream().close(); fos.close(); return doUploadFile(sessionId, outputFile, file.getOriginalFilename()); } Code Sample 2: public long copyDirAllFilesToDirectoryRecursive(String baseDirStr, String destDirStr, boolean copyOutputsRtIDsDirs) throws Exception { long plussQuotaSize = 0; if (baseDirStr.endsWith(sep)) { baseDirStr = baseDirStr.substring(0, baseDirStr.length() - 1); } if (destDirStr.endsWith(sep)) { destDirStr = destDirStr.substring(0, destDirStr.length() - 1); } FileUtils.getInstance().createDirectory(destDirStr); BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File baseDir = new File(baseDirStr); baseDir.mkdirs(); if (!baseDir.exists()) { createDirectory(baseDirStr); } if ((baseDir.exists()) && (baseDir.isDirectory())) { String[] entryList = baseDir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String oldPathFileName = baseDirStr + sep + entryName; File entryFile = new File(oldPathFileName); if (entryFile.isFile()) { String newPathFileName = destDirStr + sep + entryName; File newFile = new File(newPathFileName); if (newFile.exists()) { plussQuotaSize -= newFile.length(); newFile.delete(); } in = new BufferedInputStream(new FileInputStream(oldPathFileName), bufferSize); out = new BufferedOutputStream(new FileOutputStream(newPathFileName), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } if (entryFile.isDirectory()) { boolean enableCopyDir = false; if (copyOutputsRtIDsDirs) { enableCopyDir = true; } else { if (entryFile.getParentFile().getName().equals("outputs")) { enableCopyDir = false; } else { enableCopyDir = true; } } if (enableCopyDir) { plussQuotaSize += this.copyDirAllFilesToDirectoryRecursive(baseDirStr + sep + entryName, destDirStr + sep + entryName, copyOutputsRtIDsDirs); } } } } } else { throw new Exception("Base dir not exist ! baseDirStr = (" + baseDirStr + ")"); } return plussQuotaSize; }
00
Code Sample 1: public void init(final javax.swing.text.Document doc) { this.doc = doc; String dtdLocation = null; String schemaLocation = null; SyntaxDocument mDoc = (SyntaxDocument) doc; Object mDtd = mDoc.getProperty(XPontusConstantsIF.PARSER_DATA_DTD_COMPLETION_INFO); Object mXsd = mDoc.getProperty(XPontusConstantsIF.PARSER_DATA_SCHEMA_COMPLETION_INFO); if (mDtd != null) { dtdLocation = mDtd.toString(); } if (mXsd != null) { schemaLocation = mXsd.toString(); } Object o = doc.getProperty("BUILTIN_COMPLETION"); if (o != null) { if (o.equals("HTML")) { dtdLocation = getClass().getResource("xhtml.dtd").toExternalForm(); } } try { if (dtdLocation != null) { if (logger.isDebugEnabled()) { logger.debug("Using dtd to build completion database"); } setCompletionParser(new DTDCompletionParser()); URL url = new java.net.URL(dtdLocation); Reader dtdReader = new InputStreamReader(url.openStream()); updateAssistInfo(null, dtdLocation, dtdReader); } else if (schemaLocation != null) { if (logger.isDebugEnabled()) { logger.debug("Using schema to build completion database"); } setCompletionParser(new XSDCompletionParser()); URL url = new java.net.URL(schemaLocation); Reader dtdReader = new InputStreamReader(url.openStream()); updateAssistInfo(null, schemaLocation, dtdReader); } } catch (Exception err) { if (logger.isDebugEnabled()) { logger.debug(err.getMessage(), err); } } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private static 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: @Override public URLConnection openConnection(URL url, Proxy proxy) throws IOException { if (null == url) { throw new IllegalArgumentException(Messages.getString("luni.1B")); } String host = url.getHost(); if (host == null || host.length() == 0 || host.equalsIgnoreCase("localhost")) { return new FileURLConnection(url); } URL ftpURL = new URL("ftp", host, url.getFile()); return (proxy == null) ? ftpURL.openConnection() : ftpURL.openConnection(proxy); }
00
Code Sample 1: public static String read(URL url) throws Exception { String filename = Integer.toString(url.toString().hashCode()); boolean cached = false; File dir = new File(Config.CACHE_PATH); for (File file : dir.listFiles()) { if (!file.isFile()) continue; if (file.getName().equals(filename)) { filename = file.getName(); cached = true; break; } } File file = new File(Config.CACHE_PATH, filename); if (Config.USE_CACHE && cached) return read(file); System.out.println(">> CACHE HIT FAILED."); InputStream in = null; try { in = url.openStream(); } catch (Exception e) { System.out.println(">> OPEN STREAM FAILED: " + url.toString()); return null; } String content = read(in); save(file, content); return content; } Code Sample 2: protected void downloadCacheFile(File file) throws Exception { ApplicationProperties app = ApplicationProperties.getInstance(); String address = app.getProperty(JabberConstants.PROPERTY_JABBER_SERVERLIST, DEFAULT_SERVER_URL); URL url = new URL(address); file.createNewFile(); OutputStream cache = new FileOutputStream(file); InputStream input = url.openStream(); byte buffer[] = new byte[1024]; int bytesRead = 0; while ((bytesRead = input.read(buffer)) >= 0) cache.write(buffer, 0, bytesRead); input.close(); cache.close(); }
00
Code Sample 1: public void modify(ModifyInterceptorChain chain, DistinguishedName dn, ArrayList<LDAPModification> mods, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); HashMap<String, String> ldap2db = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_LDAP2DB + this.dbInsertName); Iterator<LDAPModification> it = mods.iterator(); String sql = "UPDATE " + this.tableName + " SET "; while (it.hasNext()) { LDAPModification mod = it.next(); if (mod.getOp() != LDAPModification.REPLACE) { throw new LDAPException("Only modify replace allowed", LDAPException.OBJECT_CLASS_VIOLATION, ""); } sql += ldap2db.get(mod.getAttribute().getName()) + "=? "; } sql += " WHERE " + this.rdnField + "=?"; PreparedStatement ps = con.prepareStatement(sql); it = mods.iterator(); int i = 1; while (it.hasNext()) { LDAPModification mod = it.next(); ps.setString(i, mod.getAttribute().getStringValue()); i++; } String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue(); ps.setString(i, uid); ps.executeUpdate(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } } Code Sample 2: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
00
Code Sample 1: private static void loadPluginsFromClassLoader(ClassLoader classLoader) throws IOException { Enumeration res = classLoader.getResources("META-INF/services/" + GDSFactoryPlugin.class.getName()); while (res.hasMoreElements()) { URL url = (URL) res.nextElement(); InputStreamReader rin = new InputStreamReader(url.openStream()); BufferedReader bin = new BufferedReader(rin); while (bin.ready()) { String className = bin.readLine(); try { Class clazz = Class.forName(className); GDSFactoryPlugin plugin = (GDSFactoryPlugin) clazz.newInstance(); registerPlugin(plugin); } catch (ClassNotFoundException ex) { if (log != null) log.error("Can't register plugin" + className, ex); } catch (IllegalAccessException ex) { if (log != null) log.error("Can't register plugin" + className, ex); } catch (InstantiationException ex) { if (log != null) log.error("Can't register plugin" + className, ex); } } } } Code Sample 2: public static String generateGuid(boolean secure) { MessageDigest md5 = null; String valueBeforeMD5 = null; String valueAfterMD5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0L; if (secure) rand = mySecureRand.nextLong(); else rand = myRand.nextLong(); sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte array[] = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; j++) { int b = array[j] & 0xff; if (b < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { log.error("Error:" + e); } String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); }
00
Code Sample 1: public void storeModule(OWLModuleManager manager, Module module, URI physicalURI, OWLModuleFormat moduleFormat) throws ModuleStorageException, UnknownModuleException { try { OutputStream os; if (!physicalURI.isAbsolute()) { throw new ModuleStorageException("Physical URI must be absolute: " + physicalURI); } if (physicalURI.getScheme().equals("file")) { File file = new File(physicalURI); file.getParentFile().mkdirs(); os = new FileOutputStream(file); } else { URL url = physicalURI.toURL(); URLConnection conn = url.openConnection(); os = conn.getOutputStream(); } Writer w = new BufferedWriter(new OutputStreamWriter(os)); storeModule(manager, module, w, moduleFormat); } catch (IOException e) { throw new ModuleStorageException(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"); }
00
Code Sample 1: private void constructDialogContent(Composite parent) { SashForm splitter = new SashForm(parent, SWT.HORIZONTAL); splitter.setLayoutData(new GridData(GridData.FILL_BOTH)); Group fragmentsGroup = new Group(splitter, SWT.NONE); fragmentsGroup.setLayout(new GridLayout(1, false)); fragmentsGroup.setText("Result Fragments"); fragmentsTable = CheckboxTableViewer.newCheckList(fragmentsGroup, SWT.NONE); fragmentsTable.getTable().setLayoutData(new GridData(GridData.FILL_BOTH)); fragmentsTable.setContentProvider(new ArrayContentProvider()); fragmentsTable.setLabelProvider(new LabelProvider() { public Image getImage(Object element) { return JFaceResources.getImage(WsmoImageRegistry.INSTANCE_ICON); } public String getText(Object element) { if (element == null) { return ""; } if (element instanceof ProcessFragment) { ProcessFragment frag = (ProcessFragment) element; String label = (frag.getName() == null) ? " <no-fragment-name>" : frag.getName(); if (frag.getDescription() != null) { label += " [" + Utils.normalizeSpaces(frag.getDescription()) + ']'; } return label; } return element.toString(); } }); fragmentsTable.setInput(results.toArray()); final MenuManager menuMgr = new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager mgr) { if (false == GUIHelper.containsCursor(fragmentsTable.getTable())) { return; } if (false == fragmentsTable.getSelection().isEmpty()) { menuMgr.add(new Action("Edit Name") { public void run() { doEditName(); } }); menuMgr.add(new Action("Edit Description") { public void run() { doEditDescription(); } }); menuMgr.add(new Separator()); } menuMgr.add(new Action("Select All") { public void run() { fragmentsTable.setAllChecked(true); updateSelectionMonitor(); } }); menuMgr.add(new Separator()); menuMgr.add(new Action("Unselect All") { public void run() { fragmentsTable.setAllChecked(false); updateSelectionMonitor(); } }); } }); fragmentsTable.getTable().setMenu(menuMgr.createContextMenu(fragmentsTable.getTable())); fragmentsTable.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updatePreviewPanel((IStructuredSelection) event.getSelection()); } }); new FragmentsToolTipProvider(this.fragmentsTable.getTable()); Group previewGroup = new Group(splitter, SWT.NONE); previewGroup.setLayout(new GridLayout(1, false)); previewGroup.setText("Fragment Preview"); createZoomToolbar(previewGroup); previewArea = new Composite(previewGroup, SWT.BORDER); previewArea.setLayoutData(new GridData(GridData.FILL_BOTH)); previewArea.setLayout(new GridLayout(1, false)); viewer = new ScrollingGraphicalViewer(); viewer.createControl(previewArea); ScalableFreeformRootEditPart rootEditPart = new ScalableFreeformRootEditPart(); viewer.setRootEditPart(rootEditPart); viewer.setEditPartFactory(new GraphicalPartFactory()); viewer.getControl().setBackground(ColorConstants.listBackground); viewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH)); ZoomManager zoomManager = rootEditPart.getZoomManager(); ArrayList<String> zoomContributions = new ArrayList<String>(); zoomContributions.add(ZoomManager.FIT_ALL); zoomContributions.add(ZoomManager.FIT_HEIGHT); zoomContributions.add(ZoomManager.FIT_WIDTH); zoomManager.setZoomLevelContributions(zoomContributions); zoomManager.setZoomLevels(new double[] { 0.25, 0.33, 0.5, 0.75, 1.0 }); zoomManager.setZoom(1.0); Composite businessGoalPanel = new Composite(previewGroup, SWT.NONE); businessGoalPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); businessGoalPanel.setLayout(new GridLayout(4, false)); Label lab = new Label(businessGoalPanel, SWT.NONE); lab.setText("Process goal:"); bpgIRI = new Text(businessGoalPanel, SWT.BORDER | SWT.READ_ONLY); bpgIRI.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); selectBpgButton = new Button(businessGoalPanel, SWT.NONE); selectBpgButton.setText("Select"); selectBpgButton.setEnabled(false); selectBpgButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent s) { doSelectProcessGoal(); } }); clearBpgButton = new Button(businessGoalPanel, SWT.NONE); clearBpgButton.setText("Clear"); clearBpgButton.setEnabled(false); clearBpgButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent s) { IStructuredSelection sel = (IStructuredSelection) fragmentsTable.getSelection(); if (sel.isEmpty() || false == sel.getFirstElement() instanceof ProcessFragment) { return; } ((ProcessFragment) sel.getFirstElement()).setBusinessProcessGoal(null); updatePreviewPanel(sel); } }); splitter.setWeights(new int[] { 1, 2 }); } Code Sample 2: public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("some text ".getBytes())); fc.close(); fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("some more".getBytes())); fc.close(); fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) { PrintUtil.prt((char) buff.get()); } }
11
Code Sample 1: private void chopFileDisk() throws IOException { File tempFile = new File("" + logFile + ".tmp"); BufferedInputStream bis = null; BufferedOutputStream bos = null; long startCopyPos; byte readBuffer[] = new byte[2048]; int readCount; long totalBytesRead = 0; if (reductionRatio > 0 && logFile.length() > 0) { startCopyPos = logFile.length() / reductionRatio; } else { startCopyPos = 0; } try { bis = new BufferedInputStream(new FileInputStream(logFile)); bos = new BufferedOutputStream(new FileOutputStream(tempFile)); do { readCount = bis.read(readBuffer, 0, readBuffer.length); if (readCount > 0) { totalBytesRead += readCount; if (totalBytesRead > startCopyPos) { bos.write(readBuffer, 0, readCount); } } } while (readCount > 0); } finally { if (bos != null) { try { bos.close(); } catch (IOException ex) { } } if (bis != null) { try { bis.close(); } catch (IOException ex) { } } } if (tempFile.isFile()) { if (!logFile.delete()) { throw new IOException("Error when attempting to delete the " + logFile + " file."); } if (!tempFile.renameTo(logFile)) { throw new IOException("Error when renaming the " + tempFile + " to " + logFile + "."); } } } Code Sample 2: public static void convertEncoding(File infile, File outfile, String from, String to) throws IOException, UnsupportedEncodingException { InputStream in; if (infile != null) in = new FileInputStream(infile); else in = System.in; OutputStream out; outfile.createNewFile(); if (outfile != null) out = new FileOutputStream(outfile); else out = System.out; if (from == null) from = System.getProperty("file.encoding"); if (to == null) to = "Unicode"; Reader r = new BufferedReader(new InputStreamReader(in, from)); Writer w = new BufferedWriter(new OutputStreamWriter(out, to)); char[] buffer = new char[4096]; int len; while ((len = r.read(buffer)) != -1) w.write(buffer, 0, len); r.close(); w.close(); }
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: @Override protected String getRawPage(String url) throws IOException { HttpClient httpClient = new HttpClient(); String proxyHost = config.getString("proxy.host"), proxyPortString = config.getString("proxy.port"); if (proxyHost != null && proxyPortString != null) { int proxyPort = -1; try { proxyPort = Integer.parseInt(proxyPortString); } catch (NumberFormatException e) { } if (proxyPort != -1) { httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort); } } GetMethod urlGet = new GetMethod(url); urlGet.setRequestHeader("Accept-Encoding", ""); urlGet.setRequestHeader("User-Agent", "Mozilla/5.0"); int retCode; if ((retCode = httpClient.executeMethod(urlGet)) != HttpStatus.SC_OK) { throw new RuntimeException("Unexpected HTTP code: " + retCode); } String encoding = null; Header contentType = urlGet.getResponseHeader("Content-Type"); if (contentType != null) { String contentTypeString = contentType.toString(); int i = contentTypeString.indexOf("charset="); if (i != -1) { encoding = contentTypeString.substring(i + "charset=".length()).trim(); } } boolean gzipped = false; Header contentEncoding = urlGet.getResponseHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { gzipped = true; } byte[] htmlData; try { InputStream in = gzipped ? new GZIPInputStream(urlGet.getResponseBodyAsStream()) : urlGet.getResponseBodyAsStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); htmlData = out.toByteArray(); in.close(); } finally { urlGet.releaseConnection(); } if (encoding == null) { Matcher m = Pattern.compile("(?i)<meta[^>]*charset=(([^\"]+\")|(\"[^\"]+\"))").matcher(new String(htmlData)); if (m.find()) { encoding = m.group(1).trim().replace("\"", ""); } } if (encoding == null) { encoding = "UTF-8"; } return new String(htmlData, encoding); }
11
Code Sample 1: protected void setUp() throws Exception { testOutputDirectory = new File(getClass().getResource("/").getPath()); zipFile = new File(this.testOutputDirectory, "/plugin.zip"); zipOutputDirectory = new File(this.testOutputDirectory, "zip"); zipOutputDirectory.mkdir(); logger.fine("zip dir created"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)); zos.putNextEntry(new ZipEntry("css/")); zos.putNextEntry(new ZipEntry("css/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("js/")); zos.putNextEntry(new ZipEntry("js/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/lib/")); zos.putNextEntry(new ZipEntry("WEB-INF/lib/mylib.jar")); File jarFile = new File(this.testOutputDirectory.getPath() + "/mylib.jar"); JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile)); jos.putNextEntry(new ZipEntry("vqwiki/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/system.properties")); System.getProperties().store(jos, null); jos.closeEntry(); jos.close(); IOUtils.copy(new FileInputStream(jarFile), zos); zos.closeEntry(); zos.close(); jarFile.delete(); } Code Sample 2: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } }
11
Code Sample 1: public static boolean copyFile(final File src, final File dest, long extent, final boolean overwrite) throws FileNotFoundException, IOException { boolean result = false; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Copying file " + src + " to " + dest + " extent " + extent + " exists " + dest.exists()); } if (dest.exists()) { if (overwrite) { dest.delete(); LOGGER.finer(dest.getAbsolutePath() + " removed before copy."); } else { return result; } } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); if (extent < 0) { extent = fcin.size(); } long trans = fcin.transferTo(0, extent, fcout); if (trans < extent) { result = false; } result = true; } catch (IOException e) { String message = "Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " with extent " + extent + " got IOE: " + e.getMessage(); if (e.getMessage().equals("Invalid argument")) { LOGGER.severe("Failed copy, trying workaround: " + message); workaroundCopyFile(src, dest); } else { IOException newE = new IOException(message); newE.setStackTrace(e.getStackTrace()); throw newE; } } finally { if (fcin != null) { fcin.close(); } if (fcout != null) { fcout.close(); } if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } } return result; } Code Sample 2: @Override public InputStream getInputStream() throws IOException { if (dfos == null) { int deferredOutputStreamThreshold = Config.getInstance().getDeferredOutputStreamThreshold(); dfos = new DeferredFileOutputStream(deferredOutputStreamThreshold, Definitions.PROJECT_NAME, "." + Definitions.TMP_EXTENSION); try { IOUtils.copy(is, dfos); } finally { dfos.close(); } } return dfos.getDeferredInputStream(); }
11
Code Sample 1: public static String generate(String documentSelector) { if (documentSelector == null) { return null; } String date = Long.toString(System.currentTimeMillis()); try { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(documentSelector.getBytes()); md.update(date.getBytes()); byte[] digest = md.digest(); return toHexString(digest); } catch (NoSuchAlgorithmException e) { return null; } } Code Sample 2: public static final synchronized String md5(final String data) { try { final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(data.getBytes()); final byte[] b = md.digest(); return toHexString(b); } catch (final Exception e) { } return ""; }
00
Code Sample 1: private void dealWith(String line) throws Exception { if (line.startsWith("#") || (line.length() == 0)) { return; } String sarr[]; sarr = StringUtil.split(line, '\t'); String path = destDir + File.separator + sarr[0]; boolean copyFile = true; if (sarr.length == 2) { try { String serverHash = sarr[1]; String fileHash = loadFileHash(destDir + File.separator + sarr[0]); if (fileHash != null) { if (serverHash.equalsIgnoreCase(fileHash)) { copyFile = false; } else { if (verbose) { System.out.println(" -- " + sarr[0] + " has changed"); } } } } catch (Exception ex) { ex.printStackTrace(); System.out.println(ex.getMessage()); System.exit(2); } } if (copyFile) { int idx = path.lastIndexOf('/'); if (idx > 0) { String dir = path.substring(0, idx); File f = new File(dir); f.mkdirs(); } FileOutputStream os = new FileOutputStream(path); byte buf[] = new byte[1024]; URLConnection urc = new URL(urlStr + "/" + sarr[0]).openConnection(); InputStream is = urc.getInputStream(); boolean done = false; while (!done) { int read = is.read(buf, 0, 1024); if (read == -1) { done = true; } else { os.write(buf, 0, read); } } os.close(); is.close(); if (verbose) { System.out.println(" -- Copied: " + sarr[0]); } } } Code Sample 2: private void doUpload(UploadKind uploadKind, WriteKind writeKind) throws Exception { int n = 512 * 1024; AtomicInteger total = new AtomicInteger(0); ServerSocket ss = startSinkServer(total); URL url = new URL("http://localhost:" + ss.getLocalPort() + "/test1"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); if (uploadKind == UploadKind.CHUNKED) { conn.setChunkedStreamingMode(-1); } else { conn.setFixedLengthStreamingMode(n); } OutputStream out = conn.getOutputStream(); if (writeKind == WriteKind.BYTE_BY_BYTE) { for (int i = 0; i < n; ++i) { out.write('x'); } } else { byte[] buf = new byte[writeKind == WriteKind.SMALL_BUFFERS ? 256 : 64 * 1024]; Arrays.fill(buf, (byte) 'x'); for (int i = 0; i < n; i += buf.length) { out.write(buf, 0, Math.min(buf.length, n - i)); } } out.close(); assertTrue(conn.getResponseCode() > 0); assertEquals(uploadKind == UploadKind.CHUNKED ? -1 : n, total.get()); }
00
Code Sample 1: private boolean Try(URL url, Metafile mf) throws Throwable { InputStream is = null; HttpURLConnection con = null; boolean success = false; try { con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.connect(); is = con.getInputStream(); Response r = new Response(is); responses.add(r); peers.addAll(r.peers); Main.log.info("got " + r.peers.size() + " peers from " + url); success = true; } finally { if (is != null) is.close(); if (con != null) con.disconnect(); } return success; } Code Sample 2: private static List<String> getContent(URL url) throws IOException { final HttpURLConnection http = (HttpURLConnection) url.openConnection(); try { http.connect(); final int code = http.getResponseCode(); if (code != 200) throw new IOException("IP Locator failed to get the location. Http Status code : " + code + " [" + url + "]"); return getContent(http); } finally { http.disconnect(); } }
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 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: public static void zip(File srcDir, File destFile, FileFilter filter) throws IOException { ZipOutputStream out = null; try { out = new ZipOutputStream(new FileOutputStream(destFile)); Collection<File> files = FileUtils.listFiles(srcDir, TrueFileFilter.TRUE, TrueFileFilter.TRUE); for (File f : files) { if (filter == null || filter.accept(f)) { FileInputStream in = FileUtils.openInputStream(f); out.putNextEntry(new ZipEntry(Util.relativePath(srcDir, f).replace('\\', '/'))); IOUtils.copyLarge(in, out); out.closeEntry(); IOUtils.closeQuietly(in); } } IOUtils.closeQuietly(out); } catch (Throwable t) { throw new IOException("Failed to create zip file", t); } finally { if (out != null) { out.flush(); IOUtils.closeQuietly(out); } } } Code Sample 2: public void testStorageString() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); r.addText("This is an example"); r.addText(" and another one."); 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()); try { r.getOutputStream(); fail("Once addText() is used the text is stored as a String and you cannot use getOutputStream anymore"); } catch (IOException e) { } try { r.getWriter(); fail("Once addText() is used the text is stored as a String and you cannot use getOutputStream anymore"); } catch (IOException e) { } r.setEndState(ResponseStateOk.getInstance()); assertTrue(r.hasEnded()); }
00
Code Sample 1: public static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); file = new File("H:\\FileServeUploader.java"); HttpPost httppost = new HttpPost(postURL); httppost.setHeader("Cookie", uprandcookie + ";" + autologincookie); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart("MAX_FILE_SIZE", new StringBody("2097152000")); mpEntity.addPart("UPLOAD_IDENTIFIER", new StringBody(uid)); mpEntity.addPart("go", new StringBody("1")); mpEntity.addPart("files", cbFile); httppost.setEntity(mpEntity); System.out.println("Now uploading your file into depositfiles..........................."); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); downloadlink = parseResponse(uploadresponse, "ud_download_url = '", "'"); deletelink = parseResponse(uploadresponse, "ud_delete_url = '", "'"); System.out.println("download link : " + downloadlink); System.out.println("delete link : " + deletelink); } } 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; }
00
Code Sample 1: @SuppressWarnings("static-access") @RequestMapping(value = "/upload/upload.html", method = RequestMethod.POST) protected void save(HttpServletRequest request, HttpServletResponse response) throws ServletException { UPLOAD_DIRECTORY = uploadDiretory(); File diretorioUsuario = new File(UPLOAD_DIRECTORY); boolean diretorioCriado = false; if (!diretorioUsuario.exists()) { diretorioCriado = diretorioUsuario.mkdir(); if (!diretorioCriado) throw new RuntimeException("Não foi possível criar o diretório do usuário"); } PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(UPLOAD_DIRECTORY + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); } Code Sample 2: private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { jButton1.setEnabled(false); for (int i = 0; i < max; i++) { Card crd = WLP.getSelectedCard(WLP.jTable1.getSelectedRows()[i]); String s, s2; s = ""; s2 = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + crd.getWord()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("popWin\\('/cgi-bin/(.+?)'", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); if (matcher.find()) { String newurl = "http://m-w.com/cgi-bin/" + matcher.group(1); try { URL url2 = new URL(newurl); BufferedReader in2 = new BufferedReader(new InputStreamReader(url2.openStream())); String str; while ((str = in2.readLine()) != null) { s2 = s2 + str; } in2.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern2 = Pattern.compile("<A HREF=\"http://(.+?)\">Click here to listen with your default audio player", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher2 = pattern2.matcher(s2); if (matcher2.find()) { getWave("http://" + matcher2.group(1), crd.getWord()); } int val = jProgressBar1.getValue(); val++; jProgressBar1.setValue(val); this.paintAll(this.getGraphics()); } } jButton1.setEnabled(true); }
11
Code Sample 1: private BinaryDocument documentFor(String code, String type, int diagramIndex) { code = code.replaceAll("\n", "").replaceAll("\t", "").trim().replaceAll(" ", "%20"); StringBuilder builder = new StringBuilder("http://yuml.me/diagram/"); builder.append(type).append("/"); builder.append(code); URL url; try { url = new URL(builder.toString()); String name = "uml" + diagramIndex + ".png"; diagramIndex++; BinaryDocument pic = new BinaryDocument(name, "image/png"); IOUtils.copy(url.openStream(), pic.getContent().getOutputStream()); return pic; } catch (MalformedURLException e) { throw ManagedIOException.manage(e); } catch (IOException e) { throw ManagedIOException.manage(e); } } Code Sample 2: public static void concatFiles(List<File> sourceFiles, File destFile) throws IOException { FileOutputStream outFile = new FileOutputStream(destFile); FileChannel outChannel = outFile.getChannel(); for (File f : sourceFiles) { FileInputStream fis = new FileInputStream(f); FileChannel channel = fis.getChannel(); channel.transferTo(0, channel.size(), outChannel); channel.close(); fis.close(); } outChannel.close(); }
11
Code Sample 1: public static void copyFile(final File source, final File target) throws FileNotFoundException, IOException { FileChannel in = new FileInputStream(source).getChannel(), out = new FileOutputStream(target).getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } out.close(); in.close(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UploadFileForm vo = (UploadFileForm) form; FormFile file = vo.getFile(); String inforId = request.getParameter("inforId"); System.out.println("inforId=" + inforId); if (file != null) { String realpath = getServlet().getServletContext().getRealPath("/"); realpath = realpath.replaceAll("\\\\", "/"); String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); String strAppend = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); if (file.getFileSize() != 0) { file.getInputStream(); String name = file.getFileName(); String fullPath = realpath + "attach/" + strAppend + name; t_attach attach = new t_attach(); attach.setAttach_fullname(fullPath); attach.setAttach_name(name); attach.setInfor_id(Integer.parseInt(inforId)); attach.setInsert_day(new Date()); attach.setUpdate_day(new Date()); t_attach_EditMap attachEdit = new t_attach_EditMap(); attachEdit.add(attach); File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(file.getInputStream(), out); out.close(); System.out.println("file name is :" + name); } } request.setAttribute("operating-status", "�����ɹ�! ��ӭ����ʹ�á�"); System.out.println("in the end...."); return "aftersave"; } Code Sample 2: public static void main(String[] args) throws IOException, DataFormatException { byte in_buf[] = new byte[20000]; if (args.length < 2) { System.out.println("too few arguments"); System.exit(0); } String inputName = args[0]; InputStream in = new FileInputStream(inputName); int index = 0; for (int i = 1; i < args.length; i++) { int size = Integer.parseInt(args[i]); boolean copy = size >= 0; if (size < 0) { size = -size; } OutputStream out = null; if (copy) { index++; out = new FileOutputStream(inputName + "." + index + ".dat"); } while (size > 0) { int read = in.read(in_buf, 0, Math.min(in_buf.length, size)); if (read < 0) { break; } size -= read; if (copy) { out.write(in_buf, 0, read); } } if (copy) { out.close(); } } index++; OutputStream out = new FileOutputStream(inputName + "." + index + ".dat"); while (true) { int read = in.read(in_buf); if (read < 0) { break; } out.write(in_buf, 0, read); } out.close(); in.close(); }
00
Code Sample 1: public void callUpdate() { LOGGER.debug("Checking for Updates"); new Thread() { @Override public void run() { String lastVersion = null; try { URL projectSite = new URL("http://code.google.com/p/g15lastfm/"); URLConnection urlC = projectSite.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlC.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("<strong>Current version:")) { lastVersion = inputLine; break; } } in.close(); if (lastVersion != null && lastVersion.length() > 0) { lastVersion = lastVersion.substring(lastVersion.indexOf("Current version:") + 16); lastVersion = lastVersion.substring(0, lastVersion.indexOf("</strong>")).trim(); LOGGER.debug("last Version=" + lastVersion); } if (!lastVersion.equals(G15LastfmPlayer.getVersion())) LOGGER.debug("Not necessary to update"); else { LOGGER.debug("New update found!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (JOptionPane.showConfirmDialog(null, "New version of G15Lastfm is available to download!", "New Update for G15Lastfm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { LOGGER.debug("User choose to update, opening browser."); Desktop desktop = Desktop.getDesktop(); try { desktop.browse(new URI("http://code.google.com/p/g15lastfm/")); } catch (IOException e) { LOGGER.debug(e); } catch (URISyntaxException e) { LOGGER.debug(e); } } else { LOGGER.debug("User choose to not update."); } } }); } } catch (Exception e) { LOGGER.debug(e); } } }.start(); } Code Sample 2: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
11
Code Sample 1: public boolean copyDirectoryTree(File srcPath, File dstPath) { try { if (srcPath.isDirectory()) { if (!dstPath.exists()) dstPath.mkdir(); String files[] = srcPath.list(); for (int i = 0; i < files.length; i++) copyDirectoryTree(new File(srcPath, files[i]), new File(dstPath, files[i])); } else { if (!srcPath.exists()) { errMsgLog += "copyDirectoryTree I/O error from '" + srcPath + "' does not exist.\n"; lastErrMsgLog = errMsgLog; return (false); } else { InputStream in = new FileInputStream(srcPath); OutputStream out = new FileOutputStream(dstPath); byte[] buf = new byte[10240]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } } return (true); } catch (Exception e) { errMsgLog += "copyDirectoryTree I/O error from '" + srcPath.getName() + "' to '" + dstPath.getName() + "\n " + e + "\n"; lastErrMsgLog = errMsgLog; return (false); } } Code Sample 2: public static void main(String[] args) throws IOException { ReadableByteChannel in = Channels.newChannel((new FileInputStream("/home/sannies/suckerpunch-distantplanet_h1080p/suckerpunch-distantplanet_h1080p.mov"))); Movie movie = MovieCreator.build(in); in.close(); List<Track> tracks = movie.getTracks(); movie.setTracks(new LinkedList<Track>()); double startTime = 35.000; double endTime = 145.000; boolean timeCorrected = false; for (Track track : tracks) { if (track.getSyncSamples() != null && track.getSyncSamples().length > 0) { if (timeCorrected) { throw new RuntimeException("The startTime has already been corrected by another track with SyncSample. Not Supported."); } startTime = correctTimeToNextSyncSample(track, startTime); endTime = correctTimeToNextSyncSample(track, endTime); timeCorrected = true; } } for (Track track : tracks) { long currentSample = 0; double currentTime = 0; long startSample = -1; long endSample = -1; for (int i = 0; i < track.getDecodingTimeEntries().size(); i++) { TimeToSampleBox.Entry entry = track.getDecodingTimeEntries().get(i); for (int j = 0; j < entry.getCount(); j++) { if (currentTime <= startTime) { startSample = currentSample; } if (currentTime <= endTime) { endSample = currentSample; } else { break; } currentTime += (double) entry.getDelta() / (double) track.getTrackMetaData().getTimescale(); currentSample++; } } movie.addTrack(new CroppedTrack(track, startSample, endSample)); } long start1 = System.currentTimeMillis(); IsoFile out = new DefaultMp4Builder().build(movie); long start2 = System.currentTimeMillis(); FileOutputStream fos = new FileOutputStream(String.format("output-%f-%f.mp4", startTime, endTime)); FileChannel fc = fos.getChannel(); out.getBox(fc); fc.close(); fos.close(); long start3 = System.currentTimeMillis(); System.err.println("Building IsoFile took : " + (start2 - start1) + "ms"); System.err.println("Writing IsoFile took : " + (start3 - start2) + "ms"); System.err.println("Writing IsoFile speed : " + (new File(String.format("output-%f-%f.mp4", startTime, endTime)).length() / (start3 - start2) / 1000) + "MB/s"); }