label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
00
|
Code Sample 1:
public void authenticate(final ConnectionHandler ch, final AuthenticationCriteria ac) throws NamingException { byte[] hash = new byte[DIGEST_SIZE]; try { final MessageDigest md = MessageDigest.getInstance(this.passwordScheme); md.update(((String) ac.getCredential()).getBytes()); hash = md.digest(); } catch (NoSuchAlgorithmException e) { throw new NamingException(e.getMessage()); } ch.connect(this.config.getBindDn(), this.config.getBindCredential()); NamingEnumeration<SearchResult> en = null; try { en = ch.getLdapContext().search(ac.getDn(), "userPassword={0}", new Object[] { String.format("{%s}%s", this.passwordScheme, LdapUtil.base64Encode(hash)).getBytes() }, LdapConfig.getCompareSearchControls()); if (!en.hasMore()) { throw new AuthenticationException("Compare authentication failed."); } } finally { if (en != null) { en.close(); } } }
Code Sample 2:
@Override protected void doFetch(HttpServletRequest request, HttpServletResponse response) throws IOException, GadgetException { if (request.getHeader("If-Modified-Since") != null) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } String host = request.getHeader("Host"); if (!lockedDomainService.isSafeForOpenProxy(host)) { String msg = "Embed request for url " + getParameter(request, URL_PARAM, "") + " made to wrong domain " + host; logger.info(msg); throw new GadgetException(GadgetException.Code.INVALID_PARAMETER, msg); } HttpRequest rcr = buildHttpRequest(request, URL_PARAM); HttpResponse results = requestPipeline.execute(rcr); if (results.isError()) { HttpRequest fallbackRcr = buildHttpRequest(request, FALLBACK_URL_PARAM); if (fallbackRcr != null) { results = requestPipeline.execute(fallbackRcr); } } if (contentRewriterRegistry != null) { try { results = contentRewriterRegistry.rewriteHttpResponse(rcr, results); } catch (RewritingException e) { throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e); } } for (Map.Entry<String, String> entry : results.getHeaders().entries()) { String name = entry.getKey(); if (!DISALLOWED_RESPONSE_HEADERS.contains(name.toLowerCase())) { response.addHeader(name, entry.getValue()); } } String responseType = results.getHeader("Content-Type"); if (!StringUtils.isEmpty(rcr.getRewriteMimeType())) { String requiredType = rcr.getRewriteMimeType(); if (requiredType.endsWith("/*") && !StringUtils.isEmpty(responseType)) { requiredType = requiredType.substring(0, requiredType.length() - 2); if (!responseType.toLowerCase().startsWith(requiredType.toLowerCase())) { response.setContentType(requiredType); responseType = requiredType; } } else { response.setContentType(requiredType); responseType = requiredType; } } setResponseHeaders(request, response, results); if (results.getHttpStatusCode() != HttpResponse.SC_OK) { response.sendError(results.getHttpStatusCode()); } IOUtils.copy(results.getResponse(), response.getOutputStream()); }
|
11
|
Code Sample 1:
public String loadFileContent(final String _resourceURI) { final Lock readLock = this.fileLock.readLock(); final Lock writeLock = this.fileLock.writeLock(); boolean hasReadLock = false; boolean hasWriteLock = false; try { readLock.lock(); hasReadLock = true; if (!this.cachedResources.containsKey(_resourceURI)) { readLock.unlock(); hasReadLock = false; writeLock.lock(); hasWriteLock = true; if (!this.cachedResources.containsKey(_resourceURI)) { final InputStream resourceAsStream = this.getClass().getResourceAsStream(_resourceURI); final StringWriter writer = new StringWriter(); try { IOUtils.copy(resourceAsStream, writer); } catch (final IOException ex) { throw new IllegalStateException("Resource not read-able", ex); } final String loadedResource = writer.toString(); this.cachedResources.put(_resourceURI, loadedResource); } writeLock.unlock(); hasWriteLock = false; readLock.lock(); hasReadLock = true; } return this.cachedResources.get(_resourceURI); } finally { if (hasReadLock) { readLock.unlock(); } if (hasWriteLock) { writeLock.unlock(); } } }
Code Sample 2:
private boolean handlePart(Part p) throws MessagingException, GetterException { String filename = p.getFileName(); if (!p.isMimeType("multipart/*")) { String disp = p.getDisposition(); if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) { if (checkCriteria(p)) { if (filename == null) filename = "Attachment" + attnum++; if (result == null) { try { File f = File.createTempFile("amorph_pop3-", ".tmp"); f.deleteOnExit(); OutputStream os = new BufferedOutputStream(new FileOutputStream(f)); InputStream is = p.getInputStream(); int c; while ((c = is.read()) != -1) os.write(c); os.close(); result = new FileInputStream(f); System.out.println("saved attachment to file: " + f.getAbsolutePath()); return true; } catch (IOException ex) { throw new GetterException(ex, "Failed to save attachment: " + ex); } } } } } return false; }
|
11
|
Code Sample 1:
public static void concatFiles(final String as_base_file_name) throws IOException, FileNotFoundException { new File(as_base_file_name).createNewFile(); final OutputStream lo_out = new FileOutputStream(as_base_file_name, true); int ln_part = 1, ln_readed = -1; final byte[] lh_buffer = new byte[32768]; File lo_file = new File(as_base_file_name + "part1"); while (lo_file.exists() && lo_file.isFile()) { final InputStream lo_input = new FileInputStream(lo_file); while ((ln_readed = lo_input.read(lh_buffer)) != -1) { lo_out.write(lh_buffer, 0, ln_readed); } ln_part++; lo_file = new File(as_base_file_name + "part" + ln_part); } lo_out.flush(); lo_out.close(); }
Code Sample 2:
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void test() throws Exception { File temp = File.createTempFile("test", ".test"); temp.deleteOnExit(); StorageFile s = new StorageFile(temp, "UTF-8"); s.addText("Test"); s.getOutputStream().write("ing is important".getBytes("UTF-8")); s.getWriter().write(" but overrated"); assertEquals("Testing is important but overrated", s.getText()); s.close(ResponseStateOk.getInstance()); assertEquals("Testing is important but overrated", s.getText()); InputStream input = s.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer, "UTF-8"); assertEquals("Testing is important but overrated", writer.toString()); try { s.getOutputStream(); fail("Should thow an IOException as it is closed."); } catch (IOException e) { } }
|
00
|
Code Sample 1:
public static void copyFile(File sourceFile, File destinationFile) throws IOException { if (!destinationFile.exists()) { destinationFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
protected InputStream getInputStream() throws IOException { if (source instanceof URL) { URL url = (URL) source; location = url.toString(); return url.openStream(); } else if (source instanceof File) { location = ((File) source).getAbsolutePath(); return new FileInputStream((File) source); } else if (source instanceof String) { location = (String) source; return new FileInputStream((String) source); } else if (source instanceof InputStream) { return (InputStream) source; } return null; }
|
00
|
Code Sample 1:
public void copyJarContent(File jarPath, File targetDir) throws IOException { log.info("Copying natives from " + jarPath.getName()); JarFile jar = new JarFile(jarPath); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry file = entries.nextElement(); File f = new File(targetDir, file.getName()); log.info("Copying native - " + file.getName()); File parentFile = f.getParentFile(); parentFile.mkdirs(); if (file.isDirectory()) { f.mkdir(); continue; } InputStream is = null; FileOutputStream fos = null; try { is = jar.getInputStream(file); fos = new FileOutputStream(f); IOUtils.copy(is, fos); } finally { if (fos != null) fos.close(); if (is != null) is.close(); } } }
Code Sample 2:
private ArrayList execAtParentServer(ArrayList paramList) throws Exception { ArrayList outputList = null; String message = ""; try { HashMap serverUrlMap = InitXml.getInstance().getServerMap(); Iterator it = serverUrlMap.keySet().iterator(); while (it.hasNext()) { String server = (String) it.next(); String serverUrl = (String) serverUrlMap.get(server); serverUrl = serverUrl + Primer3Manager.servletName; URL url = new URL(serverUrl); URLConnection uc = url.openConnection(); uc.setDoOutput(true); OutputStream os = uc.getOutputStream(); StringBuffer buf = new StringBuffer(); buf.append("actionType=designparent"); for (int i = 0; i < paramList.size(); i++) { Primer3Param param = (Primer3Param) paramList.get(i); if (i == 0) { buf.append("&sequence=" + param.getSequence()); buf.append("&upstream_size" + upstreamSize); buf.append("&downstreamSize" + downstreamSize); buf.append("&MARGIN_LENGTH=" + marginLength); buf.append("&OVERLAP_LENGTH=" + overlapLength); buf.append("&MUST_XLATE_PRODUCT_MIN_SIZE=" + param.getPrimerProductMinSize()); buf.append("&MUST_XLATE_PRODUCT_MAX_SIZE=" + param.getPrimerProductMaxSize()); buf.append("&PRIMER_PRODUCT_OPT_SIZE=" + param.getPrimerProductOptSize()); buf.append("&PRIMER_MAX_END_STABILITY=" + param.getPrimerMaxEndStability()); buf.append("&PRIMER_MAX_MISPRIMING=" + param.getPrimerMaxMispriming()); buf.append("&PRIMER_PAIR_MAX_MISPRIMING=" + param.getPrimerPairMaxMispriming()); buf.append("&PRIMER_MIN_SIZE=" + param.getPrimerMinSize()); buf.append("&PRIMER_OPT_SIZE=" + param.getPrimerOptSize()); buf.append("&PRIMER_MAX_SIZE=" + param.getPrimerMaxSize()); buf.append("&PRIMER_MIN_TM=" + param.getPrimerMinTm()); buf.append("&PRIMER_OPT_TM=" + param.getPrimerOptTm()); buf.append("&PRIMER_MAX_TM=" + param.getPrimerMaxTm()); buf.append("&PRIMER_MAX_DIFF_TM=" + param.getPrimerMaxDiffTm()); buf.append("&PRIMER_MIN_GC=" + param.getPrimerMinGc()); buf.append("&PRIMER_OPT_GC_PERCENT=" + param.getPrimerOptGcPercent()); buf.append("&PRIMER_MAX_GC=" + param.getPrimerMaxGc()); buf.append("&PRIMER_SELF_ANY=" + param.getPrimerSelfAny()); buf.append("&PRIMER_SELF_END=" + param.getPrimerSelfEnd()); buf.append("&PRIMER_NUM_NS_ACCEPTED=" + param.getPrimerNumNsAccepted()); buf.append("&PRIMER_MAX_POLY_X=" + param.getPrimerMaxPolyX()); buf.append("&PRIMER_GC_CLAMP=" + param.getPrimerGcClamp()); } buf.append("&target=" + param.getPrimerSequenceId() + "," + (param.getTarget())[0] + "," + (param.getTarget())[1]); } PrintStream ps = new PrintStream(os); ps.print(buf.toString()); ps.close(); ObjectInputStream ois = new ObjectInputStream(uc.getInputStream()); outputList = (ArrayList) ois.readObject(); ois.close(); } } catch (IOException e1) { e1.printStackTrace(); } if ((outputList == null || outputList.size() == 0) && message != null && message.length() > 0) { throw new Exception(message); } return outputList; }
|
00
|
Code Sample 1:
public void putMedia(Media m) { if (m == null) { return; } if (_conn == null) { log.error("DatabaseDatastore not connected!"); return; } if (log.isTraceEnabled()) { log.trace("Writing Media " + m.toString() + " to database"); } try { try { long trackid = getLocalID(m, _conn); if (m.isBaseDirty()) { if (log.isTraceEnabled()) { log.trace("Need to update base " + m.getID() + " to database"); } Integer artist = getArtistID(m, _conn); Integer author = getAuthorID(m, _conn); Integer artistAlias = getArtistAliasID(m, _conn); PreparedStatement s = _conn.prepareStatement("update media_track set track_name=?,track_artist_id=?,track_author_id=?,track_artist_alias_id=?,track_audit_timestamp=CURRENT_TIMESTAMP where track_id = ?"); s.setString(1, m.getName()); if (artist != null) { s.setLong(2, artist); } else { s.setNull(2, Types.BIGINT); } if (author != null) { s.setLong(3, author); } else { s.setNull(3, Types.BIGINT); } if (artistAlias != null) { s.setLong(4, artistAlias); } else { s.setNull(4, Types.BIGINT); } s.setLong(5, trackid); s.executeUpdate(); s.close(); } if (m.isUserDirty()) { if (log.isTraceEnabled()) { log.trace("Need to update user " + m.getID() + " to database"); } PreparedStatement s = _conn.prepareStatement("update media_track_rating set rating=?, play_count=? where track_id=? and user_id=?"); s.setFloat(1, m.getRating()); s.setLong(2, m.getPlayCount()); s.setLong(3, trackid); s.setLong(4, userid); if (s.executeUpdate() != 1) { s.close(); } s.close(); } if (m.isContentDirty()) { updateLocation(m, _conn); } _conn.commit(); m.resetDirty(); if (log.isTraceEnabled()) { log.trace("Committed " + m.getID() + " to database"); } } catch (Exception e) { log.error(e.toString(), e); _conn.rollback(); } } catch (Exception e) { log.error(e.toString(), e); } }
Code Sample 2:
static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
|
00
|
Code Sample 1:
public static InputStream getData(DataTransferDescriptor desc, GlobusCredential creds) throws Exception { URL url = new URL(desc.getUrl()); if (url.getProtocol().equals("http")) { URLConnection conn = url.openConnection(); conn.connect(); return conn.getInputStream(); } else if (url.getProtocol().equals("https")) { if (creds != null) { GlobusGSSCredentialImpl cred = new GlobusGSSCredentialImpl(creds, GSSCredential.INITIATE_AND_ACCEPT); GSIHttpURLConnection connection = new GSIHttpURLConnection(url); connection.setGSSMode(GSIConstants.MODE_SSL); connection.setCredentials(cred); return connection.getInputStream(); } else { throw new Exception("To use the https protocol to retrieve data from the Transfer Service you must have credentials"); } } throw new Exception("Protocol " + url.getProtocol() + " not supported."); }
Code Sample 2:
private static String makePrefixDeclarationsWithPrefix_cc(Set<String> missingPrefixes) { StringWriter sb = new StringWriter(); for (Iterator<String> iterator = missingPrefixes.iterator(); iterator.hasNext(); ) { String prefix = (String) iterator.next(); sb.append(prefix); if (iterator.hasNext()) { sb.append(','); } } String missingPrefixesForPrefix_cc = sb.toString(); String prefixDeclarations = ""; if (missingPrefixes.size() > 0) { try { String urlString = "http://prefix.cc/" + missingPrefixesForPrefix_cc + ".file.n3"; URL url = new URL(urlString); URLConnection conn = url.openConnection(); conn.setRequestProperty("accept", "application/rdf+n3, application/rdf-turtle, application/rdf-n3," + "text/rdf+n3"); InputStream openStream = conn.getInputStream(); StringWriter output = new StringWriter(); ReaderUtils.copyReader("# From prefix.cc\n", new InputStreamReader(openStream), output); prefixDeclarations = output.toString(); Logger.getLogger("prefix.cc").info("makePrefixDeclarationsWithPrefix_cc() : From prefix.cc:\n" + prefixDeclarations); } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } return prefixDeclarations; }
|
11
|
Code Sample 1:
public void run() { FileInputStream src; FileOutputStream dest; try { dest = new FileOutputStream(srcName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileChannel destC = dest.getChannel(); FileChannel srcC; ByteBuffer buf = ByteBuffer.allocateDirect(BUFFER_SIZE); try { int fileNo = 0; while (true) { int i = 1; String destName = srcName + "_" + fileNo; src = new FileInputStream(destName); srcC = src.getChannel(); while ((i > 0)) { i = srcC.read(buf); buf.flip(); destC.write(buf); buf.compact(); } srcC.close(); src.close(); fileNo++; } } catch (IOException e1) { e1.printStackTrace(); return; } }
Code Sample 2:
public static void copyFile(File source, File destination) throws IOException { if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (destination == null) { String message = Logging.getMessage("nullValue.DestinationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fic, foc; try { fis = new FileInputStream(source); fic = fis.getChannel(); fos = new FileOutputStream(destination); foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size()); fos.flush(); fis.close(); fos.close(); } finally { WWIO.closeStream(fis, source.getPath()); WWIO.closeStream(fos, destination.getPath()); } }
|
11
|
Code Sample 1:
public static String getStringFromInputStream(InputStream in) throws Exception { CachedOutputStream bos = new CachedOutputStream(); IOUtils.copy(in, bos); in.close(); bos.close(); return bos.getOut().toString(); }
Code Sample 2:
private void copyXsl(File aTargetLogDir) { Trace.println(Trace.LEVEL.UTIL, "copyXsl( " + aTargetLogDir.getName() + " )", true); if (myXslSourceDir == null) { return; } File[] files = myXslSourceDir.listFiles(); for (int i = 0; i < files.length; i++) { File srcFile = files[i]; if (!srcFile.isDirectory()) { File tgtFile = new File(aTargetLogDir + File.separator + srcFile.getName()); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(srcFile).getChannel(); outChannel = new FileOutputStream(tgtFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new IOError(e); } finally { if (inChannel != null) try { inChannel.close(); } catch (IOException exc) { throw new IOError(exc); } if (outChannel != null) try { outChannel.close(); } catch (IOException exc) { throw new IOError(exc); } } } } }
|
11
|
Code Sample 1:
public static String getTextFromUrl(final String url) throws IOException { final String lineSeparator = System.getProperty("line.separator"); InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { final StringBuilder result = new StringBuilder(); inputStreamReader = new InputStreamReader(new URL(url).openStream()); bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { result.append(line).append(lineSeparator); } return result.toString(); } finally { InputOutputUtil.close(bufferedReader, inputStreamReader); } }
Code Sample 2:
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(); } }
|
11
|
Code Sample 1:
private void backupOriginalFile(String myFile) { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_S"); String datePortion = format.format(date); try { FileInputStream fis = new FileInputStream(myFile); FileOutputStream fos = new FileOutputStream(myFile + "-" + datePortion + "_UserID" + ".html"); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); fis.close(); fos.close(); System.out.println("**** Backup of file made."); } catch (Exception e) { System.out.println(e); } }
Code Sample 2:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uuid = req.getParameterValues(Constants.PARAM_UUID)[0]; String datastream = null; if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version.foxml\""); } else { datastream = req.getParameterValues(Constants.PARAM_DATASTREAM)[0]; resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version_" + datastream + ".xml\""); } ServletOutputStream os = resp.getOutputStream(); if (uuid != null && !"".equals(uuid)) { try { StringBuffer sb = new StringBuffer(); if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/objectXML"); } else if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/").append(datastream).append("/content"); } InputStream is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), false); if (is == null) { return; } try { if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { os.write(Constants.XML_HEADER_WITH_BACKSLASHES.getBytes()); } IOUtils.copyStreams(is, os); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { is = null; } } } } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); } } }
|
00
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static String md5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
|
11
|
Code Sample 1:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final FileManager fmanager = FileManager.getFileManager(request, leechget); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (!item.isFormField()) { final FileObject file = fmanager.getFile(name); if (!file.exists()) { IOUtils.copyLarge(stream, file.getContent().getOutputStream()); } } } } catch (FileUploadException e1) { e1.printStackTrace(); } }
Code Sample 2:
public static void main(String[] args) { try { FileReader reader = new FileReader(args[0]); FileWriter writer = new FileWriter(args[1]); html2xhtml(reader, writer); writer.close(); reader.close(); } catch (Exception e) { freemind.main.Resources.getInstance().logException(e); } }
|
00
|
Code Sample 1:
public LogoutHandler(String username, String token) { try { URL url = new URL("http://eiffel.itba.edu.ar/hci/service/Security.groovy?method=LogOut&username=" + username + "&authentication_token=" + token); URLConnection urlc = url.openConnection(); urlc.setDoOutput(false); urlc.setAllowUserInteraction(false); BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); String response = sb.toString(); if (response == null) { return; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document dom = db.parse(is); NodeList nl = dom.getElementsByTagName("response"); String status = ((Element) nl.item(0)).getAttributes().item(0).getTextContent(); if (status.toString().equals("fail")) { return; } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public static void main(String[] args) { LogFrame.getInstance(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.trim().startsWith(DEBUG_PARAMETER_NAME + "=")) { properties.put(DEBUG_PARAMETER_NAME, arg.trim().substring(DEBUG_PARAMETER_NAME.length() + 1).trim()); if (properties.getProperty(DEBUG_PARAMETER_NAME).toLowerCase().equals(DEBUG_TRUE)) { DEBUG = true; } } else if (arg.trim().startsWith(AUTOCONNECT_PARAMETER_NAME + "=")) { properties.put(AUTOCONNECT_PARAMETER_NAME, arg.trim().substring(AUTOCONNECT_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(SITE_CONFIG_URL_PARAMETER_NAME + "=")) { properties.put(SITE_CONFIG_URL_PARAMETER_NAME, arg.trim().substring(SITE_CONFIG_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(LOAD_PLUGINS_PARAMETER_NAME + "=")) { properties.put(LOAD_PLUGINS_PARAMETER_NAME, arg.trim().substring(LOAD_PLUGINS_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(DOCSERVICE_URL_PARAMETER_NAME + "=")) { properties.put(DOCSERVICE_URL_PARAMETER_NAME, arg.trim().substring(DOCSERVICE_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(CORPUS_ID_PARAMETER_NAME + "=")) { properties.put(CORPUS_ID_PARAMETER_NAME, arg.trim().substring(CORPUS_ID_PARAMETER_NAME.length() + 1).trim()); } else { System.out.println("WARNING! Unknown or undefined parameter: '" + arg.trim() + "'"); } } System.out.println("Annic GUI startup parameters:"); System.out.println("------------------------------"); for (Object propName : properties.keySet()) { System.out.println(propName.toString() + "=" + properties.getProperty((String) propName)); } System.out.println("------------------------------"); if (properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME) == null || properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME).length() == 0) { String err = "Mandatory parameter '" + SITE_CONFIG_URL_PARAMETER_NAME + "' is missing.\n\nApplication will exit."; System.out.println(err); JOptionPane.showMessageDialog(new JFrame(), err, "Error!", JOptionPane.ERROR_MESSAGE); System.exit(-1); } try { String context = System.getProperty(CONTEXT); if (context == null || "".equals(context)) { context = DEFAULT_CONTEXT; } String s = System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME); if (s == null || s.length() == 0) { File f = File.createTempFile("foo", ""); String gateHome = f.getParent().toString() + context; f.delete(); System.setProperty(GateConstants.GATE_HOME_PROPERTY_NAME, gateHome); f = new File(System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME)); if (!f.exists()) { f.mkdirs(); } } s = System.getProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME); if (s == null || s.length() == 0) { System.setProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME, System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME) + "/plugins"); File f = new File(System.getProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME)); if (!f.exists()) { f.mkdirs(); } } s = System.getProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME); if (s == null || s.length() == 0) { System.setProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME, System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME) + "/gate.xml"); } if (properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME) != null && properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME).length() > 0) { File f = new File(System.getProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME)); if (f.exists()) { f.delete(); } f.getParentFile().mkdirs(); f.createNewFile(); URL url = new URL(properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME)); InputStream is = url.openStream(); FileOutputStream fos = new FileOutputStream(f); int i = is.read(); while (i != -1) { fos.write(i); i = is.read(); } fos.close(); is.close(); } try { Gate.init(); gate.Main.applyUserPreferences(); } catch (Exception e) { e.printStackTrace(); } s = BASE_PLUGIN_NAME + "," + properties.getProperty(LOAD_PLUGINS_PARAMETER_NAME); System.out.println("Loading plugins: " + s); loadPlugins(s, true); } catch (Throwable e) { e.printStackTrace(); } MainFrame.getInstance().setVisible(true); MainFrame.getInstance().pack(); if (properties.getProperty(AUTOCONNECT_PARAMETER_NAME, "").toLowerCase().equals(AUTOCONNECT_TRUE)) { if (properties.getProperty(CORPUS_ID_PARAMETER_NAME) == null || properties.getProperty(CORPUS_ID_PARAMETER_NAME).length() == 0) { String err = "Can't autoconnect. A parameter '" + CORPUS_ID_PARAMETER_NAME + "' is missing."; System.out.println(err); JOptionPane.showMessageDialog(MainFrame.getInstance(), err, "Error!", JOptionPane.ERROR_MESSAGE); ActionShowAnnicConnectDialog.getInstance().actionPerformed(null); } else { ActionConnectToAnnicGUI.getInstance().actionPerformed(null); } } else { ActionShowAnnicConnectDialog.getInstance().actionPerformed(null); } }
|
11
|
Code Sample 1:
public void setContentMD5() { MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); contentMD5 = null; } messagedigest.update(content.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } contentMD5 = chk; }
Code Sample 2:
String getOutputPage(String action, String XML, String xslFileName, InputStream pageS, HttpServletRequest request) throws NoSuchAlgorithmException, UnsupportedEncodingException, TransformerException { String sPage = null; Transformer transformer = null; String dig = null; CharArrayWriter page = new CharArrayWriter(); if (this.nCachedPages > 0) { java.security.MessageDigest mess = java.security.MessageDigest.getInstance("SHA1"); mess.update(XML.getBytes()); mess.update(Long.toString(new File(basePath + xslFileName).lastModified()).getBytes()); dig = new String(mess.digest()); synchronized (pages) { if (pages.containsKey(dig)) { sPage = pages.get(dig); } } } if (sPage == null && xslFileName.length() > 4) { try { long modifyTime = new File(basePath + xslFileName).lastModified(); String path = basePath.replaceAll("\\\\", "/") + xslFileName; path = "file:///" + path; boolean add2cache = false; if (this.nCachedTransformers > 0) { String cacheKey = action + xslFileName + modifyTime; if (this.transformers.containsKey(cacheKey)) { transformer = this.transformers.get(cacheKey); synchronized (transformer) { transformer.transform(new StreamSource(new ByteArrayInputStream(XML.getBytes("UTF-8"))), new StreamResult(page)); } } else { add2cache = true; } } if (transformer == null) { transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(path)); transformer.transform(new StreamSource(new ByteArrayInputStream(XML.getBytes("UTF-8"))), new StreamResult(page)); } sPage = page.toString(); sPage = sPage.replaceAll("<", "<"); sPage = sPage.replaceAll(">", ">"); sPage = replaceLinks(sPage, request); if (this.nCachedPages > 0) { synchronized (pages) { pages.put(dig, sPage); if (pages.size() > nCachedPages) { Iterator<String> i = pages.values().iterator(); i.next(); i.remove(); } } } if (add2cache) { synchronized (this.transformers) { this.transformers.put(action + xslFileName + modifyTime, transformer); if (this.transformers.size() > this.nCachedTransformers) { Iterator<Transformer> it = this.transformers.values().iterator(); it.next(); it.remove(); } } } } catch (TransformerException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, "---------------------------------------------"); Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); Logger.getLogger(getClass().getName()).log(Level.SEVERE, ("XSL file: " + xslFileName)); Logger.getLogger(getClass().getName()).log(Level.SEVERE, XML); Logger.getLogger(getClass().getName()).log(Level.SEVERE, "---------------------------------------------"); throw ex; } } return sPage; }
|
11
|
Code Sample 1:
private void FindAvail() throws ParserConfigurationException, SQLException { Savepoint sp1; String availsql = "select xmlquery('$c/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]' "; availsql += "passing hp_administrator.availability.AVAIL as \"c\") "; availsql += " from hp_administrator.availability "; availsql += " where date = '" + booking_details.getDate() + "' and train_no like '" + booking_details.getTrain_no() + "'"; System.out.println(availsql); String availxml = ""; String seatxml = ""; String navailstr = ""; String nspavailstr = ""; String currentcoachstr = ""; String srctillstr = "", srcavailstr = "", srcmaxstr = ""; Integer srctill, srcavail, srcmax; Integer navailcoach; Integer nspavailcoach, seatstart, seatcnt, alloccnt; String routesrcstr = "", routedeststr = ""; PreparedStatement pstseat; Statement stavail, stavailupd, stseatupd, stseat; ResultSet rsavail, rsseat; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document docavail, docseattmp, docseatfin, docseat; Element rootavail, rootseat; Node n; try { stavail = conn.createStatement(); sp1 = conn.setSavepoint(); rsavail = stavail.executeQuery(availsql); if (rsavail.next()) availxml = rsavail.getString(1); System.out.println(availxml); StringBuffer StringBuffer1 = new StringBuffer(availxml); ByteArrayInputStream Bis1 = new ByteArrayInputStream(StringBuffer1.toString().getBytes("UTF-16")); docavail = db.parse(Bis1); StringWriter sw; OutputFormat formatter; formatter = new OutputFormat(); formatter.setPreserveSpace(true); formatter.setEncoding("UTF-8"); formatter.setOmitXMLDeclaration(true); XMLSerializer serializer; rootavail = docavail.getDocumentElement(); NodeList coachlist = rootavail.getElementsByTagName("coach"); Element currentcoach, minseat; Element routesrc, routedest, nextstn, dest, user, agent; NodeList nl, nl1; number_of_tickets_rem = booking_details.getNoOfPersons(); int tickpos = 0; firsttime = true; boolean enterloop; for (int i = 0; i < coachlist.getLength(); i++) { currentcoach = (Element) coachlist.item(i); currentcoachstr = currentcoach.getAttribute("number"); String coachmaxstr = currentcoach.getAttribute("coachmax"); Integer coachmax = Integer.parseInt(coachmaxstr.trim()); routesrc = (Element) currentcoach.getFirstChild(); routedest = (Element) currentcoach.getLastChild(); routedest = (Element) routedest.getPreviousSibling().getPreviousSibling().getPreviousSibling(); routesrcstr = routesrc.getNodeName(); routedeststr = routedest.getNodeName(); String seatsql = "select xmlquery('$c/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]' "; seatsql += " passing hp_administrator.book_tickets.SEAT as \"c\") from hp_administrator.book_tickets "; seatsql += " where date = '" + booking_details.getDate() + "' and train_no like '" + booking_details.getTrain_no() + "' "; System.out.println("route :" + sourcenws); System.out.println("route :" + destnnws); System.out.println("route src :" + routesrcstr); System.out.println("route dest :" + routedeststr); System.out.println(seatsql); stseat = conn.createStatement(); rsseat = stseat.executeQuery(seatsql); if (rsseat.next()) seatxml = rsseat.getString(1); StringBuffer StringBuffer2 = new StringBuffer(seatxml); ByteArrayInputStream Bis2 = new ByteArrayInputStream(StringBuffer2.toString().getBytes("UTF-16")); docseat = db.parse(Bis2); rootseat = docseat.getDocumentElement(); enterloop = false; if (routesrcstr.equals(sourcenws) && routedeststr.equals(destnnws)) { System.out.println("case 1"); navailstr = routesrc.getTextContent(); navailcoach = Integer.parseInt(navailstr.trim()); if (useragent) nspavailstr = routesrc.getAttribute("agent"); else nspavailstr = routesrc.getAttribute("user"); nspavailcoach = Integer.parseInt(nspavailstr.trim()); srctillstr = routesrc.getAttribute(sourcenws + "TILL"); srctill = Integer.parseInt(srctillstr.trim()); srcmaxstr = routesrc.getAttribute(sourcenws); srcmax = Integer.parseInt(srcmaxstr.trim()); srcavailstr = routesrc.getTextContent(); srcavail = Integer.parseInt(srcavailstr.trim()); seatstart = coachmax - srctill + 1; seatcnt = srcmax; alloccnt = srcmax - srcavail; seatstart += alloccnt; seatcnt -= alloccnt; Element seat, stn; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); if (booking_details.getNoOfPersons() <= navailcoach && booking_details.getNoOfPersons() <= nspavailcoach) { coach.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); seatno.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } number_of_tickets_rem = 0; navailcoach -= booking_details.getNoOfPersons(); nspavailcoach -= booking_details.getNoOfPersons(); if (!firsttime) conn.rollback(sp1); String availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + navailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); int updvar = stavailupd.executeUpdate(availupdstr); if (updvar > 0) System.out.println("upda avail success"); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(seatupdstr); stseatupd = conn.createStatement(); updvar = stseatupd.executeUpdate(seatupdstr); if (updvar > 0) System.out.println("upda seat success"); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + nspavailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupdstr); stavailupd = conn.createStatement(); updvar = stavailupd.executeUpdate(availupdstr); if (updvar > 0) System.out.println("upda" + sp + " success"); break; } while (navailcoach > 0 && nspavailcoach > 0 && number_of_tickets_rem > 0) { if (firsttime) { sp1 = conn.setSavepoint(); firsttime = false; } enterloop = true; coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); tickpos++; number_of_tickets_rem--; navailcoach--; nspavailcoach--; while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } String availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + navailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + sp + "\"]/" + sourcenws + "/@" + sp + " with \"" + nspavailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); } if (enterloop) { sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); } } else if (routesrcstr.equals(sourcenws) && !routedeststr.equals(destnnws)) { System.out.println("case 2"); String excesssrcstr = routesrc.getTextContent(); System.out.println(excesssrcstr); Integer excesssrc = Integer.parseInt(excesssrcstr.trim()); NodeList nl2 = currentcoach.getElementsByTagName(destnnws); Element e2 = (Element) nl2.item(0); String desttillstr = e2.getAttribute(destnnws + "TILL"); System.out.println(desttillstr); Integer desttillcnt = Integer.parseInt(desttillstr.trim()); srcmaxstr = routesrc.getAttribute(sourcenws); System.out.println(srcmaxstr); srcmax = Integer.parseInt(srcmaxstr.trim()); String spexcesssrcstr = "", spdesttillstr = ""; if (useragent) { spexcesssrcstr = routesrc.getAttribute("agent"); spdesttillstr = e2.getAttribute("agenttill"); } else { spexcesssrcstr = routesrc.getAttribute("user"); spdesttillstr = e2.getAttribute("usertill"); } System.out.println(spdesttillstr); System.out.println(spexcesssrcstr); Integer spdesttillcnt = Integer.parseInt(spdesttillstr.trim()); Integer spexcesssrc = Integer.parseInt(spexcesssrcstr.trim()); Element seat, stn; if (booking_details.getNoOfPersons() <= desttillcnt && booking_details.getNoOfPersons() <= spdesttillcnt) { seatstart = coachmax - desttillcnt + 1; seatcnt = desttillcnt; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } number_of_tickets_rem = 0; desttillcnt -= booking_details.getNoOfPersons(); spdesttillcnt -= booking_details.getNoOfPersons(); if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); int upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update avail success"); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(seatupdstr); stseatupd = conn.createStatement(); upst = stseatupd.executeUpdate(seatupdstr); if (upst > 0) System.out.println("update seat success"); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update " + sp + " success"); break; } else if (booking_details.getNoOfPersons() > spdesttillcnt && spdesttillcnt > 0 && booking_details.getNoOfPersons() <= spdesttillcnt + spexcesssrc) { int diff = 0; if (booking_details.getNoOfPersons() > spdesttillcnt) diff = booking_details.getNoOfPersons() - spdesttillcnt; tickpos = 0; boolean initflg = true; seatstart = coachmax - desttillcnt + 1; seatcnt = desttillcnt; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } if (spdesttillcnt != 0) { desttillcnt--; spdesttillcnt--; } System.out.println("desttillcnt=" + desttillcnt + " spdes = " + desttillcnt + "initflg =" + initflg); if (spdesttillcnt == 0 && initflg == true) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; initflg = false; seat = (Element) seat.getParentNode().getFirstChild(); } } excesssrc -= diff; spexcesssrc -= diff; number_of_tickets_rem = 0; if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); int upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update avail success"); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update avail success"); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(seatupdstr); stseatupd = conn.createStatement(); upst = stseatupd.executeUpdate(seatupdstr); if (upst > 0) System.out.println("update seat success"); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update " + sp + " success"); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update " + sp + " success"); break; } else if (booking_details.getNoOfPersons() > spdesttillcnt && spdesttillcnt == 0 && booking_details.getNoOfPersons() <= spexcesssrc) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; tickpos = 0; boolean initflg = true; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } System.out.println("desttillcnt=" + desttillcnt + " spdes = " + desttillcnt + "initflg =" + initflg); } excesssrc -= booking_details.getNoOfPersons(); spexcesssrc -= booking_details.getNoOfPersons(); ; number_of_tickets_rem = 0; if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); int upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update avail success"); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(seatupdstr); stseatupd = conn.createStatement(); upst = stseatupd.executeUpdate(seatupdstr); if (upst > 0) System.out.println("update seat success"); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update " + sp + " success"); break; } NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); seatstart = 1; String sp = ""; if (useragent) sp = "agent"; else sp = "user"; while (spexcesssrc + spdesttillcnt > 0 && number_of_tickets_rem > 0) { if (firsttime) { sp1 = conn.setSavepoint(); firsttime = false; } enterloop = true; if (spdesttillcnt > 0) { seatstart = coachmax - desttillcnt + 1; desttillcnt--; spdesttillcnt--; String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); } else if (spdesttillcnt == 0) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; excesssrc--; spexcesssrc--; String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); } while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); tickpos++; number_of_tickets_rem--; } if (enterloop) { sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); } } else if (!routesrcstr.equals(sourcenws) && routedeststr.equals(destnnws)) { System.out.println("case 3"); NodeList nl2 = currentcoach.getElementsByTagName(sourcenws); Element e2 = (Element) nl2.item(0); navailstr = e2.getTextContent(); System.out.println(navailstr); navailcoach = Integer.parseInt(navailstr.trim()); if (useragent) nspavailstr = e2.getAttribute("agent"); else nspavailstr = e2.getAttribute("user"); System.out.println(nspavailstr); nspavailcoach = Integer.parseInt(nspavailstr.trim()); srctillstr = e2.getAttribute(sourcenws + "TILL"); System.out.println(srctillstr); srctill = Integer.parseInt(srctillstr.trim()); srcmaxstr = e2.getAttribute(sourcenws); System.out.println(srcmaxstr); srcmax = Integer.parseInt(srcmaxstr.trim()); seatstart = coachmax - srctill + 1; seatcnt = srcmax; alloccnt = srcmax - navailcoach; seatstart += alloccnt; seatcnt -= alloccnt; Element seat, stn; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); if (booking_details.getNoOfPersons() <= navailcoach && booking_details.getNoOfPersons() <= nspavailcoach) { coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } number_of_tickets_rem = 0; navailcoach -= booking_details.getNoOfPersons(); nspavailcoach -= booking_details.getNoOfPersons(); String availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + navailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + nspavailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); break; } while (navailcoach > 0 && nspavailcoach > 0 && number_of_tickets_rem > 0) { if (firsttime) { sp1 = conn.setSavepoint(); firsttime = false; } enterloop = true; coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); tickpos++; number_of_tickets_rem--; navailcoach--; nspavailcoach--; while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } String availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + navailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupdstr); stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + nspavailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupdstr); stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); } if (enterloop) { sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println("!@#------->" + seatupdstr); stseatupd = conn.createStatement(); } } else if (!routesrcstr.equals(sourcenws) && !routedeststr.equals(destnnws)) { System.out.println("case 4"); srcmaxstr = routesrc.getAttribute(sourcenws); System.out.println(srcmaxstr); srcmax = Integer.parseInt(srcmaxstr.trim()); Element seat, stn; NodeList nl2 = currentcoach.getElementsByTagName(sourcenws); Element e2 = (Element) nl2.item(0); navailstr = e2.getTextContent(); Integer excesssrc = Integer.parseInt(navailstr.trim()); nl2 = currentcoach.getElementsByTagName(destnnws); e2 = (Element) nl2.item(0); navailstr = e2.getAttribute(destnnws + "TILL"); Integer desttillcnt = Integer.parseInt(navailstr.trim()); String spexcesssrcstr = "", spdesttillstr = ""; if (useragent) { spexcesssrcstr = routesrc.getAttribute("agent"); spdesttillstr = e2.getAttribute("agenttill"); } else { spexcesssrcstr = routesrc.getAttribute("user"); spdesttillstr = e2.getAttribute("usertill"); } Integer spdesttillcnt = Integer.parseInt(spdesttillstr.trim()); Integer spexcesssrc = Integer.parseInt(spexcesssrcstr.trim()); NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); boolean initflg = true; if (booking_details.getNoOfPersons() <= spdesttillcnt) { seatstart = coachmax - desttillcnt + 1; seatcnt = desttillcnt; coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } number_of_tickets_rem = 0; desttillcnt -= booking_details.getNoOfPersons(); spdesttillcnt -= booking_details.getNoOfPersons(); if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); break; } else if (booking_details.getNoOfPersons() > spdesttillcnt && spdesttillcnt > 0 && booking_details.getNoOfPersons() <= spdesttillcnt + spexcesssrc) { int diff = 0; if (booking_details.getNoOfPersons() > spdesttillcnt) diff = booking_details.getNoOfPersons() - spdesttillcnt; seatstart = coachmax - desttillcnt + 1; seatcnt = desttillcnt; coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } if (spdesttillcnt != 0) { desttillcnt--; spdesttillcnt--; } if (spdesttillcnt == 0 && initflg == true) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; initflg = false; } } excesssrc -= diff; spexcesssrc -= diff; number_of_tickets_rem = 0; if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); break; } else if (spdesttillcnt == 0 && booking_details.getNoOfPersons() <= spexcesssrc) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } excesssrc -= booking_details.getNoOfPersons(); spexcesssrc -= booking_details.getNoOfPersons(); number_of_tickets_rem = 0; if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); break; } seatstart = 1; String sp = ""; if (useragent) sp = "agent"; else sp = "user"; while (spexcesssrc + spdesttillcnt > 0 && number_of_tickets_rem > 0) { if (firsttime) { sp1 = conn.setSavepoint(); firsttime = false; } enterloop = true; if (spdesttillcnt > 0) { seatstart = coachmax - desttillcnt + 1; desttillcnt--; spdesttillcnt--; String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); } else if (spdesttillcnt == 0) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; excesssrc--; spexcesssrc--; String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); } while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); tickpos++; number_of_tickets_rem--; } if (enterloop) { sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); } } } availfin = true; } catch (SQLException e) { conn.rollback(); e.printStackTrace(); } catch (UnsupportedEncodingException e) { conn.rollback(); e.printStackTrace(); } catch (SAXException e) { conn.rollback(); e.printStackTrace(); } catch (IOException e) { conn.rollback(); e.printStackTrace(); } }
Code Sample 2:
public synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws ApplicationException { PreparedStatement preStat = null; StringBuffer sqlStat = new StringBuffer(); MailSetting tmpMailSetting = (MailSetting) ((MailSetting) obj).clone(); synchronized (dbConn) { try { Integer nextID = getNextPrimaryID(); Timestamp currTime = Utility.getCurrentTimestamp(); sqlStat.append("INSERT "); sqlStat.append("INTO MAIL_SETTING(ID, USER_RECORD_ID, PROFILE_NAME, MAIL_SERVER_TYPE, DISPLAY_NAME, EMAIL_ADDRESS, REMEMBER_PWD_FLAG, SPA_LOGIN_FLAG, INCOMING_SERVER_HOST, INCOMING_SERVER_PORT, INCOMING_SERVER_LOGIN_NAME, INCOMING_SERVER_LOGIN_PWD, OUTGOING_SERVER_HOST, OUTGOING_SERVER_PORT, OUTGOING_SERVER_LOGIN_NAME, OUTGOING_SERVER_LOGIN_PWD, PARAMETER_1, PARAMETER_2, PARAMETER_3, PARAMETER_4, PARAMETER_5, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE) "); sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "); preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); setPrepareStatement(preStat, 1, nextID); setPrepareStatement(preStat, 2, tmpMailSetting.getUserRecordID()); setPrepareStatement(preStat, 3, tmpMailSetting.getProfileName()); setPrepareStatement(preStat, 4, tmpMailSetting.getMailServerType()); setPrepareStatement(preStat, 5, tmpMailSetting.getDisplayName()); setPrepareStatement(preStat, 6, tmpMailSetting.getEmailAddress()); setPrepareStatement(preStat, 7, tmpMailSetting.getRememberPwdFlag()); setPrepareStatement(preStat, 8, tmpMailSetting.getSpaLoginFlag()); setPrepareStatement(preStat, 9, tmpMailSetting.getIncomingServerHost()); setPrepareStatement(preStat, 10, tmpMailSetting.getIncomingServerPort()); setPrepareStatement(preStat, 11, tmpMailSetting.getIncomingServerLoginName()); setPrepareStatement(preStat, 12, tmpMailSetting.getIncomingServerLoginPwd()); setPrepareStatement(preStat, 13, tmpMailSetting.getOutgoingServerHost()); setPrepareStatement(preStat, 14, tmpMailSetting.getOutgoingServerPort()); setPrepareStatement(preStat, 15, tmpMailSetting.getOutgoingServerLoginName()); setPrepareStatement(preStat, 16, tmpMailSetting.getOutgoingServerLoginPwd()); setPrepareStatement(preStat, 17, tmpMailSetting.getParameter1()); setPrepareStatement(preStat, 18, tmpMailSetting.getParameter2()); setPrepareStatement(preStat, 19, tmpMailSetting.getParameter3()); setPrepareStatement(preStat, 20, tmpMailSetting.getParameter4()); setPrepareStatement(preStat, 21, tmpMailSetting.getParameter5()); setPrepareStatement(preStat, 22, GlobalConstant.RECORD_STATUS_ACTIVE); setPrepareStatement(preStat, 23, new Integer(0)); setPrepareStatement(preStat, 24, sessionContainer.getUserRecordID()); setPrepareStatement(preStat, 25, currTime); setPrepareStatement(preStat, 26, sessionContainer.getUserRecordID()); setPrepareStatement(preStat, 27, currTime); preStat.executeUpdate(); tmpMailSetting.setID(nextID); tmpMailSetting.setCreatorID(sessionContainer.getUserRecordID()); tmpMailSetting.setCreateDate(currTime); tmpMailSetting.setUpdaterID(sessionContainer.getUserRecordID()); tmpMailSetting.setUpdateDate(currTime); tmpMailSetting.setUpdateCount(new Integer(0)); tmpMailSetting.setCreatorName(UserInfoFactory.getUserFullName(tmpMailSetting.getCreatorID())); tmpMailSetting.setUpdaterName(UserInfoFactory.getUserFullName(tmpMailSetting.getUpdaterID())); dbConn.commit(); return (tmpMailSetting); } catch (SQLException sqle) { log.error(sqle, sqle); } catch (Exception e) { try { dbConn.rollback(); } catch (Exception ex) { } log.error(e, e); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } return null; } }
|
11
|
Code Sample 1:
public static void copy(File from, File to, CopyMode mode) throws IOException { if (!from.exists()) { IllegalArgumentException e = new IllegalArgumentException("Source doesn't exist: " + from.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } if (from.isFile()) { if (!to.canWrite()) { IllegalArgumentException e = new IllegalArgumentException("Cannot write to target location: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } } if (to.exists()) { if ((mode.val & CopyMode.OverwriteFile.val) != CopyMode.OverwriteFile.val) { IllegalArgumentException e = new IllegalArgumentException("Target already exists: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } if (to.isDirectory()) { if ((mode.val & CopyMode.OverwriteFolder.val) != CopyMode.OverwriteFolder.val) { IllegalArgumentException e = new IllegalArgumentException("Target is a folder: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } else to.delete(); } } if (from.isFile()) { FileChannel in = new FileInputStream(from).getChannel(); FileLock inLock = in.lock(); FileChannel out = new FileOutputStream(to).getChannel(); FileLock outLock = out.lock(); try { in.transferTo(0, (int) in.size(), out); } finally { inLock.release(); outLock.release(); in.close(); out.close(); } } else { to.mkdirs(); File[] contents = to.listFiles(); for (File file : contents) { File newTo = new File(to.getCanonicalPath() + "/" + file.getName()); copy(file, newTo, mode); } } }
Code Sample 2:
public void run() { FileInputStream src; FileOutputStream dest; try { dest = new FileOutputStream(srcName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileChannel destC = dest.getChannel(); FileChannel srcC; ByteBuffer buf = ByteBuffer.allocateDirect(BUFFER_SIZE); try { int fileNo = 0; while (true) { int i = 1; String destName = srcName + "_" + fileNo; src = new FileInputStream(destName); srcC = src.getChannel(); while ((i > 0)) { i = srcC.read(buf); buf.flip(); destC.write(buf); buf.compact(); } srcC.close(); src.close(); fileNo++; } } catch (IOException e1) { e1.printStackTrace(); return; } }
|
11
|
Code Sample 1:
public static final void parse(String infile, String outfile) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(infile)); DataOutputStream output = new DataOutputStream(new FileOutputStream(outfile)); int w = Integer.parseInt(reader.readLine()); int h = Integer.parseInt(reader.readLine()); output.writeByte(w); output.writeByte(h); int lineCount = 2; try { do { for (int i = 0; i < h; i++) { lineCount++; String line = reader.readLine(); if (line == null) { throw new RuntimeException("Unexpected end of file at line " + lineCount); } for (int j = 0; j < w; j++) { char c = line.charAt(j); System.out.print(c); output.writeByte(c); } System.out.println(""); } lineCount++; output.writeShort(Short.parseShort(reader.readLine())); } while (reader.readLine() != null); } finally { reader.close(); output.close(); } }
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:
public static String readFromURL(String urlStr) throws IOException { URL url = new URL(urlStr); StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } in.close(); return sb.toString(); }
Code Sample 2:
public void moveRowDown(int row) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); int max = findMaxRank(stmt); if ((row < 1) || (row > (max - 1))) throw new IllegalArgumentException("Row number not between 1 and " + (max - 1)); stmt.executeUpdate("update WordClassifications set Rank = -1 where Rank = " + row); stmt.executeUpdate("update WordClassifications set Rank = " + row + " where Rank = " + (row + 1)); stmt.executeUpdate("update WordClassifications set Rank = " + (row + 1) + " where Rank = -1"); 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); } }
|
00
|
Code Sample 1:
public String contactService(String service, StringBuffer xmlRequest) throws Exception { Logger.debug(UPSConnections.class, "UPS CONNECTIONS ***** Started " + service + " " + new Date().toString() + " *****"); HttpURLConnection connection; URL url; String response = ""; try { Logger.debug(UPSConnections.class, "connect to " + protocol + "://" + hostname + "/" + URLPrefix + "/" + service); if (protocol.equalsIgnoreCase("https")) { java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); System.getProperties().put("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); url = new URL(protocol + "://" + hostname + "/" + URLPrefix + "/" + service); connection = (HttpsURLConnection) url.openConnection(); } else { url = new URL(protocol + "://" + hostname + "/" + URLPrefix + "/" + service); connection = (HttpURLConnection) url.openConnection(); } Logger.debug(UPSConnections.class, "Establishing connection with " + url.toString()); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); OutputStream out = connection.getOutputStream(); StringBuffer request = new StringBuffer(); request.append(accessXMLRequest()); request.append(xmlRequest); out.write((request.toString()).getBytes()); Logger.debug(UPSConnections.class, "Transmission sent to " + url.toString() + ":\n" + xmlRequest); out.close(); try { response = readURLConnection(connection); } catch (Exception e) { Logger.debug(UPSConnections.class, "Error in reading URL Connection" + e.getMessage()); throw e; } Logger.debug(UPSConnections.class, "Response = " + response); } catch (Exception e1) { Logger.info(UPSConnections.class, "Error sending data to server" + e1.toString()); Logger.debug(UPSConnections.class, "Error sending data to server" + e1.toString()); } finally { Logger.info(UPSConnections.class, "****** Transmission Finished " + service + " " + new Date().toString() + " *********"); Logger.debug(UPSConnections.class, "****** Transmission Finished " + service + " " + new Date().toString() + " *********"); } return response; }
Code Sample 2:
public SingularValueDecomposition(Matrix Arg) { double[][] A = Arg.getArrayCopy(); m = Arg.getRowDimension(); n = Arg.getColumnDimension(); int nu = Math.min(m, n); s = new double[Math.min(m + 1, n)]; U = new double[m][nu]; V = new double[n][n]; double[] e = new double[n]; double[] work = new double[m]; boolean wantu = true; boolean wantv = true; int nct = Math.min(m - 1, n); int nrt = Math.max(0, Math.min(n - 2, m)); for (int k = 0; k < Math.max(nct, nrt); k++) { if (k < nct) { s[k] = 0; for (int i = k; i < m; i++) { s[k] = Maths.hypot(s[k], A[i][k]); } if (s[k] != 0.0) { if (A[k][k] < 0.0) { s[k] = -s[k]; } for (int i = k; i < m; i++) { A[i][k] /= s[k]; } A[k][k] += 1.0; } s[k] = -s[k]; } for (int j = k + 1; j < n; j++) { if ((k < nct) & (s[k] != 0.0)) { double t = 0; for (int i = k; i < m; i++) { t += A[i][k] * A[i][j]; } t = -t / A[k][k]; for (int i = k; i < m; i++) { A[i][j] += t * A[i][k]; } } e[j] = A[k][j]; } if (wantu & (k < nct)) { for (int i = k; i < m; i++) { U[i][k] = A[i][k]; } } if (k < nrt) { e[k] = 0; for (int i = k + 1; i < n; i++) { e[k] = Maths.hypot(e[k], e[i]); } if (e[k] != 0.0) { if (e[k + 1] < 0.0) { e[k] = -e[k]; } for (int i = k + 1; i < n; i++) { e[i] /= e[k]; } e[k + 1] += 1.0; } e[k] = -e[k]; if ((k + 1 < m) & (e[k] != 0.0)) { for (int i = k + 1; i < m; i++) { work[i] = 0.0; } for (int j = k + 1; j < n; j++) { for (int i = k + 1; i < m; i++) { work[i] += e[j] * A[i][j]; } } for (int j = k + 1; j < n; j++) { double t = -e[j] / e[k + 1]; for (int i = k + 1; i < m; i++) { A[i][j] += t * work[i]; } } } if (wantv) { for (int i = k + 1; i < n; i++) { V[i][k] = e[i]; } } } } int p = Math.min(n, m + 1); if (nct < n) { s[nct] = A[nct][nct]; } if (m < p) { s[p - 1] = 0.0; } if (nrt + 1 < p) { e[nrt] = A[nrt][p - 1]; } e[p - 1] = 0.0; if (wantu) { for (int j = nct; j < nu; j++) { for (int i = 0; i < m; i++) { U[i][j] = 0.0; } U[j][j] = 1.0; } for (int k = nct - 1; k >= 0; k--) { if (s[k] != 0.0) { for (int j = k + 1; j < nu; j++) { double t = 0; for (int i = k; i < m; i++) { t += U[i][k] * U[i][j]; } t = -t / U[k][k]; for (int i = k; i < m; i++) { U[i][j] += t * U[i][k]; } } for (int i = k; i < m; i++) { U[i][k] = -U[i][k]; } U[k][k] = 1.0 + U[k][k]; for (int i = 0; i < k - 1; i++) { U[i][k] = 0.0; } } else { for (int i = 0; i < m; i++) { U[i][k] = 0.0; } U[k][k] = 1.0; } } } if (wantv) { for (int k = n - 1; k >= 0; k--) { if ((k < nrt) & (e[k] != 0.0)) { for (int j = k + 1; j < nu; j++) { double t = 0; for (int i = k + 1; i < n; i++) { t += V[i][k] * V[i][j]; } t = -t / V[k + 1][k]; for (int i = k + 1; i < n; i++) { V[i][j] += t * V[i][k]; } } } for (int i = 0; i < n; i++) { V[i][k] = 0.0; } V[k][k] = 1.0; } } int pp = p - 1; int iter = 0; double eps = Math.pow(2.0, -52.0); double tiny = Math.pow(2.0, -966.0); while (p > 0) { int k, kase; for (k = p - 2; k >= -1; k--) { if (k == -1) { break; } if (Math.abs(e[k]) <= tiny + eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) { e[k] = 0.0; break; } } if (k == p - 2) { kase = 4; } else { int ks; for (ks = p - 1; ks >= k; ks--) { if (ks == k) { break; } double t = (ks != p ? Math.abs(e[ks]) : 0.) + (ks != k + 1 ? Math.abs(e[ks - 1]) : 0.); if (Math.abs(s[ks]) <= tiny + eps * t) { s[ks] = 0.0; break; } } if (ks == k) { kase = 3; } else if (ks == p - 1) { kase = 1; } else { kase = 2; k = ks; } } k++; switch(kase) { case 1: { double f = e[p - 2]; e[p - 2] = 0.0; for (int j = p - 2; j >= k; j--) { double t = Maths.hypot(s[j], f); double cs = s[j] / t; double sn = f / t; s[j] = t; if (j != k) { f = -sn * e[j - 1]; e[j - 1] = cs * e[j - 1]; } if (wantv) { for (int i = 0; i < n; i++) { t = cs * V[i][j] + sn * V[i][p - 1]; V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1]; V[i][j] = t; } } } } break; case 2: { double f = e[k - 1]; e[k - 1] = 0.0; for (int j = k; j < p; j++) { double t = Maths.hypot(s[j], f); double cs = s[j] / t; double sn = f / t; s[j] = t; f = -sn * e[j]; e[j] = cs * e[j]; if (wantu) { for (int i = 0; i < m; i++) { t = cs * U[i][j] + sn * U[i][k - 1]; U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1]; U[i][j] = t; } } } } break; case 3: { double scale = Math.max(Math.max(Math.max(Math.max(Math.abs(s[p - 1]), Math.abs(s[p - 2])), Math.abs(e[p - 2])), Math.abs(s[k])), Math.abs(e[k])); double sp = s[p - 1] / scale; double spm1 = s[p - 2] / scale; double epm1 = e[p - 2] / scale; double sk = s[k] / scale; double ek = e[k] / scale; double b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2.0; double c = (sp * epm1) * (sp * epm1); double shift = 0.0; if ((b != 0.0) | (c != 0.0)) { shift = Math.sqrt(b * b + c); if (b < 0.0) { shift = -shift; } shift = c / (b + shift); } double f = (sk + sp) * (sk - sp) + shift; double g = sk * ek; for (int j = k; j < p - 1; j++) { double t = Maths.hypot(f, g); double cs = f / t; double sn = g / t; if (j != k) { e[j - 1] = t; } f = cs * s[j] + sn * e[j]; e[j] = cs * e[j] - sn * s[j]; g = sn * s[j + 1]; s[j + 1] = cs * s[j + 1]; if (wantv) { for (int i = 0; i < n; i++) { t = cs * V[i][j] + sn * V[i][j + 1]; V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1]; V[i][j] = t; } } t = Maths.hypot(f, g); cs = f / t; sn = g / t; s[j] = t; f = cs * e[j] + sn * s[j + 1]; s[j + 1] = -sn * e[j] + cs * s[j + 1]; g = sn * e[j + 1]; e[j + 1] = cs * e[j + 1]; if (wantu && (j < m - 1)) { for (int i = 0; i < m; i++) { t = cs * U[i][j] + sn * U[i][j + 1]; U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1]; U[i][j] = t; } } } e[p - 2] = f; iter = iter + 1; } break; case 4: { if (s[k] <= 0.0) { s[k] = (s[k] < 0.0 ? -s[k] : 0.0); if (wantv) { for (int i = 0; i <= pp; i++) { V[i][k] = -V[i][k]; } } } while (k < pp) { if (s[k] >= s[k + 1]) { break; } double t = s[k]; s[k] = s[k + 1]; s[k + 1] = t; if (wantv && (k < n - 1)) { for (int i = 0; i < n; i++) { t = V[i][k + 1]; V[i][k + 1] = V[i][k]; V[i][k] = t; } } if (wantu && (k < m - 1)) { for (int i = 0; i < m; i++) { t = U[i][k + 1]; U[i][k + 1] = U[i][k]; U[i][k] = t; } } k++; } iter = 0; p--; } break; } } }
|
11
|
Code Sample 1:
public static void unzip(String destDir, String zipPath) { PrintWriter stdout = new PrintWriter(System.out, true); int read = 0; byte[] data = new byte[1024]; ZipEntry entry; try { ZipInputStream in = new ZipInputStream(new FileInputStream(zipPath)); stdout.println(zipPath); while ((entry = in.getNextEntry()) != null) { if (entry.getMethod() == ZipEntry.DEFLATED) { stdout.println(" Inflating: " + entry.getName()); } else { stdout.println(" Extracting: " + entry.getName()); } FileOutputStream out = new FileOutputStream(destDir + File.separator + entry.getName()); while ((read = in.read(data, 0, 1024)) != -1) { out.write(data, 0, read); } out.close(); } in.close(); stdout.println(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private void tar(FileHolder fileHolder, boolean gzipIt) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File tarDestFile = new File(fileHolder.destFiles[0]); try { OutputStream outStream = new FileOutputStream(tarDestFile); if (gzipIt) { outStream = new GZIPOutputStream(outStream); } TarOutputStream tarOutStream = new TarOutputStream(outStream); for (int i = 0; i < fileHolder.selectedFileList.size(); i++) { File selectedFile = fileHolder.selectedFileList.get(i); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); TarEntry tarEntry = null; try { tarEntry = new TarEntry(selectedFile, selectedFile.getName()); } catch (InvalidHeaderException e) { errEntry.setThrowable(e); errEntry.setAppContext("tar()"); errEntry.setAppMessage("Error tar'ing: " + selectedFile); logger.logError(errEntry); } tarOutStream.putNextEntry(tarEntry); while ((bytes_read = inStream.read(buffer)) != -1) { tarOutStream.write(buffer, 0, bytes_read); } tarOutStream.closeEntry(); inStream.close(); super.processorSyncFlag.restartWaitUntilFalse(); } tarOutStream.close(); } catch (Exception e) { errEntry.setThrowable(e); errEntry.setAppContext("tar()"); errEntry.setAppMessage("Error tar'ing: " + tarDestFile); logger.logError(errEntry); } }
|
00
|
Code Sample 1:
private void bokActionPerformed(java.awt.event.ActionEvent evt) { if (this.seriesstatementpanel.getEnteredvalues().get(0).toString().trim().equals("")) { this.showWarningMessage("Enter Series Title"); } else { String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds(); String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveSeriesName("2", seriesstatementpanel.getEnteredvalues(), patlib); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SeriesNameServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); if (rootelement.getChild("Error") == null) { this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase")); } else { this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor")); } } catch (Exception e) { System.out.println(e); } } }
Code Sample 2:
public void handleEvent(Event event) { if (fileDialog == null) { fileDialog = new FileDialog(getShell(), SWT.OPEN); fileDialog.setText("Open device profile file..."); fileDialog.setFilterNames(new String[] { "Device profile (*.jar)" }); fileDialog.setFilterExtensions(new String[] { "*.jar" }); } fileDialog.open(); if (fileDialog.getFileName() != null) { File file; String manifestDeviceName = null; URL[] urls = new URL[1]; ArrayList descriptorEntries = new ArrayList(); try { file = new File(fileDialog.getFilterPath(), fileDialog.getFileName()); JarFile jar = new JarFile(file); Manifest manifest = jar.getManifest(); if (manifest != null) { Attributes attrs = manifest.getMainAttributes(); manifestDeviceName = attrs.getValue("Device-Name"); } for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorEntries.add(entry); } } jar.close(); urls[0] = file.toURL(); } catch (IOException ex) { Message.error("Error reading file: " + fileDialog.getFileName() + ", " + Message.getCauseMessage(ex), ex); return; } if (descriptorEntries.size() == 0) { Message.error("Cannot find any device profile in file: " + fileDialog.getFileName()); return; } if (descriptorEntries.size() > 1) { manifestDeviceName = null; } ClassLoader classLoader = Common.createExtensionsClassLoader(urls); HashMap devices = new HashMap(); for (Iterator it = descriptorEntries.iterator(); it.hasNext(); ) { JarEntry entry = (JarEntry) it.next(); try { devices.put(entry.getName(), DeviceImpl.create(emulatorContext, classLoader, entry.getName(), SwtDevice.class)); } catch (IOException ex) { Message.error("Error parsing device profile, " + Message.getCauseMessage(ex), ex); return; } } for (int i = 0; i < deviceModel.size(); i++) { DeviceEntry entry = (DeviceEntry) deviceModel.elementAt(i); if (devices.containsKey(entry.getDescriptorLocation())) { devices.remove(entry.getDescriptorLocation()); } } if (devices.size() == 0) { Message.info("Device profile already added"); return; } try { File deviceFile = new File(Config.getConfigPath(), file.getName()); if (deviceFile.exists()) { deviceFile = File.createTempFile("device", ".jar", Config.getConfigPath()); } IOUtils.copyFile(file, deviceFile); DeviceEntry entry = null; for (Iterator it = devices.keySet().iterator(); it.hasNext(); ) { String descriptorLocation = (String) it.next(); Device device = (Device) devices.get(descriptorLocation); if (manifestDeviceName != null) { entry = new DeviceEntry(manifestDeviceName, deviceFile.getName(), descriptorLocation, false); } else { entry = new DeviceEntry(device.getName(), deviceFile.getName(), descriptorLocation, false); } deviceModel.addElement(entry); for (int i = 0; i < deviceModel.size(); i++) { if (deviceModel.elementAt(i) == entry) { lsDevices.add(entry.getName()); lsDevices.select(i); } } Config.addDeviceEntry(entry); } lsDevicesListener.widgetSelected(null); } catch (IOException ex) { Message.error("Error adding device profile, " + Message.getCauseMessage(ex), ex); return; } } }
|
00
|
Code Sample 1:
public final String encrypt(String input) throws Exception { try { MessageDigest messageDigest = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); messageDigest.reset(); messageDigest.update(input.getBytes()); String output = convert(messageDigest.digest()); return output; } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Fatal Error while digesting input string", ex); } } return input; }
Code Sample 2:
private void copyEntries() { if (zipFile != null) { Enumeration<? extends ZipEntry> enumerator = zipFile.entries(); while (enumerator.hasMoreElements()) { ZipEntry entry = enumerator.nextElement(); if (!entry.isDirectory() && !toIgnore.contains(normalizePath(entry.getName()))) { ZipEntry originalEntry = new ZipEntry(entry.getName()); try { zipOutput.putNextEntry(originalEntry); IOUtils.copy(getInputStream(entry.getName()), zipOutput); zipOutput.closeEntry(); } catch (IOException e) { e.printStackTrace(); } } } } }
|
11
|
Code Sample 1:
@Override public void doHandler(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String directURL = request.getRequestURL().toString(); response.setCharacterEncoding("gbk"); PrintWriter out = response.getWriter(); try { directURL = urlTools.urlFilter(directURL, true); URL url = new URL(directURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "gbk")); String line; while ((line = in.readLine()) != null) { out.println(line); } in.close(); } catch (Exception e) { out.println("file not find"); } out.flush(); }
Code Sample 2:
public static String loadURLToString(String url, String EOL) throws FileNotFoundException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); String result = ""; String str; while ((str = in.readLine()) != null) { result += str + EOL; } in.close(); return result; }
|
00
|
Code Sample 1:
public void insertArchiveEntries(ArchiveEntry entries[]) throws WeatherMonitorException { String sql = null; try { Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rslt = null; con.setAutoCommit(false); for (int i = 0; i < entries.length; i++) { if (!sanityCheck(entries[i])) { } else { sql = getSelectSql(entries[i]); rslt = stmt.executeQuery(sql); if (rslt.next()) { if (rslt.getInt(1) == 0) { sql = getInsertSql(entries[i]); if (stmt.executeUpdate(sql) != 1) { con.rollback(); System.out.println("rolling back sql"); throw new WeatherMonitorException("exception on insert"); } } } } } con.commit(); stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new WeatherMonitorException(e.getMessage()); } }
Code Sample 2:
public static byte[] getURLContent(String urlPath) { HttpURLConnection conn = null; InputStream inStream = null; byte[] buffer = null; try { URL url = new URL(urlPath); HttpURLConnection.setFollowRedirects(false); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.setUseCaches(false); conn.setDefaultUseCaches(false); conn.setConnectTimeout(10000); conn.setReadTimeout(60000); conn.connect(); int repCode = conn.getResponseCode(); if (repCode == 200) { inStream = conn.getInputStream(); int contentLength = conn.getContentLength(); buffer = getResponseBody(inStream, contentLength); } } catch (Exception ex) { logger.error("", ex); } finally { try { if (inStream != null) { inStream.close(); } if (conn != null) { conn.disconnect(); } } catch (Exception ex) { } } return buffer; }
|
11
|
Code Sample 1:
public boolean moveFileSafely(final File in, final File out) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; FileChannel inChannel = null; FileChannel outChannel = null; final File tempOut = File.createTempFile("move", ".tmp"); try { fis = new FileInputStream(in); fos = new FileOutputStream(tempOut); inChannel = fis.getChannel(); outChannel = fos.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { try { if (inChannel != null) inChannel.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", inChannel); } try { if (outChannel != null) outChannel.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", outChannel); } try { if (fis != null) fis.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fis); } try { if (fos != null) fos.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fos); } } out.delete(); if (!out.exists()) { tempOut.renameTo(out); return in.delete(); } return false; }
Code Sample 2:
protected void copyFile(String from, String to, String workingDirectory) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File f = new File(monitorCallShellScriptUrl.getFile()); String directoryPath = f.getAbsolutePath(); String fileName = from; InputStream in = null; if (directoryPath.indexOf(".jar!") > -1) { URL urlJar = new URL(directoryPath.substring(directoryPath.indexOf("file:"), directoryPath.indexOf('!'))); JarFile jf = new JarFile(urlJar.getFile()); JarEntry je = jf.getJarEntry(from); fileName = je.getName(); in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); } else { in = new FileInputStream(f); } File outScriptFile = new File(to); FileOutputStream fos = new FileOutputStream(outScriptFile); int nextChar; while ((nextChar = in.read()) != -1) fos.write(nextChar); fos.flush(); fos.close(); try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } }
|
00
|
Code Sample 1:
public static boolean canWeConnectToInternet() { String s = "http://www.google.com/"; URL url = null; boolean can = false; URLConnection conection = null; try { url = new URL(s); } catch (MalformedURLException e) { System.out.println("This should never happend. Error in URL name. URL specified was:" + s + "."); } try { conection = url.openConnection(); conection.connect(); can = true; } catch (IOException e) { can = false; } if (can) { } return can; }
Code Sample 2:
public static void printResource(OutputStream os, String resourceName) throws IOException { InputStream is = null; try { is = ResourceLoader.loadResource(resourceName); if (is == null) { throw new IOException("Given resource not found!"); } IOUtils.copy(is, os); } finally { IOUtils.closeQuietly(is); } }
|
11
|
Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
protected void copyFile(String from, String to, String workingDirectory) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File f = new File(monitorCallShellScriptUrl.getFile()); String directoryPath = f.getAbsolutePath(); String fileName = from; InputStream in = null; if (directoryPath.indexOf(".jar!") > -1) { URL urlJar = new URL(directoryPath.substring(directoryPath.indexOf("file:"), directoryPath.indexOf('!'))); JarFile jf = new JarFile(urlJar.getFile()); JarEntry je = jf.getJarEntry(from); fileName = je.getName(); in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); } else { in = new FileInputStream(f); } File outScriptFile = new File(to); FileOutputStream fos = new FileOutputStream(outScriptFile); int nextChar; while ((nextChar = in.read()) != -1) fos.write(nextChar); fos.flush(); fos.close(); try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } }
|
11
|
Code Sample 1:
private void parseExternalCss(Document d) throws XPathExpressionException, IOException { InputStream is = null; try { XPath xp = xpf.newXPath(); XPathExpression xpe = xp.compile("//link[@type='text/css']/@href"); NodeList nl = (NodeList) xpe.evaluate(d, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { Attr a = (Attr) nl.item(i); String url = a.getValue(); URL u = new URL(url); is = new BufferedInputStream(u.openStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); parser.add(new String(baos.toByteArray(), "UTF-8")); Element linkNode = a.getOwnerElement(); Element parent = (Element) linkNode.getParentNode(); parent.removeChild(linkNode); IOUtils.closeQuietly(is); is = null; } } finally { IOUtils.closeQuietly(is); } }
Code Sample 2:
public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
|
00
|
Code Sample 1:
public static void copyFile(File file, File dest_file) throws FileNotFoundException, IOException { DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest_file))); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) > 0) { out.write(buffer, 0, read); } in.close(); out.close(); }
Code Sample 2:
public void parse(String file) throws IOException, URISyntaxException { if (file == null) { throw new IOException("File '" + file + "' file not found"); } InputStream is = null; if (file.startsWith("http://")) { URL url = new URL(file); is = url.openStream(); } else if (file.startsWith("file:/")) { is = new FileInputStream(new File(new URI(file))); } else { is = new FileInputStream(file); } if (file.endsWith(".gz")) { is = new GZIPInputStream(is); } parse(new InputStreamReader(is)); }
|
00
|
Code Sample 1:
private static String retrieveVersion(InputStream is) throws RepositoryException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { IOUtils.copy(is, buffer); } catch (IOException e) { throw new RepositoryException(exceptionLocalizer.format("device-repository-file-missing", DeviceRepositoryConstants.VERSION_FILENAME), e); } return buffer.toString().trim(); }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
|
11
|
Code Sample 1:
public void 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 boolean copyFile(File source, File dest) { try { FileReader in = new FileReader(source); FileWriter out = new FileWriter(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return true; } catch (Exception e) { return false; } }
|
00
|
Code Sample 1:
public void download() throws IOException { new File(file.getPath().substring(0, file.getPath().lastIndexOf(File.separator))).mkdirs(); URLConnection urlConnection = url.openConnection(); size = urlConnection.getContentLength(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file)); InputStream inputStream = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int numRead; fetchedSize = 0; date = urlConnection.getLastModified(); while (!failed && (numRead = inputStream.read(buffer)) != -1) { if (failed) { throw new IOException("Download manually stopped"); } bufferedOutputStream.write(buffer, 0, numRead); fetchedSize += numRead; for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).downloadProgress(this); } } } inputStream.close(); bufferedOutputStream.close(); if (file.toString().endsWith(".gz") || file.toString().endsWith(".gzip")) { for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).uncompressingProgress(this); } } try { GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(file)); String fileName = file.toString().substring(0, file.toString().lastIndexOf(".")); OutputStream outputStream = new FileOutputStream(fileName); byte[] unpackBuffer = new byte[1024]; int length; while ((length = gzipInputStream.read(unpackBuffer)) > 0) { outputStream.write(unpackBuffer, 0, length); } gzipInputStream.close(); outputStream.close(); file.delete(); file = new File(fileName); file.setLastModified(date); failed = false; finished = true; for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).uncompressingFinished(this); } } for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).downloadFinished(this); } } } catch (IOException ioException) { file.delete(); failed = true; for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).exceptionWasThrown(this, ioException); } } } try { Runtime.getRuntime().exec("chmod 777 " + file.getCanonicalPath()); } catch (Exception exception) { } } else { failed = false; finished = true; file.setLastModified(date); for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).downloadFinished(this); } } } }
Code Sample 2:
public void performUpdates(List<PackageDescriptor> downloadList, ProgressListener progressListener) throws IOException, UpdateServiceException_Exception { int i = 0; try { for (PackageDescriptor desc : downloadList) { String urlString = service.getDownloadURL(desc.getPackageId(), desc.getVersion(), desc.getPlatformName()); int minProgress = 20 + 80 * i / downloadList.size(); int maxProgress = 20 + 80 * (i + 1) / downloadList.size(); boolean incremental = UpdateManager.isIncrementalUpdate(); if (desc.getPackageTypeName().equals("RAPIDMINER_PLUGIN")) { ManagedExtension extension = ManagedExtension.getOrCreate(desc.getPackageId(), desc.getName(), desc.getLicenseName()); String baseVersion = extension.getLatestInstalledVersionBefore(desc.getVersion()); incremental &= baseVersion != null; URL url = UpdateManager.getUpdateServerURI(urlString + (incremental ? "?baseVersion=" + URLEncoder.encode(baseVersion, "UTF-8") : "")).toURL(); if (incremental) { LogService.getRoot().info("Updating " + desc.getPackageId() + " incrementally."); try { updatePluginIncrementally(extension, openStream(url, progressListener, minProgress, maxProgress), baseVersion, desc.getVersion()); } catch (IOException e) { LogService.getRoot().warning("Incremental Update failed. Trying to fall back on non incremental Update..."); incremental = false; } } if (!incremental) { LogService.getRoot().info("Updating " + desc.getPackageId() + "."); updatePlugin(extension, openStream(url, progressListener, minProgress, maxProgress), desc.getVersion()); } extension.addAndSelectVersion(desc.getVersion()); } else { URL url = UpdateManager.getUpdateServerURI(urlString + (incremental ? "?baseVersion=" + URLEncoder.encode(RapidMiner.getLongVersion(), "UTF-8") : "")).toURL(); LogService.getRoot().info("Updating RapidMiner core."); updateRapidMiner(openStream(url, progressListener, minProgress, maxProgress), desc.getVersion()); } i++; progressListener.setCompleted(20 + 80 * i / downloadList.size()); } } catch (URISyntaxException e) { throw new IOException(e); } finally { progressListener.complete(); } }
|
00
|
Code Sample 1:
List<String> HttpGet(URL url) throws IOException { List<String> responseList = new ArrayList<String>(); Logger.getInstance().logInfo("HTTP GET: " + url, null, null); URLConnection con = url.openConnection(); con.setAllowUserInteraction(false); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) responseList.add(inputLine); in.close(); return responseList; }
Code Sample 2:
protected void doBackupOrganizeTypeRelation() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strSelQuery = "SELECT parent_organize_type,child_organize_type " + "FROM " + Common.ORGANIZE_TYPE_RELATION_TABLE; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_RELATION_B_TABLE + " " + "(version_no,parent_organize_type,child_organize_type) " + "VALUES (?,?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strSelQuery); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setInt(1, this.versionNO); ps.setString(2, result.getString("parent_organize_type")); ps.setString(3, result.getString("child_organize_type")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeTypeRelation(): ERROR Inserting data " + "in T_SYS_ORGANIZE_TYPE_RELATION_B INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeTypeRelation(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doBackupOrganizeTypeRelation(): SQLException while committing or rollback"); } }
|
00
|
Code Sample 1:
public static XMLShowInfo NzbSearch(TVRageShowInfo tvrage, XMLShowInfo xmldata, int latestOrNext) { String newzbin_query = "", csvData = "", hellaQueueDir = "", newzbinUsr = "", newzbinPass = ""; String[] tmp; DateFormat tvRageDateFormat = new SimpleDateFormat("MMM/dd/yyyy"); DateFormat tvRageDateFormatFix = new SimpleDateFormat("yyyy-MM-dd"); newzbin_query = "?q=" + xmldata.showName + "+"; if (latestOrNext == 0) { if (xmldata.searchBy.equals("ShowName Season x Episode")) newzbin_query += tvrage.latestSeasonNum + "x" + tvrage.latestEpisodeNum; else if (xmldata.searchBy.equals("Showname SeriesNum")) newzbin_query += tvrage.latestSeriesNum; else if (xmldata.searchBy.equals("Showname YYYY-MM-DD")) { try { Date airTime = tvRageDateFormat.parse(tvrage.latestAirDate); newzbin_query += tvRageDateFormatFix.format(airTime); } catch (ParseException e) { e.printStackTrace(); } } else if (xmldata.searchBy.equals("Showname EpisodeTitle")) newzbin_query += tvrage.latestTitle; } else { if (xmldata.searchBy.equals("ShowName Season x Episode")) newzbin_query += tvrage.nextSeasonNum + "x" + tvrage.nextEpisodeNum; else if (xmldata.searchBy.equals("Showname SeriesNum")) newzbin_query += tvrage.nextSeriesNum; else if (xmldata.searchBy.equals("Showname YYYY-MM-DD")) { try { Date airTime = tvRageDateFormat.parse(tvrage.nextAirDate); newzbin_query += tvRageDateFormatFix.format(airTime); } catch (ParseException e) { e.printStackTrace(); } } else if (xmldata.searchBy.equals("Showname EpisodeTitle")) newzbin_query += tvrage.nextTitle; } newzbin_query += "&searchaction=Search"; newzbin_query += "&fpn=p"; newzbin_query += "&category=8category=11"; newzbin_query += "&area=-1"; newzbin_query += "&u_nfo_posts_only=0"; newzbin_query += "&u_url_posts_only=0"; newzbin_query += "&u_comment_posts_only=0"; newzbin_query += "&u_v3_retention=1209600"; newzbin_query += "&ps_rb_language=" + xmldata.language; newzbin_query += "&sort=ps_edit_date"; newzbin_query += "&order=desc"; newzbin_query += "&areadone=-1"; newzbin_query += "&feed=csv"; newzbin_query += "&ps_rb_video_format=" + xmldata.format; newzbin_query = newzbin_query.replaceAll(" ", "%20"); System.out.println("http://v3.newzbin.com/search/" + newzbin_query); try { URL url = new URL("http://v3.newzbin.com/search/" + newzbin_query); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); csvData = in.readLine(); if (csvData != null) { JavaNZB.searchCount++; if (searchCount == 6) { searchCount = 0; System.out.println("Sleeping for 60 seconds"); try { Thread.sleep(60000); } catch (InterruptedException e) { e.printStackTrace(); } } tmp = csvData.split(","); tmp[2] = tmp[2].substring(1, tmp[2].length() - 1); tmp[3] = tmp[3].substring(1, tmp[3].length() - 1); Pattern p = Pattern.compile("[\\\\</:>?\\[|\\]\"]"); Matcher matcher = p.matcher(tmp[3]); tmp[3] = matcher.replaceAll(" "); tmp[3] = tmp[3].replaceAll("&", "and"); URLConnection urlConn; DataOutputStream printout; url = new URL("http://v3.newzbin.com/api/dnzb/"); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); printout = new DataOutputStream(urlConn.getOutputStream()); String content = "username=" + JavaNZB.newzbinUsr + "&password=" + JavaNZB.newzbinPass + "&reportid=" + tmp[2]; printout.writeBytes(content); printout.flush(); printout.close(); BufferedReader nzbInput = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); File f = new File(JavaNZB.hellaQueueDir, tmp[3] + ".nzb"); BufferedWriter out = new BufferedWriter(new FileWriter(f)); String str; System.out.println("--Downloading " + tmp[3] + ".nzb" + " to queue directory--"); while (null != ((str = nzbInput.readLine()))) out.write(str); nzbInput.close(); out.close(); if (latestOrNext == 0) { xmldata.episode = tvrage.latestEpisodeNum; xmldata.season = tvrage.latestSeasonNum; } else { xmldata.episode = tvrage.nextEpisodeNum; xmldata.season = tvrage.nextSeasonNum; } } else System.out.println("No new episode posted"); System.out.println(); } catch (MalformedURLException e) { } catch (IOException e) { System.out.println("IO Exception from NzbSearch"); } return xmldata; }
Code Sample 2:
private static Bitmap loadFromUrl(String url, String portId) { Bitmap bitmap = null; final HttpGet get = new HttpGet(url); HttpEntity entity = null; try { final HttpResponse response = ServiceProxy.getInstance(portId).execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { entity = response.getEntity(); try { InputStream in = entity.getContent(); bitmap = BitmapFactory.decodeStream(in); } catch (IOException e) { Log.error(e); } } } catch (IOException e) { Log.error(e); } finally { if (entity != null) { try { entity.consumeContent(); } catch (IOException e) { Log.error(e); } } } return bitmap; }
|
00
|
Code Sample 1:
public String readURL(URL url) throws JasenException { OutputStream out = new ByteArrayOutputStream(); InputStream in = null; String html = null; NonBlockingStreamReader reader = null; try { in = url.openStream(); reader = new NonBlockingStreamReader(); reader.read(in, out, readBufferSize, readTimeout, null); html = new String(((ByteArrayOutputStream) out).toByteArray()); } catch (IOException e) { throw new JasenException(e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } return html; }
Code Sample 2:
@Override public final byte[] getDigest() { try { final MessageDigest hashing = MessageDigest.getInstance("SHA-256"); final Charset utf16 = Charset.forName("UTF-16"); for (final CollationKey wordKey : this.words) { hashing.update(wordKey.toByteArray()); } hashing.update(this.locale.toString().getBytes(utf16)); hashing.update(ByteUtils.toBytesLE(this.collator.getStrength())); hashing.update(ByteUtils.toBytesLE(this.collator.getDecomposition())); return hashing.digest(); } catch (final NoSuchAlgorithmException e) { FileBasedDictionary.LOG.severe(e.toString()); return new byte[0]; } }
|
11
|
Code Sample 1:
public String getResource(String resourceName) throws IOException { InputStream resourceStream = resourceClass.getResourceAsStream(resourceName); ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); IOUtils.copyAndClose(resourceStream, baos); String expected = new String(baos.toByteArray()); return expected; }
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:
private String determineGuardedHtml() { StringBuffer buf = new StringBuffer(); if (m_guardedButtonPresent) { buf.append("\n<span id='" + getHtmlIdPrefix() + PUSH_PAGE_SUFFIX + "' style='display:none'>\n"); String location = m_guardedHtmlLocation != null ? m_guardedHtmlLocation : (String) Config.getProperty(Config.PROP_PRESENTATION_DEFAULT_GUARDED_HTML_LOCATION); String html = (String) c_guardedHtmlCache.get(location); if (html == null) { if (log.isDebugEnabled()) log.debug(this.NAME + ".determineGuardedHtml: Reading the Guarded Html Fragment: " + location); URL url = getUrl(location); if (url != null) { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf1 = new StringBuffer(); String line = null; while ((line = in.readLine()) != null) { buf1.append(line); buf1.append('\n'); } html = buf1.toString(); } catch (IOException e) { log.warn(this.NAME + ".determineGuardedHtml: Failed to read the Guarded Html Fragment: " + location, e); } finally { try { if (in != null) in.close(); } catch (IOException ex) { log.warn(this.NAME + ".determineGuardedHtml: Failed to close the Guarded Html Fragment: " + location, ex); } } } else { log.warn("Failed to read the Guarded Html Fragment: " + location); } if (html == null) html = "Transaction in Progress"; c_guardedHtmlCache.put(location, html); } buf.append(html); buf.append("\n</span>\n"); } return buf.toString(); }
Code Sample 2:
public static InputStream downloadStream(URL url) { InputStream inputStream = null; try { URLConnection urlConnection = url.openConnection(); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; httpURLConnection.setFollowRedirects(true); httpURLConnection.setRequestMethod("GET"); int responseCode = httpURLConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) return null; } return urlConnection.getInputStream(); } catch (Exception ex) { try { inputStream.close(); } catch (Exception ex1) { } return null; } }
|
00
|
Code Sample 1:
private void getImage(String filename) throws MalformedURLException, IOException, SAXException, FileNotFoundException { String url = Constants.STRATEGICDOMINATION_URL + "/images/gameimages/" + filename; WebRequest req = new GetMethodWebRequest(url); SiteResponse response = getSiteResponse(req); File file = new File("etc/images/" + filename); FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(response.getInputStream(), outputStream); }
Code Sample 2:
protected String readFileUsingHttp(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Type", "text/html"); httpConn.setRequestProperty("Content-Length", "0"); httpConn.setRequestMethod("GET"); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setAllowUserInteraction(false); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; }
|
11
|
Code Sample 1:
public static void compress(final File zip, final Map<InputStream, String> entries) throws IOException { if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet())) throw new IllegalArgumentException("One ore more parameters are empty!"); if (zip.exists()) zip.delete(); else if (!zip.getParentFile().exists()) zip.getParentFile().mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip))); out.setLevel(Deflater.BEST_COMPRESSION); InputStream in = null; try { for (InputStream inputStream : entries.keySet()) { in = inputStream; ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(in))); out.putNextEntry(zipEntry); IOUtils.copy(in, out); out.closeEntry(); in.close(); } } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
Code Sample 2:
public static FileChannel getFileChannel(Object o) throws IOException { Class c = o.getClass(); try { Method m = c.getMethod("getChannel", null); return (FileChannel) m.invoke(o, null); } catch (IllegalAccessException x) { } catch (NoSuchMethodException x) { } catch (InvocationTargetException x) { if (x.getTargetException() instanceof IOException) throw (IOException) x.getTargetException(); } if (o instanceof FileInputStream) return new MyFileChannelImpl((FileInputStream) o); if (o instanceof FileOutputStream) return new MyFileChannelImpl((FileOutputStream) o); if (o instanceof RandomAccessFile) return new MyFileChannelImpl((RandomAccessFile) o); Assert.UNREACHABLE(o.getClass().toString()); return null; }
|
11
|
Code Sample 1:
private void copy(File fromFile, File toFile) throws IOException { String fromFileName = fromFile.getName(); File tmpFile = new File(fromFileName); String toFileName = toFile.getName(); if (!tmpFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!tmpFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!tmpFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(tmpFile); File toF = new File(toFile.getCanonicalPath()); if (!toF.exists()) ; toF.createNewFile(); if (!SBCMain.DEBUG_MODE) to = new FileOutputStream(toFile); else to = new FileOutputStream(toF); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
public void copy(final File source, final File target) throws FileSystemException { LogHelper.logMethod(log, toObjectString(), "copy(), source = " + source + ", target = " + target); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); sourceChannel.transferTo(0L, sourceChannel.size(), targetChannel); log.info("Copied " + source + " to " + target); } catch (FileNotFoundException e) { throw new FileSystemException("Unexpected FileNotFoundException while copying a file", e); } catch (IOException e) { throw new FileSystemException("Unexpected IOException while copying a file", e); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException e) { log.error("IOException during source channel close after copy", e); } } if (targetChannel != null) { try { targetChannel.close(); } catch (IOException e) { log.error("IOException during target channel close after copy", e); } } } }
|
11
|
Code Sample 1:
public static void copy(File file1, File file2) throws IOException { FileReader in = new FileReader(file1); FileWriter out = new FileWriter(file2); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
Code Sample 2:
public static boolean start(RootDoc root) { Logger log = Logger.getLogger("DocletGenerator"); if (destination == null) { try { ruleListenerDef = IOUtils.toString(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/RuleListenersFragment.xsd"), "UTF-8"); String fn = System.getenv("annocultor.xconverter.destination.file.name"); fn = (fn == null) ? "./../../../src/site/resources/schema/XConverterInclude.xsd" : fn; destination = new File(fn); if (destination.exists()) { destination.delete(); } FileOutputStream os; os = new FileOutputStream(new File(destination.getParentFile(), "XConverter.xsd")); IOUtils.copy(new AutoCloseInputStream(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/XConverterTemplate.xsd")), os); os.close(); os = new FileOutputStream(destination); IOUtils.copy(new AutoCloseInputStream(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/XConverterInclude.xsd")), os); os.close(); } catch (Exception e) { try { throw new RuntimeException("On destination " + destination.getCanonicalPath(), e); } catch (IOException e1) { throw new RuntimeException(e1); } } } try { String s = Utils.loadFileToString(destination.getCanonicalPath(), "\n"); int breakPoint = s.indexOf(XSD_TEXT_TO_REPLACED_WITH_GENERATED_XML_SIGNATURES); if (breakPoint < 0) { throw new Exception("Signature not found in XSD: " + XSD_TEXT_TO_REPLACED_WITH_GENERATED_XML_SIGNATURES); } String preambula = s.substring(0, breakPoint); String appendix = s.substring(breakPoint); destination.delete(); PrintWriter schemaWriter = new PrintWriter(destination); schemaWriter.print(preambula); ClassDoc[] classes = root.classes(); for (int i = 0; i < classes.length; ++i) { ClassDoc cd = classes[i]; PrintWriter documentationWriter = null; if (getSuperClasses(cd).contains(Rule.class.getName())) { for (ConstructorDoc constructorDoc : cd.constructors()) { if (constructorDoc.isPublic()) { if (isMeantForXMLAccess(constructorDoc)) { if (documentationWriter == null) { File file = new File("./../../../src/site/xdoc/rules." + cd.name() + ".xml"); documentationWriter = new PrintWriter(file); log.info("Generating doc for rule " + file.getCanonicalPath()); printRuleDocStart(cd, documentationWriter); } boolean initFound = false; for (MethodDoc methodDoc : cd.methods()) { if ("init".equals(methodDoc.name())) { if (methodDoc.parameters().length == 0) { initFound = true; break; } } } if (!initFound) { } printConstructorSchema(constructorDoc, schemaWriter); if (documentationWriter != null) { printConstructorDoc(constructorDoc, documentationWriter); } } } } } if (documentationWriter != null) { printRuleDocEnd(documentationWriter); } } schemaWriter.print(appendix); schemaWriter.close(); log.info("Saved to " + destination.getCanonicalPath()); } catch (Exception e) { throw new RuntimeException(e); } return true; }
|
00
|
Code Sample 1:
private void loadNumberFormats() { String fileToLocate = "/" + FILENAME_NUMBER_FMT; URL url = getClass().getClassLoader().getResource(fileToLocate); if (url == null) { return; } List<String> lines; try { lines = IOUtils.readLines(url.openStream()); } catch (IOException e) { throw new ConfigurationException("Problem loading file " + fileToLocate, e); } for (String line : lines) { if (line.startsWith("#") || StringUtils.isBlank(line)) { continue; } String[] parts = StringUtils.split(line, "="); addFormat(parts[0], new DecimalFormat(parts[1])); } }
Code Sample 2:
protected static void clearTables() throws SQLException { Connection conn = null; Statement stmt = null; try { conn = FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); ClearData.clearTables(stmt); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (2, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (3, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (4, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (5, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (6, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (7, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (8, '')"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws Exception { if (args.length != 2) { PrintUtil.prt("arguments: sourcefile, destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); in.transferTo(0, in.size(), out); }
Code Sample 2:
@Override public void run() { URL url = null; FileOutputStream fos = null; FTPClient ftp = null; try { url = new URL(super.getAddress()); String host = url.getHost(); String folder = StringUtils.substringBeforeLast(url.getPath(), "/"); String fileName = StringUtils.substringAfterLast(url.getPath(), "/"); ftp = new FTPClient(host, 21); if (!ftp.connected()) { ftp.connect(); } ftp.login("anonymous", "[email protected]"); logger.info("Connected to " + host + "."); logger.info(ftp.getLastValidReply().getReplyText()); logger.debug("changing dir to " + folder); ftp.chdir(folder); fos = new FileOutputStream(localFileName); logger.info("Downloading file " + fileName + "..."); ftp.setType(FTPTransferType.BINARY); ftp.get(fos, fileName); logger.info("Done."); } catch (Exception e) { logger.error(e.getMessage()); logger.debug(e.getStackTrace()); } finally { try { ftp.quit(); fos.close(); } catch (Exception e) { } } }
|
00
|
Code Sample 1:
private 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); }
Code Sample 2:
public static FTPClient getClient(String serverAddress, String login, String password, boolean PASV) throws SocketException, IOException { FTPClient client = new FTPClient(); client.connect(serverAddress); if (PASV) { client.enterLocalPassiveMode(); } client.login(login, password); return client; }
|
00
|
Code Sample 1:
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(); } }
Code Sample 2:
private void Download(String uri) throws MalformedURLException { URL url = new URL(uri); try { bm = BitmapFactory.decodeStream(url.openConnection().getInputStream()); } catch (IOException ex) { bm = getError(); } }
|
00
|
Code Sample 1:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { from.close(); to.close(); } }
Code Sample 2:
public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
|
11
|
Code Sample 1:
public int[] do_it(final int[] x) { int temp = 0; int j = x.length; while (j > 0) { for (int i = 0; i < j - 1; i++) { if (x[i] > x[i + 1]) { temp = x[i]; x[i] = x[i + 1]; x[i + 1] = temp; } ; } ; j--; } ; return x; }
Code Sample 2:
public void bubbleSort(int[] arr) { BasicProcessor.getInstance().getStartBlock(); BasicProcessor.getInstance().getVarDeclaration(); boolean swapped = true; BasicProcessor.getInstance().getVarDeclaration(); int j = 0; BasicProcessor.getInstance().getVarDeclaration(); int tmp; { BasicProcessor.getInstance().getWhileStatement(); while (swapped) { BasicProcessor.getInstance().getStartBlock(); swapped = false; j++; { BasicProcessor.getInstance().getForStatement(); for (int i = 0; i < arr.length - j; i++) { BasicProcessor.getInstance().getStartBlock(); { BasicProcessor.getInstance().getIfStatement(); if (arr[i] > arr[i + 1]) { BasicProcessor.getInstance().getStartBlock(); tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); }
|
00
|
Code Sample 1:
public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
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()); }
|
00
|
Code Sample 1:
public static boolean sendPostRequest(String path, Map<String, String> params, String encoding) throws Exception { StringBuilder sb = new StringBuilder(""); if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), encoding)).append('&'); } sb.deleteCharAt(sb.length() - 1); } byte[] data = sb.toString().getBytes(); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5 * 1000); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); OutputStream outStream = conn.getOutputStream(); outStream.write(data); outStream.flush(); outStream.close(); if (conn.getResponseCode() == 200) { InputStream inputStream = conn.getInputStream(); return ResponseResult.parseXML(inputStream); } return false; }
Code Sample 2:
private void gerarComissao() { int opt = Funcoes.mensagemConfirma(null, "Confirma gerar comiss�es para o vendedor " + txtNomeVend.getVlrString().trim() + "?"); if (opt == JOptionPane.OK_OPTION) { StringBuilder insert = new StringBuilder(); insert.append("INSERT INTO RPCOMISSAO "); insert.append("(CODEMP, CODFILIAL, CODPED, CODITPED, "); insert.append("CODEMPVD, CODFILIALVD, CODVEND, VLRCOMISS ) "); insert.append("VALUES "); insert.append("(?,?,?,?,?,?,?,?)"); PreparedStatement ps; int parameterIndex; boolean gerou = false; try { for (int i = 0; i < tab.getNumLinhas(); i++) { if (((BigDecimal) tab.getValor(i, 8)).floatValue() > 0) { parameterIndex = 1; ps = con.prepareStatement(insert.toString()); ps.setInt(parameterIndex++, AplicativoRep.iCodEmp); ps.setInt(parameterIndex++, ListaCampos.getMasterFilial("RPCOMISSAO")); ps.setInt(parameterIndex++, txtCodPed.getVlrInteger()); ps.setInt(parameterIndex++, (Integer) tab.getValor(i, ETabNota.ITEM.ordinal())); ps.setInt(parameterIndex++, AplicativoRep.iCodEmp); ps.setInt(parameterIndex++, ListaCampos.getMasterFilial("RPVENDEDOR")); ps.setInt(parameterIndex++, txtCodVend.getVlrInteger()); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.VLRCOMIS.ordinal())); ps.executeUpdate(); gerou = true; } } if (gerou) { Funcoes.mensagemInforma(null, "Comiss�o gerada para " + txtNomeVend.getVlrString().trim()); txtCodPed.setText("0"); lcPedido.carregaDados(); carregaTabela(); con.commit(); } else { Funcoes.mensagemInforma(null, "N�o foi possiv�l gerar comiss�o!\nVerifique os valores das comiss�es dos itens."); } } catch (Exception e) { e.printStackTrace(); Funcoes.mensagemErro(this, "Erro ao gerar comiss�o!\n" + e.getMessage()); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } } }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static void main(String[] args) { try { int encodeFlag = 0; if (args[0].equals("-e")) { encodeFlag = Base64.ENCODE; } else if (args[0].equals("-d")) { encodeFlag = Base64.DECODE; } String infile = args[1]; String outfile = args[2]; File fin = new File(infile); FileInputStream fis = new FileInputStream(fin); BufferedInputStream bis = new BufferedInputStream(fis); Base64.InputStream b64in = new Base64.InputStream(bis, encodeFlag | Base64.DO_BREAK_LINES); File fout = new File(outfile); FileOutputStream fos = new FileOutputStream(fout); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buff = new byte[1024]; int read = -1; while ((read = b64in.read(buff)) >= 0) { bos.write(buff, 0, read); } bos.close(); b64in.close(); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
@Override public RServiceResponse execute(final NexusServiceRequest inData) throws NexusServiceException { final RServiceRequest data = (RServiceRequest) inData; final RServiceResponse retval = new RServiceResponse(); final StringBuilder result = new StringBuilder("R service call results:\n"); RSession session; RConnection connection = null; try { result.append("Session Attachment: \n"); final byte[] sessionBytes = data.getSession(); if (sessionBytes != null && sessionBytes.length > 0) { session = RUtils.getInstance().bytesToSession(sessionBytes); result.append(" attaching to " + session + "\n"); connection = session.attach(); } else { result.append(" creating new session\n"); connection = new RConnection(data.getServerAddress()); } result.append("Input Parameters: \n"); for (String attributeName : data.getInputVariables().keySet()) { final Object parameter = data.getInputVariables().get(attributeName); if (parameter instanceof URI) { final FileObject file = VFS.getManager().resolveFile(((URI) parameter).toString()); final RFileOutputStream ros = connection.createFile(file.getName().getBaseName()); IOUtils.copy(file.getContent().getInputStream(), ros); connection.assign(attributeName, file.getName().getBaseName()); } else { connection.assign(attributeName, RUtils.getInstance().convertToREXP(parameter)); } result.append(" " + parameter.getClass().getSimpleName() + " " + attributeName + "=" + parameter + "\n"); } final REXP rExpression = connection.eval(RUtils.getInstance().wrapCode(data.getCode().replace('\r', '\n'))); result.append("Execution results:\n" + rExpression.asString() + "\n"); if (rExpression.isNull() || rExpression.asString().startsWith("Error")) { retval.setErr(rExpression.asString()); throw new NexusServiceException("R error: " + rExpression.asString()); } result.append("Output Parameters:\n"); final String[] rVariables = connection.eval("ls();").asStrings(); for (String varname : rVariables) { final String[] rVariable = connection.eval("class(" + varname + ")").asStrings(); if (rVariable.length == 2 && "file".equals(rVariable[0]) && "connection".equals(rVariable[1])) { final String rFileName = connection.eval("showConnections(TRUE)[" + varname + "]").asString(); result.append(" R File ").append(varname).append('=').append(rFileName).append('\n'); final RFileInputStream rInputStream = connection.openFile(rFileName); final File file = File.createTempFile("nexus-" + data.getRequestId(), ".dat"); IOUtils.copy(rInputStream, new FileOutputStream(file)); retval.getOutputVariables().put(varname, file.getCanonicalFile().toURI()); } else { final Object varvalue = RUtils.getInstance().convertREXP(connection.eval(varname)); retval.getOutputVariables().put(varname, varvalue); final String printValue = varvalue == null ? "null" : varvalue.getClass().isArray() ? Arrays.asList(varvalue).toString() : varvalue.toString(); result.append(" ").append(varvalue == null ? "" : varvalue.getClass().getSimpleName()).append(' ').append(varname).append('=').append(printValue).append('\n'); } } } catch (ClassNotFoundException cnfe) { retval.setErr(cnfe.getMessage()); LOGGER.error("Rserve Exception", cnfe); } catch (RserveException rse) { retval.setErr(rse.getMessage()); LOGGER.error("Rserve Exception", rse); } catch (REXPMismatchException rme) { retval.setErr(rme.getMessage()); LOGGER.error("REXP Mismatch Exception", rme); } catch (IOException rme) { retval.setErr(rme.getMessage()); LOGGER.error("IO Exception copying file ", rme); } finally { result.append("Session Detachment:\n"); if (connection != null) { RSession outSession; if (retval.isKeepSession()) { try { outSession = connection.detach(); } catch (RserveException e) { LOGGER.debug("Error detaching R session", e); outSession = null; } } else { outSession = null; } final boolean close = outSession == null; if (!close) { retval.setSession(RUtils.getInstance().sessionToBytes(outSession)); result.append(" suspended session for later use\n"); } connection.close(); retval.setSession(null); result.append(" session closed.\n"); } } retval.setOut(result.toString()); return retval; }
Code Sample 2:
private void processHelpFile() { InputStream in = null; if (line.hasOption("helpfile")) { OutputStream out = null; try { String filename = line.getOptionValue("helpfile"); in = new FileInputStream(filename); filename = filename.replace('\\', '/'); filename = filename.substring(filename.lastIndexOf('/') + 1); File outFile = new File(outputDir, filename); if (LOG.isInfoEnabled()) { LOG.info("Processing generated file " + outFile.getAbsolutePath()); } out = new FileOutputStream(outFile); baseProperties.setProperty("helpfile", filename); IOUtils.copy(in, out); } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } return; } Properties props = new Properties(baseProperties); ClassLoader cl = this.getClass().getClassLoader(); Document doc = null; try { in = cl.getResourceAsStream(RESOURCE_PKG + "/help-doc.xml"); doc = XmlUtils.parse(in); } catch (XmlException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } transformResource(doc, "help-doc.xsl", props, "help-doc.html"); baseProperties.setProperty("helpfile", "help-doc.html"); }
|
11
|
Code Sample 1:
public 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 write(File file, InputStream source) throws IOException { OutputStream outputStream = null; assert file != null : "file must not be null."; assert file.isFile() : "file must be a file."; assert file.canWrite() : "file must be writable."; assert source != null : "source must not be null."; try { outputStream = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(source, outputStream); outputStream.flush(); } finally { IOUtils.closeQuietly(outputStream); } }
|
00
|
Code Sample 1:
private String readData(URL url) { try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer responseBuffer = new StringBuffer(); String line; while ((line = in.readLine()) != null) { responseBuffer.append(line); } in.close(); return new String(responseBuffer); } catch (Exception e) { System.out.println(e); } return null; }
Code Sample 2:
public StringBuffer render(RenderEngine c) { String logTime = null; if (c.getWorkerContext() != null) { logTime = c.getWorkerContext().getWorkerStart(); } if (c.isBreakState() || !c.canRender("u")) { return new StringBuffer(); } StringBuffer buffer = new StringBuffer(); varname = TagInspector.processElement(varname, c); action = TagInspector.processElement(action, c); filemode = TagInspector.processElement(filemode, c); xmlparse = TagInspector.processElement(xmlparse, c); encoding = TagInspector.processElement(encoding, c); decoding = TagInspector.processElement(decoding, c); filter = TagInspector.processElement(filter, c); sort = TagInspector.processElement(sort, c); useDocroot = TagInspector.processElement(useDocroot, c); useFilename = TagInspector.processElement(useFilename, c); useDest = TagInspector.processElement(useDest, c); xmlOutput = TagInspector.processElement(xmlOutput, c); renderOutput = TagInspector.processElement(renderOutput, c); callProc = TagInspector.processElement(callProc, c); vartype = TagInspector.processElement(vartype, c); if (sort == null || sort.equals("")) { sort = "asc"; } if (useFilename.equals("") && !action.equalsIgnoreCase("listing")) { return new StringBuffer(); } boolean isRooted = true; if (useDocroot.equalsIgnoreCase("true")) { if (c.getVendContext().getVend().getIgnorableDocroot(c.getClientContext().getMatchedHost())) { isRooted = false; } } if (isRooted && (useFilename.indexOf("/") == -1 || useFilename.startsWith("./"))) { if (c.getWorkerContext() != null && useFilename.startsWith("./")) { useFilename = c.getWorkerContext().getClientContext().getPostVariable("current_path") + useFilename.substring(2); Debug.inform("CWD path specified in filename, rewritten to '" + useFilename + "'"); } else if (c.getWorkerContext() != null && useFilename.indexOf("/") == -1) { useFilename = c.getWorkerContext().getClientContext().getPostVariable("current_path") + useFilename; Debug.inform("No path specified in filename, rewritten to '" + useFilename + "'"); } else { Debug.inform("No path specified in filename, no worker context, not rewriting filename."); } } StringBuffer filenameData = null; StringBuffer contentsData = null; StringBuffer fileDestData = null; contentsData = TagInspector.processBody(this, c); filenameData = new StringBuffer(useFilename); fileDestData = new StringBuffer(useDest); String currentDocroot = null; if (c.getWorkerContext() == null) { if (c.getRenderContext().getCurrentDocroot() == null) { currentDocroot = "."; } else { currentDocroot = c.getRenderContext().getCurrentDocroot(); } } else { currentDocroot = c.getWorkerContext().getDocRoot(); } if (!isRooted) { currentDocroot = ""; } if (useDocroot.equalsIgnoreCase("true")) { if (c.getVendContext().getVend().getIgnorableDocroot(c.getClientContext().getMatchedHost())) { isRooted = false; currentDocroot = ""; } } if (!currentDocroot.endsWith("/")) { if (!currentDocroot.equals("") && currentDocroot.length() > 0) { currentDocroot += "/"; } } if (filenameData != null) { filenameData = new StringBuffer(filenameData.toString().replaceAll("\\.\\.", "")); } if (fileDestData != null) { fileDestData = new StringBuffer(fileDestData.toString().replaceAll("\\.\\.", "")); } if (action.equalsIgnoreCase("read")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); FileInputStream is = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte data[] = null; boolean vfsLoaded = false; try { data = c.getVendContext().getFileAccess().getFile(c.getWorkerContext(), filenameData.toString().replaceAll("\\.\\.", ""), c.getClientContext().getMatchedHost(), c.getVendContext().getVend().getRenderExtension(c.getClientContext().getMatchedHost()), null); bos.write(data, 0, data.length); vfsLoaded = true; } catch (Exception e) { Debug.user(logTime, "Included file attempt with VFS of file '" + filenameData + "' failed: " + e); } if (data == null) { try { is = new FileInputStream(file); } catch (Exception e) { Debug.user(logTime, "Unable to render: Filename '" + currentDocroot + filenameData + "' does not exist."); return new StringBuffer(); } } if (xmlparse == null || xmlparse.equals("")) { if (data == null) { Debug.user(logTime, "Opening filename '" + currentDocroot + filenameData + "' for reading into buffer '" + varname + "'"); data = new byte[32768]; int totalBytesRead = 0; while (true) { int bytesRead; try { bytesRead = is.read(data); bos.write(data, 0, bytesRead); } catch (Exception e) { break; } if (bytesRead <= 0) { break; } totalBytesRead += bytesRead; } } byte docOutput[] = bos.toByteArray(); if (renderOutput != null && renderOutput.equalsIgnoreCase("ssp")) { String outputData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n" + new String(FileAccess.getDefault().processServerPageData(c.getWorkerContext(), docOutput)); docOutput = outputData.getBytes(); } Debug.user(logTime, "File read complete: " + docOutput.length + " byte(s)"); if (is != null) { try { is.close(); } catch (Exception e) { } } is = null; if (encoding != null && encoding.equalsIgnoreCase("url")) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Encoder.URLEncode(new String(docOutput))); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Encoder.URLEncode(new String(docOutput))); } } else if (encoding != null && encoding.equalsIgnoreCase("xml")) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Encoder.XMLEncode(new String(docOutput))); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Encoder.XMLEncode(new String(docOutput))); } } else if (encoding != null && encoding.equalsIgnoreCase("base64")) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Base64.encode(docOutput)); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Base64.encode(docOutput)); } } else if (encoding != null && (encoding.equalsIgnoreCase("javascript") || encoding.equalsIgnoreCase("js"))) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Encoder.JavascriptEncode(new String(docOutput))); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Encoder.JavascriptEncode(new String(docOutput))); } } else { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, new String(docOutput)); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(new String(docOutput)); } } } else { RenderEngine engine = new RenderEngine(null); DocumentEngine docEngine = null; try { if (vfsLoaded) { ByteArrayInputStream bais = new ByteArrayInputStream(data); docEngine = new DocumentEngine(bais); } else { docEngine = new DocumentEngine(is); } } catch (Exception e) { c.setExceptionState(true, "XML parse of data read from file failed: " + e.getMessage()); } engine.setDocumentEngine(docEngine); c.addNodeSet(varname, docEngine.rootTag.thisNode); } if (is != null) { try { is.close(); } catch (Exception e) { } } is = null; if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(); } else if (action.equalsIgnoreCase("write")) { try { String rootDir = filenameData.toString(); if (rootDir.lastIndexOf("/") != -1 && rootDir.lastIndexOf("/") != 0) { rootDir = rootDir.substring(0, rootDir.lastIndexOf("/")); java.io.File mkdirFile = new java.io.File(currentDocroot + rootDir); if (!mkdirFile.mkdirs()) { Debug.inform("Unable to create directory '" + currentDocroot + rootDir + "'"); } else { Debug.inform("Created directory '" + currentDocroot + rootDir + "'"); } } java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); FileOutputStream fos = null; if (file == null) { c.setExceptionState(true, "Unable to write to file '" + filenameData + "': Cannot write to location specified"); return new StringBuffer(); } else if (file.isDirectory()) { c.setExceptionState(true, "Unable to write to file '" + filenameData + "': Is a directory."); return new StringBuffer(); } if (filemode.equalsIgnoreCase("append")) { fos = new FileOutputStream(file, true); } else { fos = new FileOutputStream(file, false); } if (decoding != null && !decoding.equals("")) { if (decoding.equalsIgnoreCase("base64")) { try { byte contentsDecoded[] = Base64.decode(contentsData.toString().getBytes()); fos.write(contentsDecoded); } catch (Exception e) { c.setExceptionState(true, "Encoded data in <content> element does not contain valid Base64-" + "encoded data."); } } else { fos.write(contentsData.toString().getBytes()); } } else { fos.write(contentsData.toString().getBytes()); } try { fos.flush(); } catch (IOException e) { Debug.inform("Unable to flush output data: " + e.getMessage()); } fos.close(); Debug.user(logTime, "Wrote contents to filename '" + currentDocroot + filenameData + "' (length=" + contentsData.length() + ")"); } catch (IOException e) { c.setExceptionState(true, "Unable to write to filename '" + filenameData + "': " + e.getMessage()); } catch (Exception e) { c.setExceptionState(true, "Unable to write to filename '" + filenameData + "': " + e.getMessage()); } } else if (action.equalsIgnoreCase("listing")) { String filenameDataString = filenameData.toString(); if (filenameDataString.equals("")) { filenameDataString = c.getClientContext().getPostVariable("current_path"); } if (filenameDataString == null) { c.setExceptionState(true, "Filename cannot be blank when listing."); return new StringBuffer(); } while (filenameDataString.endsWith("/")) { filenameDataString = filenameDataString.substring(0, filenameDataString.length() - 1); } Vector fileList = new Vector(); java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); String curDirname = filenameData.toString(); String parentDirectory = null; String[] dirEntries = curDirname.split("/"); int numSlashes = 0; for (int i = 0; i < curDirname.length(); i++) { if (curDirname.toString().charAt(i) == '/') { numSlashes++; } } parentDirectory = "/"; if (numSlashes > 1) { for (int i = 0; i < (dirEntries.length - 1); i++) { if (dirEntries[i] != null && !dirEntries[i].equals("")) { parentDirectory += dirEntries[i] + "/"; } } } if (parentDirectory.length() > 1 && parentDirectory.endsWith("/")) { parentDirectory = parentDirectory.substring(0, parentDirectory.length() - 1); } if (c.getVendContext() != null && c.getVendContext().getFileAccess() != null && c.getVendContext().getFileAccess().getVFSType(filenameData.toString(), c.getClientContext().getMatchedHost()) == FileAccess.TYPE_JAR) { Vector listFiles = c.getVendContext().getFileAccess().listFiles(filenameData.toString(), c.getClientContext().getMatchedHost()); Object[] list = listFiles.toArray(); int depth = 0; for (int i = 0; i < filenameData.toString().length(); i++) { if (filenameData.toString().charAt(i) == '/') { depth++; } } buffer = new StringBuffer(); buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\">\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } if (sort.equalsIgnoreCase("asc")) { Arrays.sort(list, new ZipSorterAscending()); } else { Arrays.sort(list, new ZipSorterDescending()); } for (int i = 0; i < list.length; i++) { ZipEntry zEntry = (ZipEntry) list[i]; String zipFile = filenameData.toString() + "/" + zEntry.getName(); String displayFilename = zipFile.replaceFirst(filenameData.toString(), ""); int curDepth = 0; if (zipFile.equalsIgnoreCase(".acl") || zipFile.equalsIgnoreCase("access.list") || zipFile.equalsIgnoreCase("application.inc") || zipFile.equalsIgnoreCase("global.inc") || zipFile.indexOf("/.proc") != -1 || zipFile.indexOf("/procedures") != -1) { continue; } for (int x = 0; x < displayFilename.length(); x++) { if (displayFilename.charAt(x) == '/') { curDepth++; } } if (zipFile.startsWith(filenameData.toString())) { String fileLength = "" + zEntry.getSize(); String fileType = "file"; if (curDepth == depth) { if (zEntry.isDirectory()) { fileType = "directory"; } else { fileType = "file"; } String fileMode = "read-only"; String fileTime = Long.toString(zEntry.getTime()); buffer.append(" <file name=\""); buffer.append(displayFilename); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(length)", false, "" + fileLength); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(type)", false, fileType); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(mode)", false, fileMode); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(time)", false, fileTime); } } else { if (curDepth == depth) { fileList.add(zipFile); } } } buffer.append("</listing>"); if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); return new StringBuffer(); } c.getVariableContainer().setVector(varname, fileList); } else if (c.getVendContext() != null && c.getVendContext().getFileAccess() != null && c.getVendContext().getFileAccess().getVFSType(filenameData.toString(), c.getClientContext().getMatchedHost()) == FileAccess.TYPE_FS) { Vector listFiles = c.getVendContext().getFileAccess().listFiles(filenameData.toString(), c.getClientContext().getMatchedHost()); Object[] list = listFiles.toArray(); java.io.File[] filesorted = new java.io.File[list.length]; for (int i = 0; i < list.length; i++) { filesorted[i] = (java.io.File) list[i]; } if (sort.equalsIgnoreCase("asc")) { Arrays.sort(filesorted, new FileSorterAscending()); } else { Arrays.sort(filesorted, new FileSorterDescending()); } buffer = new StringBuffer(); buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\">\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } for (int i = 0; i < filesorted.length; i++) { java.io.File zEntry = filesorted[i]; String filename = filenameData.toString() + "/" + zEntry.getName(); if (filename.equalsIgnoreCase(".acl") || filename.equalsIgnoreCase("access.list") || filename.equalsIgnoreCase("application.inc") || filename.equalsIgnoreCase("global.inc") || filename.indexOf("/.proc") != -1 || filename.indexOf("/procedures") != -1) { continue; } String displayFilename = filename.replaceFirst(filenameData.toString(), ""); String fileLength = "" + zEntry.length(); String fileType = "file"; if (zEntry.isDirectory()) { fileType = "directory"; } else if (zEntry.isFile()) { fileType = "file"; } else if (zEntry.isHidden()) { fileType = "hidden"; } else if (zEntry.isAbsolute()) { fileType = "absolute"; } String fileMode = "read-only"; if (zEntry.canRead() && !zEntry.canWrite()) { fileMode = "read-only"; } else if (!zEntry.canRead() && zEntry.canWrite()) { fileMode = "write-only"; } else if (zEntry.canRead() && zEntry.canWrite()) { fileMode = "read/write"; } String fileTime = Long.toString(zEntry.lastModified()); if (xmlOutput.equalsIgnoreCase("true")) { buffer.append(" <file name=\""); buffer.append(filename); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); } else { fileList.add(zEntry); } c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(length)", false, "" + fileLength); c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(type)", false, fileType); c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(mode)", false, fileMode); c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(time)", false, fileTime); } buffer.append("</listing>"); if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); return new StringBuffer(); } c.getVariableContainer().setVector(varname, fileList); } else { String[] fileStringList = null; if (!filter.equals("")) { fileStringList = file.list(new ListFilter(filter)); } else { fileStringList = file.list(); } if (sort.equalsIgnoreCase("asc")) { Arrays.sort(fileStringList, new StringSorterAscending()); } else { Arrays.sort(fileStringList, new StringSorterDescending()); } if (fileStringList == null) { buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\"/>\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); } else { c.getVariableContainer().setVector(varname, fileList); } return new StringBuffer(); } else { Debug.user(logTime, "Directory '" + currentDocroot + filenameData + "' returns " + fileStringList.length + " entry(ies)"); } buffer = new StringBuffer(); buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\">\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } for (int i = 0; i < fileStringList.length; i++) { file = new java.io.File(currentDocroot + filenameData.toString() + "/" + fileStringList[i]); String fileLength = Long.toString(file.length()); String fileType = "file"; if (file.isDirectory()) { fileType = "directory"; } else if (file.isFile()) { fileType = "file"; } else if (file.isHidden()) { fileType = "hidden"; } else if (file.isAbsolute()) { fileType = "absolute"; } String fileMode = "read-only"; if (file.canRead() && !file.canWrite()) { fileMode = "read-only"; } else if (!file.canRead() && file.canWrite()) { fileMode = "write-only"; } else if (file.canRead() && file.canWrite()) { fileMode = "read/write"; } String fileTime = Long.toString(file.lastModified()); if (xmlOutput.equalsIgnoreCase("true")) { buffer.append(" <file name=\""); buffer.append(fileStringList[i]); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); } else { fileList.add(fileStringList[i]); } c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(length)", false, "" + fileLength); c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(type)", false, fileType); c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(mode)", false, fileMode); c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(time)", false, fileTime); } buffer.append("</listing>"); if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); return new StringBuffer(); } c.getVariableContainer().setVector(varname, fileList); } } else if (action.equalsIgnoreCase("delete")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); if (file.isDirectory()) { boolean success = deleteDir(new java.io.File(currentDocroot + filenameData.toString())); if (!success) { c.setExceptionState(true, "Unable to delete '" + currentDocroot + filenameData + "'"); } } else { String filenamePattern = null; if (filenameData.toString().indexOf("/") != -1) { filenamePattern = filenameData.toString().substring(filenameData.toString().lastIndexOf("/") + 1); } String filenameDirectory = currentDocroot; if (filenameData.toString().indexOf("/") != -1) { filenameDirectory += filenameData.substring(0, filenameData.toString().lastIndexOf("/")); } String[] fileStringList = null; file = new java.io.File(filenameDirectory); fileStringList = file.list(new ListFilter(filenamePattern)); for (int i = 0; i < fileStringList.length; i++) { (new java.io.File(filenameDirectory + "/" + fileStringList[i])).delete(); } } } else if (action.equalsIgnoreCase("rename") || action.equalsIgnoreCase("move")) { if (fileDestData.equals("")) { c.getVariableContainer().setVariable(varname + "-result", filenameData + ": File operation failed: No destination filename given."); return new StringBuffer(); } java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); boolean success = file.renameTo(new java.io.File(currentDocroot + fileDestData.toString(), file.getName())); if (!success) { c.setExceptionState(true, "Unable to rename '" + currentDocroot + filenameData + "' to '" + currentDocroot + fileDestData + "'"); } } else if (action.equalsIgnoreCase("copy")) { if (fileDestData.equals("")) { c.setExceptionState(true, "File copy operation failed for file '" + filenameData + "': No destination file specified."); return new StringBuffer(); } FileChannel srcChannel; FileChannel destChannel; String filename = null; filename = currentDocroot + filenameData.toString(); if (vartype != null && vartype.equalsIgnoreCase("file")) { if (useFilename.indexOf("/") != -1) { useFilename = useFilename.substring(useFilename.lastIndexOf("/") + 1); } filename = c.getVariableContainer().getFileVariable(useFilename); } try { Debug.debug("Copying from file '" + filename + "' to '" + fileDestData.toString() + "'"); srcChannel = new FileInputStream(filename).getChannel(); } catch (IOException e) { c.setExceptionState(true, "Filecopy from '" + filenameData + "' failed to read: " + e.getMessage()); return new StringBuffer(); } try { destChannel = new FileOutputStream(currentDocroot + fileDestData.toString()).getChannel(); } catch (IOException e) { c.setExceptionState(true, "Filecopy to '" + fileDestData + "' failed to write: " + e.getMessage()); return new StringBuffer(); } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); if (varname != null) { c.getVariableContainer().setVariable(varname + "-result", filenameData + " copy to " + fileDestData + ": File copy succeeded."); } else { return new StringBuffer("true"); } } catch (IOException e) { c.setExceptionState(true, "Filecopy from '" + filenameData + "' to '" + fileDestData + "' failed: " + e.getMessage()); } } else if (action.equalsIgnoreCase("exists")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); if (file.exists()) { if (varname != null) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, "true"); } else { return new StringBuffer("true"); } } else { if (varname != null) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, "false"); } else { return new StringBuffer("false"); } } } else if (action.equalsIgnoreCase("mkdir")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); if (file.mkdirs()) { if (varname != null) { c.getVariableContainer().setVariable(varname + "-result", "created"); } else { return new StringBuffer("true"); } } else { c.setExceptionState(true, "Unable to create directory '" + filenameData + "'"); } } else if (action.equalsIgnoreCase("info")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); String fileLength = Long.toString(file.length()); String fileType = "file"; if (file.isAbsolute()) { fileType = "absolute"; } else if (file.isDirectory()) { fileType = "directory"; } else if (file.isFile()) { fileType = "file"; } else if (file.isHidden()) { fileType = "hidden"; } String fileMode = "read-only"; if (file.canRead() && !file.canWrite()) { fileMode = "read-only"; } else if (!file.canRead() && file.canWrite()) { fileMode = "write-only"; } else if (file.canRead() && file.canWrite()) { fileMode = "read/write"; } String fileTime = Long.toString(file.lastModified()); if (varname != null && !varname.equals("")) { c.getVariableContainer().setVariable(varname + ".length", fileLength); c.getVariableContainer().setVariable(varname + ".type", fileType); c.getVariableContainer().setVariable(varname + ".mode", fileMode); c.getVariableContainer().setVariable(varname + ".modtime", fileTime); } else { buffer = new StringBuffer(); buffer.append("<file name=\""); buffer.append(filenameData); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); return buffer; } } if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(); }
|
00
|
Code Sample 1:
public void render(ParagraphElement cnt, double x, double y, Graphics2D g, LayoutingContext layoutingContext, FlowContext flowContext) { InlineImageContent ic = (InlineImageContent) cnt; try { URLConnection urlConn = ic.getUrl().openConnection(); urlConn.setConnectTimeout(15000); ImageInputStream iis = ImageIO.createImageInputStream(urlConn.getInputStream()); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { System.out.println("loading image " + ic.getUrl()); ImageReader reader = readers.next(); reader.setInput(iis, true); if (flowContext.pdfContext == null) { RenderedImage img = reader.readAsRenderedImage(0, null); renderOnGraphics(img, x, y, ic, g, layoutingContext, flowContext); } else { BufferedImage img = reader.read(0); renderDirectPdf(img, x, y, ic, g, layoutingContext, flowContext); } reader.dispose(); } else System.err.println("cannot render image " + ic.getUrl() + " - no suitable reader!"); } catch (Exception exc) { System.err.println("cannot render image " + ic.getUrl() + " due to exception:"); System.err.println(exc); exc.printStackTrace(System.err); } }
Code Sample 2:
static ConversionMap create(String file) { ConversionMap out = new ConversionMap(); URL url = ConversionMap.class.getResource("data/" + file); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); while (line != null) { if (line.length() > 0) { String[] arr = line.split("\t"); try { double value = Double.parseDouble(arr[1]); out.put(translate(lowercase(arr[0].getBytes())), value); out.defaultValue += value; out.length = arr[0].length(); } catch (NumberFormatException e) { throw new RuntimeException("Something is wrong with in conversion file: " + e); } } line = in.readLine(); } in.close(); out.defaultValue /= Math.pow(4, out.length); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Their was an error while reading the conversion map: " + e); } return out; }
|
00
|
Code Sample 1:
public Resource get(String serviceUrl, String resourceId, String svcId, boolean appendProfile) throws Exception { Resource resource = new Resource(); String openurl = getURL(serviceUrl, resourceId, svcId, appendProfile); logger.debug("OpenURL Request: " + openurl); URL url; try { url = new URL(openurl); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); int code = huc.getResponseCode(); if (code == 200) { InputStream is = huc.getInputStream(); resource.setBytes(IOUtils.getByteArray(is)); resource.setContentType(huc.getContentType()); } else if (code == 404) { return null; } else { logger.error("An error of type " + code + " occurred for " + url.toString()); throw new Exception("Cannot get " + url.toString()); } } catch (MalformedURLException e) { throw new Exception("A MalformedURLException occurred for " + openurl); } catch (IOException e) { throw new Exception("An IOException occurred attempting to connect to " + openurl); } return resource; }
Code Sample 2:
public boolean compile(URL url, String name) { try { final InputStream stream = url.openStream(); final InputSource input = new InputSource(stream); input.setSystemId(url.toString()); return compile(input, name); } catch (IOException e) { _parser.reportError(Constants.FATAL, new ErrorMsg(e)); return false; } }
|
11
|
Code Sample 1:
private void sendFile(File file, HttpServletResponse response) throws IOException { response.setContentLength((int) file.length()); InputStream inputStream = null; try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, response.getOutputStream()); } finally { IOUtils.closeQuietly(inputStream); } }
Code Sample 2:
public void includeCss(Group group, Writer out, PageContext pageContext) throws IOException { ByteArrayOutputStream outtmp = new ByteArrayOutputStream(); if (AbstractGroupBuilder.getInstance().buildGroupJsIfNeeded(group, outtmp, pageContext.getServletContext())) { FileOutputStream fileStream = null; try { fileStream = new FileOutputStream(new File(RetentionHelper.buildFullRetentionFilePath(group, ".css"))); IOUtils.copy(new ByteArrayInputStream(outtmp.toByteArray()), fileStream); } finally { if (fileStream != null) fileStream.close(); } } }
|
11
|
Code Sample 1:
@Override public int write(FileStatus.FileTrackingStatus fileStatus, InputStream input, PostWriteAction postWriteAction) throws WriterException, InterruptedException { String key = logFileNameExtractor.getFileName(fileStatus); int wasWritten = 0; FileOutputStreamPool fileOutputStreamPool = fileOutputStreamPoolFactory.getPoolForKey(key); RollBackOutputStream outputStream = null; File file = null; try { file = getOutputFile(key); lastWrittenFile = file; outputStream = fileOutputStreamPool.open(key, compressionCodec, file, true); outputStream.mark(); wasWritten = IOUtils.copy(input, outputStream); if (postWriteAction != null) { postWriteAction.run(wasWritten); } } catch (Throwable t) { LOG.error(t.toString(), t); if (outputStream != null && wasWritten > 0) { LOG.error("Rolling back file " + file.getAbsolutePath()); try { outputStream.rollback(); } catch (IOException e) { throwException(e); } catch (InterruptedException e) { throw e; } } throwException(t); } finally { try { fileOutputStreamPool.releaseFile(key); } catch (IOException e) { throwException(e); } } return wasWritten; }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
public void test() throws Exception { StringDocument doc = new StringDocument("Test", "UTF-8"); doc.open(); try { assertEquals("UTF-8", doc.getCharacterEncoding()); assertEquals("Test", doc.getText()); InputStream input = doc.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { writer.close(); } assertEquals("Test", writer.toString()); } finally { doc.close(); } }
Code Sample 2:
public void write(URL exportUrl, OutputStream output) throws Exception { if (exportUrl == null || output == null) { throw new RuntimeException("null passed in for required parameters"); } MediaContent mc = new MediaContent(); mc.setUri(exportUrl.toString()); MediaSource ms = service.getMedia(mc); InputStream input = ms.getInputStream(); IOUtils.copy(input, output); }
|
00
|
Code Sample 1:
protected long getUrlSize(String location) { long returnValue = 0L; try { URL url = new URL(location); java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); returnValue = conn.getContentLength(); } catch (IOException ioe) { logger.error("Failed to find proper size for entity at " + location, ioe); } return returnValue; }
Code Sample 2:
private void importUrl(String str) throws Exception { URL url = new URL(str); InputStream xmlStream = url.openStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); MessageHolder messages = MessageHolder.getInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(xmlStream); Element rootElement = document.getDocumentElement(); EntrySetParser entrySetParser = new EntrySetParser(); EntrySetTag entrySet = entrySetParser.process(rootElement); UpdateProteinsI proteinFactory = new UpdateProteins(); BioSourceFactory bioSourceFactory = new BioSourceFactory(); ControlledVocabularyRepository.check(); EntrySetChecker.check(entrySet, proteinFactory, bioSourceFactory); if (messages.checkerMessageExists()) { MessageHolder.getInstance().printCheckerReport(System.err); } else { EntrySetPersister.persist(entrySet); if (messages.checkerMessageExists()) { MessageHolder.getInstance().printPersisterReport(System.err); } else { System.out.println("The data have been successfully saved in your Intact node."); } } }
|
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:
private String MD5Sum(String input) { String hashtext = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(input.getBytes()); byte[] digest = md.digest(); BigInteger bigInt = new BigInteger(1, digest); hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hashtext; }
|
00
|
Code Sample 1:
public Location getLocation(String ip) throws Exception { URL url = new URL("http://api.hostip.info/?ip=" + ip); SAXReader reader = new SAXReader(); Document doc = reader.read(url.openStream()); System.out.println(doc.asXML()); Location location = new Location(doc); return location; }
Code Sample 2:
@Override public InputStream getStream(String uri) throws IOException { debug.print("uri=" + uri); boolean isStreamFile = false; for (int i = 0; i < GLOBAL.extList.length; i++) { if (uri.toLowerCase().endsWith(GLOBAL.extList[i].toLowerCase())) { isStreamFile = true; } } if (isStreamFile) { GLOBAL.streamFile = DIR + File.separator + uri; File file = new File(GLOBAL.streamFile); URL url = file.toURI().toURL(); System.out.println("url=" + url); GLOBAL.cstream = new CountInputStream(url.openStream()); if (GLOBAL.Resume && GLOBAL.positions.containsKey(GLOBAL.streamFile)) { GLOBAL.Resume = false; if (uri.toLowerCase().endsWith(".mpg") || uri.toLowerCase().endsWith(".vob") || uri.toLowerCase().endsWith(".mp2") || uri.toLowerCase().endsWith(".mpeg") || uri.toLowerCase().endsWith(".mpeg2")) { System.out.println("--Skipping to last bookmark=" + GLOBAL.positions.get(GLOBAL.streamFile)); GLOBAL.cstream.skip(GLOBAL.positions.get(GLOBAL.streamFile)); } } return GLOBAL.cstream; } return super.getStream(uri); }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public boolean restore() { try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "/Android/bluebox.bak"; String backupDBPath = "/data/android.bluebox/databases/bluebox.db"; File currentDB = new File(sd, currentDBPath); File backupDB = new File(data, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); return true; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
|
00
|
Code Sample 1:
public static String getMd5Password(final String password) { String response = null; try { final MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes()); final byte[] md5Byte = algorithm.digest(); final StringBuffer buffer = new StringBuffer(); for (final byte b : md5Byte) { if ((b <= 15) && (b >= 0)) { buffer.append("0"); } buffer.append(Integer.toHexString(0xFF & b)); } response = buffer.toString(); } catch (final NoSuchAlgorithmException e) { ProjektUtil.LOG.error("No digester MD5 found in classpath!", e); } return response; }
Code Sample 2:
@Test public void testCopy_inputStreamToWriter() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); }
|
00
|
Code Sample 1:
public void getDownloadInfo(String _url) throws Exception { cl = new FTPClient(); Authentication auth = new FTPAuthentication(); cl.connect(getHostName()); while (!cl.login(auth.getUser(), auth.getPassword())) { log.debug("getDownloadInfo() - login error state: " + Arrays.asList(cl.getReplyStrings())); ap.setSite(getSite()); auth = ap.promptAuthentication(); if (auth == null) throw new Exception("User Cancelled Auth Operation"); } AuthManager.putAuth(getSite(), auth); cl.enterLocalPassiveMode(); FTPFile file = cl.listFiles(new URL(_url).getFile())[0]; setURL(_url); setLastModified(file.getTimestamp().getTimeInMillis()); setSize(file.getSize()); setResumable(cl.rest("0") == 350); setRangeEnd(getSize() - 1); }
Code Sample 2:
public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) return; FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
|
11
|
Code Sample 1:
public boolean copyTo(String targetFilePath) { try { FileInputStream srcFile = new FileInputStream(filePath); FileOutputStream target = new FileOutputStream(targetFilePath); byte[] buff = new byte[1024]; int readed = -1; while ((readed = srcFile.read(buff)) > 0) target.write(buff, 0, readed); srcFile.close(); target.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
Code Sample 2:
public static void copy(File file1, File file2) throws IOException { FileReader in = new FileReader(file1); FileWriter out = new FileWriter(file2); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
|
00
|
Code Sample 1:
public void upload() throws UnknownHostException, SocketException, FTPConnectionClosedException, LoginFailedException, DirectoryChangeFailedException, CopyStreamException, RefusedConnectionException, IOException { final int NUM_XML_FILES = 2; final String META_XML_SUFFIX = "_meta.xml"; final String FILES_XML_SUFFIX = "_files.xml"; final String username = getUsername(); final String password = getPassword(); if (getFtpServer() == null) { throw new IllegalStateException("ftp server not set"); } if (getFtpPath() == null) { throw new IllegalStateException("ftp path not set"); } if (username == null) { throw new IllegalStateException("username not set"); } if (password == null) { throw new IllegalStateException("password not set"); } final String metaXmlString = serializeDocument(getMetaDocument()); final String filesXmlString = serializeDocument(getFilesDocument()); final byte[] metaXmlBytes = metaXmlString.getBytes(); final byte[] filesXmlBytes = filesXmlString.getBytes(); final int metaXmlLength = metaXmlBytes.length; final int filesXmlLength = filesXmlBytes.length; final Collection files = getFiles(); final int totalFiles = NUM_XML_FILES + files.size(); final String[] fileNames = new String[totalFiles]; final long[] fileSizes = new long[totalFiles]; final String metaXmlName = getIdentifier() + META_XML_SUFFIX; fileNames[0] = metaXmlName; fileSizes[0] = metaXmlLength; final String filesXmlName = getIdentifier() + FILES_XML_SUFFIX; fileNames[1] = filesXmlName; fileSizes[1] = filesXmlLength; int j = 2; for (Iterator i = files.iterator(); i.hasNext(); ) { final ArchiveFile f = (ArchiveFile) i.next(); fileNames[j] = f.getRemoteFileName(); fileSizes[j] = f.getFileSize(); j++; } for (int i = 0; i < fileSizes.length; i++) { _fileNames2Progress.put(fileNames[i], new UploadFileProgress(fileSizes[i])); _totalUploadSize += fileSizes[i]; } FTPClient ftp = new FTPClient(); try { if (isCancelled()) { return; } ftp.enterLocalPassiveMode(); if (isCancelled()) { return; } ftp.connect(getFtpServer()); final int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new RefusedConnectionException(getFtpServer() + "refused FTP connection"); } if (isCancelled()) { return; } if (!ftp.login(username, password)) { throw new LoginFailedException(); } try { if (!ftp.changeWorkingDirectory(getFtpPath())) { if (!isFtpDirPreMade() && !ftp.makeDirectory(getFtpPath())) { throw new DirectoryChangeFailedException(); } if (isCancelled()) { return; } if (!ftp.changeWorkingDirectory(getFtpPath())) { throw new DirectoryChangeFailedException(); } } if (isCancelled()) { return; } connected(); uploadFile(metaXmlName, new ByteArrayInputStream(metaXmlBytes), ftp); uploadFile(filesXmlName, new ByteArrayInputStream(filesXmlBytes), ftp); if (isCancelled()) { return; } ftp.setFileType(FTP.BINARY_FILE_TYPE); for (final Iterator i = files.iterator(); i.hasNext(); ) { final ArchiveFile f = (ArchiveFile) i.next(); uploadFile(f.getRemoteFileName(), new FileInputStream(f.getIOFile()), ftp); } } catch (InterruptedIOException ioe) { return; } finally { ftp.logout(); } } finally { try { ftp.disconnect(); } catch (IOException e) { } } if (isCancelled()) { return; } checkinStarted(); if (isCancelled()) { return; } checkin(); if (isCancelled()) { return; } checkinCompleted(); }
Code Sample 2:
public GeocodeResponse getGKCoordinateFromAddress(SearchAddressRequest searchAddressRequest) { GeocodeResponse result = null; String adress = null; if (searchAddressRequest.getAdressTextField() != null) adress = searchAddressRequest.getAdressTextField().getText(); if (adress == null || adress.length() == 0) adress = " "; String postRequest = ""; postRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n" + "<xls:XLS xmlns:xls=\"http://www.opengis.net/xls\" xmlns:sch=\"http://www.ascc.net/xml/schematron\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/xls \n" + "http://gdi3d.giub.uni-bonn.de:8080/openls-lus/schemas/LocationUtilityService.xsd\" version=\"1.1\"> \n" + " <xls:RequestHeader srsName=\"EPSG:" + Navigator.getEpsg_code() + "\"/> \n" + " <xls:Request methodName=\"GeocodeRequest\" requestID=\"123456789\" version=\"1.1\"> \n" + " <xls:GeocodeRequest> \n" + " <xls:Address countryCode=\"DE\"> \n" + " <xls:freeFormAddress>" + adress + "</xls:freeFormAddress> \n" + " </xls:Address> \n" + " </xls:GeocodeRequest> \n" + " </xls:Request> \n" + "</xls:XLS> \n"; if (Navigator.isVerbose()) { System.out.println("OpenLSGeocoder postRequest " + postRequest); } String errorMessage = ""; try { System.out.println("contacting " + serviceEndPoint); URL u = new URL(serviceEndPoint); HttpURLConnection urlc = (HttpURLConnection) u.openConnection(); urlc.setReadTimeout(Navigator.TIME_OUT); urlc.setAllowUserInteraction(false); urlc.setRequestMethod("POST"); urlc.setRequestProperty("Content-Type", "application/xml"); urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); PrintWriter xmlOut = null; xmlOut = new java.io.PrintWriter(urlc.getOutputStream()); xmlOut.write(postRequest); xmlOut.flush(); xmlOut.close(); InputStream is = urlc.getInputStream(); result = new GeocodeResponse(); XLSDocument xlsResponse = XLSDocument.Factory.parse(is); XLSType xlsTypeResponse = xlsResponse.getXLS(); Node node0 = xlsTypeResponse.getDomNode(); NodeList nodes1 = node0.getChildNodes(); for (int i = 0; i < nodes1.getLength(); i++) { Node node1 = nodes1.item(i); NodeList nodes2 = node1.getChildNodes(); for (int j = 0; j < nodes2.getLength(); j++) { Node node2 = nodes2.item(j); NodeList nodes3 = node2.getChildNodes(); for (int k = 0; k < nodes3.getLength(); k++) { Node node3 = nodes3.item(k); String nodeName = node3.getNodeName(); if (nodeName.equalsIgnoreCase("xls:GeocodeResponseList")) { net.opengis.xls.GeocodeResponseListDocument gcrld = net.opengis.xls.GeocodeResponseListDocument.Factory.parse(node3); net.opengis.xls.GeocodeResponseListType geocodeResponseList = gcrld.getGeocodeResponseList(); result.setGeocodeResponseList(geocodeResponseList); } } } } is.close(); } catch (java.net.ConnectException ce) { JOptionPane.showMessageDialog(null, "no connection to geocoder", "Connection Error", JOptionPane.ERROR_MESSAGE); } catch (SocketTimeoutException ste) { ste.printStackTrace(); errorMessage += "<p>Time Out Exception, Server is not responding</p>"; } catch (IOException ioe) { ioe.printStackTrace(); errorMessage += "<p>IO Exception</p>"; } catch (XmlException xmle) { xmle.printStackTrace(); errorMessage += "<p>Error occured during parsing the XML response</p>"; } if (!errorMessage.equals("")) { System.out.println("\nerrorMessage: " + errorMessage + "\n\n"); JLabel label1 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: bold;}--></style></head><body><span class=\"Stil2\">Geocoder Error</span></body></html>"); JLabel label2 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: normal;}--></style></head><body><span class=\"Stil2\">" + "<br>" + errorMessage + "<br>" + "<p>please check Java console. If problem persits, please report to system manager</p>" + "</span></body></html>"); Object[] objects = { label1, label2 }; JOptionPane.showMessageDialog(null, objects, "Error Message", JOptionPane.ERROR_MESSAGE); return null; } return result; }
|
11
|
Code Sample 1:
@Test public void testCopy_inputStreamToWriter_Encoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer, "UTF8"); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); byte[] bytes = baout.toByteArray(); bytes = new String(bytes, "UTF8").getBytes("US-ASCII"); assertTrue("Content differs", Arrays.equals(inData, bytes)); }
Code Sample 2:
public void includeCss(Group group, Writer out, PageContext pageContext) throws IOException { ByteArrayOutputStream outtmp = new ByteArrayOutputStream(); if (AbstractGroupBuilder.getInstance().buildGroupJsIfNeeded(group, outtmp, pageContext.getServletContext())) { FileOutputStream fileStream = null; try { fileStream = new FileOutputStream(new File(RetentionHelper.buildFullRetentionFilePath(group, ".css"))); IOUtils.copy(new ByteArrayInputStream(outtmp.toByteArray()), fileStream); } finally { if (fileStream != null) fileStream.close(); } } }
|
11
|
Code Sample 1:
public static void kopirujSoubor(File vstup, File vystup) throws IOException { FileChannel sourceChannel = new FileInputStream(vstup).getChannel(); FileChannel destinationChannel = new FileOutputStream(vystup).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
private static File copyFileTo(File file, File directory) throws IOException { File newFile = new File(directory, file.getName()); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(file); fos = new FileOutputStream(newFile); byte buff[] = new byte[1024]; int val; while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val); } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } return newFile; }
|
00
|
Code Sample 1:
protected BufferedImage handleICCException() { if (params.uri.startsWith("http://vacani.icc.cat") || params.uri.startsWith("http://louisdl.louislibraries.org")) try { params.uri = params.uri.replace("cdm4/item_viewer.php", "cgi-bin/getimage.exe") + "&DMSCALE=3"; params.uri = params.uri.replace("/u?", "cgi-bin/getimage.exe?CISOROOT=").replace(",", "&CISOPTR=") + "&DMSCALE=3"; URL url = new URL(params.uri); URLConnection connection = url.openConnection(); return processNewUri(connection); } catch (Exception e) { } return null; }
Code Sample 2:
public static String getMd5(String str) { try { final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); final byte b[] = md.digest(); int i; final StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) { i += 256; } if (i < 16) { buf.append("0"); } buf.append(Integer.toHexString(i)); } return buf.toString(); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
|
11
|
Code Sample 1:
private void initUserExtensions(SeleniumConfiguration seleniumConfiguration) throws IOException { StringBuilder contents = new StringBuilder(); StringOutputStream s = new StringOutputStream(); IOUtils.copy(SeleniumConfiguration.class.getResourceAsStream("default-user-extensions.js"), s); contents.append(s.toString()); File providedUserExtensions = seleniumConfiguration.getFile(ConfigurationPropertyKeys.SELENIUM_USER_EXTENSIONS, seleniumConfiguration.getDirectoryConfiguration().getInput(), false); if (providedUserExtensions != null) { contents.append(FileUtils.readFileToString(providedUserExtensions, null)); } seleniumUserExtensions = new File(seleniumConfiguration.getDirectoryConfiguration().getInput(), "user-extensions.js"); FileUtils.forceMkdir(seleniumUserExtensions.getParentFile()); FileUtils.writeStringToFile(seleniumUserExtensions, contents.toString(), null); }
Code Sample 2:
public static DownloadedContent downloadContent(final InputStream is) throws IOException { if (is == null) { return new DownloadedContent.InMemory(new byte[] {}); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int nbRead; try { while ((nbRead = is.read(buffer)) != -1) { bos.write(buffer, 0, nbRead); if (bos.size() > MAX_IN_MEMORY) { final File file = File.createTempFile("htmlunit", ".tmp"); file.deleteOnExit(); final FileOutputStream fos = new FileOutputStream(file); bos.writeTo(fos); IOUtils.copyLarge(is, fos); fos.close(); return new DownloadedContent.OnFile(file); } } } finally { IOUtils.closeQuietly(is); } return new DownloadedContent.InMemory(bos.toByteArray()); }
|
11
|
Code Sample 1:
public boolean copy(String file, String path) { try { File file_in = new File(file); String tmp1, tmp2; tmp1 = file; tmp2 = path; while (tmp2.contains("\\")) { tmp2 = tmp2.substring(tmp2.indexOf("\\") + 1); tmp1 = tmp1.substring(tmp1.indexOf("\\") + 1); } tmp1 = file.substring(0, file.length() - tmp1.length()) + tmp2 + tmp1.substring(tmp1.indexOf("\\")); File file_out = new File(tmp1); File parent = file_out.getParentFile(); parent.mkdirs(); FileInputStream in1 = new FileInputStream(file_in); FileOutputStream out1 = new FileOutputStream(file_out); byte[] bytes = new byte[1024]; int c; while ((c = in1.read(bytes)) != -1) out1.write(bytes, 0, c); in1.close(); out1.close(); return true; } catch (Exception e) { e.printStackTrace(); System.out.println("Error!"); return false; } }
Code Sample 2:
@Test public void shouldDownloadFileUsingPublicLink() throws Exception { String bucketName = "test-" + UUID.randomUUID(); Service service = new WebClientService(credentials); service.createBucket(bucketName); File file = folder.newFile("foo.txt"); FileUtils.writeStringToFile(file, UUID.randomUUID().toString()); service.createObject(bucketName, file.getName(), file, new NullProgressListener()); String publicUrl = service.getPublicUrl(bucketName, file.getName(), new DateTime().plusDays(5)); File saved = folder.newFile("saved.txt"); InputStream input = new URL(publicUrl).openConnection().getInputStream(); FileOutputStream output = new FileOutputStream(saved); IOUtils.copy(input, output); output.close(); assertThat("Corrupted download", Files.computeMD5(saved), equalTo(Files.computeMD5(file))); service.deleteObject(bucketName, file.getName()); service.deleteBucket(bucketName); }
|
11
|
Code Sample 1:
@Override public String toString() { if (byteArrayOutputStream == null) return "<Unparsed binary data: Content-Type=" + getHeader("Content-Type") + " >"; String charsetName = getCharsetName(); if (charsetName == null) charsetName = "ISO-8859-1"; try { if (unzip) { GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); ByteArrayOutputStream unzippedResult = new ByteArrayOutputStream(); IOUtils.copy(gzipInputStream, unzippedResult); return unzippedResult.toString(charsetName); } else { return byteArrayOutputStream.toString(charsetName); } } catch (UnsupportedEncodingException e) { throw new OutputException(e); } catch (IOException e) { throw new OutputException(e); } }
Code Sample 2:
private static void exportConfigResource(ClassLoader classLoader, String resourceName, String targetFileName) throws Exception { InputStream is = classLoader.getResourceAsStream(resourceName); FileOutputStream fos = new FileOutputStream(targetFileName, false); IOUtils.copy(is, fos); fos.close(); is.close(); }
|
11
|
Code Sample 1:
public synchronized String getSerialNumber() { if (serialNum != null) return serialNum; final StringBuffer buf = new StringBuffer(); Iterator it = classpath.iterator(); while (it.hasNext()) { ClassPathEntry entry = (ClassPathEntry) it.next(); buf.append(entry.getResourceURL().toString()); buf.append(":"); } serialNum = (String) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { try { MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(buf.toString().getBytes()); byte[] data = digest.digest(); serialNum = new BASE64Encoder().encode(data); return serialNum; } catch (NoSuchAlgorithmException exp) { BootSecurityManager.securityLogger.log(Level.SEVERE, exp.getMessage(), exp); return buf.toString(); } } }); return serialNum; }
Code Sample 2:
public static synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
|
11
|
Code Sample 1:
public void test() throws Exception { StringDocument doc = new StringDocument("Test", "UTF-8"); doc.open(); try { assertEquals("UTF-8", doc.getCharacterEncoding()); assertEquals("Test", doc.getText()); InputStream input = doc.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { writer.close(); } assertEquals("Test", writer.toString()); } finally { doc.close(); } }
Code Sample 2:
public void generate(String rootDir, RootModel root) throws Exception { IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("stylesheet.css"), new FileOutputStream(new File(rootDir, "stylesheet.css"))); Velocity.init(); VelocityContext context = new VelocityContext(); context.put("model", root); context.put("util", new VelocityUtils()); context.put("msg", messages); processTemplate("index.html", new File(rootDir, "index.html"), context); processTemplate("list.html", new File(rootDir, "list.html"), context); processTemplate("summary.html", new File(rootDir, "summary.html"), context); File imageDir = new File(rootDir, "images"); imageDir.mkdir(); IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("primarykey.gif"), new FileOutputStream(new File(imageDir, "primarykey.gif"))); File tableDir = new File(rootDir, "tables"); tableDir.mkdir(); for (TableModel table : root.getTables()) { context.put("table", table); processTemplate("table.html", new File(tableDir, table.getTableName() + ".html"), context); } }
|
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 byte[] getFile(final String file) throws IOException { if (this.files.contains(file)) { ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(this.bytes)); ZipEntry entry = input.getNextEntry(); while (entry != null) { entry = input.getNextEntry(); if ((entry.getName().equals(file)) && (!entry.isDirectory())) { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(input, output); output.close(); input.close(); return output.toByteArray(); } } input.close(); } return null; }
|
11
|
Code Sample 1:
public String getScript(String script, String params) { params = params.replaceFirst("&", "?"); StringBuffer document = new StringBuffer(); try { URL url = new URL(script + params); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { document.append(line + "\n"); } reader.close(); } catch (Exception e) { return e.toString(); } return document.toString(); }
Code Sample 2:
private static void updateLeapSeconds() throws IOException, MalformedURLException, NumberFormatException { URL url = new URL("http://cdf.gsfc.nasa.gov/html/CDFLeapSeconds.txt"); InputStream in; try { in = url.openStream(); } catch (IOException ex) { url = LeapSecondsConverter.class.getResource("CDFLeapSeconds.txt"); in = url.openStream(); System.err.println("Using local copy of leap seconds!!!"); } BufferedReader r = new BufferedReader(new InputStreamReader(in)); String s = ""; leapSeconds = new ArrayList(50); withoutLeapSeconds = new ArrayList(50); String lastLine = s; while (s != null) { s = r.readLine(); if (s == null) { System.err.println("Last leap second read from " + url + " " + lastLine); continue; } if (s.startsWith(";")) { continue; } String[] ss = s.trim().split("\\s+", -2); if (ss[0].compareTo("1972") < 0) { continue; } int iyear = Integer.parseInt(ss[0]); int imonth = Integer.parseInt(ss[1]); int iday = Integer.parseInt(ss[2]); int ileap = (int) (Double.parseDouble(ss[3])); double us2000 = TimeUtil.createTimeDatum(iyear, imonth, iday, 0, 0, 0, 0).doubleValue(Units.us2000); leapSeconds.add(Long.valueOf(((long) us2000) * 1000L - 43200000000000L + (long) (ileap - 32) * 1000000000)); withoutLeapSeconds.add(us2000); } leapSeconds.add(Long.MAX_VALUE); withoutLeapSeconds.add(Double.MAX_VALUE); lastUpdateMillis = System.currentTimeMillis(); }
|
00
|
Code Sample 1:
@Override public InputStream getResourceAsStream(String path) { try { URL url = this.getResource(path); if (url == null) return null; return url.openStream(); } catch (Exception e) { log(e.getMessage(), e); return null; } }
Code Sample 2:
public void run(IProgressMonitor runnerMonitor) throws CoreException { try { Map<String, File> projectFiles = new HashMap<String, File>(); IPath basePath = new Path("/"); for (File nextLocation : filesToZip) { projectFiles.putAll(getFilesToZip(nextLocation, basePath, fileFilter)); } if (projectFiles.isEmpty()) { PlatformActivator.logDebug("Zip file (" + zipFileName + ") not created because there were no files to zip"); return; } IPath resultsPath = PlatformActivator.getDefault().getResultsPath(); File copyRoot = resultsPath.toFile(); copyRoot.mkdirs(); IPath zipFilePath = resultsPath.append(new Path(finalZip)); String zipFileName = zipFilePath.toPortableString(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); try { out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String filePath : projectFiles.keySet()) { File nextFile = projectFiles.get(filePath); FileInputStream fin = new FileInputStream(nextFile); try { out.putNextEntry(new ZipEntry(filePath)); try { byte[] bin = new byte[4096]; int bread = fin.read(bin, 0, 4096); while (bread != -1) { out.write(bin, 0, bread); bread = fin.read(bin, 0, 4096); } } finally { out.closeEntry(); } } finally { fin.close(); } } } finally { out.close(); } } catch (FileNotFoundException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } catch (IOException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } }
|
00
|
Code Sample 1:
public String obfuscateString(String string) { String obfuscatedString = null; try { MessageDigest md = MessageDigest.getInstance(ENCRYPTION_ALGORITHM); md.update(string.getBytes()); byte[] digest = md.digest(); obfuscatedString = new String(Base64.encode(digest)).replace(DELIM_PATH, '='); } catch (NoSuchAlgorithmException e) { StatusHandler.log("SHA not available", null); obfuscatedString = LABEL_FAILED_TO_OBFUSCATE; } return obfuscatedString; }
Code Sample 2:
public void run() { btnReintentar.setEnabled(false); try { lblEstado.setText("Conectando con servidor..."); escribir("\nConectando con servidor..."); URL url = new URL("http://apeiron.sourceforge.net/version.php"); lblEstado.setText("Obteniendo informaci�n de versi�n..."); escribir("Ok\n"); escribir("Obteniendo informaci�n sobre �ltima versi�n..."); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String linea = br.readLine(); escribir("Ok\n"); if (linea != null) { escribir("Versi�n mas reciente: " + linea + "\n"); if (Principal.version < Double.parseDouble(linea)) { lblEstado.setText("Hay una nueva versi�n: Apeiron " + linea); escribir("Puede obtener la actualizaci�n de: http://apeiron.sourceforge.net\n"); btnActualizar.setEnabled(true); setVisible(true); } else { lblEstado.setText("Usted tiene la �ltima versi�n"); } } br.close(); } catch (MalformedURLException e) { escribir("Fall�\n" + e + "\n"); e.printStackTrace(); } catch (IOException e) { escribir("Fall�\n" + e + "\n"); e.printStackTrace(); } btnReintentar.setEnabled(true); }
|
11
|
Code Sample 1:
public static void copy(File in, File out) throws IOException { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
Code Sample 2:
public static final void copyFile(File source, File target) { try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (java.io.IOException e) { } }
|
11
|
Code Sample 1:
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()); }
Code Sample 2:
public static void copyFile(File sourceFile, File destFile) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(sourceFile); os = new FileOutputStream(destFile); IOUtils.copy(is, os); } finally { try { if (os != null) os.close(); } catch (Exception e) { } try { if (is != null) is.close(); } catch (Exception e) { } } }
|
11
|
Code Sample 1:
public static String crypt(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("String to encript cannot be null or zero length"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { throw new ForumException("" + e); } return hexString.toString(); }
Code Sample 2:
@SuppressWarnings("unused") private static int chkPasswd(final String sInputPwd, final String sSshaPwd) { assert sInputPwd != null; assert sSshaPwd != null; int r = ERR_LOGIN_ACCOUNT; try { BASE64Decoder decoder = new BASE64Decoder(); byte[] ba = decoder.decodeBuffer(sSshaPwd); assert ba.length >= FIXED_HASH_SIZE; byte[] hash = new byte[FIXED_HASH_SIZE]; byte[] salt = new byte[FIXED_SALT_SIZE]; System.arraycopy(ba, 0, hash, 0, FIXED_HASH_SIZE); System.arraycopy(ba, FIXED_HASH_SIZE, salt, 0, FIXED_SALT_SIZE); MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(sInputPwd.getBytes()); md.update(salt); byte[] baPwdHash = md.digest(); if (MessageDigest.isEqual(hash, baPwdHash)) { r = ERR_LOGIN_OK; } } catch (Exception exc) { exc.printStackTrace(); } return r; }
|
00
|
Code Sample 1:
private void loadNumberFormats() { String fileToLocate = "/" + FILENAME_NUMBER_FMT; URL url = getClass().getClassLoader().getResource(fileToLocate); if (url == null) { return; } List<String> lines; try { lines = IOUtils.readLines(url.openStream()); } catch (IOException e) { throw new ConfigurationException("Problem loading file " + fileToLocate, e); } for (String line : lines) { if (line.startsWith("#") || StringUtils.isBlank(line)) { continue; } String[] parts = StringUtils.split(line, "="); addFormat(parts[0], new DecimalFormat(parts[1])); } }
Code Sample 2:
private static void ftpTest() { FTPClient f = new FTPClient(); try { f.connect("oscomak.net"); System.out.print(f.getReplyString()); f.setFileType(FTPClient.BINARY_FILE_TYPE); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String password = JOptionPane.showInputDialog("Enter password"); if (password == null || password.equals("")) { System.out.println("No password"); return; } try { f.login("oscomak_pointrel", password); System.out.print(f.getReplyString()); } catch (IOException e) { e.printStackTrace(); } try { String workingDirectory = f.printWorkingDirectory(); System.out.println("Working directory: " + workingDirectory); System.out.print(f.getReplyString()); } catch (IOException e1) { e1.printStackTrace(); } try { f.enterLocalPassiveMode(); System.out.print(f.getReplyString()); System.out.println("Trying to list files"); String[] fileNames = f.listNames(); System.out.print(f.getReplyString()); System.out.println("Got file list fileNames: " + fileNames.length); for (String fileName : fileNames) { System.out.println("File: " + fileName); } System.out.println(); System.out.println("done reading stream"); System.out.println("trying alterative way to read stream"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); f.retrieveFile(fileNames[0], outputStream); System.out.println("size: " + outputStream.size()); System.out.println(outputStream.toString()); System.out.println("done with alternative"); System.out.println("Trying to store file back"); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); boolean storeResult = f.storeFile("test.txt", inputStream); System.out.println("Done storing " + storeResult); f.disconnect(); System.out.print(f.getReplyString()); System.out.println("disconnected"); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
private static void copyObjects(File[] source, String target) { for (int i = 0; i < source.length; i++) { try { File inputFile = source[i]; File outputFile = new File(target + source[i].getName()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { Logger.error(ex.getClass() + " " + ex.getMessage()); for (int j = 0; j < ex.getStackTrace().length; j++) Logger.error(" " + ex.getStackTrace()[j].toString()); ex.printStackTrace(); } } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
public void updateFailedStatus(THLEventStatus failedEvent, ArrayList<THLEventStatus> events) throws THLException { Timestamp now = new Timestamp(System.currentTimeMillis()); Statement stmt = null; PreparedStatement pstmt = null; try { conn.setAutoCommit(false); if (events != null && events.size() > 0) { String seqnoList = buildCommaSeparatedList(events); stmt = conn.createStatement(); stmt.executeUpdate("UPDATE history SET status = " + THLEvent.FAILED + ", comments = 'Event was rollbacked due to failure while processing event#" + failedEvent.getSeqno() + "'" + ", processed_tstamp = " + conn.getNowFunction() + " WHERE seqno in " + seqnoList); } pstmt = conn.prepareStatement("UPDATE history SET status = ?" + ", comments = ?" + ", processed_tstamp = ?" + " WHERE seqno = ?"); pstmt.setShort(1, THLEvent.FAILED); pstmt.setString(2, truncate(failedEvent.getException() != null ? failedEvent.getException().getMessage() : "Unknown failure", commentLength)); pstmt.setTimestamp(3, now); pstmt.setLong(4, failedEvent.getSeqno()); pstmt.executeUpdate(); conn.commit(); } catch (SQLException e) { THLException exception = new THLException("Failed to update events status"); exception.initCause(e); try { conn.rollback(); } catch (SQLException e1) { THLException exception2 = new THLException("Failed to rollback after failure while updating events status"); e1.initCause(exception); exception2.initCause(e1); exception = exception2; } throw exception; } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException ignore) { } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException ignore) { } } try { conn.setAutoCommit(true); } catch (SQLException ignore) { } } }
Code Sample 2:
@Override public User updateUser(User bean) throws SitoolsException { checkUser(); Connection cx = null; try { cx = ds.getConnection(); cx.setAutoCommit(false); PreparedStatement st; int i = 1; if (bean.getSecret() != null && !"".equals(bean.getSecret())) { st = cx.prepareStatement(jdbcStoreResource.UPDATE_USER_WITH_PW); st.setString(i++, bean.getFirstName()); st.setString(i++, bean.getLastName()); st.setString(i++, bean.getSecret()); st.setString(i++, bean.getEmail()); st.setString(i++, bean.getIdentifier()); } else { st = cx.prepareStatement(jdbcStoreResource.UPDATE_USER_WITHOUT_PW); st.setString(i++, bean.getFirstName()); st.setString(i++, bean.getLastName()); st.setString(i++, bean.getEmail()); st.setString(i++, bean.getIdentifier()); } st.executeUpdate(); st.close(); if (bean.getProperties() != null) { deleteProperties(bean.getIdentifier(), cx); createProperties(bean, cx); } if (!cx.getAutoCommit()) { cx.commit(); } } catch (SQLException e) { try { cx.rollback(); } catch (SQLException e1) { throw new SitoolsException("UPDATE_USER ROLLBACK" + e1.getMessage(), e1); } throw new SitoolsException("UPDATE_USER " + e.getMessage(), e); } finally { closeConnection(cx); } return getUserById(bean.getIdentifier()); }
|
11
|
Code Sample 1:
public void transport(File file) throws TransportException { if (file.exists()) { if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { transport(file); } } else if (file.isFile()) { try { FileChannel inChannel = new FileInputStream(file).getChannel(); FileChannel outChannel = new FileOutputStream(getOption("destination")).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { log.error("File transfer failed", e); } } } }
Code Sample 2:
private String choosePivotVertex() throws ProcessorExecutionException { String result = null; Graph src; Graph dest; Path tmpDir; System.out.println("##########>" + _dirMgr.getSeqNum() + " Choose the pivot vertex"); src = new Graph(Graph.defaultGraph()); src.setPath(_curr_path); dest = new Graph(Graph.defaultGraph()); try { tmpDir = _dirMgr.getTempDir(); } catch (IOException e) { throw new ProcessorExecutionException(e); } dest.setPath(tmpDir); GraphAlgorithm choose_pivot = new PivotChoose(); choose_pivot.setConf(context); choose_pivot.setSource(src); choose_pivot.setDestination(dest); choose_pivot.setMapperNum(getMapperNum()); choose_pivot.setReducerNum(getReducerNum()); choose_pivot.execute(); try { Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); result = the_line.substring(PivotChoose.KEY_PIVOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("##########> Chosen pivot id = " + result); } catch (IOException e) { throw new ProcessorExecutionException(e); } return result; }
|
00
|
Code Sample 1:
public File addFile(File file, String suffix) throws IOException { if (file.exists() && file.isFile()) { File nf = File.createTempFile(prefix, "." + suffix, workdir); nf.delete(); if (!file.renameTo(nf)) { IOUtils.copy(file, nf); } synchronized (fileList) { fileList.add(nf); } if (log.isDebugEnabled()) { log.debug("Add file [" + file.getPath() + "] -> [" + nf.getPath() + "]"); } return nf; } return file; }
Code Sample 2:
public boolean smsResponse(String customerPhoneNumber) throws ClientProtocolException, IOException { boolean message = true; String textMessage = "La%20sua%20prenotazione%20e%60%20andata%20a%20buon%20fine"; DefaultHttpClient httpclient = new DefaultHttpClient(); String uri = "http://smswizard.globalitalia.it/smsgateway/send.asp"; String other = "http://smswizard.globalitalia.it/smsgateway/send.asp"; String url = uri + "?" + "Account=sardricerche" + "&Password=v8LomdZT" + "&PhoneNumbers=" + "%2b393285683484" + "&SMSData=" + textMessage + "&Recipients=1" + "&Sender=Web Hotel" + "&ID=11762"; String urlProva = other + "?" + "Account=sardricerche" + "&Password=v8LomdZT" + "&PhoneNumbers=" + customerPhoneNumber + "&SMSData=" + textMessage + "&Recipients=1" + "&Sender=+393337589951" + "&ID=11762"; HttpPost httpPost = new HttpPost(urlProva); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); return message; }
|
00
|
Code Sample 1:
private static String getData(String myurl) throws Exception { URL url = new URL(myurl); uc = (HttpURLConnection) url.openConnection(); if (login) { uc.setRequestProperty("Cookie", logincookie + ";" + xfsscookie); } br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String temp = "", k = ""; while ((temp = br.readLine()) != null) { k += temp; } br.close(); return k; }
Code Sample 2:
public void onMessage(Message message) { LOG.debug("onMessage"); DownloadMessage downloadMessage; try { downloadMessage = new DownloadMessage(message); } catch (JMSException e) { LOG.error("JMS error: " + e.getMessage(), e); return; } String caName = downloadMessage.getCaName(); boolean update = downloadMessage.isUpdate(); LOG.debug("issuer: " + caName); CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO.findCertificateAuthority(caName); if (null == certificateAuthority) { LOG.error("unknown certificate authority: " + caName); return; } if (!update && Status.PROCESSING != certificateAuthority.getStatus()) { LOG.debug("CA status not marked for processing"); return; } String crlUrl = certificateAuthority.getCrlUrl(); if (null == crlUrl) { LOG.warn("No CRL url for CA " + certificateAuthority.getName()); certificateAuthority.setStatus(Status.NONE); return; } NetworkConfig networkConfig = this.configurationDAO.getNetworkConfig(); HttpClient httpClient = new HttpClient(); if (null != networkConfig) { httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort()); } HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setParameter("http.socket.timeout", new Integer(1000 * 20)); LOG.debug("downloading CRL from: " + crlUrl); GetMethod getMethod = new GetMethod(crlUrl); getMethod.addRequestHeader("User-Agent", "jTrust CRL Client"); int statusCode; try { statusCode = httpClient.executeMethod(getMethod); } catch (Exception e) { downloadFailed(caName, crlUrl); throw new RuntimeException(); } if (HttpURLConnection.HTTP_OK != statusCode) { LOG.debug("HTTP status code: " + statusCode); downloadFailed(caName, crlUrl); throw new RuntimeException(); } String crlFilePath; File crlFile = null; try { crlFile = File.createTempFile("crl-", ".der"); InputStream crlInputStream = getMethod.getResponseBodyAsStream(); OutputStream crlOutputStream = new FileOutputStream(crlFile); IOUtils.copy(crlInputStream, crlOutputStream); IOUtils.closeQuietly(crlInputStream); IOUtils.closeQuietly(crlOutputStream); crlFilePath = crlFile.getAbsolutePath(); LOG.debug("temp CRL file: " + crlFilePath); } catch (IOException e) { downloadFailed(caName, crlUrl); if (null != crlFile) { crlFile.delete(); } throw new RuntimeException(e); } try { this.notificationService.notifyHarvester(caName, crlFilePath, update); } catch (JMSException e) { crlFile.delete(); throw new RuntimeException(e); } }
|
00
|
Code Sample 1:
private PrecomputedAnimatedModel loadPrecomputedModel_(URL url) { if (precompCache.containsKey(url.toExternalForm())) { return (precompCache.get(url.toExternalForm()).copy()); } TextureLoader.getInstance().getTexture(""); List<SharedGroup> frames = new ArrayList<SharedGroup>(); Map<String, Animation> animations = new Hashtable<String, Animation>(); if (url.toExternalForm().endsWith(".amo")) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String objFileName = reader.readLine(); objFileName = url.toExternalForm().substring(0, url.toExternalForm().lastIndexOf("/")) + "/" + objFileName; frames = loadOBJFrames(objFileName); String line; while ((line = reader.readLine()) != null) { StringTokenizer tokenizer = new StringTokenizer(line); String animName = tokenizer.nextToken(); int from = Integer.valueOf(tokenizer.nextToken()); int to = Integer.valueOf(tokenizer.nextToken()); tokenizer.nextToken(); animations.put(animName, new Animation(animName, from, to)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { frames = loadOBJFrames(url.toExternalForm()); } PrecomputedAnimatedModel precompModel = new PrecomputedAnimatedModel(frames, animations); precompCache.put(url.toExternalForm(), precompModel); return (precompModel); }
Code Sample 2:
public static Document send(final String urlAddress) { Document responseMessage = null; try { URL url = new URL(urlAddress); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setAllowUserInteraction(false); int response = connection.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { String contentType = connection.getContentType(); if (contentType != null && contentType.startsWith("text/html")) { InputStream inputStream = connection.getInputStream(); responseMessage = XmlUtils.fromStream(inputStream); } else { responseMessage = XmlUtils.newDocument(); Element responseElement = XmlUtils.createElement(responseMessage, "rsp"); Element messageElement = XmlUtils.createElement(responseElement, "message"); messageElement.setTextContent(String.valueOf(connection.getResponseCode())); Element commentElement = XmlUtils.createElement(responseElement, "comment"); commentElement.setTextContent(contentType); } } else { responseMessage = XmlUtils.newDocument(); Element responseElement = XmlUtils.createElement(responseMessage, "rsp"); Element messageElement = XmlUtils.createElement(responseElement, "message"); messageElement.setTextContent(String.valueOf(connection.getResponseCode())); Element commentElement = XmlUtils.createElement(responseElement, "comment"); commentElement.setTextContent(connection.getResponseMessage()); } } catch (Exception e) { e.printStackTrace(); } return responseMessage; }
|
00
|
Code Sample 1:
private static void readFileEntry(Zip64File zip64File, FileEntry fileEntry, File destFolder) { FileOutputStream fileOut; File target = new File(destFolder, fileEntry.getName()); File targetsParent = target.getParentFile(); if (targetsParent != null) { targetsParent.mkdirs(); } try { fileOut = new FileOutputStream(target); log.info("[readFileEntry] writing entry: " + fileEntry.getName() + " to file: " + target.getAbsolutePath()); EntryInputStream entryReader = zip64File.openEntryInputStream(fileEntry.getName()); IOUtils.copyLarge(entryReader, fileOut); entryReader.close(); fileOut.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (ZipException e) { log.warning("ATTENTION PLEASE: Some strange, but obviously not serious ZipException occured! Extracted file '" + target.getName() + "' anyway! So don't Panic!" + "\n"); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
@Override public void backup() { Connection connection = null; PreparedStatement prestm = null; try { if (logger.isInfoEnabled()) logger.info("backup table " + getOrigin() + " start..."); Class.forName(driver); connection = DriverManager.getConnection(url, username, password); String tableExistsResult = ""; prestm = connection.prepareStatement("show tables from " + schema + " like '" + getDestination() + "';"); ResultSet rs = prestm.executeQuery(); if (rs.next()) tableExistsResult = rs.getString(1); rs.close(); prestm.close(); if (StringUtils.isBlank(tableExistsResult)) { String createTableSql = ""; prestm = connection.prepareStatement("show create table " + getOrigin() + ";"); rs = prestm.executeQuery(); if (rs.next()) createTableSql = rs.getString(2); rs.close(); prestm.close(); createTableSql = createTableSql.replaceAll("`" + getOrigin() + "`", "`" + getDestination() + "`"); createTableSql = createTableSql.replaceAll("auto_increment", ""); createTableSql = createTableSql.replaceAll("AUTO_INCREMENT", ""); Matcher matcher = stripRelationTablePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll(""); matcher = normalizePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll("\n )"); Statement stm = connection.createStatement(); stm.execute(createTableSql); if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' created!"); } else if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' already exists"); Date date = new Date(); date.setTime(TimeUtil.addHours(date, -getHours()).getTimeInMillis()); date.setTime(TimeUtil.getTodayAtMidnight().getTimeInMillis()); if (logger.isInfoEnabled()) logger.info("backuping records before: " + date); long currentRows = 0L; prestm = connection.prepareStatement("select count(*) from " + getOrigin() + " where " + getCondition() + ""); java.sql.Date sqlDate = new java.sql.Date(date.getTime()); prestm.setDate(1, sqlDate); rs = prestm.executeQuery(); if (rs.next()) currentRows = rs.getLong(1); rs.close(); prestm.close(); if (currentRows > 0) { connection.setAutoCommit(false); prestm = connection.prepareStatement("INSERT INTO " + getDestination() + " SELECT * FROM " + getOrigin() + " WHERE " + getCondition()); prestm.setDate(1, sqlDate); int rows = prestm.executeUpdate(); prestm.close(); if (logger.isInfoEnabled()) logger.info(rows + " rows backupped"); prestm = connection.prepareStatement("DELETE FROM " + getOrigin() + " WHERE " + getCondition()); prestm.setDate(1, sqlDate); rows = prestm.executeUpdate(); prestm.close(); connection.commit(); if (logger.isInfoEnabled()) logger.info(rows + " rows deleted"); } else if (logger.isInfoEnabled()) logger.info("no backup need"); if (logger.isInfoEnabled()) logger.info("backup table " + getOrigin() + " end"); } catch (SQLException e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "dbcon", "Errore SQL durante il backup dei dati della tabella " + getOrigin(), e)); try { connection.rollback(); } catch (SQLException e1) { } } catch (Throwable e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "generic", "Errore generico durante il backup dei dati della tabella " + getOrigin(), e)); try { connection.rollback(); } catch (SQLException e1) { } } finally { try { if (prestm != null) prestm.close(); } catch (SQLException e) { } try { if (connection != null) connection.close(); } catch (SQLException e) { } } }
|
11
|
Code Sample 1:
public void resumereceive(HttpServletRequest req, HttpServletResponse resp, SessionCommand command) { setHeader(resp); try { logger.debug("ResRec: Resume a 'receive' session with session id " + command.getSession() + " this client already received " + command.getLen() + " bytes"); File tempFile = new File(this.getSyncWorkDirectory(req), command.getSession() + ".smodif"); if (!tempFile.exists()) { logger.debug("ResRec: the file doesn't exist, so we created it by serializing the entities"); try { OutputStream fos = new FileOutputStream(tempFile); syncServer.getServerModifications(command.getSession(), fos); fos.close(); } catch (ImogSerializationException mse) { logger.error(mse.getMessage(), mse); } } InputStream fis = new FileInputStream(tempFile); fis.skip(command.getLen()); resp.setContentLength(fis.available()); while (fis.available() > 0) { resp.getOutputStream().write(fis.read()); } resp.getOutputStream().flush(); resp.flushBuffer(); fis.close(); } catch (IOException ioe) { logger.error(ioe.getMessage()); } }
Code Sample 2:
public static void main(String args[]) { String midletClass = null; ; File appletInputFile = null; File deviceInputFile = null; File midletInputFile = null; File htmlOutputFile = null; File appletOutputFile = null; File deviceOutputFile = null; File midletOutputFile = null; List params = new ArrayList(); for (int i = 0; i < args.length; i++) { params.add(args[i]); } Iterator argsIterator = params.iterator(); while (argsIterator.hasNext()) { String arg = (String) argsIterator.next(); argsIterator.remove(); if ((arg.equals("--help")) || (arg.equals("-help"))) { System.out.println(usage()); System.exit(0); } else if (arg.equals("--midletClass")) { midletClass = (String) argsIterator.next(); argsIterator.remove(); } else if (arg.equals("--appletInput")) { appletInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--deviceInput")) { deviceInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--midletInput")) { midletInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--htmlOutput")) { htmlOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--appletOutput")) { appletOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--deviceOutput")) { deviceOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--midletOutput")) { midletOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } } if (midletClass == null || appletInputFile == null || deviceInputFile == null || midletInputFile == null || htmlOutputFile == null || appletOutputFile == null || deviceOutputFile == null || midletOutputFile == null) { System.out.println(usage()); System.exit(0); } try { DeviceImpl device = null; String descriptorLocation = null; JarFile jar = new JarFile(deviceInputFile); for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorLocation = entry; break; } } if (descriptorLocation != null) { EmulatorContext context = new EmulatorContext() { private DisplayComponent displayComponent = new NoUiDisplayComponent(); private InputMethod inputMethod = new J2SEInputMethod(); private DeviceDisplay deviceDisplay = new J2SEDeviceDisplay(this); private FontManager fontManager = new J2SEFontManager(); private DeviceComponent deviceComponent = new SwingDeviceComponent(true); public DisplayComponent getDisplayComponent() { return displayComponent; } public InputMethod getDeviceInputMethod() { return inputMethod; } public DeviceDisplay getDeviceDisplay() { return deviceDisplay; } public FontManager getDeviceFontManager() { return fontManager; } public InputStream getResourceAsStream(String name) { return MIDletBridge.getCurrentMIDlet().getClass().getResourceAsStream(name); } public DeviceComponent getDeviceComponent() { return deviceComponent; } }; URL[] urls = new URL[1]; urls[0] = deviceInputFile.toURI().toURL(); ClassLoader classLoader = new ExtensionsClassLoader(urls, urls.getClass().getClassLoader()); device = DeviceImpl.create(context, classLoader, descriptorLocation, J2SEDevice.class); } if (device == null) { System.out.println("Error parsing device package: " + descriptorLocation); System.exit(0); } createHtml(htmlOutputFile, device, midletClass, midletOutputFile, appletOutputFile, deviceOutputFile); createMidlet(midletInputFile.toURI().toURL(), midletOutputFile); IOUtils.copyFile(appletInputFile, appletOutputFile); IOUtils.copyFile(deviceInputFile, deviceOutputFile); } catch (IOException ex) { ex.printStackTrace(); } System.exit(0); }
|
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:
@Override public Object init() throws Exception { if (url != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); ClassLoader parent = getClass().getClassLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); Class groovyClass = loader.parseClass(new File(url.getFile())); groovyObject = (GroovyObject) groovyClass.newInstance(); reader.close(); initDeclaredMethods(); return groovyObject; } else return null; }
|
00
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public Document retrieveDefinition(String uri) throws IOException, UnvalidResponseException { if (!isADbPediaURI(uri)) throw new IllegalArgumentException("Not a DbPedia Resource URI"); String rawDataUri = fromResourceToRawDataUri(uri); URL url = new URL(rawDataUri); URLConnection conn = url.openConnection(); logger.debug(".conn open"); conn.setDoOutput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); logger.debug(".resp obtained"); StringBuffer responseBuffer = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { responseBuffer.append(line); responseBuffer.append(NEWLINE); } rd.close(); logger.debug(".done"); try { return documentParser.parse(responseBuffer.toString()); } catch (SAXException e) { throw new UnvalidResponseException("Incorrect XML document", e); } }
|
00
|
Code Sample 1:
@Override public EntrySet read(EntrySet set) throws ReadFailedException { if (!SourceCache.contains(url)) { SSL.certify(url); try { super.setParser(Parser.detectParser(url.openStream(), url)); final PipedInputStream in = new PipedInputStream(); final PipedOutputStream forParser = new PipedOutputStream(in); new Thread(new Runnable() { public void run() { try { OutputStream out = SourceCache.startCaching(url); InputStream is = url.openStream(); byte[] buffer = new byte[100000]; while (true) { int amountRead = is.read(buffer); if (amountRead == -1) { break; } forParser.write(buffer, 0, amountRead); out.write(buffer, 0, amountRead); } forParser.close(); out.close(); SourceCache.finish(url); } catch (IOException e) { e.printStackTrace(); } } }).start(); super.setIos(in); } catch (Exception e) { throw new ReadFailedException(e); } return super.read(set); } else { try { return SourceCache.get(url).read(set); } catch (IOException e) { throw new ReadFailedException(e); } } }
Code Sample 2:
public FTPClient sample2(String server, String username, String password) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { FTPClient ftpClient = new FTPClient(); ftpClient.connect(server); ftpClient.login(username, password); return ftpClient; }
|
11
|
Code Sample 1:
private static String getSummaryText(File packageFile) { String retVal = null; Reader in = null; try { in = new FileReader(packageFile); StringWriter out = new StringWriter(); IOUtils.copy(in, out); StringBuffer buf = out.getBuffer(); int pos1 = buf.indexOf("<body>"); int pos2 = buf.lastIndexOf("</body>"); if (pos1 >= 0 && pos1 < pos2) { retVal = buf.substring(pos1 + 6, pos2); } else { retVal = ""; } } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } return retVal; }
Code Sample 2:
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); } }
|
00
|
Code Sample 1:
public T04MixedOTSDTMUnitTestCase(String name) throws java.io.IOException { super(name); java.net.URL url = ClassLoader.getSystemResource("host0.cosnaming.jndi.properties"); jndiProps = new java.util.Properties(); jndiProps.load(url.openStream()); }
Code Sample 2:
public static void readDefault() { ClassLoader l = Skeleton.class.getClassLoader(); URL url = l.getResource("weka/core/parser/JFlex/skeleton.default"); if (url == null) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } try { InputStreamReader reader = new InputStreamReader(url.openStream()); readSkel(new BufferedReader(reader)); } catch (IOException e) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } }
|
11
|
Code Sample 1:
public static void main(String[] args) { File directory = new File(args[0]); File[] files = directory.listFiles(); try { PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(args[1]))); for (int i = 0; i < files.length; i++) { BufferedReader reader = new BufferedReader(new FileReader(files[i])); while (reader.ready()) writer.println(reader.readLine()); reader.close(); } writer.flush(); writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static void copyFileByNIO(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
11
|
Code Sample 1:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final FileManager fmanager = FileManager.getFileManager(request, leechget); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (!item.isFormField()) { final FileObject file = fmanager.getFile(name); if (!file.exists()) { IOUtils.copyLarge(stream, file.getContent().getOutputStream()); } } } } catch (FileUploadException e1) { e1.printStackTrace(); } }
Code Sample 2:
@Override public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("DOWNLOAD - Send content: " + realFile.getAbsolutePath()); LOGGER.debug("Output stream: " + out.toString()); if (ServerConfiguration.isDynamicSEL()) { LOGGER.error("IS DINAMIC SEL????"); } else { } if (".tokens".equals(realFile.getName()) || ".response".equals(realFile.getName()) || ".request".equals(realFile.getName()) || isAllowedClient) { FileInputStream in = null; try { in = new FileInputStream(realFile); int bytes = IOUtils.copy(in, out); LOGGER.debug("System resource or Allowed Client wrote bytes: " + bytes); out.flush(); } catch (Exception e) { LOGGER.error("Error while uploading over encryption system " + realFile.getName() + " file", e); } finally { IOUtils.closeQuietly(in); } } else { FileInputStream in = null; try { in = new FileInputStream(realFile); int bytes = IOUtils.copy(in, out); LOGGER.debug("System resource or Allowed Client wrote bytes: " + bytes); out.flush(); } catch (Exception e) { LOGGER.error("Error while uploading over encryption system " + realFile.getName() + " file", e); } finally { IOUtils.closeQuietly(in); } } }
|
00
|
Code Sample 1:
@Override public boolean postPage() { MySpaceBlogExporterGuiApp.getApplication().getWizContainer().showStatus(myResourceMap.getString("CheckingBlogUrl.text")); URL url; try { url = new URL(txtBlogUrl.getText()); URLConnection con = url.openConnection(); con.getContentType(); String newLink = con.getURL().toString(); if (!newLink.equalsIgnoreCase(txtBlogUrl.getText())) { JOptionPane.showMessageDialog(new JFrame(), myResourceMap.getString("InvalidBlogUrl.text"), "Error", JOptionPane.ERROR_MESSAGE); return false; } } catch (Exception ex) { JOptionPane.showMessageDialog(new JFrame(), myResourceMap.getString("InvalidUrl.text"), "Error", JOptionPane.ERROR_MESSAGE); return false; } finally { MySpaceBlogExporterGuiApp.getApplication().getWizContainer().hideStatus(); } if (txtBlogUrl.getText().toLowerCase().indexOf("friendid") > 0) { JOptionPane.showMessageDialog(new JFrame(), myResourceMap.getString("InvalidBlogUrl.text"), "Error", JOptionPane.ERROR_MESSAGE); return false; } MySpaceBlogExporterGuiApp.getApplication().getMySpaceBlogExporter().setBlogUrl(txtBlogUrl.getText()); return true; }
Code Sample 2:
public int getHttpStatus(ProxyInfo proxyInfo, String sUrl, String cookie, String host) { HttpURLConnection connection = null; try { if (proxyInfo == null) { URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(); } else { InetSocketAddress addr = new InetSocketAddress(proxyInfo.getPxIp(), proxyInfo.getPxPort()); Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(proxy); } if (!isStringNull(host)) setHttpInfo(connection, cookie, host, ""); connection.setConnectTimeout(90 * 1000); connection.setReadTimeout(90 * 1000); connection.connect(); connection.getInputStream(); return connection.getResponseCode(); } catch (IOException e) { log.info(proxyInfo + " getHTTPConent Error "); return 0; } catch (Exception e) { log.info(proxyInfo + " getHTTPConent Error "); return 0; } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.