label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
11
|
Code Sample 1:
private void doIt() throws Throwable { int numCachedTiles = 0; try { List<MapTile> backTiles = new ArrayList<MapTile>(); final LatLngRectangle bounds = new LatLngRectangle(new LatLngPoint(south, west), new LatLngPoint(north, east)); final String backMapGuid = "gst"; final XFile dstDir = new XFile(new XFile(Configuration.getInstance().getPublicMapStorage().toString()), backMapGuid); dstDir.mkdir(); for (int z = Math.min(Tile.getOptimalZoom(bounds, 768), 9); z <= 17; z++) { final Tile tileStart = new Tile(bounds.getSouthWest().getLat(), bounds.getSouthWest().getLng(), z); final Tile tileEnd = new Tile(bounds.getNorthEast().getLat(), bounds.getNorthEast().getLng(), z); for (double y = tileEnd.getTileCoord().getY(); y <= tileStart.getTileCoord().getY(); y++) for (double x = tileStart.getTileCoord().getX(); x <= tileEnd.getTileCoord().getX(); x++) { NASAMapTile tile = new NASAMapTile((int) x, (int) y, z); XFile file = new XFile(dstDir, tile.toKeyString()); if (file.exists() && file.isFile()) continue; backTiles.add(tile); } } logger.info(backTiles.size() + " tiles to cache"); for (MapTile tile : backTiles) { InputStream in = null; OutputStream out = null; final URL url = new URL(tile.getPath()); try { int i = 4; while (--i > 0) { final XFile outFile = new XFile(dstDir, tile.toKeyString()); final URLConnection conn = url.openConnection(); if (conn == null || !conn.getContentType().startsWith("image")) { logger.error("onearth.jpl.nasa.gov service returns non-image file, " + "content-type='" + conn.getContentType() + "'"); Thread.sleep(1000L * (long) Math.pow(2, 8 - i)); continue; } in = conn.getInputStream(); if (in != null) { out = new XFileOutputStream(outFile); IOUtils.copy(in, out); break; } else throw new IllegalStateException("opened stream is null"); } } finally { if (out != null) { out.flush(); out.close(); } if (in != null) in.close(); } if (++numCachedTiles % 10 == 0) { logger.info(numCachedTiles + " tiles cached"); Thread.sleep(sleep); } } } catch (Throwable e) { logger.error("map tile caching has failed: ", e); throw e; } }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
|
00
|
Code Sample 1:
public Certificate(URL url) throws CertificateException { try { URLConnection con = url.openConnection(); InputStream in2 = con.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(in2)); String inputLine; StringBuffer cert = new StringBuffer(); while ((inputLine = in.readLine()) != null) { cert.append(inputLine); cert.append("\n"); } in.close(); this.certificate = cert.toString(); } catch (IOException ex) { throw new CertificateException("Unable to read in credential: " + ex.getMessage(), ex); } loadCredential(this.certificate); }
Code Sample 2:
private void getImage(String filename) throws MalformedURLException, IOException, SAXException, FileNotFoundException { String url = Constants.STRATEGICDOMINATION_URL + "/images/gameimages/" + filename; WebRequest req = new GetMethodWebRequest(url); WebResponse response = wc.getResponse(req); File file = new File("etc/images/" + filename); FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(response.getInputStream(), outputStream); }
|
11
|
Code Sample 1:
public static Board readStream(InputStream is) throws IOException { StringWriter stringWriter = new StringWriter(); IOUtils.copy(is, stringWriter); String s = stringWriter.getBuffer().toString(); Board board = read(s); return board; }
Code Sample 2:
public static void copyFile(File source, File dest) throws IOException { log.debug("Copy from {} to {}", source.getAbsoluteFile(), dest.getAbsoluteFile()); FileInputStream fi = new FileInputStream(source); FileChannel fic = fi.getChannel(); MappedByteBuffer mbuf = fic.map(FileChannel.MapMode.READ_ONLY, 0, source.length()); fic.close(); fi.close(); fi = null; if (!dest.exists()) { String destPath = dest.getPath(); log.debug("Destination path: {}", destPath); String destDir = destPath.substring(0, destPath.lastIndexOf(File.separatorChar)); log.debug("Destination dir: {}", destDir); File dir = new File(destDir); if (!dir.exists()) { if (dir.mkdirs()) { log.debug("Directory created"); } else { log.warn("Directory not created"); } } dir = null; } FileOutputStream fo = new FileOutputStream(dest); FileChannel foc = fo.getChannel(); foc.write(mbuf); foc.close(); fo.close(); fo = null; mbuf.clear(); mbuf = null; }
|
00
|
Code Sample 1:
@Override protected Integer doInBackground() throws Exception { int numOfRows = 0; combinationMap = new HashMap<AnsweredQuestion, Integer>(); combinationMapReverse = new HashMap<Integer, AnsweredQuestion>(); LinkedHashSet<AnsweredQuestion> answeredQuestionSet = new LinkedHashSet<AnsweredQuestion>(); LinkedHashSet<Integer> studentSet = new LinkedHashSet<Integer>(); final String delimiter = ";"; final String typeToProcess = "F"; String line; String[] chunks = new String[9]; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "ISO-8859-2")); in.readLine(); while ((line = in.readLine()) != null) { chunks = line.split(delimiter); numOfRows++; if (chunks[2].equals(typeToProcess)) { answeredQuestionSet.add(new AnsweredQuestion(chunks[4], chunks[5])); studentSet.add(new Integer(chunks[0])); } } in.close(); int i = 0; Integer I; for (AnsweredQuestion pair : answeredQuestionSet) { I = new Integer(i++); combinationMap.put(pair, I); combinationMapReverse.put(I, pair); } matrix = new SparseObjectMatrix2D(answeredQuestionSet.size(), studentSet.size()); int lastStudentNumber = -1; AnsweredQuestion pair; in = new BufferedReader(new InputStreamReader(url.openStream(), "ISO-8859-2")); in.readLine(); while ((line = in.readLine()) != null) { chunks = line.split(delimiter); pair = null; if (chunks[2].equals(typeToProcess)) { if (Integer.parseInt(chunks[0]) != lastStudentNumber) { lastStudentNumber++; } pair = new AnsweredQuestion(chunks[4], chunks[5]); if (combinationMap.containsKey(pair)) { matrix.setQuick(combinationMap.get(pair), lastStudentNumber, Boolean.TRUE); } } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } supportVector = new int[combinationMap.size()]; ObjectMatrix1D row = null; for (int i = 0; i < combinationMap.size(); i++) { row = matrix.viewRow(i); int sum = 0; for (int k = 0; k < row.size(); k++) { if (row.getQuick(k) != null && row.getQuick(k).equals(Boolean.TRUE)) { sum++; } } supportVector[i] = sum; } applet.combinationMap = this.combinationMap; applet.combinationMapReverse = this.combinationMapReverse; applet.matrix = this.matrix; applet.supportVector = supportVector; System.out.println("data loaded."); return null; }
Code Sample 2:
private static String hashPassword(String password, String customsalt) throws NoSuchAlgorithmException, UnsupportedEncodingException { password = SALT1 + password; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); password += convertToHex(md5.digest()) + SALT2 + customsalt; MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(password.getBytes("UTF-8"), 0, password.length()); sha1hash = md.digest(); return convertToHex(sha1hash) + "|" + customsalt; }
|
00
|
Code Sample 1:
public static File doRequestPost(URL url, String req, String fName, boolean override) throws ArcImsException { File f = null; URL virtualUrl = getVirtualRequestUrlFromUrlAndRequest(url, req); if ((f = getPreviousDownloadedURL(virtualUrl, override)) == null) { File tempDirectory = new File(tempDirectoryPath); if (!tempDirectory.exists()) { tempDirectory.mkdir(); } String nfName = normalizeFileName(fName); f = new File(tempDirectoryPath + "/" + nfName); f.deleteOnExit(); logger.info("downloading '" + url.toString() + "' to: " + f.getAbsolutePath()); try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-length", "" + req.length()); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(req); wr.flush(); DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f))); byte[] buffer = new byte[1024 * 256]; InputStream is = conn.getInputStream(); long readed = 0; for (int i = is.read(buffer); i > 0; i = is.read(buffer)) { dos.write(buffer, 0, i); readed += i; } dos.close(); is.close(); wr.close(); addDownloadedURL(virtualUrl, f.getAbsolutePath()); } catch (ConnectException ce) { logger.error("Timed out error", ce); throw new ArcImsException("arcims_server_timeout"); } catch (FileNotFoundException fe) { logger.error("FileNotFound Error", fe); throw new ArcImsException("arcims_server_error"); } catch (IOException e) { logger.error("IO Error", e); throw new ArcImsException("arcims_server_error"); } } if (!f.exists()) { downloadedFiles.remove(virtualUrl); f = doRequestPost(url, req, fName, override); } return f; }
Code Sample 2:
@Override protected ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String filename = ServletRequestUtils.getRequiredStringParameter(request, "id"); final File file = new File(path, filename + ".html"); logger.debug("Getting static content from: " + file.getPath()); final InputStream is = getServletContext().getResourceAsStream(file.getPath()); OutputStream out = null; if (is != null) { try { out = response.getOutputStream(); IOUtils.copy(is, out); } catch (IOException ioex) { logger.error(ioex); } finally { is.close(); if (out != null) { out.close(); } } } return null; }
|
11
|
Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public static File copyFile(File file, String dirName) { File destDir = new File(dirName); if (!destDir.exists() || !destDir.isDirectory()) { destDir.mkdirs(); } File src = file; File dest = new File(dirName, src.getName()); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
|
00
|
Code Sample 1:
public void salva(UploadedFile imagem, Usuario usuario) { File destino; if (usuario.getId() == null) { destino = new File(pastaImagens, usuario.hashCode() + ".jpg"); } else { destino = new File(pastaImagens, usuario.getId() + ".jpg"); } try { IOUtils.copyLarge(imagem.getFile(), new FileOutputStream(destino)); } catch (Exception e) { throw new RuntimeException("Erro ao copiar imagem", e); } redimensionar(destino.getPath(), destino.getPath(), "jpg", 110, 110); }
Code Sample 2:
public static void checkForUpdate(String version) { try { URL url = new URL(WiimoteWhiteboard.getProperty("updateURL")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); final String current = in.readLine(); if (compare(version, current)) showUpdateNotification(version, current); in.close(); } catch (Exception e) { } }
|
11
|
Code Sample 1:
public static Object deployNewService(String scNodeRmiName, String userName, String password, String name, String jarName, String serviceClass, String serviceInterface, Logger log) throws RemoteException, MalformedURLException, StartServiceException, NotBoundException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, SessionException { try { SCNodeInterface node = (SCNodeInterface) Naming.lookup(scNodeRmiName); String session = node.login(userName, password); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(new FileInputStream(jarName), baos); ServiceAdapterIfc adapter = node.deploy(session, name, baos.toByteArray(), jarName, serviceClass, serviceInterface); if (adapter != null) { return new ExternalDomain(node, adapter, adapter.getUri(), log).getProxy(Thread.currentThread().getContextClassLoader()); } } catch (Exception e) { log.warn("Could not send deploy command: " + e.getMessage(), e); } return null; }
Code Sample 2:
public void testRevcounter() throws ServiceException, IOException { JCRNodeSource emptySource = loadTestSource(); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } System.out.println(emptySource.getLatestSourceRevision()); } String testSourceUri = BASE_URL + "users/lars.trieloff?revision=1.1"; JCRNodeSource secondSource = (JCRNodeSource) resolveSource(testSourceUri); System.out.println("Created at: " + secondSource.getSourceRevision()); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } System.out.println(emptySource.getLatestSourceRevision()); } System.out.println("Read again at:" + secondSource.getSourceRevision()); assertNotNull(emptySource.getSourceRevision()); }
|
11
|
Code Sample 1:
public void deleteType(String id) throws Exception { String tmp = ""; PreparedStatement prepStmt = null; try { if (id == null || id.length() == 0) throw new Exception("Invalid parameter"); con = database.getConnection(); String delType = "delete from type where TYPE_ID='" + id + "'"; con.setAutoCommit(false); prepStmt = con.prepareStatement("delete from correlation where TYPE_ID='" + id + "' OR CORRELATEDTYPE_ID='" + id + "'"); prepStmt.executeUpdate(); prepStmt = con.prepareStatement("delete from composition where TYPE_ID='" + id + "'"); prepStmt.executeUpdate(); prepStmt = con.prepareStatement("delete from distribution where TYPE_ID='" + id + "'"); prepStmt.executeUpdate(); prepStmt = con.prepareStatement("delete from typename where TYPE_ID='" + id + "'"); prepStmt.executeUpdate(); prepStmt = con.prepareStatement("delete from typereference where TYPE_ID='" + id + "'"); prepStmt.executeUpdate(); prepStmt = con.prepareStatement("delete from plot where TYPE_ID='" + id + "'"); prepStmt.executeUpdate(); prepStmt = con.prepareStatement(delType); prepStmt.executeUpdate(); con.commit(); prepStmt.close(); con.close(); } catch (Exception e) { if (!con.isClosed()) { con.rollback(); prepStmt.close(); con.close(); } throw e; } }
Code Sample 2:
private void load() 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 (100, 'Person')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (101, 'john')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (200, 'Dog')"); stmt.executeQuery("select setval('objects_objectid_seq', 1000)"); stmt.executeUpdate("insert into ClassLinkTypes (LinkName, LinkType) values ('hasa', 2)"); stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (100, 'isa', 1)"); stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (101, 'instance', 100)"); stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (200, 'isa', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('LEFT-WALL', '1', 'AV+', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('john', '1', 'S+ | DO-', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('a', '1', 'D+', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('dog', '1', '[D-] & (S+ | DO-)', 200)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('have', '1', 'S- & AV- & DO+', 1)"); stmt.executeUpdate("insert into LanguageMorphologies (LanguageName, MorphologyTag, Rank, Root, Surface, Used) values " + " ('English', 'third singular', 1, 'have', 'has', TRUE)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('S', 1)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('DO', 3)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('AV', 7)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('D', 10)"); stmt.executeUpdate("insert into Articles (ArticleName, Dereference) values ('a', 2)"); stmt.executeUpdate("insert into FrameSlots (SlotName) values ('actor')"); stmt.executeUpdate("insert into FrameSlots (SlotName) values ('object')"); stmt.executeUpdate("insert into Verbs (VerbName, Type, SubjectSlot, IndirectObjectSlot, PredicateNounSlot) values ('have', 1, 'actor', '', 'object')"); stmt.executeQuery("select setval('instructions_instructionid_seq', 1)"); stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (3, 'link %actor hasa %object', null, 0, null, null, null)"); stmt.executeQuery("select setval('transactions_transactionid_seq', 1)"); stmt.executeUpdate("insert into Transactions (InstructionId, Description) values (2, 'have - link')"); stmt.executeQuery("select setval('verbtransactions_verbid_seq', 1)"); stmt.executeUpdate("insert into VerbTransactions (VerbString, MoodType, TransactionId) values ('have', 1, 2)"); stmt.executeUpdate("insert into VerbConstraints (VerbId, FrameSlot, ObjectId) values (2, 'actor', 1)"); stmt.executeUpdate("insert into VerbConstraints (VerbId, FrameSlot, ObjectId) values (2, 'object', 1)"); stmt.executeUpdate("insert into ProperNouns (Noun, SenseNumber, ObjectId) values ('john', 1, 101)"); stmt.executeUpdate("update SystemProperties set value = 'Tutorial 1 Data' where name = 'DB Data Version'"); 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 void run() { m_stats.setRunning(); URL url = m_stats.url; if (url != null) { try { URLConnection connection = url.openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; handleHTTPConnection(httpConnection, m_stats); } else { System.out.println("Unknown URL Connection Type " + url); } } catch (java.io.IOException ioe) { m_stats.setStatus(m_stats.IOError); m_stats.setErrorString("Error making or reading from connection" + ioe.toString()); } } m_stats.setDone(); m_manager.threadFinished(this); }
Code Sample 2:
public void writeFile(OutputStream outputStream) throws IOException { InputStream inputStream = null; if (file != null) { try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, outputStream); } finally { if (inputStream != null) { IOUtils.closeQuietly(inputStream); } } } }
|
00
|
Code Sample 1:
public void execute(HttpResponse response) throws HttpException, IOException { Collection<Data> allData = internalDataBank.getAll(); StringBuffer content = new StringBuffer(); for (Data data : allData) { content.append("keyHash:").append(data.getKeyHash()).append(", "); content.append("version:").append(data.getVersion()).append(", "); content.append("size:").append(data.getContent().length); content.append(SystemUtils.LINE_SEPARATOR); } StringEntity body = new StringEntity(content.toString()); body.setContentType(PLAIN_TEXT_RESPONSE_CONTENT_TYPE); response.setEntity(body); }
Code Sample 2:
public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; }
|
00
|
Code Sample 1:
public ActionForward sendTrackback(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws RollerException { ActionForward forward = mapping.findForward("weblogEdit.page"); ActionErrors errors = new ActionErrors(); WeblogEntryData entry = null; try { RollerRequest rreq = RollerRequest.getRollerRequest(request); if (rreq.isUserAuthorizedToEdit()) { WeblogEntryFormEx form = (WeblogEntryFormEx) actionForm; String entryid = form.getId(); if (entryid == null) { entryid = request.getParameter(RollerRequest.WEBLOGENTRYID_KEY); } RollerContext rctx = RollerContext.getRollerContext(request); WeblogManager wmgr = rreq.getRoller().getWeblogManager(); entry = wmgr.retrieveWeblogEntry(entryid); String title = entry.getTitle(); PageHelper pageHelper = PageHelper.createPageHelper(request, response); pageHelper.setSkipFlag(true); String excerpt = pageHelper.renderPlugins(entry); excerpt = StringUtils.left(Utilities.removeHTML(excerpt), 255); String url = rctx.createEntryPermalink(entry, request, true); String blog_name = entry.getWebsite().getName(); if (form.getTrackbackUrl() != null) { try { String data = URLEncoder.encode("title", "UTF-8") + "=" + URLEncoder.encode(title, "UTF-8"); data += ("&" + URLEncoder.encode("excerpt", "UTF-8") + "=" + URLEncoder.encode(excerpt, "UTF-8")); data += ("&" + URLEncoder.encode("url", "UTF-8") + "=" + URLEncoder.encode(url, "UTF-8")); data += ("&" + URLEncoder.encode("blog_name", "UTF-8") + "=" + URLEncoder.encode(blog_name, "UTF-8")); URL tburl = new URL(form.getTrackbackUrl()); URLConnection conn = tburl.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; StringBuffer resultBuff = new StringBuffer(); while ((line = rd.readLine()) != null) { resultBuff.append(Utilities.escapeHTML(line, true)); resultBuff.append("<br />"); } ActionMessages resultMsg = new ActionMessages(); resultMsg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("weblogEdit.trackbackResults", resultBuff)); saveMessages(request, resultMsg); wr.close(); rd.close(); } catch (IOException e) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.trackback", e)); } } else { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.noTrackbackUrlSpecified")); } form.setTrackbackUrl(null); } else { forward = mapping.findForward("access-denied"); } } catch (Exception e) { mLogger.error(e); String msg = e.getMessage(); if (msg == null) { msg = e.getClass().getName(); } errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.general", msg)); } if (!errors.isEmpty()) { saveErrors(request, errors); } request.setAttribute("model", new WeblogEntryPageModel(request, response, mapping, (WeblogEntryFormEx) actionForm, WeblogEntryPageModel.EDIT_MODE)); return forward; }
Code Sample 2:
public static String getRandomUserAgent() { if (USER_AGENT_CACHE == null) { Collection<String> userAgentsCache = new ArrayList<String>(); try { URL url = Tools.getResource(UserAgent.class.getClassLoader(), "user-agents-browser.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { userAgentsCache.add(str); } in.close(); USER_AGENT_CACHE = userAgentsCache.toArray(new String[userAgentsCache.size()]); } catch (Exception e) { System.err.println("Can not read file; using default user-agent; error message: " + e.getMessage()); return DEFAULT_USER_AGENT; } } return USER_AGENT_CACHE[new Random().nextInt(USER_AGENT_CACHE.length)]; }
|
11
|
Code Sample 1:
public static void main(String[] args) { try { String completePath = null; String predictionFileName = null; if (args.length == 2) { completePath = args[0]; predictionFileName = args[1]; } else { System.out.println("Please provide complete path to training_set parent folder as an argument. EXITING"); System.exit(0); } File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); MovieLimitsTHash = new TShortObjectHashMap(17770, 1); int i = 0, totalcount = 0; short movie; int startIndex, endIndex; TIntArrayList a; while (mappedfile.hasRemaining()) { movie = mappedfile.getShort(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); MovieLimitsTHash.put(movie, a); } inC.close(); mappedfile = null; System.out.println("Loaded movie index hash"); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); MoviesAndRatingsPerCustomer = InitializeMovieRatingsForCustomerHashMap(completePath, CustomerLimitsTHash); System.out.println("Populated MoviesAndRatingsPerCustomer hashmap"); File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionFileName); FileChannel out = new FileOutputStream(outfile, true).getChannel(); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "formattedProbeData.txt"); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); int custAndRatingSize = 0; TIntByteHashMap custsandratings = new TIntByteHashMap(); int ignoreProcessedRows = 0; int movieViewershipSize = 0; while (probemappedfile.hasRemaining()) { short testmovie = probemappedfile.getShort(); int testCustomer = probemappedfile.getInt(); if ((CustomersAndRatingsPerMovie != null) && (CustomersAndRatingsPerMovie.containsKey(testmovie))) { } else { CustomersAndRatingsPerMovie = InitializeCustomerRatingsForMovieHashMap(completePath, testmovie); custsandratings = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(testmovie); custAndRatingSize = custsandratings.size(); } TShortByteHashMap testCustMovieAndRatingsMap = (TShortByteHashMap) MoviesAndRatingsPerCustomer.get(testCustomer); short[] testCustMovies = testCustMovieAndRatingsMap.keys(); float finalPrediction = 0; finalPrediction = predictRating(testCustomer, testmovie, custsandratings, custAndRatingSize, testCustMovies, testCustMovieAndRatingsMap); System.out.println("prediction for movie: " + testmovie + " for customer " + testCustomer + " is " + finalPrediction); ByteBuffer buf = ByteBuffer.allocate(11); buf.putShort(testmovie); buf.putInt(testCustomer); buf.putFloat(finalPrediction); buf.flip(); out.write(buf); buf = null; testCustMovieAndRatingsMap = null; testCustMovies = null; } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private File copyFile(String fileInClassPath, String systemPath) throws Exception { InputStream is = getClass().getResourceAsStream(fileInClassPath); OutputStream os = new FileOutputStream(systemPath); IOUtils.copy(is, os); is.close(); os.close(); return new File(systemPath); }
|
00
|
Code Sample 1:
public void run() { if (data.length() > 0) { String method = getMethod(); String action = getAction(); URL url; try { URL actionURL; URL baseURL = hdoc.getBase(); if (action == null) { String file = baseURL.getFile(); actionURL = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(), file); } else actionURL = new URL(baseURL, action); URLConnection connection; if ("post".equalsIgnoreCase(method)) { url = actionURL; connection = url.openConnection(); ((HttpURLConnection) connection).setFollowRedirects(false); XRendererSupport.setCookies(url, connection); connection.setRequestProperty("Accept-Language", "en-us"); connection.setRequestProperty("User-Agent", XRendererSupport.getContext().getUserAgent()); postData(connection, data); XRendererSupport.getContext().getLogger().message(this, "Posted data: {" + data + "}"); } else { url = new URL(actionURL + "?" + data); connection = url.openConnection(); XRendererSupport.setCookies(url, connection); } connection.connect(); in = connection.getInputStream(); URL base = connection.getURL(); XRendererSupport.getCookies(base, connection); XRendererSupport.getContext().getLogger().message(this, "Stream got ok."); JEditorPane c = (JEditorPane) getContainer(); HTMLEditorKit kit = (HTMLEditorKit) c.getEditorKit(); newDoc = (HTMLDocument) kit.createDefaultDocument(); newDoc.putProperty(Document.StreamDescriptionProperty, base); SwingUtilities.invokeLater(new Runnable() { public void run() { XRendererSupport.getContext().getLogger().message(this, "loading..."); loadDocument(); XRendererSupport.getContext().getLogger().message(this, "document loaded..."); } }); } catch (MalformedURLException m) { } catch (IOException e) { } } }
Code Sample 2:
public static void bubbleSort(int[] a) { if (a == null) { throw new IllegalArgumentException("Null-pointed array"); } int right = a.length - 1; int k = 0; while (right > 0) { k = 0; for (int i = 0; i <= right - 1; i++) { if (a[i] > a[i + 1]) { k = i; int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } right = k; } }
|
11
|
Code Sample 1:
private void packageDestZip(File tmpFile) throws FileNotFoundException, IOException { log("Creating launch profile package " + destfile); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destfile))); ZipEntry e = new ZipEntry(RESOURCE_JAR_FILENAME); e.setMethod(ZipEntry.STORED); e.setSize(tmpFile.length()); e.setCompressedSize(tmpFile.length()); e.setCrc(calcChecksum(tmpFile, new CRC32())); out.putNextEntry(e); InputStream in = new BufferedInputStream(new FileInputStream(tmpFile)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.closeEntry(); out.finish(); out.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 AssessmentItemType getAssessmentItemType(String filename) { if (filename.contains(" ") && (System.getProperty("os.name").contains("Windows"))) { File source = new File(filename); String tempDir = System.getenv("TEMP"); File dest = new File(tempDir + "/temp.xml"); MQMain.logger.info("Importing from " + dest.getAbsolutePath()); FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } filename = tempDir + "/temp.xml"; } } AssessmentItemType assessmentItemType = null; JAXBElement<?> jaxbe = null; try { XMLReader reader = XMLReaderFactory.createXMLReader(); ChangeNamespace convertfromv2p0tov2p1 = new ChangeNamespace(reader, "http://www.imsglobal.org/xsd/imsqti_v2p0", "http://www.imsglobal.org/xsd/imsqti_v2p1"); SAXSource source = null; try { FileInputStream fis = new FileInputStream(filename); InputStreamReader isr = null; try { isr = new InputStreamReader(fis, "UTF-8"); } catch (UnsupportedEncodingException e) { } InputSource is = new InputSource(isr); source = new SAXSource(convertfromv2p0tov2p1, is); } catch (FileNotFoundException e) { MQMain.logger.error("SAX/getAssessmentItemType/file not found"); } jaxbe = (JAXBElement<?>) MQModel.qtiCf.unmarshal(MQModel.imsqtiUnmarshaller, source); assessmentItemType = (AssessmentItemType) jaxbe.getValue(); } catch (JAXBException e) { MQMain.logger.error("JAX/getAssessmentItemType", e); } catch (SAXException e) { MQMain.logger.error("SAX/getAssessmentItemType", e); } return assessmentItemType; }
Code Sample 2:
public void actionPerformed(ActionEvent e) { String line, days; String oldType, newType; String dept = ""; buttonPressed = true; char first; int caretIndex; int tempIndex; int oldDisplayNum = displayNum; for (int i = 0; i < 10; i++) { if (e.getSource() == imageButtons[i]) { if (rePrintAnswer) printAnswer(); print.setVisible(true); selectTerm.setVisible(true); displayNum = i; textArea2.setCaretPosition(textArea2.getText().length() - 1); caretIndex = textArea2.getText().indexOf("#" + (i + 1)); if (caretIndex != -1) textArea2.setCaretPosition(caretIndex); repaint(); } } if (e.getSource() == print) { if (textArea2.getText().charAt(0) != '#') printAnswer(); String data = textArea2.getText(); int start = data.indexOf("#" + (displayNum + 1)); start = data.indexOf("\n", start); start++; int end = data.indexOf("\n---------", start); data = data.substring(start, end); String tr = ""; if (term.getSelectedItem() == "Spring") tr = "SP"; else if (term.getSelectedItem() == "Summer") tr = "SU"; else tr = "FL"; String s = getCodeBase().toString() + "schedule.cgi?term=" + tr + "&data=" + URLEncoder.encode(data); try { AppletContext a = getAppletContext(); URL u = new URL(s); a.showDocument(u, "_blank"); } catch (MalformedURLException rea) { } } if (e.getSource() == webSite) { String tr; if (term.getSelectedItem() == "Spring") tr = "SP"; else if (term.getSelectedItem() == "Summer") tr = "SU"; else tr = "FL"; String num = courseNum.getText().toUpperCase(); String s = "http://sis450.berkeley.edu:4200/OSOC/osoc?p_term=" + tr + "&p_deptname=" + URLEncoder.encode(lst.getSelectedItem().toString()) + "&p_course=" + num; try { AppletContext a = getAppletContext(); URL u = new URL(s); a.showDocument(u, "_blank"); } catch (MalformedURLException rea) { } } if (e.getSource() == loadButton) { printSign("Loading..."); String fileName = idField.getText(); fileName = fileName.replace(' ', '_'); String text = readURL(fileName); if (!publicSign.equals("Error loading.")) { textArea1.setText(text); fileName += ".2"; text = readURL(fileName); absorb(text); printAnswer(); for (int i = 0; i < 10; i++) { if (answer[i].gap != -1 && answer[i].gap != 9999 && answer[i].gap != 10000) { imageButtons[i].setVisible(true); } else imageButtons[i].setVisible(false); } if (!imageButtons[0].isVisible()) { print.setVisible(false); selectTerm.setVisible(false); } else { print.setVisible(true); selectTerm.setVisible(true); } printSign("Load complete."); } displayNum = 0; repaint(); } if (e.getSource() == saveButton) { String fileName = idField.getText(); fileName = fileName.replace(' ', '_'); printSign("Saving..."); writeURL(fileName, 1); printSign("Saving......"); fileName += ".2"; writeURL(fileName, 2); printSign("Save complete."); } if (e.getSource() == instructions) { showInstructions(); } if (e.getSource() == net) { drawWarning = false; String inputLine = ""; String text = ""; String out; String urlIn = ""; textArea2.setText("Retrieving Data..."); try { String tr; if (term.getSelectedItem() == "Spring") tr = "SP"; else if (term.getSelectedItem() == "Summer") tr = "SU"; else tr = "FL"; String num = courseNum.getText().toUpperCase(); dept = lst.getSelectedItem().toString(); { urlIn = "http://sis450.berkeley.edu:4200/OSOC/osoc?p_term=" + tr + "&p_deptname=" + URLEncoder.encode(dept) + "&p_course=" + num; try { URL url = new URL(getCodeBase().toString() + "getURL.cgi"); URLConnection con = url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); DataOutputStream out2 = new DataOutputStream(con.getOutputStream()); String content = "url=" + URLEncoder.encode(urlIn); out2.writeBytes(content); out2.flush(); DataInputStream in = new DataInputStream(con.getInputStream()); String s; while ((s = in.readLine()) != null) { } in.close(); } catch (IOException err) { } } URL yahoo = new URL(this.getCodeBase(), "classData.txt"); URLConnection yc = yahoo.openConnection(); StringBuffer buf = new StringBuffer(""); DataInputStream in = new DataInputStream(new BufferedInputStream(yc.getInputStream())); while ((inputLine = in.readLine()) != null) { buf.append(inputLine); } text = buf.toString(); in.close(); } catch (IOException errr) { } String inText = (parseData(text, false)); if (inText.equals("-1")) inText = parseData(text, true); if (inText.equals("\n")) { textArea2.append("\nNO DATA FOUND \n(" + urlIn + ")"); } else textArea1.append(inText); repaint(); } badInput = false; if (e.getSource() == button1) { if (t != null && t.isAlive()) { t.stop(); epilogue(); return; } displayNum = 0; textArea2.setCaretPosition(0); for (int i = 0; i < 30; i++) for (int j = 0; j < 20; j++) { matrix[i][j] = new entry(); matrix[i][j].time = new Time[4]; for (int k = 0; k < 4; k++) { matrix[i][j].time[k] = new Time(); matrix[i][j].time[k].from = 0; } } val = new entry[30]; for (int i = 0; i < 30; i++) { val[i] = new entry(); val[i].time = new Time[4]; for (int j = 0; j < 4; j++) { val[i].time[j] = new Time(); val[i].time[j].from = 0; } } oldPercentDone = -5; oldAmountDone = -1 * PRINTINTERVAL; percentDone = 0; amountDone = 0; drawWarning = false; errorMessage = ""; String text1 = textArea1.getText(); if (text1.toUpperCase().indexOf("OR:") == -1) containsOR = false; else containsOR = true; text1 = removeOR(text1.toUpperCase()); StringTokenizer st = new StringTokenizer(text1, "\n"); clss = -1; timeEntry = -1; boolean noTimesListed = false; while (st.hasMoreTokens()) { line = st.nextToken().toString(); if (line.equals("")) break; else first = line.charAt(0); if (first == '0') { badInput = true; repaint(); break; } if (first >= '1' && first <= '9') { noTimesListed = false; timeEntry++; if (timeEntry == 30) { rePrintAnswer = true; textArea2.setText("Error: Exceeded 30 time entries per class."); badInput = true; repaint(); return; } nextTime = -1; StringTokenizer andST = new StringTokenizer(line, ","); while (andST.hasMoreTokens()) { String temp; String entry; int index, fromTime, toTime; nextTime++; if (nextTime == 4) { rePrintAnswer = true; textArea2.setText("Error: Exceeded 4 time intervals per entry!"); badInput = true; repaint(); return; } StringTokenizer timeST = new StringTokenizer(andST.nextToken()); temp = timeST.nextToken().toString(); entry = ""; index = 0; if (temp.equals("")) break; while (temp.charAt(index) != '-') { entry += temp.charAt(index); index++; if (index >= temp.length()) { rePrintAnswer = true; textArea2.setText("Error: There should be no space before hyphens."); badInput = true; repaint(); return; } } try { fromTime = Integer.parseInt(entry); } catch (NumberFormatException re) { rePrintAnswer = true; textArea2.setText("Error: There should be no a/p sign after FROM_TIME."); badInput = true; repaint(); return; } index++; entry = ""; if (index >= temp.length()) { badInput = true; repaint(); rePrintAnswer = true; textArea2.setText("Error: am/pm sign missing??"); return; } while (temp.charAt(index) >= '0' && temp.charAt(index) <= '9') { entry += temp.charAt(index); index++; if (index >= temp.length()) { badInput = true; repaint(); rePrintAnswer = true; textArea2.setText("Error: am/pm sign missing??"); return; } } toTime = Integer.parseInt(entry); if (temp.charAt(index) == 'a' || temp.charAt(index) == 'A') { } else { if (isLesse(fromTime, toTime) && !timeEq(toTime, 1200)) { if (String.valueOf(fromTime).length() == 4 || String.valueOf(fromTime).length() == 3) { fromTime += 1200; } else fromTime += 12; } if (!timeEq(toTime, 1200)) { if (String.valueOf(toTime).length() == 4 || String.valueOf(toTime).length() == 3) { toTime += 1200; } else toTime += 12; } } if (String.valueOf(fromTime).length() == 2 || String.valueOf(fromTime).length() == 1) fromTime *= 100; if (String.valueOf(toTime).length() == 2 || String.valueOf(toTime).length() == 1) toTime *= 100; matrix[timeEntry][clss].time[nextTime].from = fromTime; matrix[timeEntry][clss].time[nextTime].to = toTime; if (timeST.hasMoreTokens()) days = timeST.nextToken().toString(); else { rePrintAnswer = true; textArea2.setText("Error: days not specified?"); badInput = true; repaint(); return; } if (days.equals("")) return; if (days.indexOf("M") != -1 || days.indexOf("m") != -1) matrix[timeEntry][clss].time[nextTime].m = 1; if (days.indexOf("TU") != -1 || days.indexOf("Tu") != -1 || days.indexOf("tu") != -1) matrix[timeEntry][clss].time[nextTime].tu = 1; if (days.indexOf("W") != -1 || days.indexOf("w") != -1) matrix[timeEntry][clss].time[nextTime].w = 1; if (days.indexOf("TH") != -1 || days.indexOf("Th") != -1 || days.indexOf("th") != -1) matrix[timeEntry][clss].time[nextTime].th = 1; if (days.indexOf("F") != -1 || days.indexOf("f") != -1) matrix[timeEntry][clss].time[nextTime].f = 1; } } else { if (noTimesListed) clss--; clss++; if (clss == 20) { rePrintAnswer = true; textArea2.setText("Error: No more than 20 class entries!"); badInput = true; repaint(); return; } timeEntry = -1; line = line.trim(); for (int i = 0; i < 30; i++) matrix[i][clss].name = line; noTimesListed = true; } } for (int i = 0; i < 30; i++) { for (int j = 0; j < 4; j++) { val[i].time[j].from = 0; } } for (int i = 0; i < 10; i++) { beat10[i] = 10000; answer[i].gap = 10000; for (int j = 0; j < 30; j++) answer[i].classes[j].name = ""; } time = 0; calcTotal = 0; int k = 0; calculateTotalPercent(0, "\n"); amountToReach = calcTotal; button1.setLabel("...HALT GENERATION..."); printWarn(); if (t != null && t.isAlive()) t.stop(); t = new Thread(this, "Generator"); t.start(); } }
|
00
|
Code Sample 1:
public static String read(URL url) throws Exception { String filename = Integer.toString(url.toString().hashCode()); boolean cached = false; File dir = new File(Config.CACHE_PATH); for (File file : dir.listFiles()) { if (!file.isFile()) continue; if (file.getName().equals(filename)) { filename = file.getName(); cached = true; break; } } File file = new File(Config.CACHE_PATH, filename); if (Config.USE_CACHE && cached) return read(file); System.out.println(">> CACHE HIT FAILED."); InputStream in = null; try { in = url.openStream(); } catch (Exception e) { System.out.println(">> OPEN STREAM FAILED: " + url.toString()); return null; } String content = read(in); save(file, content); return content; }
Code Sample 2:
public static URL getIconURLForUser(String id) { try { URL url = new URL("http://profiles.yahoo.com/" + id); BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream())); String input = null; while ((input = r.readLine()) != null) { if (input.indexOf("<a href=\"") < 0) continue; if (input.indexOf("<img src=\"") < 0) continue; if (input.indexOf("<a href=\"") > input.indexOf("<img src=\"")) continue; String href = input.substring(input.indexOf("<a href=\"") + 9); String src = input.substring(input.indexOf("<img src=\"") + 10); if (href.indexOf("\"") < 0) continue; if (src.indexOf("\"") < 0) continue; href = href.substring(0, href.indexOf("\"")); src = src.substring(0, src.indexOf("\"")); if (href.equals(src)) { return new URL(href); } } } catch (IOException e) { } URL toReturn = null; try { toReturn = new URL("http://us.i1.yimg.com/us.yimg.com/i/ppl/no_photo.gif"); } catch (MalformedURLException e) { Debug.assrt(false); } return toReturn; }
|
11
|
Code Sample 1:
private void packageDestZip(File tmpFile) throws FileNotFoundException, IOException { log("Creating launch profile package " + destfile); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destfile))); ZipEntry e = new ZipEntry(RESOURCE_JAR_FILENAME); e.setMethod(ZipEntry.STORED); e.setSize(tmpFile.length()); e.setCompressedSize(tmpFile.length()); e.setCrc(calcChecksum(tmpFile, new CRC32())); out.putNextEntry(e); InputStream in = new BufferedInputStream(new FileInputStream(tmpFile)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.closeEntry(); out.finish(); out.close(); }
Code Sample 2:
public void createResource(String resourceUri, boolean publish, User user) throws IOException { PermissionAPI perAPI = APILocator.getPermissionAPI(); Logger.debug(this.getClass(), "createResource"); resourceUri = stripMapping(resourceUri); String hostName = getHostname(resourceUri); String path = getPath(resourceUri); String folderName = getFolderName(path); String fileName = getFileName(path); fileName = deleteSpecialCharacter(fileName); if (fileName.startsWith(".")) { return; } Host host = HostFactory.getHostByHostName(hostName); Folder folder = FolderFactory.getFolderByPath(folderName, host); boolean hasPermission = perAPI.doesUserHavePermission(folder, PERMISSION_WRITE, user, false); if (hasPermission) { if (!checkFolderFilter(folder, fileName)) { throw new IOException("The file doesn't comply the folder's filter"); } if (host.getInode() != 0 && folder.getInode() != 0) { File file = new File(); file.setTitle(fileName); file.setFileName(fileName); file.setShowOnMenu(false); file.setLive(publish); file.setWorking(true); file.setDeleted(false); file.setLocked(false); file.setModDate(new Date()); String mimeType = FileFactory.getMimeType(fileName); file.setMimeType(mimeType); String author = user.getFullName(); file.setAuthor(author); file.setModUser(author); file.setSortOrder(0); file.setShowOnMenu(false); try { Identifier identifier = null; if (!isResource(resourceUri)) { WebAssetFactory.createAsset(file, user.getUserId(), folder, publish); identifier = IdentifierCache.getIdentifierFromIdentifierCache(file); } else { File actualFile = FileFactory.getFileByURI(path, host, false); identifier = IdentifierCache.getIdentifierFromIdentifierCache(actualFile); WebAssetFactory.createAsset(file, user.getUserId(), folder, identifier, false, false); WebAssetFactory.publishAsset(file); String assetsPath = FileFactory.getRealAssetsRootPath(); new java.io.File(assetsPath).mkdir(); java.io.File workingIOFile = FileFactory.getAssetIOFile(file); DotResourceCache vc = CacheLocator.getVeloctyResourceCache(); vc.remove(ResourceManager.RESOURCE_TEMPLATE + workingIOFile.getPath()); if (file != null && file.getInode() > 0) { byte[] currentData = new byte[0]; FileInputStream is = new FileInputStream(workingIOFile); int size = is.available(); currentData = new byte[size]; is.read(currentData); java.io.File newVersionFile = FileFactory.getAssetIOFile(file); vc.remove(ResourceManager.RESOURCE_TEMPLATE + newVersionFile.getPath()); FileChannel channelTo = new FileOutputStream(newVersionFile).getChannel(); ByteBuffer currentDataBuffer = ByteBuffer.allocate(currentData.length); currentDataBuffer.put(currentData); currentDataBuffer.position(0); channelTo.write(currentDataBuffer); channelTo.force(false); channelTo.close(); } java.util.List<Tree> parentTrees = TreeFactory.getTreesByChild(file); for (Tree tree : parentTrees) { Tree newTree = TreeFactory.getTree(tree.getParent(), file.getInode()); if (newTree.getChild() == 0) { newTree.setParent(tree.getParent()); newTree.setChild(file.getInode()); newTree.setRelationType(tree.getRelationType()); newTree.setTreeOrder(0); TreeFactory.saveTree(newTree); } } } List<Permission> permissions = perAPI.getPermissions(folder); for (Permission permission : permissions) { Permission filePermission = new Permission(); filePermission.setPermission(permission.getPermission()); filePermission.setRoleId(permission.getRoleId()); filePermission.setInode(identifier.getInode()); perAPI.save(filePermission); } } catch (Exception ex) { Logger.debug(this, ex.toString()); } } } else { throw new IOException("You don't have access to add that folder/host"); } }
|
11
|
Code Sample 1:
public String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.err.println(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static String toPWD(String pwd) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(pwd.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
|
11
|
Code Sample 1:
public Main(String[] args) { boolean encrypt = false; if (args[0].compareTo("-e") == 0) { encrypt = true; } else if (args[0].compareTo("-d") == 0) { encrypt = false; } else { System.out.println("first argument is invalid"); System.exit(-2); } char[] password = new char[args[2].length()]; for (int i = 0; i < args[2].length(); i++) { password[i] = (char) args[2].getBytes()[i]; } try { InitializeCipher(encrypt, password); } catch (Exception e) { System.out.println("error initializing cipher"); System.exit(-3); } try { InputStream is = new FileInputStream(args[1]); OutputStream os; int read, max = 10; byte[] buffer = new byte[max]; if (encrypt) { os = new FileOutputStream(args[1] + ".enc"); os = new CipherOutputStream(os, cipher); } else { os = new FileOutputStream(args[1] + ".dec"); is = new CipherInputStream(is, cipher); } read = is.read(buffer); while (read != -1) { os.write(buffer, 0, read); read = is.read(buffer); } while (read == max) ; os.close(); is.close(); System.out.println(new String(buffer)); } catch (Exception e) { System.out.println("error encrypting/decrypting message:"); e.printStackTrace(); System.exit(-4); } System.out.println("done"); }
Code Sample 2:
public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
|
00
|
Code Sample 1:
protected void doProxyInternally(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpRequestBase proxyReq = buildProxyRequest(req); URI reqUri = proxyReq.getURI(); String cookieDomain = reqUri.getHost(); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute("org.atricorel.idbus.kernel.main.binding.http.HttpServletRequest", req); int intIdx = 0; for (int i = 0; i < httpClient.getRequestInterceptorCount(); i++) { if (httpClient.getRequestInterceptor(i) instanceof RequestAddCookies) { intIdx = i; break; } } IDBusRequestAddCookies interceptor = new IDBusRequestAddCookies(cookieDomain); httpClient.removeRequestInterceptorByClass(RequestAddCookies.class); httpClient.addRequestInterceptor(interceptor, intIdx); httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false); httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (logger.isTraceEnabled()) logger.trace("Staring to follow redirects for " + req.getPathInfo()); HttpResponse proxyRes = null; List<Header> storedHeaders = new ArrayList<Header>(40); boolean followTargetUrl = true; byte[] buff = new byte[1024]; while (followTargetUrl) { if (logger.isTraceEnabled()) logger.trace("Sending internal request " + proxyReq); proxyRes = httpClient.execute(proxyReq, httpContext); String targetUrl = null; Header[] headers = proxyRes.getAllHeaders(); for (Header header : headers) { if (header.getName().equals("Server")) continue; if (header.getName().equals("Transfer-Encoding")) continue; if (header.getName().equals("Location")) continue; if (header.getName().equals("Expires")) continue; if (header.getName().equals("Content-Length")) continue; if (header.getName().equals("Content-Type")) continue; storedHeaders.add(header); } if (logger.isTraceEnabled()) logger.trace("HTTP/STATUS:" + proxyRes.getStatusLine().getStatusCode() + "[" + proxyReq + "]"); switch(proxyRes.getStatusLine().getStatusCode()) { case 200: followTargetUrl = false; break; case 404: followTargetUrl = false; break; case 500: followTargetUrl = false; break; case 302: Header location = proxyRes.getFirstHeader("Location"); targetUrl = location.getValue(); if (!internalProcessingPolicy.match(req, targetUrl)) { if (logger.isTraceEnabled()) logger.trace("Do not follow HTTP 302 to [" + location.getValue() + "]"); Collections.addAll(storedHeaders, proxyRes.getHeaders("Location")); followTargetUrl = false; } else { if (logger.isTraceEnabled()) logger.trace("Do follow HTTP 302 to [" + location.getValue() + "]"); followTargetUrl = true; } break; default: followTargetUrl = false; break; } HttpEntity entity = proxyRes.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { if (!followTargetUrl) { for (Header header : headers) { if (header.getName().equals("Content-Type")) res.setHeader(header.getName(), header.getValue()); if (header.getName().equals("Content-Length")) res.setHeader(header.getName(), header.getValue()); } res.setStatus(proxyRes.getStatusLine().getStatusCode()); for (Header header : storedHeaders) { if (header.getName().startsWith("Set-Cookie")) res.addHeader(header.getName(), header.getValue()); else res.setHeader(header.getName(), header.getValue()); } IOUtils.copy(instream, res.getOutputStream()); res.getOutputStream().flush(); } else { int r = instream.read(buff); int total = r; while (r > 0) { r = instream.read(buff); total += r; } if (total > 0) logger.warn("Ignoring response content size : " + total); } } catch (IOException ex) { throw ex; } catch (RuntimeException ex) { proxyReq.abort(); throw ex; } finally { try { instream.close(); } catch (Exception ignore) { } } } else { if (!followTargetUrl) { res.setStatus(proxyRes.getStatusLine().getStatusCode()); for (Header header : headers) { if (header.getName().equals("Content-Type")) res.setHeader(header.getName(), header.getValue()); if (header.getName().equals("Content-Length")) res.setHeader(header.getName(), header.getValue()); } for (Header header : storedHeaders) { if (header.getName().startsWith("Set-Cookie")) res.addHeader(header.getName(), header.getValue()); else res.setHeader(header.getName(), header.getValue()); } } } if (followTargetUrl) { proxyReq = buildProxyRequest(targetUrl); httpContext = null; } } if (logger.isTraceEnabled()) logger.trace("Ended following redirects for " + req.getPathInfo()); }
Code Sample 2:
@Override public void setOntology1Document(URL url1) throws IllegalArgumentException { if (url1 == null) throw new IllegalArgumentException("Input parameter URL for ontology 1 is null."); try { ont1 = OWLManager.createOWLOntologyManager().loadOntologyFromOntologyDocument(url1.openStream()); } catch (IOException e) { throw new IllegalArgumentException("Cannot open stream for ontology 1 from given URL."); } catch (OWLOntologyCreationException e) { throw new IllegalArgumentException("Cannot load ontology 1 from given URL."); } }
|
11
|
Code Sample 1:
public static void copyFile(File inputFile, File outputFile) throws IOException { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(inputFile).getChannel(); outChannel = new FileOutputStream(outputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { try { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } catch (IOException e) { throw e; } } }
Code Sample 2:
public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
|
00
|
Code Sample 1:
public static boolean ejecutarDMLTransaccion(List<String> tirasSQL) throws Exception { boolean ok = true; try { getConexion(); conexion.setAutoCommit(false); Statement st = conexion.createStatement(); for (String cadenaSQL : tirasSQL) { if (st.executeUpdate(cadenaSQL) < 1) { ok = false; break; } } if (ok) conexion.commit(); else conexion.rollback(); conexion.setAutoCommit(true); conexion.close(); } catch (SQLException e) { if (conexion != null && !conexion.isClosed()) { conexion.rollback(); } throw new Exception("Error en Transaccion"); } catch (Exception e) { throw new Exception("Error en Transaccion"); } return ok; }
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(); }
|
00
|
Code Sample 1:
@SuppressWarnings("static-access") @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 { filename = URLDecoder.decode(filename, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { is = request.getInputStream(); File newFile = new File(realPath + filename); if (!newFile.exists()) { fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true,detailMsg}"); } else { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false,detailMsg:'文件已经存在!请重命名后上传!'}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + filename + " has existed!"); } } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
Code Sample 2:
public synchronized void connectURL(String url) throws IllegalArgumentException, IOException, MalformedURLException { URL myurl = new URL(url); InputStream in = myurl.openStream(); BufferedReader page = new BufferedReader(new InputStreamReader(in)); String ior = null; ArrayList nodesAL = new ArrayList(); while ((ior = page.readLine()) != null) { if (ior.trim().equals("")) continue; nodesAL.add(ior); } in.close(); Object[] nodesOA = nodesAL.toArray(); Node[] nodes = new Node[nodesOA.length]; for (int i = 0; i < nodesOA.length; i++) nodes[i] = TcbnetOrb.getInstance().getNode((String) nodesOA[i]); this.connect(nodes); }
|
11
|
Code Sample 1:
public static void copyAFile(final String entree, final String sortie) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(entree).getChannel(); out = new FileOutputStream(sortie).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Code Sample 2:
@SuppressWarnings("unchecked") public static void unzip(String input, String output) { try { if (!output.endsWith("/")) output = output + "/"; ZipFile zip = new ZipFile(input); Enumeration entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { FileUtils.forceMkdir(new File(output + entry.getName())); } else { FileOutputStream out = new FileOutputStream(output + entry.getName()); IOUtils.copy(zip.getInputStream(entry), out); IOUtils.closeQuietly(out); } } } catch (Exception e) { log.error("�����ҵ��ļ�:" + output, e); throw new RuntimeException("�����ҵ��ļ�:" + output, e); } }
|
11
|
Code Sample 1:
private static void addFile(File file, TarArchiveOutputStream taos) throws IOException { String filename = null; filename = file.getName(); TarArchiveEntry tae = new TarArchiveEntry(filename); tae.setSize(file.length()); taos.putArchiveEntry(tae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, taos); taos.closeArchiveEntry(); }
Code Sample 2:
@Override public void render(Output output) throws IOException { output.setStatus(statusCode, statusMessage); if (headersMap != null) { Iterator<Entry<String, String>> iterator = headersMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> header = iterator.next(); output.addHeader(header.getKey(), header.getValue()); } } if (file != null) { InputStream inputStream = new FileInputStream(file); try { output.open(); OutputStream out = output.getOutputStream(); IOUtils.copy(inputStream, out); } finally { inputStream.close(); output.close(); } } }
|
00
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
private void mergeOne(String level, char strand, String filename, Path outPath, FileSystem srcFS, FileSystem dstFS, Timer to) throws IOException { to.start(); final OutputStream outs = dstFS.create(new Path(outPath, filename)); final FileStatus[] parts = srcFS.globStatus(new Path(sorted ? getSortOutputDir(level, strand) : wrkDir, filename + "-[0-9][0-9][0-9][0-9][0-9][0-9]")); for (final FileStatus part : parts) { final InputStream ins = srcFS.open(part.getPath()); IOUtils.copyBytes(ins, outs, getConf(), false); ins.close(); } for (final FileStatus part : parts) srcFS.delete(part.getPath(), false); outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); outs.close(); System.out.printf("summarize :: Merged %s%c in %d.%03d s.\n", level, strand, to.stopS(), to.fms()); }
|
11
|
Code Sample 1:
public static void copyFile(File file, File destination) throws Exception { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(file)); out = new BufferedOutputStream(new FileOutputStream(destination)); int c; while ((c = in.read()) != -1) out.write(c); } finally { try { if (out != null) out.close(); } catch (Exception e) { } try { if (in != null) in.close(); } catch (Exception e) { } } }
Code Sample 2:
public static boolean copyFile(final File src, final File dst) throws FileNotFoundException { if (src == null || dst == null || src.equals(dst)) { return false; } boolean result = false; if (src.exists()) { if (dst.exists() && !dst.canWrite()) { return false; } final FileInputStream srcStream = new FileInputStream(src); final FileOutputStream dstStream = new FileOutputStream(dst); final FileChannel srcChannel = srcStream.getChannel(); final FileChannel dstChannel = dstStream.getChannel(); FileLock dstLock = null; FileLock srcLock = null; try { srcLock = srcChannel.tryLock(0, Long.MAX_VALUE, true); dstLock = dstChannel.tryLock(); if (srcLock != null && dstLock != null) { int maxCount = 64 * 1024 * 1024 - 32 * 1024; long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, maxCount, dstChannel); } } } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } finally { if (srcChannel != null) { try { if (srcLock != null) { srcLock.release(); } srcChannel.close(); srcStream.close(); } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } } if (dstChannel != null) { try { if (dstLock != null) { dstLock.release(); } dstChannel.close(); dstStream.close(); result = true; } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } } } } return result; }
|
00
|
Code Sample 1:
private void handleInterfaceDown(long eventID, long nodeID, String ipAddr, String eventTime) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (eventID == -1 || nodeID == -1 || ipAddr == null) { log.warn(EventConstants.INTERFACE_DOWN_EVENT_UEI + " ignored - info incomplete - eventid/nodeid/ip: " + eventID + "/" + nodeID + "/" + ipAddr); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement activeSvcsStmt = dbConn.prepareStatement(OutageConstants.DB_GET_ACTIVE_SERVICES_FOR_INTERFACE); PreparedStatement openStmt = dbConn.prepareStatement(OutageConstants.DB_OPEN_RECORD); PreparedStatement newOutageWriter = dbConn.prepareStatement(OutageConstants.DB_INS_NEW_OUTAGE); PreparedStatement getNextOutageIdStmt = dbConn.prepareStatement(OutageManagerConfigFactory.getInstance().getGetNextOutageID()); newOutageWriter = dbConn.prepareStatement(OutageConstants.DB_INS_NEW_OUTAGE); if (log.isDebugEnabled()) log.debug("handleInterfaceDown: creating new outage entries..."); activeSvcsStmt.setLong(1, nodeID); activeSvcsStmt.setString(2, ipAddr); ResultSet activeSvcsRS = activeSvcsStmt.executeQuery(); while (activeSvcsRS.next()) { long serviceID = activeSvcsRS.getLong(1); if (openOutageExists(dbConn, nodeID, ipAddr, serviceID)) { if (log.isDebugEnabled()) log.debug("handleInterfaceDown: " + nodeID + "/" + ipAddr + "/" + serviceID + " already down"); } else { long outageID = -1; ResultSet seqRS = getNextOutageIdStmt.executeQuery(); if (seqRS.next()) { outageID = seqRS.getLong(1); } seqRS.close(); newOutageWriter.setLong(1, outageID); newOutageWriter.setLong(2, eventID); newOutageWriter.setLong(3, nodeID); newOutageWriter.setString(4, ipAddr); newOutageWriter.setLong(5, serviceID); newOutageWriter.setTimestamp(6, convertEventTimeIntoTimestamp(eventTime)); newOutageWriter.executeUpdate(); if (log.isDebugEnabled()) log.debug("handleInterfaceDown: Recording new outage for " + nodeID + "/" + ipAddr + "/" + serviceID); } } activeSvcsRS.close(); try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("Outage recorded for all active services for " + nodeID + "/" + ipAddr); } catch (SQLException se) { log.warn("Rolling back transaction, interfaceDown could not be recorded for nodeid/ipAddr: " + nodeID + "/" + ipAddr, se); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } activeSvcsStmt.close(); openStmt.close(); newOutageWriter.close(); } catch (SQLException sqle) { log.warn("SQL exception while handling \'interfaceDown\'", sqle); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } }
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:
private void copy(URL url, IFile file, IProgressMonitor monitor) throws CoreException, IOException { InputStream input = null; try { input = url.openStream(); if (file.exists()) { file.setContents(input, IResource.FORCE, monitor); } else { file.create(input, IResource.FORCE, monitor); } } finally { if (input != null) { try { input.close(); } catch (IOException ignore) { } } } }
Code Sample 2:
public static int getContentLength(URL urlFileLocation) { HttpURLConnection connFile = null; int iFileSize = -1; try { connFile = (HttpURLConnection) urlFileLocation.openConnection(); connFile.setDoInput(true); InputStream is = connFile.getInputStream(); iFileSize = connFile.getContentLength(); is.close(); connFile.disconnect(); } catch (IOException e) { e.printStackTrace(); } return iFileSize; }
|
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 copyDirectory(File sourceDirectory, File targetDirectory) throws IOException { File[] sourceFiles = sourceDirectory.listFiles(FILE_FILTER); File[] sourceDirectories = sourceDirectory.listFiles(DIRECTORY_FILTER); targetDirectory.mkdirs(); if (sourceFiles != null && sourceFiles.length > 0) { for (int i = 0; i < sourceFiles.length; i++) { File sourceFile = sourceFiles[i]; FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(targetDirectory + File.separator + sourceFile.getName()); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(8192); long size = fcin.size(); long n = 0; while (n < size) { buf.clear(); if (fcin.read(buf) < 0) { break; } buf.flip(); n += fcout.write(buf); } fcin.close(); fcout.close(); fis.close(); fos.close(); } } if (sourceDirectories != null && sourceDirectories.length > 0) { for (int i = 0; i < sourceDirectories.length; i++) { File directory = sourceDirectories[i]; File newTargetDirectory = new File(targetDirectory, directory.getName()); copyDirectory(directory, newTargetDirectory); } } }
|
11
|
Code Sample 1:
private String fetchLocalPage(String page) throws IOException { final String fullUrl = HOST + page; LOG.debug("Fetching local page: " + fullUrl); URL url = new URL(fullUrl); URLConnection connection = url.openConnection(); StringBuilder sb = new StringBuilder(); BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = input.readLine()) != null) { sb.append(line).append("\n"); } } finally { if (input != null) try { input.close(); } catch (IOException e) { LOG.error("Could not close reader!", e); } } return sb.toString(); }
Code Sample 2:
public void getLyricsFromMAWebSite(TrackMABean tb) throws Exception { URL fileURL = new URL("http://www.metal-archives.com/viewlyrics.php?id=" + tb.getMaid()); URLConnection urlConnection = fileURL.openConnection(); InputStream httpStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1")); String ligne; boolean chargerLyrics = false; StringBuffer sb = new StringBuffer(""); String lyrics = null; while ((ligne = br.readLine()) != null) { log.debug("==> " + ligne); if (chargerLyrics && ligne.indexOf("<center>") != -1) { break; } if (chargerLyrics) { sb.append(ligne.trim()); } if (!chargerLyrics && ligne.indexOf("<center>") != -1) { chargerLyrics = true; } } lyrics = sb.toString(); lyrics = lyrics.replaceAll("<br>", "\n").trim(); log.debug("Parole : " + lyrics); tb.setLyrics(lyrics); br.close(); httpStream.close(); }
|
11
|
Code Sample 1:
private boolean copyFile(File inFile, File outFile) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(inFile)); writer = new BufferedWriter(new FileWriter(outFile)); while (reader.ready()) { writer.write(reader.read()); } writer.flush(); } catch (IOException ex) { ex.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { ex.printStackTrace(); return false; } } if (writer != null) { try { writer.close(); } catch (IOException ex) { return false; } } } return true; }
Code Sample 2:
public static boolean cpy(File a, File b) { try { FileInputStream astream = null; FileOutputStream bstream = null; try { astream = new FileInputStream(a); bstream = new FileOutputStream(b); long flength = a.length(); int bufsize = (int) Math.min(flength, 1024); byte buf[] = new byte[bufsize]; long n = 0; while (n < flength) { int naread = astream.read(buf); bstream.write(buf, 0, naread); n += naread; } } finally { if (astream != null) astream.close(); if (bstream != null) bstream.close(); } } catch (IOException e) { e.printStackTrace(); return false; } return true; }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private void stripOneFilex(File inFile, File outFile) throws IOException { StreamTokenizer reader = new StreamTokenizer(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); reader.slashSlashComments(false); reader.slashStarComments(false); reader.eolIsSignificant(true); int token; while ((token = reader.nextToken()) != StreamTokenizer.TT_EOF) { switch(token) { case StreamTokenizer.TT_NUMBER: throw new IllegalStateException("didn't expect TT_NUMBER: " + reader.nval); case StreamTokenizer.TT_WORD: System.out.print(reader.sval); writer.write("WORD:" + reader.sval, 0, reader.sval.length()); default: char outChar = (char) reader.ttype; System.out.print(outChar); writer.write(outChar); } } }
|
00
|
Code Sample 1:
@Override protected Drawing construct() throws IOException { Drawing result; System.out.println("getParameter.datafile:" + getParameter("datafile")); if (getParameter("data") != null) { NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), new StringReader(getParameter("data"))); result = (Drawing) domi.readObject(0); } else if (getParameter("datafile") != null) { URL url = new URL(getDocumentBase(), getParameter("datafile")); InputStream in = url.openConnection().getInputStream(); try { NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), in); result = (Drawing) domi.readObject(0); } finally { in.close(); } } else { result = null; } return result; }
Code Sample 2:
@Override public Reader openReader(final Charset charset) throws LocatorException { try { if (charset != null) { return new InputStreamReader(url.openStream(), charset); } return new InputStreamReader(url.openStream()); } catch (final IOException e) { throw new LocatorException("Failed to read from URL: " + url, e); } }
|
00
|
Code Sample 1:
@Override public DataUpdateResult<Record> archiveRecord(String authToken, Record record, Filter filter, Field sourceField, InputModel inputmodel) throws DataOperationException { validateUserIsSignedOn(authToken); validateUserHasAdminRights(authToken); DataUpdateResult<Record> recordUpdateResult = new DataUpdateResult<Record>(); if (record != null) { Connection connection = null; boolean archived = false; try { long userId = getSignedOnUser(authToken).getUserId(); connection = DatabaseConnector.getConnection(); connection.setAutoCommit(false); recordUpdateResult.setMessage(messages.server_record_delete_success("")); recordUpdateResult.setSuccessful(true); String sql = "update tms.records set archivedtimestamp = now() where recordid = ?"; PreparedStatement updateRecord = connection.prepareStatement(sql); updateRecord.setLong(1, record.getRecordid()); int recordArchived = 0; recordArchived = updateRecord.executeUpdate(); if (recordArchived > 0) AuditTrailManager.updateAuditTrail(connection, AuditTrailManager.createAuditTrailEvent(record, userId, AuditableEvent.EVENTYPE_DELETE), authToken, getSession()); TopicUpdateServiceImpl.archiveRecordTopics(connection, record.getTopics(), record.getRecordid()); ArrayList<RecordAttribute> recordAttributes = record.getRecordattributes(); if (recordAttributes != null && recordAttributes.size() > 0) { Iterator<RecordAttribute> rItr = recordAttributes.iterator(); while (rItr.hasNext()) { RecordAttribute r = rItr.next(); String rAtSql = "update tms.recordattributes set archivedtimestamp = now() where recordattributeid = ?"; PreparedStatement updateRecordAttribute = connection.prepareStatement(rAtSql); updateRecordAttribute.setLong(1, r.getRecordattributeid()); int recordAttribArchived = 0; recordAttribArchived = updateRecordAttribute.executeUpdate(); if (recordAttribArchived > 0) AuditTrailManager.updateAuditTrail(connection, AuditTrailManager.createAuditTrailEvent(r, userId, AuditableEvent.EVENTYPE_DELETE), authToken, getSession()); } } ArrayList<Term> terms = record.getTerms(); Iterator<Term> termsItr = terms.iterator(); while (termsItr.hasNext()) { Term term = termsItr.next(); TermUpdater.archiveTerm(connection, term, userId, authToken, getSession()); } connection.commit(); archived = true; if (filter != null) RecordIdTracker.refreshRecordIdsInSessionByFilter(this.getThreadLocalRequest().getSession(), connection, true, filter, sourceField, authToken); else RecordIdTracker.refreshRecordIdsInSession(this.getThreadLocalRequest().getSession(), connection, false, authToken); RecordRetrievalServiceImpl retriever = new RecordRetrievalServiceImpl(); RecordIdTracker.refreshRecordIdsInSession(this.getThreadLocalRequest().getSession(), connection, false, authToken); Record updatedRecord = retriever.retrieveRecordByRecordId(initSignedOnUser(authToken), record.getRecordid(), this.getThreadLocalRequest().getSession(), false, inputmodel, authToken); recordUpdateResult.setResult(updatedRecord); } catch (Exception e) { if (!archived && connection != null) { try { connection.rollback(); } catch (SQLException e1) { LogUtility.log(Level.SEVERE, getSession(), messages.log_db_rollback(""), e1, authToken); e1.printStackTrace(); } } recordUpdateResult.setFailed(true); if (archived) { recordUpdateResult.setMessage(messages.server_record_delete_retrieve("")); recordUpdateResult.setException(e); LogUtility.log(Level.SEVERE, getSession(), messages.server_record_delete_retrieve(""), e, authToken); } else { recordUpdateResult.setMessage(messages.server_record_delete_fail("")); recordUpdateResult.setException(new PersistenceException(e)); LogUtility.log(Level.SEVERE, getSession(), messages.server_record_delete_fail(""), e, authToken); } GWT.log(recordUpdateResult.getMessage(), e); } finally { try { if (connection != null) { connection.setAutoCommit(true); connection.close(); } } catch (Exception e) { LogUtility.log(Level.SEVERE, getSession(), messages.log_db_close(""), e, authToken); } } } return recordUpdateResult; }
Code Sample 2:
protected static List<Pattern> getBotPatterns() { List<Pattern> patterns = new ArrayList<Pattern>(); try { Enumeration<URL> urls = AbstractPustefixRequestHandler.class.getClassLoader().getResources("META-INF/org/pustefixframework/http/bot-user-agents.txt"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf8")); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!line.startsWith("#")) { Pattern pattern = Pattern.compile(line); patterns.add(pattern); } } in.close(); } } catch (IOException e) { throw new RuntimeException("Error reading bot user-agent configuration", e); } return patterns; }
|
11
|
Code Sample 1:
public void convert(CSVReader reader, Writer writer, int nbTotalRows) throws IOException, InterruptedException { Validate.notNull(reader, "CSVReader"); Validate.notNull(writer, "Writer"); Writer bufferedWriter = new BufferedWriter(writer); File fileForColsDef = createTempFileForCss(); BufferedWriter colsDefWriter = new BufferedWriter(new FileWriter(fileForColsDef)); File fileForTable = createTempFileForTable(); BufferedWriter tableWriter = new BufferedWriter(new FileWriter(fileForTable)); try { int currentRow = 0; String[] nextLine = reader.readNext(); if (nextLine != null) { int[] colsCharCount = new int[nextLine.length]; writeTableRowHeader(tableWriter, nextLine); while ((nextLine = reader.readNext()) != null) { currentRow++; if (progress != null) { float percent = ((float) currentRow / (float) nbTotalRows) * 100f; progress.updateProgress(ConvertionStepEnum.PROCESSING_ROWS, percent); } writeTableRow(tableWriter, nextLine, colsCharCount); } writeTableStart(colsDefWriter, colsCharCount); writeColsDefinitions(colsDefWriter, colsCharCount); } writeConverterInfos(bufferedWriter); writeTableEnd(tableWriter); flushAndClose(tableWriter); flushAndClose(colsDefWriter); BufferedReader colsDefReader = new BufferedReader(new FileReader(fileForColsDef)); BufferedReader tableReader = new BufferedReader(new FileReader(fileForTable)); mergeFiles(bufferedWriter, colsDefReader, tableReader); } finally { closeQuietly(tableWriter); closeQuietly(colsDefWriter); fileForTable.delete(); fileForColsDef.delete(); } }
Code Sample 2:
public void testCreateNewXMLFile() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource emptySource = loadTestSource(); assertEquals(false, emptySource.exists()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } InputStream expected = getClass().getResourceAsStream(CONTENT_FILE); JCRNodeSource persistentSource = loadTestSource(); assertEquals(true, persistentSource.exists()); InputStream actual = persistentSource.getInputStream(); try { assertTrue(isXmlEqual(expected, actual)); } finally { expected.close(); actual.close(); } JCRNodeSource tmpSrc = (JCRNodeSource) resolveSource(BASE_URL + "users/alexander.saar"); persistentSource.delete(); tmpSrc.delete(); }
|
11
|
Code Sample 1:
public String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.err.println(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static String toMD5Sum(String arg0) { String ret; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(arg0.getBytes()); ret = toHexString(md.digest()); } catch (Exception e) { ret = arg0; } return ret; }
|
00
|
Code Sample 1:
public static String replace(URL url, Replacer replacer) throws Exception { URLConnection con = url.openConnection(); InputStreamReader reader = new InputStreamReader(con.getInputStream()); StringWriter wr = new StringWriter(); int c; StringBuffer token = null; while ((c = reader.read()) != -1) { if (c == '@') { if (token == null) { token = new StringBuffer(); } else { String val = replacer.replace(token.toString()); if (val != null) { wr.write(val); token = null; } else { wr.write('@'); wr.write(token.toString()); token.delete(0, token.length()); } } } else { if (token == null) { wr.write((char) c); } else { token.append((char) c); } } } if (token != null) { wr.write('@'); wr.write(token.toString()); } return wr.toString(); }
Code Sample 2:
protected static void copyFile(File in, File out) throws IOException { java.io.FileWriter filewriter = null; java.io.FileReader filereader = null; try { filewriter = new java.io.FileWriter(out); filereader = new java.io.FileReader(in); char[] buf = new char[4096]; int nread = filereader.read(buf, 0, 4096); while (nread >= 0) { filewriter.write(buf, 0, nread); nread = filereader.read(buf, 0, 4096); } buf = null; } finally { try { filereader.close(); } catch (Throwable t) { } try { filewriter.close(); } catch (Throwable t) { } } }
|
00
|
Code Sample 1:
public static String encrypt(String text) { char[] toEncrypt = text.toCharArray(); StringBuffer hexString = new StringBuffer(); try { MessageDigest dig = MessageDigest.getInstance("MD5"); dig.reset(); String pw = ""; for (int i = 0; i < toEncrypt.length; i++) { pw += toEncrypt[i]; } dig.update(pw.getBytes()); byte[] digest = dig.digest(); int digestLength = digest.length; for (int i = 0; i < digestLength; i++) { hexString.append(hexDigit(digest[i])); } } catch (java.security.NoSuchAlgorithmException ae) { ae.printStackTrace(); } return hexString.toString(); }
Code Sample 2:
public String preProcessHTML(String uri) { final StringBuffer buf = new StringBuffer(); try { HTMLDocument doc = new HTMLDocument() { public HTMLEditorKit.ParserCallback getReader(int pos) { return new HTMLEditorKit.ParserCallback() { public void handleText(char[] data, int pos) { buf.append(data); buf.append('\n'); } }; } }; URL url = new URI(uri).toURL(); URLConnection conn = url.openConnection(); Reader rd = new InputStreamReader(conn.getInputStream()); new ParserDelegator().parse(rd, doc.getReader(0), Boolean.TRUE); } catch (MalformedURLException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (URISyntaxException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } return buf.toString(); }
|
00
|
Code Sample 1:
private Document saveFile(Document document, File file) throws Exception { List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { preference = preferences.get(0); } SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); String repo = preference.getRepository(); Calendar calendar = Calendar.getInstance(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(sdf.format(calendar.getTime())); sbFolder.append(File.separator).append(calendar.get(Calendar.HOUR_OF_DAY)); File folder = new File(sbRepo.append(sbFolder).toString()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()); StringBuffer fname = new StringBuffer(document.getId().toString()); fname.append(".").append(document.getExt()); sbFile.append(File.separator).append(fname); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } return document; }
Code Sample 2:
public static byte[] hash(String identifier) { if (function.equals("SHA-1")) { try { MessageDigest md = MessageDigest.getInstance(function); md.reset(); byte[] code = md.digest(identifier.getBytes()); byte[] value = new byte[KEY_LENGTH / 8]; int shrink = code.length / value.length; int bitCount = 1; for (int j = 0; j < code.length * 8; j++) { int currBit = ((code[j / 8] & (1 << (j % 8))) >> j % 8); if (currBit == 1) bitCount++; if (((j + 1) % shrink) == 0) { int shrinkBit = (bitCount % 2 == 0) ? 0 : 1; value[j / shrink / 8] |= (shrinkBit << ((j / shrink) % 8)); bitCount = 1; } } return value; } catch (Exception e) { e.printStackTrace(); } } if (function.equals("CRC32")) { CRC32 crc32 = new CRC32(); crc32.reset(); crc32.update(identifier.getBytes()); long code = crc32.getValue(); code &= (0xffffffffffffffffL >>> (64 - KEY_LENGTH)); byte[] value = new byte[KEY_LENGTH / 8]; for (int i = 0; i < value.length; i++) { value[value.length - i - 1] = (byte) ((code >> 8 * i) & 0xff); } return value; } if (function.equals("Java")) { int code = identifier.hashCode(); code &= (0xffffffff >>> (32 - KEY_LENGTH)); byte[] value = new byte[KEY_LENGTH / 8]; for (int i = 0; i < value.length; i++) { value[value.length - i - 1] = (byte) ((code >> 8 * i) & 0xff); } return value; } return null; }
|
00
|
Code Sample 1:
private String readUrl(String feature) { StringBuffer content = new StringBuffer(); try { URL url = new URL(feature); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { content.append(line); } conn.disconnect(); } catch (Exception e) { } return content.toString(); }
Code Sample 2:
public static void copyFile(File file, String pathExport) throws IOException { File out = new File(pathExport); FileChannel sourceChannel = new FileInputStream(file).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
00
|
Code Sample 1:
public void loadScripts() { org.apache.batik.script.Window window = null; NodeList scripts = document.getElementsByTagNameNS(SVGConstants.SVG_NAMESPACE_URI, SVGConstants.SVG_SCRIPT_TAG); int len = scripts.getLength(); if (len == 0) { return; } for (int i = 0; i < len; i++) { Element script = (Element) scripts.item(i); String type = script.getAttributeNS(null, SVGConstants.SVG_TYPE_ATTRIBUTE); if (type.length() == 0) { type = SVGConstants.SVG_SCRIPT_TYPE_DEFAULT_VALUE; } if (type.equals(SVGConstants.SVG_SCRIPT_TYPE_JAVA)) { try { String href = XLinkSupport.getXLinkHref(script); ParsedURL purl = new ParsedURL(XMLBaseSupport.getCascadedXMLBase(script), href); checkCompatibleScriptURL(type, purl); DocumentJarClassLoader cll; URL docURL = null; try { docURL = new URL(docPURL.toString()); } catch (MalformedURLException mue) { } cll = new DocumentJarClassLoader(new URL(purl.toString()), docURL); URL url = cll.findResource("META-INF/MANIFEST.MF"); if (url == null) { continue; } Manifest man = new Manifest(url.openStream()); String sh; sh = man.getMainAttributes().getValue("Script-Handler"); if (sh != null) { ScriptHandler h; h = (ScriptHandler) cll.loadClass(sh).newInstance(); if (window == null) { window = createWindow(); } h.run(document, window); } sh = man.getMainAttributes().getValue("SVG-Handler-Class"); if (sh != null) { EventListenerInitializer initializer; initializer = (EventListenerInitializer) cll.loadClass(sh).newInstance(); if (window == null) { window = createWindow(); } initializer.initializeEventListeners((SVGDocument) document); } } catch (Exception e) { if (userAgent != null) { userAgent.displayError(e); } } continue; } Interpreter interpreter = getInterpreter(type); if (interpreter == null) continue; try { String href = XLinkSupport.getXLinkHref(script); String desc = null; Reader reader; if (href.length() > 0) { desc = href; ParsedURL purl = new ParsedURL(XMLBaseSupport.getCascadedXMLBase(script), href); checkCompatibleScriptURL(type, purl); reader = new InputStreamReader(purl.openStream()); } else { checkCompatibleScriptURL(type, docPURL); DocumentLoader dl = bridgeContext.getDocumentLoader(); Element e = script; SVGDocument d = (SVGDocument) e.getOwnerDocument(); int line = dl.getLineNumber(script); desc = Messages.formatMessage(INLINE_SCRIPT_DESCRIPTION, new Object[] { d.getURL(), "<" + script.getNodeName() + ">", new Integer(line) }); Node n = script.getFirstChild(); if (n != null) { StringBuffer sb = new StringBuffer(); while (n != null) { if (n.getNodeType() == Node.CDATA_SECTION_NODE || n.getNodeType() == Node.TEXT_NODE) sb.append(n.getNodeValue()); n = n.getNextSibling(); } reader = new StringReader(sb.toString()); } else { continue; } } interpreter.evaluate(reader, desc); } catch (IOException e) { if (userAgent != null) { userAgent.displayError(e); } return; } catch (InterpreterException e) { System.err.println("InterpExcept: " + e); handleInterpreterException(e); return; } catch (SecurityException e) { if (userAgent != null) { userAgent.displayError(e); } } } }
Code Sample 2:
@Override public String entryToObject(TupleInput input) { boolean zipped = input.readBoolean(); if (!zipped) { return input.readString(); } int len = input.readInt(); try { byte array[] = new byte[len]; input.read(array); GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(array)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyTo(in, out); in.close(); out.close(); return new String(out.toByteArray()); } catch (IOException err) { throw new RuntimeException(err); } }
|
00
|
Code Sample 1:
public Login authenticateClient() { Object o; String user, password; Vector<Login> clientLogins = ClientLoginsTableModel.getClientLogins(); Login login = null; try { socket.setSoTimeout(25000); objectOut.writeObject("JFRITZ SERVER 1.1"); objectOut.flush(); o = objectIn.readObject(); if (o instanceof String) { user = (String) o; objectOut.flush(); for (Login l : clientLogins) { if (l.getUser().equals(user)) { login = l; break; } } if (login != null) { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(login.getPassword().getBytes()); DESKeySpec desKeySpec = new DESKeySpec(md.digest()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); desCipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] dataKeySeed = new byte[32]; Random random = new Random(); random.nextBytes(dataKeySeed); md.reset(); md.update(dataKeySeed); dataKeySeed = md.digest(); SealedObject dataKeySeedSealed; dataKeySeedSealed = new SealedObject(dataKeySeed, desCipher); objectOut.writeObject(dataKeySeedSealed); objectOut.flush(); desKeySpec = new DESKeySpec(dataKeySeed); secretKey = keyFactory.generateSecret(desKeySpec); inCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); outCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); inCipher.init(Cipher.DECRYPT_MODE, secretKey); outCipher.init(Cipher.ENCRYPT_MODE, secretKey); SealedObject sealedObject = (SealedObject) objectIn.readObject(); o = sealedObject.getObject(inCipher); if (o instanceof String) { String response = (String) o; if (response.equals("OK")) { SealedObject ok_sealed = new SealedObject("OK", outCipher); objectOut.writeObject(ok_sealed); return login; } else { Debug.netMsg("Client sent false response to challenge!"); } } else { Debug.netMsg("Client sent false object as response to challenge!"); } } else { Debug.netMsg("client sent unkown username: " + user); } } } catch (IllegalBlockSizeException e) { Debug.netMsg("Wrong blocksize for sealed object!"); Debug.error(e.toString()); e.printStackTrace(); } catch (ClassNotFoundException e) { Debug.netMsg("received unrecognized object from client!"); Debug.error(e.toString()); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { Debug.netMsg("MD5 Algorithm not present in this JVM!"); Debug.error(e.toString()); e.printStackTrace(); } catch (InvalidKeySpecException e) { Debug.netMsg("Error generating cipher, problems with key spec?"); Debug.error(e.toString()); e.printStackTrace(); } catch (InvalidKeyException e) { Debug.netMsg("Error genertating cipher, problems with key?"); Debug.error(e.toString()); e.printStackTrace(); } catch (NoSuchPaddingException e) { Debug.netMsg("Error generating cipher, problems with padding?"); Debug.error(e.toString()); e.printStackTrace(); } catch (IOException e) { Debug.netMsg("Error authenticating client!"); Debug.error(e.toString()); e.printStackTrace(); } catch (BadPaddingException e) { Debug.netMsg("Bad padding exception!"); Debug.error(e.toString()); e.printStackTrace(); } return null; }
Code Sample 2:
public static void copy(File src, File dest) throws IOException { OutputStream stream = new FileOutputStream(dest); FileInputStream fis = new FileInputStream(src); byte[] buffer = new byte[16384]; while (fis.available() != 0) { int read = fis.read(buffer); stream.write(buffer, 0, read); } stream.flush(); }
|
00
|
Code Sample 1:
private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public String encrypt(String pwd) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.out.println("Error"); } try { md5.update(pwd.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "That is not a valid encrpytion type"); } byte raw[] = md5.digest(); String empty = ""; String hash = ""; for (byte b : raw) { String tmp = empty + Integer.toHexString(b & 0xff); if (tmp.length() == 1) { tmp = 0 + tmp; } hash += tmp; } return hash; }
|
11
|
Code Sample 1:
private void copyJdbcDriverToWL(final WLPropertyPage page) { final File url = new File(page.getDomainDirectory()); final File lib = new File(url, "lib"); final File mysqlLibrary = new File(lib, NexOpenUIActivator.getDefault().getMySQLDriver()); if (!mysqlLibrary.exists()) { InputStream driver = null; FileOutputStream fos = null; try { driver = AppServerPropertyPage.toInputStream(new Path("jdbc/" + NexOpenUIActivator.getDefault().getMySQLDriver())); fos = new FileOutputStream(mysqlLibrary); IOUtils.copy(driver, fos); } catch (final IOException e) { Logger.log(Logger.ERROR, "Could not copy the MySQL Driver jar file to Bea WL", e); final Status status = new Status(Status.ERROR, NexOpenUIActivator.PLUGIN_ID, Status.ERROR, "Could not copy the MySQL Driver jar file to Bea WL", e); ErrorDialog.openError(page.getShell(), "Bea WebLogic MSQL support", "Could not copy the MySQL Driver jar file to Bea WL", status); } finally { try { if (driver != null) { driver.close(); driver = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } }
Code Sample 2:
public static void _save(PortletRequest req, PortletResponse res, PortletConfig config, ActionForm form) throws Exception { try { String filePath = getUserManagerConfigPath() + "user_manager_config.properties"; String tmpFilePath = UtilMethods.getTemporaryDirPath() + "user_manager_config_properties.tmp"; File from = new java.io.File(tmpFilePath); from.createNewFile(); File to = new java.io.File(filePath); to.createNewFile(); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (NonWritableChannelException we) { } catch (IOException e) { Logger.error(UserManagerPropertiesFactory.class, "Property File save Failed " + e, e); } SessionMessages.add(req, "message", "message.usermanager.display.save"); }
|
11
|
Code Sample 1:
public static void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } }
Code Sample 2:
public static void decryptFile(String input, String output, String pwd) throws Exception { CipherInputStream in; OutputStream out; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.DECRYPT_MODE, key); in = new CipherInputStream(new FileInputStream(input), cipher); out = new FileOutputStream(output); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
|
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 public void save(File folder) { actInstance = instance; this.setProperty(EsomMapper.PROPERTY_INSTANCE, String.valueOf(actInstance)); log.debug("instance: " + this.getProperty(EsomMapper.PROPERTY_INSTANCE)); if (this.getProperty(EsomMapper.PROPERTY_LRN_RADIO_SELECTED) == EsomMapper.RADIO_LOAD_SELECTED) { File src = new File(this.getProperty(EsomMapper.PROPERTY_LRN_FILE)); if (src.getParent() != folder.getPath()) { log.debug("saving lrn file in save folder " + folder.getPath()); File dst = new File(folder.getAbsolutePath() + File.separator + src.getName() + String.valueOf(actInstance)); try { FileReader fr = new FileReader(src); BufferedReader br = new BufferedReader(fr); dst.createNewFile(); FileWriter fw = new FileWriter(dst); BufferedWriter bw = new BufferedWriter(fw); int i = 0; while ((i = br.read()) != -1) bw.write(i); bw.flush(); bw.close(); br.close(); fr.close(); } catch (FileNotFoundException e) { log.error("Error while opening lrn sourcefile! Saving wasn't possible!!!"); e.printStackTrace(); } catch (IOException e) { log.error("Error while creating lrn destfile! Creating wasn't possible!!!"); e.printStackTrace(); } this.setProperty(EsomMapper.PROPERTY_LRN_FILE, dst.getName()); log.debug("done saving lrn file"); } } if (this.getProperty(EsomMapper.PROPERTY_WTS_RADIO_SELECTED) == EsomMapper.RADIO_LOAD_SELECTED) { File src = new File(this.getProperty(EsomMapper.PROPERTY_WTS_FILE)); if (src.getParent() != folder.getPath()) { log.debug("saving wts file in save folder " + folder.getPath()); File dst = new File(folder.getAbsolutePath() + File.separator + src.getName() + String.valueOf(actInstance)); try { FileReader fr = new FileReader(src); BufferedReader br = new BufferedReader(fr); dst.createNewFile(); FileWriter fw = new FileWriter(dst); BufferedWriter bw = new BufferedWriter(fw); int i = 0; while ((i = br.read()) != -1) bw.write(i); bw.flush(); bw.close(); br.close(); fr.close(); } catch (FileNotFoundException e) { log.error("Error while opening wts sourcefile! Saving wasn't possible!!!"); e.printStackTrace(); } catch (IOException e) { log.error("Error while creating wts destfile! Creating wasn't possible!!!"); e.printStackTrace(); } this.setProperty(EsomMapper.PROPERTY_WTS_FILE, dst.getName()); log.debug("done saving wts file"); } } if (this.getProperty(EsomMapper.PROPERTY_LRN_RADIO_SELECTED) == EsomMapper.RADIO_SELECT_FROM_DATANAV_SELECTED) { this.setProperty(EsomMapper.PROPERTY_LRN_FILE, "EsomMapper" + this.actInstance + ".lrn"); File dst = new File(folder + File.separator + this.getProperty(EsomMapper.PROPERTY_LRN_FILE)); try { FileWriter fw = new FileWriter(dst); BufferedWriter bw = new BufferedWriter(fw); bw.write("# EsomMapper LRN save file\n"); bw.write("% " + this.inputVectors.getNumRows() + "\n"); bw.write("% " + this.inputVectors.getNumCols() + "\n"); bw.write("% 9"); for (IColumn col : this.inputVectors.getColumns()) { if (col.getType() == IClusterNumber.class) bw.write("\t2"); else if (col.getType() == String.class) bw.write("\t8"); else bw.write("\t1"); } bw.write("\n% Key"); for (IColumn col : this.inputVectors.getColumns()) { bw.write("\t" + col.getLabel()); } bw.write("\n"); int keyIterator = 0; for (Vector<Object> row : this.inputVectors.getGrid()) { bw.write(this.inputVectors.getKey(keyIterator++).toString()); for (Object point : row) bw.write("\t" + point.toString()); bw.write("\n"); } bw.flush(); fw.flush(); bw.close(); fw.close(); } catch (IOException e) { e.printStackTrace(); } this.setProperty(EsomMapper.PROPERTY_LRN_RADIO_SELECTED, EsomMapper.RADIO_LOAD_SELECTED); } if (this.getProperty(EsomMapper.PROPERTY_WTS_RADIO_SELECTED) == EsomMapper.RADIO_SELECT_FROM_DATANAV_SELECTED) { this.setProperty(EsomMapper.PROPERTY_WTS_FILE, "EsomMapper" + this.actInstance + ".wts"); MyRetina tempRetina = new MyRetina(this.outputRetina.getNumRows(), this.outputRetina.getNumCols(), this.outputRetina.getDim(), this.outputRetina.getDistanceFunction(), this.outputRetina.isToroid()); for (int row = 0; row < this.outputRetina.getNumRows(); row++) { for (int col = 0; col < this.outputRetina.getNumCols(); col++) { for (int dim = 0; dim < this.outputRetina.getDim(); dim++) { tempRetina.setNeuron(row, col, dim, this.outputRetina.getPointasDoubleArray(row, col)[dim]); } } } EsomIO.writeWTSFile(folder + File.separator + this.getProperty(EsomMapper.PROPERTY_WTS_FILE), tempRetina); this.setProperty(EsomMapper.PROPERTY_WTS_RADIO_SELECTED, EsomMapper.RADIO_LOAD_SELECTED); } EsomMapper.instance++; }
|
00
|
Code Sample 1:
public OAuthResponseMessage access(OAuthMessage request, net.oauth.ParameterStyle style) throws IOException { HttpMessage httpRequest = HttpMessage.newRequest(request, style); HttpResponseMessage httpResponse = http.execute(httpRequest, httpParameters); httpResponse = HttpMessageDecoder.decode(httpResponse); return new OAuthResponseMessage(httpResponse); }
Code Sample 2:
public static String calcolaMd5(String messaggio) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } md.reset(); md.update(messaggio.getBytes()); byte[] impronta = md.digest(); return new String(impronta); }
|
11
|
Code Sample 1:
static List<String> readZipFilesOftypeToFolder(String zipFileLocation, String outputDir, String fileType) { List<String> list = new ArrayList<String>(); ZipFile zipFile = readZipFile(zipFileLocation); FileOutputStream output = null; InputStream inputStream = null; Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries(); try { while (entries.hasMoreElements()) { java.util.zip.ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName != null && entryName.toLowerCase().endsWith(fileType)) { inputStream = zipFile.getInputStream(entry); String fileName = outputDir + entryName.substring(entryName.lastIndexOf("/")); File file = new File(fileName); output = new FileOutputStream(file); IOUtils.copy(inputStream, output); list.add(fileName); } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (output != null) output.close(); if (inputStream != null) inputStream.close(); if (zipFile != null) zipFile.close(); } catch (IOException e) { throw new RuntimeException(e); } } return list; }
Code Sample 2:
public void concatFiles() throws IOException { Writer writer = null; try { final File targetFile = new File(getTargetDirectory(), getTargetFile()); targetFile.getParentFile().mkdirs(); if (null != getEncoding()) { getLog().info("Writing aggregated file with encoding '" + getEncoding() + "'"); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), getEncoding())); } else { getLog().info("WARNING: writing aggregated file with system encoding"); writer = new FileWriter(targetFile); } for (File file : getFiles()) { Reader reader = null; try { if (null != getEncoding()) { getLog().info("Reading file " + file.getCanonicalPath() + " with encoding '" + getEncoding() + "'"); reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), getEncoding())); } else { getLog().info("WARNING: Reading file " + file.getCanonicalPath() + " with system encoding"); reader = new FileReader(file); } IOUtils.copy(reader, writer); final String delimiter = getDelimiter(); if (delimiter != null) { writer.write(delimiter.toCharArray()); } } finally { IOUtils.closeQuietly(reader); } } } finally { IOUtils.closeQuietly(writer); } }
|
11
|
Code Sample 1:
public static String generateHash(String message) throws NoSuchAlgorithmException, UnsupportedEncodingException, DigestException { MessageDigest digest; digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(message.getBytes("iso-8859-1"), 0, message.length()); byte[] output = new byte[20]; digest.digest(output, 0, output.length); return convertToHex(output); }
Code Sample 2:
@Test public void testRegisterOwnJceProvider() throws Exception { MyTestProvider provider = new MyTestProvider(); assertTrue(-1 != Security.addProvider(provider)); MessageDigest messageDigest = MessageDigest.getInstance("SHA-1", MyTestProvider.NAME); assertEquals(MyTestProvider.NAME, messageDigest.getProvider().getName()); messageDigest.update("hello world".getBytes()); byte[] result = messageDigest.digest(); Assert.assertArrayEquals("hello world".getBytes(), result); Security.removeProvider(MyTestProvider.NAME); }
|
00
|
Code Sample 1:
public static String sendGetRequest(String endpoint, String requestParameters) { if (endpoint == null) return null; String result = null; if (endpoint.startsWith("http://")) { try { StringBuffer data = new StringBuffer(); String urlStr = endpoint; if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } URL url = new URL(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); result = sb.toString(); } catch (Exception e) { Logger.getLogger(HTTPClient.class.getClass().getName()).log(Level.FINE, "Could not connect to URL, is the service online?"); } } return result; }
Code Sample 2:
public static final void copyFile(File source, File destination) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(destination).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
|
11
|
Code Sample 1:
public static void copyFile(String source, String destination, boolean overwrite) { File sourceFile = new File(source); try { File destinationFile = new File(destination); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destinationFile)); int temp = 0; while ((temp = bis.read()) != -1) bos.write(temp); bis.close(); bos.close(); } catch (Exception e) { } return; }
Code Sample 2:
public void handleEvent(Event event) { if (fileDialog == null) { fileDialog = new FileDialog(getShell(), SWT.OPEN); fileDialog.setText("Open device profile file..."); fileDialog.setFilterNames(new String[] { "Device profile (*.jar)" }); fileDialog.setFilterExtensions(new String[] { "*.jar" }); } fileDialog.open(); if (fileDialog.getFileName() != null) { File file; String manifestDeviceName = null; URL[] urls = new URL[1]; ArrayList descriptorEntries = new ArrayList(); try { file = new File(fileDialog.getFilterPath(), fileDialog.getFileName()); JarFile jar = new JarFile(file); Manifest manifest = jar.getManifest(); if (manifest != null) { Attributes attrs = manifest.getMainAttributes(); manifestDeviceName = attrs.getValue("Device-Name"); } for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorEntries.add(entry); } } jar.close(); urls[0] = file.toURL(); } catch (IOException ex) { Message.error("Error reading file: " + fileDialog.getFileName() + ", " + Message.getCauseMessage(ex), ex); return; } if (descriptorEntries.size() == 0) { Message.error("Cannot find any device profile in file: " + fileDialog.getFileName()); return; } if (descriptorEntries.size() > 1) { manifestDeviceName = null; } ClassLoader classLoader = Common.createExtensionsClassLoader(urls); HashMap devices = new HashMap(); for (Iterator it = descriptorEntries.iterator(); it.hasNext(); ) { JarEntry entry = (JarEntry) it.next(); try { devices.put(entry.getName(), DeviceImpl.create(emulatorContext, classLoader, entry.getName(), SwtDevice.class)); } catch (IOException ex) { Message.error("Error parsing device profile, " + Message.getCauseMessage(ex), ex); return; } } for (int i = 0; i < deviceModel.size(); i++) { DeviceEntry entry = (DeviceEntry) deviceModel.elementAt(i); if (devices.containsKey(entry.getDescriptorLocation())) { devices.remove(entry.getDescriptorLocation()); } } if (devices.size() == 0) { Message.info("Device profile already added"); return; } try { File deviceFile = new File(Config.getConfigPath(), file.getName()); if (deviceFile.exists()) { deviceFile = File.createTempFile("device", ".jar", Config.getConfigPath()); } IOUtils.copyFile(file, deviceFile); DeviceEntry entry = null; for (Iterator it = devices.keySet().iterator(); it.hasNext(); ) { String descriptorLocation = (String) it.next(); Device device = (Device) devices.get(descriptorLocation); if (manifestDeviceName != null) { entry = new DeviceEntry(manifestDeviceName, deviceFile.getName(), descriptorLocation, false); } else { entry = new DeviceEntry(device.getName(), deviceFile.getName(), descriptorLocation, false); } deviceModel.addElement(entry); for (int i = 0; i < deviceModel.size(); i++) { if (deviceModel.elementAt(i) == entry) { lsDevices.add(entry.getName()); lsDevices.select(i); } } Config.addDeviceEntry(entry); } lsDevicesListener.widgetSelected(null); } catch (IOException ex) { Message.error("Error adding device profile, " + Message.getCauseMessage(ex), ex); return; } } }
|
11
|
Code Sample 1:
public static void main(String[] args) throws Exception { String codecClassname = args[0]; Class<?> codecClass = Class.forName(codecClassname); Configuration conf = new Configuration(); CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf); CompressionOutputStream out = codec.createOutputStream(System.out); IOUtils.copyBytes(System.in, out, 4096, false); out.finish(); }
Code Sample 2:
private void _save(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception { List list = (List) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST); for (int i = 0; i < list.size(); i++) { long langId = ((Language) list.get(i)).getId(); try { String filePath = getGlobalVariablesPath() + "cms_language_" + langId + ".properties"; String tmpFilePath = getTemporyDirPath() + "cms_language_" + langId + "_properties.tmp"; File from = new java.io.File(tmpFilePath); from.createNewFile(); File to = new java.io.File(filePath); to.createNewFile(); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (NonWritableChannelException we) { } catch (IOException e) { Logger.error(this, "Property File save Failed " + e, e); } } SessionMessages.add(req, "message", "message.languagemanager.save"); }
|
11
|
Code Sample 1:
public String setEncryptedPassword(String rawPassword) { String out = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(rawPassword.getBytes()); byte raw[] = md.digest(); out = new String(); for (int x = 0; x < raw.length; x++) { String hex2 = Integer.toHexString((int) raw[x] & 0xFF); if (1 == hex2.length()) { hex2 = "0" + hex2; } out += hex2; int a = 1; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return out; }
Code Sample 2:
public String calculateProjectMD5(String scenarioName) throws Exception { Scenario s = ScenariosManager.getInstance().getScenario(scenarioName); s.loadParametersAndValues(); String scenarioMD5 = calculateScenarioMD5(s); Map<ProjectComponent, String> map = getProjectMD5(new ProjectComponent[] { ProjectComponent.resources, ProjectComponent.classes, ProjectComponent.suts, ProjectComponent.libs }); map.put(ProjectComponent.currentScenario, scenarioMD5); MessageDigest md = MessageDigest.getInstance("MD5"); Iterator<String> iter = map.values().iterator(); while (iter.hasNext()) { md.update(iter.next().getBytes()); } byte[] hash = md.digest(); BigInteger result = new BigInteger(hash); String rc = result.toString(16); return rc; }
|
00
|
Code Sample 1:
public static String getHashedPassword(String password) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); BigInteger hashedInt = new BigInteger(1, digest.digest()); return String.format("%1$032X", hashedInt); } catch (NoSuchAlgorithmException nsae) { System.err.println(nsae.getMessage()); } return ""; }
Code Sample 2:
private void setInlineXML(Entry entry, DatastreamXMLMetadata ds) throws UnsupportedEncodingException, StreamIOException { String content; if (m_obj.hasContentModel(Models.SERVICE_DEPLOYMENT_3_0) && (ds.DatastreamID.equals("SERVICE-PROFILE") || ds.DatastreamID.equals("WSDL"))) { content = DOTranslationUtility.normalizeInlineXML(new String(ds.xmlContent, m_encoding), m_transContext); } else { content = new String(ds.xmlContent, m_encoding); } if (m_format.equals(ATOM_ZIP1_1)) { String name = ds.DSVersionID + ".xml"; try { m_zout.putNextEntry(new ZipEntry(name)); InputStream is = new ByteArrayInputStream(content.getBytes(m_encoding)); IOUtils.copy(is, m_zout); m_zout.closeEntry(); is.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); entry.setSummary(ds.DSVersionID); entry.setContent(iri, ds.DSMIME); } else { entry.setContent(content, ds.DSMIME); } }
|
00
|
Code Sample 1:
private static String func(String sf) { int total = 0, temp; String fnctn[] = { "sin", "cos", "tan", "log", "ln", "sqrt", "!" }, temp2 = ""; int pos[] = new int[7]; for (int n = 0; n < fnctn.length; n++) { pos[n] = sf.lastIndexOf(fnctn[n]); } for (int m = 0; m < fnctn.length; m++) { total += pos[m]; } if (total == -7) { return sf; } for (int i = pos.length; i > 1; i--) { for (int j = 0; j < i - 1; j++) { if (pos[j] < pos[j + 1]) { temp = pos[j]; pos[j] = pos[j + 1]; pos[j + 1] = temp; temp2 = fnctn[j]; fnctn[j] = fnctn[j + 1]; fnctn[j + 1] = temp2; } } } if (fnctn[0].equals("sin")) { if ((pos[0] == 0 || sf.charAt(pos[0] - 1) != 'a')) { return func(Functions.sine(sf, pos[0], false)); } else { return func(Functions.asin(sf, pos[0], false)); } } else if (fnctn[0].equals("cos")) { if ((pos[0] == 0 || sf.charAt(pos[0] - 1) != 'a')) { return func(Functions.cosine(sf, pos[0], false)); } else { return func(Functions.acos(sf, pos[0], false)); } } else if (fnctn[0].equals("tan")) { if ((pos[0] == 0 || sf.charAt(pos[0] - 1) != 'a')) { return func(Functions.tangent(sf, pos[0], false)); } else { return func(Functions.atan(sf, pos[0], false)); } } else if (fnctn[0].equals("log")) { return func(Functions.logarithm(sf, pos[0])); } else if (fnctn[0].equals("ln")) { return func(Functions.lnat(sf, pos[0])); } else if (fnctn[0].equals("sqrt")) { return func(Functions.sqroot(sf, pos[0])); } else { return func(Functions.factorial(sf, pos[0])); } }
Code Sample 2:
public static String encrypt(String input) { try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(input.getBytes("UTF-8")); return toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
|
11
|
Code Sample 1:
public static boolean writeFile(HttpServletResponse resp, File reqFile) { boolean retVal = false; InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(reqFile)); IOUtils.copy(in, resp.getOutputStream()); logger.debug("File successful written to servlet response: " + reqFile.getAbsolutePath()); } catch (FileNotFoundException e) { logger.error("Resource not found: " + reqFile.getAbsolutePath()); } catch (IOException e) { logger.error(String.format("Error while rendering [%s]: %s", reqFile.getAbsolutePath(), e.getMessage()), e); } finally { IOUtils.closeQuietly(in); } return retVal; }
Code Sample 2:
@Test public void testTransactWriteAndRead() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwritetrans.txt"); RFileOutputStream out = new RFileOutputStream(file, WriteMode.TRANSACTED, false, 1); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } }
|
11
|
Code Sample 1:
private void copyFile(File source, File dest) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
public static boolean copyFileChannel(final File _fileFrom, final File _fileTo, final boolean _append) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(_fileFrom).getChannel(); dstChannel = new FileOutputStream(_fileTo, _append).getChannel(); if (_append) { dstChannel.transferFrom(srcChannel, dstChannel.size(), srcChannel.size()); } else { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } srcChannel.close(); dstChannel.close(); } catch (final IOException e) { return false; } finally { try { if (srcChannel != null) { srcChannel.close(); } } catch (final IOException _evt) { FuLog.error(_evt); } try { if (dstChannel != null) { dstChannel.close(); } } catch (final IOException _evt) { FuLog.error(_evt); } } return true; }
|
00
|
Code Sample 1:
private static AtomContainer askForMovieSettings() throws IOException, QTException { final InputStream inputStream = QuickTimeFormatGenerator.class.getResourceAsStream(REFERENCE_MOVIE_RESOURCE); final ByteArrayOutputStream byteArray = new ByteArrayOutputStream(1024 * 100); IOUtils.copy(inputStream, byteArray); final byte[] movieBytes = byteArray.toByteArray(); final QTHandle qtHandle = new QTHandle(movieBytes); final DataRef dataRef = new DataRef(qtHandle, StdQTConstants.kDataRefFileExtensionTag, ".mov"); final Movie movie = Movie.fromDataRef(dataRef, StdQTConstants.newMovieActive | StdQTConstants4.newMovieAsyncOK); final MovieExporter exporter = new MovieExporter(StdQTConstants.kQTFileTypeMovie); exporter.doUserDialog(movie, null, 0, movie.getDuration()); return exporter.getExportSettingsFromAtomContainer(); }
Code Sample 2:
public void addUser(String name, String unit, String organizeName, int userId, int orgId, String email) { Connection connection = null; PreparedStatement ps = null; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { connection = dbo.getConnection(); ps = connection.prepareStatement(INSERT_USER); ps.setInt(1, AddrslistMainDao.getNewID()); ps.setInt(2, -100); ps.setString(3, name.substring(0, 1)); ps.setString(4, name.substring(1)); ps.setString(5, unit); ps.setString(6, organizeName); ps.setString(7, ""); ps.setString(8, email); ps.setString(9, ""); ps.setString(10, ""); ps.setString(11, ""); ps.setString(12, ""); ps.setString(13, ""); ps.setString(14, ""); ps.setString(15, ""); ps.setString(16, ""); ps.setString(17, ""); ps.setString(18, ""); ps.setInt(19, userId); ps.setInt(20, orgId); ps.executeUpdate(); connection.commit(); } catch (Exception e) { e.printStackTrace(); try { connection.rollback(); } catch (SQLException e1) { } } finally { try { ps.close(); connection.close(); dbo.close(); } catch (Exception e) { } } }
|
11
|
Code Sample 1:
private static void addFile(File file, TarArchiveOutputStream taos) throws IOException { String filename = null; filename = file.getName(); TarArchiveEntry tae = new TarArchiveEntry(filename); tae.setSize(file.length()); taos.putArchiveEntry(tae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, taos); taos.closeArchiveEntry(); }
Code Sample 2:
@Override public void createCopy(File sourceFile, File destinnationFile) throws IOException { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinnationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
11
|
Code Sample 1:
public static void main(String[] args) { Usage u = new ccngetmeta(); for (int i = 0; i < args.length - 3; i++) { if (!CommonArguments.parseArguments(args, i, u)) { u.usage(); System.exit(1); } if (CommonParameters.startArg > i + 1) i = CommonParameters.startArg - 1; } if (args.length != CommonParameters.startArg + 3) { u.usage(); System.exit(1); } try { int readsize = 1024; CCNHandle handle = CCNHandle.open(); String metaArg = args[CommonParameters.startArg + 1]; if (!metaArg.startsWith("/")) metaArg = "/" + metaArg; ContentName fileName = MetadataProfile.getLatestVersion(ContentName.fromURI(args[CommonParameters.startArg]), ContentName.fromNative(metaArg), CommonParameters.timeout, handle); if (fileName == null) { System.out.println("File " + args[CommonParameters.startArg] + " does not exist"); System.exit(1); } if (VersioningProfile.hasTerminalVersion(fileName)) { } else { System.out.println("File " + fileName + " does not exist... exiting"); System.exit(1); } File theFile = new File(args[CommonParameters.startArg + 2]); if (theFile.exists()) { System.out.println("Overwriting file: " + args[CommonParameters.startArg + 1]); } FileOutputStream output = new FileOutputStream(theFile); long starttime = System.currentTimeMillis(); CCNInputStream input; if (CommonParameters.unversioned) input = new CCNInputStream(fileName, handle); else input = new CCNFileInputStream(fileName, handle); if (CommonParameters.timeout != null) { input.setTimeout(CommonParameters.timeout); } byte[] buffer = new byte[readsize]; int readcount = 0; long readtotal = 0; while ((readcount = input.read(buffer)) != -1) { readtotal += readcount; output.write(buffer, 0, readcount); output.flush(); } if (CommonParameters.verbose) System.out.println("ccngetfile took: " + (System.currentTimeMillis() - starttime) + "ms"); System.out.println("Retrieved content " + args[CommonParameters.startArg + 1] + " got " + readtotal + " bytes."); System.exit(0); } catch (ConfigurationException e) { System.out.println("Configuration exception in ccngetfile: " + e.getMessage()); e.printStackTrace(); } catch (MalformedContentNameStringException e) { System.out.println("Malformed name: " + args[CommonParameters.startArg] + " " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println("Cannot write file or read content. " + e.getMessage()); e.printStackTrace(); } System.exit(1); }
Code Sample 2:
public void copyTo(File folder) { if (!isNewFile()) { return; } if (!folder.exists()) { folder.mkdir(); } File dest = new File(folder, name); try { FileInputStream in = new FileInputStream(currentPath); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; long totalCopiedSize = 0; boolean canceled = false; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); if (canceled) { dest.delete(); } else { currentPath = dest; newFile = false; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public String getMD5(String data) { try { MessageDigest md5Algorithm = MessageDigest.getInstance("MD5"); md5Algorithm.update(data.getBytes(), 0, data.length()); byte[] digest = md5Algorithm.digest(); StringBuffer hexString = new StringBuffer(); String hexDigit = null; for (int i = 0; i < digest.length; i++) { hexDigit = Integer.toHexString(0xFF & digest[i]); if (hexDigit.length() < 2) { hexDigit = "0" + hexDigit; } hexString.append(hexDigit); } return hexString.toString(); } catch (NoSuchAlgorithmException ne) { return data; } }
Code Sample 2:
@Override public String encryptString(String passphrase, String message) throws Exception { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes("UTF-8")); byte digest[] = md.digest(); String digestString = base64encode(digest); System.out.println(digestString); SecureRandom sr = new SecureRandom(digestString.getBytes()); KeyGenerator kGen = KeyGenerator.getInstance("AES"); kGen.init(128, sr); Key key = kGen.generateKey(); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] bIn = cipher.doFinal(message.getBytes("UTF-8")); String base64Encoded = base64encode(bIn); return base64Encoded; }
|
00
|
Code Sample 1:
public static final InputStream openStream(Bundle bundle, IPath file, boolean localized) throws IOException { URL url = null; if (!localized) { url = findInPlugin(bundle, file); if (url == null) url = findInFragments(bundle, file); } else { url = FindSupport.find(bundle, file); } if (url != null) return url.openStream(); throw new IOException("Cannot find " + file.toString()); }
Code Sample 2:
public static void copyFile(File inputFile, File outputFile) throws IOException { BufferedInputStream fr = new BufferedInputStream(new FileInputStream(inputFile)); BufferedOutputStream fw = new BufferedOutputStream(new FileOutputStream(outputFile)); byte[] buf = new byte[8192]; int n; while ((n = fr.read(buf)) >= 0) fw.write(buf, 0, n); fr.close(); fw.close(); }
|
00
|
Code Sample 1:
public ResponseStatus submit(Collection<SubmissionData> data) throws IOException { if (sessionId == null) throw new IllegalStateException("Perform successful handshake first."); if (data.size() > 50) throw new IllegalArgumentException("Max 50 submissions at once"); StringBuilder builder = new StringBuilder(data.size() * 100); int index = 0; for (SubmissionData submissionData : data) { builder.append(submissionData.toString(sessionId, index)); builder.append('\n'); index++; } String body = builder.toString(); if (Caller.getInstance().isDebugMode()) System.out.println("submit: " + body); HttpURLConnection urlConnection = Caller.getInstance().openConnection(submissionUrl); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); OutputStream outputStream = urlConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream)); writer.write(body); writer.close(); InputStream is = urlConnection.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); String status = r.readLine(); r.close(); int statusCode = ResponseStatus.codeForStatus(status); if (statusCode == ResponseStatus.FAILED) { return new ResponseStatus(statusCode, status.substring(status.indexOf(' ') + 1)); } return new ResponseStatus(statusCode); }
Code Sample 2:
public static int ToGSML(GeoSciML_Mapping mapping, String strTemplate, String strRequest, PrintWriter sortie, String requestedSRS) throws Exception { String level = "info."; if (ConnectorServlet.debug) level = "debug."; Log log = LogFactory.getLog(level + "fr.brgm.exows.gml2gsml.Gml2Gsml"); log.debug(strRequest); String tagFeature = "FIELDS"; URL url2Request = new URL(strRequest); URLConnection conn = url2Request.openConnection(); Date dDebut = new Date(); BufferedReader buffin = new BufferedReader(new InputStreamReader(conn.getInputStream())); String strLine = null; int nbFeatures = 0; Template template = VelocityCreator.createTemplate("/fr/brgm/exows/gml2gsml/templates/" + strTemplate); while ((strLine = buffin.readLine()) != null) { if (strLine.indexOf(tagFeature) != -1) { nbFeatures++; GSMLFeatureGeneric feature = createGSMLFeatureFromGMLFeatureString(mapping, strLine); VelocityContext context = new VelocityContext(); context.put("feature", feature); String outputFeatureMember = VelocityCreator.createXMLbyContext(context, template); sortie.println(outputFeatureMember); } } buffin.close(); Date dFin = new Date(); String output = "GEOSCIML : " + nbFeatures + " features handled - time : " + (dFin.getTime() - dDebut.getTime()) / 1000 + " [" + dDebut + " // " + dFin + "]"; log.trace(output); return nbFeatures; }
|
11
|
Code Sample 1:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
@Override protected void copyContent(String filename) throws IOException { InputStream in = null; try { in = LOADER.getResourceAsStream(RES_PKG + filename); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); setResponseData(out.toByteArray()); } finally { if (in != null) { in.close(); } } }
|
11
|
Code Sample 1:
public static void copyTo(java.io.File source, java.io.File dest) throws Exception { java.io.FileInputStream inputStream = null; java.nio.channels.FileChannel sourceChannel = null; java.io.FileOutputStream outputStream = null; java.nio.channels.FileChannel destChannel = null; long size = source.length(); long bufferSize = 1024; long count = 0; if (size < bufferSize) bufferSize = size; Exception exception = null; try { if (dest.exists() == false) dest.createNewFile(); inputStream = new java.io.FileInputStream(source); sourceChannel = inputStream.getChannel(); outputStream = new java.io.FileOutputStream(dest); destChannel = outputStream.getChannel(); while (count < size) count += sourceChannel.transferTo(count, bufferSize, destChannel); } catch (Exception e) { exception = e; } finally { closeFileChannel(sourceChannel); closeFileChannel(destChannel); } if (exception != null) throw exception; }
Code Sample 2:
public static void main(String[] args) throws Exception { DES des = new DES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test1.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\test2.txt")); SingleKey key = new SingleKey(new Block(64), ""); key = new SingleKey(new Block("1111111100000000111111110000000011111111000000001111111100000000"), ""); Mode mode = new ECBDESMode(des); des.decrypt(reader, writer, key, mode); }
|
00
|
Code Sample 1:
public static Object deployNewService(String scNodeRmiName, String userName, String password, String name, String jarName, String serviceClass, String serviceInterface, Logger log) throws RemoteException, MalformedURLException, StartServiceException, NotBoundException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, SessionException { try { SCNodeInterface node = (SCNodeInterface) Naming.lookup(scNodeRmiName); String session = node.login(userName, password); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(new FileInputStream(jarName), baos); ServiceAdapterIfc adapter = node.deploy(session, name, baos.toByteArray(), jarName, serviceClass, serviceInterface); if (adapter != null) { return new ExternalDomain(node, adapter, adapter.getUri(), log).getProxy(Thread.currentThread().getContextClassLoader()); } } catch (Exception e) { log.warn("Could not send deploy command: " + e.getMessage(), e); } return null; }
Code Sample 2:
@Override public long insertStatement(String sql) { Statement statement = null; try { statement = getConnection().createStatement(); long result = statement.executeUpdate(sql.toString()); if (result == 0) log.warn(sql + " result row count is 0"); getConnection().commit(); return getInsertId(statement); } catch (SQLException e) { try { getConnection().rollback(); } catch (SQLException e1) { log.error(e1.getMessage(), e1); } log.error(e.getMessage(), e); throw new RuntimeException(); } finally { try { statement.close(); getConnection().close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } }
|
11
|
Code Sample 1:
public static String MD5(String text) { byte[] md5hash = new byte[32]; try { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); } catch (Exception e) { e.printStackTrace(); } return convertToHex(md5hash); }
Code Sample 2:
public synchronized String getEncryptedPassword(String plaintext, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance(algorithm); md.update(plaintext.getBytes("UTF-8")); return bytesToHexString(md.digest()); }
|
00
|
Code Sample 1:
private static Properties getProperties(String propFilename, ClassLoader loader) { Properties properties = new Properties(); try { URL url = Loader.getResource(loader, propFilename); properties.load(url.openStream()); } catch (Exception e) { log.debug("Cannot find crypto property file: " + propFilename); throw new RuntimeException("CryptoFactory: Cannot load properties: " + propFilename); } return properties; }
Code Sample 2:
public void downloadFrinika() throws Exception { if (!frinikaFile.exists()) { String urlString = remoteURLPath + frinikaFileName; showMessage("Connecting to " + urlString); URLConnection uc = new URL(urlString).openConnection(); progressBar.setIndeterminate(false); showMessage("Downloading from " + urlString); progressBar.setValue(0); progressBar.setMinimum(0); progressBar.setMaximum(fileSize); InputStream is = uc.getInputStream(); FileOutputStream fos = new FileOutputStream(frinikaFile); byte[] b = new byte[BUFSIZE]; int c; while ((c = is.read(b)) != -1) { fos.write(b, 0, c); progressBar.setValue(progressBar.getValue() + c); } fos.close(); } }
|
00
|
Code Sample 1:
public static String calculateHash(String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); md.reset(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } md.update(password.getBytes()); return byteToBase64(md.digest()); }
Code Sample 2:
public Object run() { if (type == GET_THEME_DIR) { String sep = File.separator; String[] dirs = new String[] { userHome + sep + ".themes", System.getProperty("swing.metacitythemedir"), "/usr/share/themes", "/usr/gnome/share/themes", "/opt/gnome2/share/themes" }; URL themeDir = null; for (int i = 0; i < dirs.length; i++) { if (dirs[i] == null) { continue; } File dir = new File(dirs[i] + sep + arg + sep + "metacity-1"); if (new File(dir, "metacity-theme-1.xml").canRead()) { try { themeDir = dir.toURL(); } catch (MalformedURLException ex) { themeDir = null; } break; } } if (themeDir == null) { String filename = "resources/metacity/" + arg + "/metacity-1/metacity-theme-1.xml"; URL url = getClass().getResource(filename); if (url != null) { String str = url.toString(); try { themeDir = new URL(str.substring(0, str.lastIndexOf('/')) + "/"); } catch (MalformedURLException ex) { themeDir = null; } } } return themeDir; } else if (type == GET_USER_THEME) { try { userHome = System.getProperty("user.home"); String theme = System.getProperty("swing.metacitythemename"); if (theme != null) { return theme; } URL url = new URL(new File(userHome).toURL(), ".gconf/apps/metacity/general/%25gconf.xml"); Reader reader = new InputStreamReader(url.openStream(), "ISO-8859-1"); char[] buf = new char[1024]; StringBuffer strBuf = new StringBuffer(); int n; while ((n = reader.read(buf)) >= 0) { strBuf.append(buf, 0, n); } reader.close(); String str = strBuf.toString(); if (str != null) { String strLowerCase = str.toLowerCase(); int i = strLowerCase.indexOf("<entry name=\"theme\""); if (i >= 0) { i = strLowerCase.indexOf("<stringvalue>", i); if (i > 0) { i += "<stringvalue>".length(); int i2 = str.indexOf("<", i); return str.substring(i, i2); } } } } catch (MalformedURLException ex) { } catch (IOException ex) { } return null; } else if (type == GET_IMAGE) { return new ImageIcon((URL) arg).getImage(); } else { return null; } }
|
11
|
Code Sample 1:
private void setInlineXML(Entry entry, DatastreamXMLMetadata ds) throws UnsupportedEncodingException, StreamIOException { String content; if (m_obj.hasContentModel(Models.SERVICE_DEPLOYMENT_3_0) && (ds.DatastreamID.equals("SERVICE-PROFILE") || ds.DatastreamID.equals("WSDL"))) { content = DOTranslationUtility.normalizeInlineXML(new String(ds.xmlContent, m_encoding), m_transContext); } else { content = new String(ds.xmlContent, m_encoding); } if (m_format.equals(ATOM_ZIP1_1)) { String name = ds.DSVersionID + ".xml"; try { m_zout.putNextEntry(new ZipEntry(name)); InputStream is = new ByteArrayInputStream(content.getBytes(m_encoding)); IOUtils.copy(is, m_zout); m_zout.closeEntry(); is.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); entry.setSummary(ds.DSVersionID); entry.setContent(iri, ds.DSMIME); } else { entry.setContent(content, ds.DSMIME); } }
Code Sample 2:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
11
|
Code Sample 1:
@Override public void run() { File file = new File(LogHandler.path); FileFilter filter = new FileFilter() { @Override public boolean accept(File file) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date()); cal.add(GregorianCalendar.DAY_OF_YEAR, -1); String oldTime = LogHandler.dateFormat.format(cal.getTime()); return file.getName().toLowerCase().startsWith(oldTime); } }; File[] list = file.listFiles(filter); if (list.length > 0) { FileInputStream in; int read = 0; byte[] data = new byte[1024]; for (int i = 0; i < list.length; i++) { try { in = new FileInputStream(LogHandler.path + list[i].getName()); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(LogHandler.path + list[i].getName() + ".temp")); while ((read = in.read(data, 0, 1024)) != -1) out.write(data, 0, read); in.close(); out.close(); new File(LogHandler.path + list[i].getName() + ".temp").renameTo(new File(LogHandler.path + list[i].getName() + ".gz")); list[i].delete(); } catch (FileNotFoundException e) { TrackingServer.incExceptionCounter(); e.printStackTrace(); } catch (IOException ioe) { } } } }
Code Sample 2:
@Override public String transformSingleFile(X3DEditorSupport.X3dEditor xed) { Node[] node = xed.getActivatedNodes(); X3DDataObject dob = (X3DDataObject) xed.getX3dEditorSupport().getDataObject(); FileObject mySrc = dob.getPrimaryFile(); File mySrcF = FileUtil.toFile(mySrc); File myOutF = new File(mySrcF.getParentFile(), mySrc.getName() + ".x3d.gz"); TransformListener co = TransformListener.getInstance(); co.message(NbBundle.getMessage(getClass(), "Gzip_compression_starting")); co.message(NbBundle.getMessage(getClass(), "Saving_as_") + myOutF.getAbsolutePath()); co.moveToFront(); co.setNode(node[0]); try { FileInputStream fis = new FileInputStream(mySrcF); GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(myOutF)); byte[] buf = new byte[4096]; int ret; while ((ret = fis.read(buf)) > 0) gzos.write(buf, 0, ret); gzos.close(); } catch (Exception ex) { co.message(NbBundle.getMessage(getClass(), "Exception:__") + ex.getLocalizedMessage()); return null; } co.message(NbBundle.getMessage(getClass(), "Gzip_compression_complete")); return myOutF.getAbsolutePath(); }
|
00
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
private void fetch() throws IOException { if (getAttachmentUrl() != null && (!getAttachmentUrl().isEmpty())) { InputStream input = null; ByteArrayOutputStream output = null; try { URL url = new URL(getAttachmentUrl()); input = url.openStream(); output = new ByteArrayOutputStream(); int i; while ((i = input.read()) != -1) { output.write(i); } this.data = output.toByteArray(); } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } } } }
|
11
|
Code Sample 1:
public static void main(String[] args) { String fe = null, fk = null, f1 = null, f2 = null; DecimalFormat df = new DecimalFormat("000"); int key = 0; int i = 1; for (; ; ) { System.out.println("==================================================="); System.out.println("\n2009 BME\tTeam ESC's Compare\n"); System.out.println("===================================================\n"); System.out.println(" *** Menu ***\n"); System.out.println("1. Fajlok osszehasonlitasa"); System.out.println("2. Hasznalati utasitas"); System.out.println("3. Kilepes"); System.out.print("\nKivalasztott menu szama: "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { key = reader.read(); switch(key) { case '3': System.exit(0); break; case '2': System.out.println("\n @author Bedo Zotlan - F3VFDE"); System.out.println("Team ESC's Compare"); System.out.println("2009."); System.out.println(); System.out.println("(1) A program ket fajl osszahesonlitasat vegzi. A fajloknak a program gyokerkonyvtaraban kell lenniuk!"); System.out.println("(2) A menubol ertelem szeruen valasztunk az opciok kozul, majd a program keresere megadjuk a ket osszehasonlitando " + "fajl nevet kiterjesztessel egyutt, kulonben hibat kapunk!"); System.out.println("(3) Miutan elvegeztuk az osszehasonlitasokat a program mindegyiket kimenti a compare_xxx.txt fajlba, azonban ha kilepunk a programbol, " + "majd utana ismet elinditjuk es elkezdunk osszehasonlitasokat vegezni, akkor felulirhatja " + "az elozo futtatasbol kapott fajlainkat, erre kulonosen figyelni kell!"); System.out.println("(4) A kimeneti compare_xxx.txt fajlon kivul minden egyes osszehasonlitott fajlrol csinal egy <fajl neve>.<fajl kiterjesztese>.numbered " + "nevu fajlt, ami annyiban ter el az eredeti fajloktol, hogy soronkent sorszamozva vannak!"); System.out.println("(5) Egy nem ures es egy ures fajl osszehasonlitasa utan azt az eredmenyt kapjuk, hogy \"OK, megyezenek!\". Ez termeszetesen hibas" + " es a kimeneti fajlunk is ures lesz. Ezt szinten keruljuk el, ne hasonlitsunk ures fajlokhoz mas fajlokat!"); System.out.println("(6) A fajlok megtekintesehez Notepad++ 5.0.0 verzioja ajanlott legalabb!\n"); break; case '1': { System.out.print("\nAz etalon adatokat tartalmazo fajl neve: "); try { int lnNo = 1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inFileName = br.readLine(); BufferedReader bin = new BufferedReader(new FileReader(inFileName)); BufferedWriter bout = new BufferedWriter(new FileWriter(inFileName + ".numbered")); fe = (inFileName + ".numbered"); f1 = inFileName; String aLine; while ((aLine = bin.readLine()) != null) bout.write("Line " + df.format(lnNo++) + ": " + aLine + "\n"); bin.close(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajlnev"); } System.out.print("A kapott adatokat tartalmazo fajl neve: "); try { int lnNo = 1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inFileName = br.readLine(); BufferedReader bin = new BufferedReader(new FileReader(inFileName)); BufferedWriter bout = new BufferedWriter(new FileWriter(inFileName + ".numbered")); fk = (inFileName + ".numbered"); f2 = inFileName; String aLine_k; while ((aLine_k = bin.readLine()) != null) bout.write("Line " + df.format(lnNo++) + ": " + aLine_k + "\n"); bin.close(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajlnev"); } try { int lnNo_c = 1; int mstk = 0; BufferedReader bin_e = new BufferedReader(new FileReader(fe)); BufferedReader bin_k = new BufferedReader(new FileReader(fk)); BufferedWriter bout = new BufferedWriter(new FileWriter("compare_" + i++ + ".txt")); Calendar actDate = Calendar.getInstance(); bout.write("==================================================\n"); bout.write("\n2009 BME\tTeam ESC's Compare"); bout.write("\n" + actDate.get(Calendar.YEAR) + "." + (actDate.get(Calendar.MONTH) + 1) + "." + actDate.get(Calendar.DATE) + ".\n" + actDate.get(Calendar.HOUR) + ":" + actDate.get(Calendar.MINUTE) + "\n\n"); bout.write("==================================================\n"); bout.write("Az etalon ertekekkel teli fajl neve: " + f1 + "\n"); bout.write("A kapott ertekekkel teli fajl neve: " + f2 + "\n\n"); System.out.println("==================================================\n"); System.out.println("\n2009 BME\tTeam ESC's Compare"); System.out.println(actDate.get(Calendar.YEAR) + "." + (actDate.get(Calendar.MONTH) + 1) + "." + actDate.get(Calendar.DATE) + ".\n" + actDate.get(Calendar.HOUR) + ":" + actDate.get(Calendar.MINUTE) + "\n"); System.out.println("==================================================\n"); System.out.println("\nAz etalon ertekekkel teli fajl neve: " + f1); System.out.println("A kapott ertekekkel teli fajl neve: " + f2 + "\n"); String aLine_c1 = null, aLine_c2 = null; File fa = new File(fe); File fb = new File(fk); if (fa.length() != fb.length()) { bout.write("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!\n Kulonbozo meretu fajlok: " + fa.length() + " byte illetve " + fb.length() + " byte!\n"); System.out.println("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!\n Kulonbozo meretu fajlok: " + fa.length() + " byte illetve " + fb.length() + " byte!\n"); } else { while (((aLine_c1 = bin_e.readLine()) != null) && ((aLine_c2 = bin_k.readLine()) != null)) if (aLine_c1.equals(aLine_c2)) { } else { mstk++; bout.write("#" + df.format(lnNo_c) + ": HIBA --> \t" + f1 + " : " + aLine_c1 + " \n\t\t\t\t\t" + f2 + " : " + aLine_c2 + "\n"); System.out.println("#" + df.format(lnNo_c) + ": HIBA -->\t " + f1 + " : " + aLine_c1 + " \n\t\t\t" + f2 + " : " + aLine_c2 + "\n"); lnNo_c++; } if (mstk != 0) { bout.write("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!"); bout.write("\nHibas sorok szama: " + mstk); System.out.println("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!"); System.out.println("Hibas sorok szama: " + mstk); } else { bout.write("\nOsszehasonlitas eredmenye: OK, megegyeznek!"); System.out.println("\nOsszehasonlitas eredm�nye: OK, megegyeznek!\n"); } } bin_e.close(); bin_k.close(); fa.delete(); fb.delete(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajl"); } break; } } } catch (Exception e) { System.out.println("A fut�s sor�n hiba t�rt�nt!"); } } }
Code Sample 2:
public static void copyFile(String fileName, String dstPath) throws IOException { FileChannel sourceChannel = new FileInputStream(fileName).getChannel(); FileChannel destinationChannel = new FileOutputStream(dstPath).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
00
|
Code Sample 1:
@Override protected svm_model loadModel(InputStream inputStream) throws IOException { File tmpFile = File.createTempFile("tmp", ".mdl"); FileOutputStream output = new FileOutputStream(tmpFile); try { IOUtils.copy(inputStream, output); return libsvm.svm.svm_load_model(tmpFile.getPath()); } finally { output.close(); tmpFile.delete(); } }
Code Sample 2:
public void deploy(String baseDir, boolean clean) throws IOException { try { ftp.connect(hostname, port); log.debug("Connected to: " + hostname + ":" + port); ftp.login(username, password); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("Error logging onto ftp server. FTPClient returned code: " + reply); } log.debug("Logged in"); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); if (clean) { deleteDir(remoteDir); } storeFolder(baseDir, remoteDir); } finally { ftp.disconnect(); } }
|
11
|
Code Sample 1:
public void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void copyFile(File src, File dst) throws IOException { FileChannel from = new FileInputStream(src).getChannel(); FileChannel to = new FileOutputStream(dst).getChannel(); from.transferTo(0, src.length(), to); from.close(); to.close(); }
|
00
|
Code Sample 1:
public void signAndSend() throws Exception { SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("TLS"); X509TrustManager[] xtmArray = new X509TrustManager[] { xtm }; sslContext.init(null, xtmArray, new java.security.SecureRandom()); } catch (GeneralSecurityException gse) { this.addException("GeneralSecurityException", gse); } if (sslContext != null) { HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); } HttpsURLConnection.setDefaultHostnameVerifier(hnv); String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI"); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance()); DigestMethod dm = fac.newDigestMethod(DigestMethod.SHA1, null); List transforms = new Vector(2); transforms.add(fac.newTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature", (TransformParameterSpec) null)); List prefixlist = new Vector(1); prefixlist.add("xsd"); transforms.add(fac.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", new ExcC14NParameterSpec(prefixlist))); Random randgen = new Random(); byte[] rand_bytes = new byte[20]; randgen.nextBytes(rand_bytes); String assertion_id_str = "i" + new String(Hex.encodeHex(rand_bytes)); Reference ref = fac.newReference("#" + assertion_id_str, dm, transforms, null, null); CanonicalizationMethod cm = fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); SignatureMethod sm = fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null); SignedInfo si = fac.newSignedInfo(cm, sm, Collections.singletonList(ref)); KeyStore ks = KeyStore.getInstance("JKS"); FileInputStream fis = null; if (TEST_SIGNED_WITH_WRONG_CERT == testNumber) { fis = new FileInputStream(resourceFolder + "z-xtra-sign.jks"); } else { fis = new FileInputStream(resourceFolder + "z-idp-sign.jks"); } ks.load(fis, "changeit".toCharArray()); { Enumeration aliases = ks.aliases(); for (; aliases.hasMoreElements(); ) { String alias = (String) aliases.nextElement(); boolean b = ks.isKeyEntry(alias); b = ks.isCertificateEntry(alias); System.out.println(b + " " + alias); } } PrivateKey privateKey = (PrivateKey) ks.getKey("tomcat", "changeit".toCharArray()); XMLSignature signature = fac.newXMLSignature(si, null); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); File docFile = new File(resourceFolder + "BaseRequest.xml"); Document doc = db.parse(docFile); Element root = doc.getDocumentElement(); NamedNodeMap root_atts = root.getAttributes(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); GregorianCalendar right_now = new GregorianCalendar(); if (TEST_NOT_ON_OR_AFTER_EXPIRED == testNumber) { right_now.add(Calendar.MINUTE, alterNowDateBy); } Date issue_date = right_now.getTime(); right_now.add(Calendar.MINUTE, -10); Date auth_instant_date = right_now.getTime(); right_now.add(Calendar.MINUTE, 20); Date not_on_or_after_date = right_now.getTime(); System.out.println("Not on or after 1: " + sdf.format(right_now.getTime())); Node response_id = root_atts.getNamedItem("ID"); randgen.nextBytes(rand_bytes); response_id.setNodeValue("i" + new String(Hex.encodeHex(rand_bytes))); Node response_issue_instant = root_atts.getNamedItem("IssueInstant"); response_issue_instant.setNodeValue(sdf.format(issue_date)); NodeList tmp_nlist = root.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Assertion"); Element assertion_node = (Element) tmp_nlist.item(0); NamedNodeMap ass_node_atts = assertion_node.getAttributes(); Node assertion_id = ass_node_atts.getNamedItem("ID"); assertion_id.setNodeValue(assertion_id_str); Node assertion_issue_instant = ass_node_atts.getNamedItem("IssueInstant"); assertion_issue_instant.setNodeValue(sdf.format(issue_date)); tmp_nlist = assertion_node.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Subject"); Element subject_node = (Element) tmp_nlist.item(0); if (TEST_UNKNOWN_CONFIRMATION == testNumber) { tmp_nlist = subject_node.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "SubjectConfirmation"); Element subj_conf_node = (Element) tmp_nlist.item(0); NamedNodeMap subj_conf_node_atts = subj_conf_node.getAttributes(); Node method_node = subj_conf_node_atts.getNamedItem("Method"); method_node.setNodeValue(badConfirmationMethod); } tmp_nlist = subject_node.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "NameID"); Element name_id_node = (Element) tmp_nlist.item(0); NamedNodeMap name_id_node_atts = name_id_node.getAttributes(); Node sp_name_qualifier = name_id_node_atts.getNamedItem("SPNameQualifier"); sp_name_qualifier.setNodeValue(sPEntityId); Node name_id_value = name_id_node.getFirstChild(); randgen.nextBytes(rand_bytes); name_id_value.setNodeValue(new String(Hex.encodeHex(rand_bytes))); tmp_nlist = subject_node.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "SubjectConfirmationData"); Element subj_conf_data_node = (Element) tmp_nlist.item(0); NamedNodeMap subj_conf_data_node_atts = subj_conf_data_node.getAttributes(); Node not_on_or_after_node = subj_conf_data_node_atts.getNamedItem("NotOnOrAfter"); not_on_or_after_node.setNodeValue(sdf.format(not_on_or_after_date)); Node recipient_node = subj_conf_data_node_atts.getNamedItem("Recipient"); if (TEST_WRONG_RECIPIENT == testNumber) { recipient_node.setNodeValue(badRecipientValue); } else { recipient_node.setNodeValue(sPAssertionConsumerService); } tmp_nlist = assertion_node.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Audience"); Element audience_node = (Element) tmp_nlist.item(0); Node audience_value = audience_node.getFirstChild(); if (TEST_WRONG_AUDIENCE == testNumber) { audience_value.setNodeValue(badAudienceValue); } else { audience_value.setNodeValue(sPEntityId); } tmp_nlist = assertion_node.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "AuthnStatement"); Element authn_statement_node = (Element) tmp_nlist.item(0); NamedNodeMap authn_statement_node_atts = authn_statement_node.getAttributes(); Node authn_instant_node = authn_statement_node_atts.getNamedItem("AuthnInstant"); authn_instant_node.setNodeValue(sdf.format(auth_instant_date)); Node sess_idx_node = authn_statement_node_atts.getNamedItem("SessionIndex"); sess_idx_node.setNodeValue(assertion_id_str); DOMSignContext signContext = new DOMSignContext(privateKey, assertion_node, subject_node); signContext.putNamespacePrefix("http://www.w3.org/2000/09/xmldsig#", "ds"); signContext.putNamespacePrefix("http://www.w3.org/2001/10/xml-exc-c14n#", "ec"); signature.sign(signContext); TransformerFactory tf = TransformerFactory.newInstance(); Transformer trans; if (TEST_DATA_ALTERED_AFTER_SIG == testNumber) { right_now.add(Calendar.MINUTE, 10); System.out.println("Not on or after: " + sdf.format(right_now.getTime())); not_on_or_after_node.setNodeValue(sdf.format(right_now.getTime())); } trans = tf.newTransformer(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); trans.transform(new DOMSource(doc), new StreamResult(pw)); if (useJavaPOST) { try { URL url = new URL(sPAssertionConsumerService); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setInstanceFollowRedirects(false); conn.setUseCaches(false); String base64ofDoc = Base64.encode(sw.toString().getBytes()); DataOutputStream printout = new DataOutputStream(conn.getOutputStream()); String content = "SAMLResponse=" + URLEncoder.encode(base64ofDoc, "UTF-8"); printout.writeBytes(content); printout.flush(); printout.close(); if (TEST_GOOD_REPLAY == testNumber) { base64Assertion = Base64.encode(sw.toString().getBytes()); replay = true; } BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream())); String redirect = conn.getHeaderField("Location"); if (redirect != null) { input.close(); URL url2 = new URL(redirect); URLConnection conn2 = url2.openConnection(); String cookie = conn.getHeaderField("Set-Cookie"); if (cookie != null) { int index = cookie.indexOf(";"); if (index >= 0) cookie = cookie.substring(0, index); conn2.setRequestProperty("Cookie", cookie); } input = new BufferedReader(new InputStreamReader(conn2.getInputStream())); } StringBuffer buff = new StringBuffer(); String str2; while (null != ((str2 = input.readLine()))) { buff.append(str2); } input.close(); result = buff.toString(); success = true; } catch (MalformedURLException me) { this.addException("MalformedURLException", me); } catch (IOException ioe) { this.addException("IOException", ioe); } } else { base64Assertion = Base64.encode(sw.toString().getBytes()); Transformer transPretty = tf.newTransformer(new StreamSource(resourceFolder + "PrettyPrint.xslt")); StringWriter swPretty = new StringWriter(); PrintWriter pwPretty = new PrintWriter(sw); trans.transform(new DOMSource(doc), new StreamResult(pwPretty)); prettyAssertion = sw.toString(); System.out.println(XMLHelper.prettyPrintXML(doc.getFirstChild())); success = true; } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
public static long checksum(IFile file) throws IOException { InputStream contents; try { contents = file.getContents(); } catch (CoreException e) { throw new CausedIOException("Failed to calculate checksum.", e); } CheckedInputStream in = new CheckedInputStream(contents, new Adler32()); try { IOUtils.copy(in, new NullOutputStream()); } catch (IOException e) { throw new CausedIOException("Failed to calculate checksum.", e); } finally { IOUtils.closeQuietly(in); } return in.getChecksum().getValue(); }
Code Sample 2:
@Override protected void copy(InputStream inputs, OutputStream outputs) throws IOException { if (outputs == null) { throw new NullPointerException(); } if (inputs == null) { throw new NullPointerException(); } ZipOutputStream zipoutputs = null; try { zipoutputs = new ZipOutputStream(outputs); zipoutputs.putNextEntry(new ZipEntry("default")); IOUtils.copy(inputs, zipoutputs); } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (zipoutputs != null) { zipoutputs.close(); } if (inputs != null) { inputs.close(); } } }
|
11
|
Code Sample 1:
public void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; Closer c = new Closer(); try { source = c.register(new FileInputStream(sourceFile).getChannel()); destination = c.register(new FileOutputStream(destFile).getChannel()); destination.transferFrom(source, 0, source.size()); } catch (IOException e) { c.doNotThrow(); throw e; } finally { c.closeAll(); } }
Code Sample 2:
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 doInsertImage() { logger.debug(">>> Inserting image..."); logger.debug(" fullFileName : #0", uploadedFileName); String fileName = uploadedFileName.substring(uploadedFileName.lastIndexOf(File.separator) + 1); logger.debug(" fileName : #0", fileName); String newFileName = System.currentTimeMillis() + "_" + fileName; String filePath = ImageResource.getResourceDirectory() + File.separator + newFileName; logger.debug(" filePath : #0", filePath); try { File file = new File(filePath); file.createNewFile(); FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(uploadedFile).getChannel(); dstChannel = new FileOutputStream(file).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { closeChannel(srcChannel); closeChannel(dstChannel); } StringBuilder imageTag = new StringBuilder(); imageTag.append("<img src=\""); imageTag.append(getRequest().getContextPath()); imageTag.append("/seam/resource"); imageTag.append(ImageResource.RESOURCE_PATH); imageTag.append("/"); imageTag.append(newFileName); imageTag.append("\"/>"); if (getQuestionDefinition().getDescription() == null) { getQuestionDefinition().setDescription(""); } getQuestionDefinition().setDescription(getQuestionDefinition().getDescription() + imageTag); } catch (IOException e) { logger.error("Error during saving image file", e); } uploadedFile = null; uploadedFileName = null; logger.debug("<<< Inserting image...Ok"); }
Code Sample 2:
@Override public String entryToObject(TupleInput input) { boolean zipped = input.readBoolean(); if (!zipped) { return input.readString(); } int len = input.readInt(); try { byte array[] = new byte[len]; input.read(array); GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(array)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyTo(in, out); in.close(); out.close(); return new String(out.toByteArray()); } catch (IOException err) { throw new RuntimeException(err); } }
|
00
|
Code Sample 1:
public String getSHA1(String input) { byte[] output = null; try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(input.getBytes()); output = md.digest(); } catch (Exception e) { System.out.println("Exception: " + e); } return StringUtils.byte2hex(output); }
Code Sample 2:
public static Builder fromURL(URL url) { try { InputStream in = null; try { in = url.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int read = -1; byte[] buf = new byte[4096]; while ((read = in.read(buf)) >= 0) { if (read > 0) { baos.write(buf, 0, read); } } StreamBuilder b = (StreamBuilder) fromMemory(baos.toByteArray()); try { b.setSystemId(url.toURI().toString()); } catch (URISyntaxException use) { b.setSystemId(url.toString()); } return b; } finally { if (in != null) { in.close(); } } } catch (IOException ex) { throw new XMLUnitException(ex); } }
|
00
|
Code Sample 1:
private void login() throws LoginException { log.info("# iモード.netにログイン"); try { this.httpClient.getCookieStore().clear(); HttpPost post = new HttpPost(LoginUrl); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("HIDEURL", "?WM_AK=https%3a%2f%2fimode.net%2fag&path=%2fimail%2ftop&query=")); formparams.add(new BasicNameValuePair("LOGIN", "WM_LOGIN")); formparams.add(new BasicNameValuePair("WM_KEY", "0")); formparams.add(new BasicNameValuePair("MDCM_UID", this.name)); formparams.add(new BasicNameValuePair("MDCM_PWD", this.pass)); UrlEncodedFormEntity entity = null; try { entity = new UrlEncodedFormEntity(formparams, "UTF-8"); } catch (Exception e) { } post.setHeader("User-Agent", "Mozilla/4.0 (compatible;MSIE 7.0; Windows NT 6.0;)"); post.setEntity(entity); try { HttpResponse res = this.executeHttp(post); if (res == null) { this.logined = Boolean.FALSE; throw new IOException("Redirect Error"); } if (res.getStatusLine().getStatusCode() != 200) { this.logined = Boolean.FALSE; throw new IOException("http login response bad status code " + res.getStatusLine().getStatusCode()); } String body = toStringBody(res); if (body.indexOf("<title>認証エラー") > 0) { this.logined = Boolean.FALSE; log.info("認証エラー"); log.debug(body); this.clearCookie(); throw new LoginException("認証エラー"); } } finally { post.abort(); } post = new HttpPost(JsonUrl + "login"); try { HttpResponse res = this.requestPost(post, null); if (res == null) { this.logined = Boolean.FALSE; throw new IOException("Login Error"); } if (res.getStatusLine().getStatusCode() != 200) { this.logined = Boolean.FALSE; throw new IOException("http login2 response bad status code " + res.getStatusLine().getStatusCode()); } this.logined = Boolean.TRUE; } finally { post.abort(); } } catch (Exception e) { this.logined = Boolean.FALSE; throw new LoginException("Docomo i mode.net Login Error.", e); } }
Code Sample 2:
public static String addWeibo(String weibo, File pic, String uid) throws Throwable { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("_surl", "")); qparams.add(new BasicNameValuePair("_t", "0")); qparams.add(new BasicNameValuePair("location", "home")); qparams.add(new BasicNameValuePair("module", "stissue")); if (pic != null) { String picId = upLoadImg(pic, uid); qparams.add(new BasicNameValuePair("pic_id", picId)); } qparams.add(new BasicNameValuePair("rank", "weibo")); qparams.add(new BasicNameValuePair("text", weibo)); HttpPost post = getHttpPost("http://weibo.com/aj/mblog/add?__rnd=1333611402611", uid); UrlEncodedFormEntity params = new UrlEncodedFormEntity(qparams, HTTP.UTF_8); post.setEntity(params); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity, HTTP.UTF_8); post.abort(); return content; }
|
11
|
Code Sample 1:
private ArrayList<Stock> fetchStockData(Stock[] stocks) throws IOException { Log.d(TAG, "Fetching stock data from Yahoo"); ArrayList<Stock> newStocks = new ArrayList<Stock>(stocks.length); if (stocks.length > 0) { StringBuilder sb = new StringBuilder(); for (Stock stock : stocks) { sb.append(stock.getSymbol()); sb.append('+'); } sb.deleteCharAt(sb.length() - 1); String urlStr = "http://finance.yahoo.com/d/quotes.csv?f=sb2n&s=" + sb.toString(); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(urlStr.toString()); HttpResponse response = client.execute(request); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = reader.readLine(); int i = 0; Log.d(TAG, "Parsing stock data from Yahoo"); while (line != null) { Log.d(TAG, "Parsing: " + line); String[] values = line.split(","); Stock stock = new Stock(stocks[i], stocks[i].getId()); stock.setCurrentPrice(Double.parseDouble(values[1])); stock.setName(values[2]); Log.d(TAG, "Parsed Stock: " + stock); newStocks.add(stock); line = reader.readLine(); i++; } } return newStocks; }
Code Sample 2:
protected void discoverFactories() { DataSourceRegistry registry = this; try { ClassLoader loader = DataSetURI.class.getClassLoader(); Enumeration<URL> urls; if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFactory"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFactory"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { if (s.trim().length() > 0) { List<String> extensions = null; List<String> mimeTypes = null; String factoryClassName = s; try { Class c = Class.forName(factoryClassName); DataSourceFactory f = (DataSourceFactory) c.newInstance(); try { Method m = c.getMethod("extensions", new Class[0]); extensions = (List<String>) m.invoke(f, new Object[0]); } catch (NoSuchMethodException ex) { } catch (InvocationTargetException ex) { ex.printStackTrace(); } try { Method m = c.getMethod("mimeTypes", new Class[0]); mimeTypes = (List<String>) m.invoke(f, new Object[0]); } catch (NoSuchMethodException ex) { } catch (InvocationTargetException ex) { ex.printStackTrace(); } } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } if (extensions != null) { for (String e : extensions) { registry.registerExtension(factoryClassName, e, null); } } if (mimeTypes != null) { for (String m : mimeTypes) { registry.registerMimeType(factoryClassName, m); } } } s = reader.readLine(); } reader.close(); } } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public void testHttpPostsWithExpectContinue() throws Exception { int reqNo = 20; Random rnd = new Random(); List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); this.client.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } }
Code Sample 2:
public static String uploadArticleMedia(String localPath, String articleImageName, String year, String month, String day, DataStore db, HttpSession session) { CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user"); if (!localPath.endsWith(File.separator)) { localPath += File.separator; } FTPClient ftp = new FTPClient(); String liveFTPLogin = (String) user.workingPubConfigElementsHash.get("LIVEFTPLOGIN"); String liveFTPPassword = (String) user.workingPubConfigElementsHash.get("LIVEFTPPASSWORD"); String liveImagesServer = (String) user.workingPubConfigElementsHash.get("LIVEFTPSERVER"); String liveImagesFolder = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESFOLDER"); if (!liveImagesFolder.endsWith("/")) { liveImagesFolder = liveImagesFolder + "/"; } String liveImagesYearFolder = ""; String liveImagesMonthFolder = ""; String fileLocation = ""; fileLocation += "/" + year + "/" + month + "/" + day; liveImagesYearFolder = liveImagesFolder + year; liveImagesMonthFolder = (liveImagesYearFolder + "/" + month); liveImagesFolder = (liveImagesMonthFolder + "/" + day); CofaxToolsUtil.log("CofaxToolsFTP: liveImagesServer: " + liveImagesServer); CofaxToolsUtil.log("CofaxToolsFTP: liveImagesFolder: " + liveImagesFolder); boolean stored = false; ArrayList servers = splitServers(liveImagesServer); for (int count = 0; count < servers.size(); count++) { String server = (String) servers.get(count); try { int reply; ftp.connect(server); CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia connecting to server : " + server); CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia results: " + ftp.getReplyString()); CofaxToolsUtil.log(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return ("CofaxToolsFTP uploadArticleMedia ERROR: FTP server refused connection."); } else { ftp.login(liveFTPLogin, liveFTPPassword); } try { ftp.setFileType(FTP.IMAGE_FILE_TYPE); InputStream input; CofaxToolsUtil.log("CofaxToolsFTP: opening file stream: " + localPath + articleImageName); input = new FileInputStream(localPath + articleImageName); CofaxToolsUtil.log("CofaxToolsFTP: attempting to change working directory to: " + liveImagesFolder); boolean changed = ftp.changeWorkingDirectory(liveImagesFolder); CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia results: " + changed); if (changed == false) { CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia attempting to create directory :" + liveImagesFolder); boolean newDirYear = ftp.makeDirectory(liveImagesYearFolder); boolean newDirMonth = ftp.makeDirectory(liveImagesMonthFolder); boolean newDir = ftp.makeDirectory(liveImagesFolder); CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia results: YearDir: " + newDirYear + " MonthDir: " + newDirMonth + " finalDir: " + newDir); changed = ftp.changeWorkingDirectory(liveImagesFolder); } if (changed) { CofaxToolsUtil.log("CofaxToolsFTP: storing " + articleImageName + " to " + liveImagesFolder); stored = ftp.storeFile(articleImageName, input); } else { CofaxToolsUtil.log("CofaxToolsFTP: failed changing: " + liveImagesFolder); } if (stored) { CofaxToolsUtil.log("CofaxToolsFTP: Successfully ftped file."); } else { CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file."); } input.close(); ftp.logout(); ftp.disconnect(); } catch (org.apache.commons.net.io.CopyStreamException e) { CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file." + e.toString()); CofaxToolsUtil.log("CofaxToolsFTP: " + e.getIOException().toString()); return ("Cannot upload file " + liveImagesFolder + "/" + articleImageName); } catch (IOException e) { CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file." + e.toString()); return ("Cannot upload file " + liveImagesFolder + "/" + articleImageName); } catch (Exception e) { CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file." + e.toString()); return ("Cannot upload file " + liveImagesFolder + "/" + articleImageName); } } catch (IOException e) { return ("Could not connect to server: " + e); } } return (""); }
|
11
|
Code Sample 1:
public void load(String filename) throws VisbardException { String defaultFilename = VisbardMain.getSettingsDir() + File.separator + DEFAULT_SETTINGS_FILE; File defaultFile = new File(defaultFilename); InputStream settingsInStreamFromFile = null; try { sLogger.info("Loading settings from : " + defaultFilename); settingsInStreamFromFile = new FileInputStream(defaultFile); } catch (FileNotFoundException fnf) { sLogger.info("Unable to load custom settings from user's settings directory (" + fnf.getMessage() + "); reverting to default settings"); try { InputStream settingsInStreamFromJar = VisbardMain.class.getClassLoader().getResourceAsStream(filename); FileOutputStream settingsOutStream = new FileOutputStream(defaultFile); int c; while ((c = settingsInStreamFromJar.read()) != -1) settingsOutStream.write(c); settingsInStreamFromJar.close(); settingsOutStream.close(); settingsInStreamFromFile = new FileInputStream(defaultFile); } catch (IOException ioe) { sLogger.warn("Unable to copy default settings to user's settings directory (" + ioe.getMessage() + "); using default settings from ViSBARD distribution package"); settingsInStreamFromFile = VisbardMain.class.getClassLoader().getResourceAsStream(filename); } } this.processSettingsFile(settingsInStreamFromFile, filename); }
Code Sample 2:
@Test public void testWriteAndReadFirstLevel() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile directory1 = new RFile("directory1"); RFile file = new RFile(directory1, "testreadwrite1st.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } }
|
11
|
Code Sample 1:
public void render(ServiceContext serviceContext) throws Exception { if (serviceContext.getTemplateName() == null) throw new Exception("no Template defined for service: " + serviceContext.getServiceInfo().getRefName()); File f = new File(serviceContext.getTemplateName()); serviceContext.getResponse().setContentLength((int) f.length()); InputStream in = new FileInputStream(f); IOUtils.copy(in, serviceContext.getResponse().getOutputStream(), 0, (int) f.length()); in.close(); }
Code Sample 2:
public static void copyResourceToFile(Class owningClass, String resourceName, File destinationDir) { final byte[] resourceBytes = readResource(owningClass, resourceName); final ByteArrayInputStream inputStream = new ByteArrayInputStream(resourceBytes); final File destinationFile = new File(destinationDir, resourceName); final FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream(destinationFile); } catch (FileNotFoundException e) { throw new RuntimeException(e); } try { IOUtils.copy(inputStream, fileOutputStream); } catch (IOException e) { throw new RuntimeException(e); } }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files, int label, String charset) throws FilesException { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { if ((files == null) || (files.size() <= 0)) { return; } if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } Users user = getUser(hsession, repositoryName); Identity identity = getDefaultIdentity(hsession, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); for (int i = 0; i < files.size(); i++) { MultiPartEmail email = email = new MultiPartEmail(); email.setCharset(charset); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if (_to != null) { email.addTo(_to.getAddress(), _to.getPersonal()); } MailPartObj obj = (MailPartObj) files.get(i); email.setSubject("Files-System " + obj.getName()); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); email.attach(attachment); String mid = getId(); email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader("X-DBox", "FILES"); email.addHeader("X-DRecent", "false"); email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeMessage(mid, mime, user); } } catch (FilesException e) { throw e; } catch (Exception e) { throw new FilesException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new FilesException(ex); } catch (Throwable e) { throw new FilesException(e); } finally { GeneralOperations.closeHibernateSession(hsession); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } }
|
11
|
Code Sample 1:
public void setBckImg(String newPath) { try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = null; try { out = new FileOutputStream(outputFile); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); JOptionPane.showMessageDialog(null, ex1.getMessage().substring(0, Math.min(ex1.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } int c; if (out != null) { while ((c = in.read()) != -1) out.write(c); out.close(); } in.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } setPath(newPath); bckImg = new ImageIcon(getPath()); }
Code Sample 2:
public static void unzip2(String strZipFile, String folder) throws IOException, ArchiveException { FileUtil.fileExists(strZipFile, true); final InputStream is = new FileInputStream(strZipFile); ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is); ZipArchiveEntry entry = null; OutputStream out = null; while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) { File zipPath = new File(folder); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (entry.isDirectory()) { continue; } else { out = new FileOutputStream(new File(folder, entry.getName())); IOUtils.copy(in, out); out.close(); } } in.close(); }
|
00
|
Code Sample 1:
public void adicionaCliente(ClienteBean cliente) { PreparedStatement pstmt = null; ResultSet rs = null; String sql = "insert into cliente(nome,cpf,telefone,cursoCargo,bloqueado,ativo,tipo) values(?,?,?,?,?,?,?)"; try { pstmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstmt.setString(1, cliente.getNome()); pstmt.setString(2, cliente.getCPF()); pstmt.setString(3, cliente.getTelefone()); pstmt.setString(4, cliente.getCursoCargo()); pstmt.setString(5, cliente.getBloqueado()); pstmt.setString(6, cliente.getAtivo()); pstmt.setString(7, cliente.getTipo()); pstmt.executeUpdate(); rs = pstmt.getGeneratedKeys(); if (rs.next()) { cliente.setIdCliente(rs.getLong(1)); } connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (SQLException ex1) { throw new RuntimeException("Erro ao inserir cliente.", ex1); } throw new RuntimeException("Erro ao inserir cliente.", ex); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); } catch (SQLException ex) { throw new RuntimeException("Ocorreu um erro no banco de dados.", ex); } } }
Code Sample 2:
private void writeFile(File file, String fileName) { try { FileInputStream fin = new FileInputStream(file); FileOutputStream fout = new FileOutputStream(dirTableModel.getDirectory().getAbsolutePath() + File.separator + fileName); int val; while ((val = fin.read()) != -1) fout.write(val); fin.close(); fout.close(); dirTableModel.reset(); } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
public static String do_checksum(String data) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); StringBuffer strbuf = new StringBuffer(); md5.update(data.getBytes(), 0, data.length()); byte[] digest = md5.digest(); for (int i = 0; i < digest.length; i++) { strbuf.append(toHexString(digest[i])); } return strbuf.toString(); }
|
11
|
Code Sample 1:
private void backupFile(ZipOutputStream out, String base, String fn) throws IOException { String f = FileUtils.getAbsolutePath(fn); base = FileUtils.getAbsolutePath(base); if (!f.startsWith(base)) { Message.throwInternalError(f + " does not start with " + base); } f = f.substring(base.length()); f = correctFileName(f); out.putNextEntry(new ZipEntry(f)); InputStream in = FileUtils.openFileInputStream(fn); IOUtils.copyAndCloseInput(in, out); out.closeEntry(); }
Code Sample 2:
public static void copy(File from_file, File to_file) throws IOException { if (!from_file.exists()) { throw new IOException("FileCopy: no such source file: " + from_file.getPath()); } if (!from_file.isFile()) { throw new IOException("FileCopy: can't copy directory: " + from_file.getPath()); } if (!from_file.canRead()) { throw new IOException("FileCopy: source file is unreadable: " + from_file.getPath()); } if (to_file.isDirectory()) { to_file = new File(to_file, from_file.getName()); } if (to_file.exists()) { if (!to_file.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + to_file.getPath()); } int choice = JOptionPane.showConfirmDialog(null, "Overwrite existing file " + to_file.getPath(), "File Exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (choice != JOptionPane.YES_OPTION) { throw new IOException("FileCopy: existing file was not overwritten."); } } else { String parent = to_file.getParent(); if (parent == null) { parent = Globals.getDefaultPath(); } File dir = new File(parent); if (!dir.exists()) { throw new IOException("FileCopy: destination directory doesn't exist: " + parent); } if (dir.isFile()) { throw new IOException("FileCopy: destination is not a directory: " + parent); } if (!dir.canWrite()) { throw new IOException("FileCopy: destination directory is unwriteable: " + parent); } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } } finally { if (from != null) { try { from.close(); } catch (IOException e) { } } if (to != null) { try { to.close(); } catch (IOException e) { } } } }
|
00
|
Code Sample 1:
public boolean copy(File fromFile) throws IOException { FileUtility toFile = this; if (!fromFile.exists()) { abort("FileUtility: no such source file: " + fromFile.getAbsolutePath()); return false; } if (!fromFile.isFile()) { abort("FileUtility: can't copy directory: " + fromFile.getAbsolutePath()); return false; } if (!fromFile.canRead()) { abort("FileUtility: source file is unreadable: " + fromFile.getAbsolutePath()); return false; } if (this.isDirectory()) toFile = (FileUtility) (new File(this, fromFile.getName())); if (toFile.exists()) { if (!toFile.canWrite()) { abort("FileUtility: destination file is unwriteable: " + pathName); return false; } } else { String parent = toFile.getParent(); File dir = new File(parent); if (!dir.exists()) { abort("FileUtility: destination directory doesn't exist: " + parent); return false; } if (dir.isFile()) { abort("FileUtility: destination is not a directory: " + parent); return false; } if (!dir.canWrite()) { abort("FileUtility: destination directory is unwriteable: " + parent); return false; } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } return true; }
Code Sample 2:
public boolean renameTo(Folder f) throws MessagingException, StoreClosedException, NullPointerException { String[] aLabels = new String[] { "en", "es", "fr", "de", "it", "pt", "ca", "ja", "cn", "tw", "fi", "ru", "pl", "nl", "xx" }; PreparedStatement oUpdt = null; if (!((DBStore) getStore()).isConnected()) throw new StoreClosedException(getStore(), "Store is not connected"); if (oCatg.isNull(DB.gu_category)) throw new NullPointerException("Folder is closed"); try { oUpdt = getConnection().prepareStatement("DELETE FROM " + DB.k_cat_labels + " WHERE " + DB.gu_category + "=?"); oUpdt.setString(1, oCatg.getString(DB.gu_category)); oUpdt.executeUpdate(); oUpdt.close(); oUpdt.getConnection().prepareStatement("INSERT INTO " + DB.k_cat_labels + " (" + DB.gu_category + "," + DB.id_language + "," + DB.tr_category + "," + DB.url_category + ") VALUES (?,?,?,NULL)"); oUpdt.setString(1, oCatg.getString(DB.gu_category)); for (int l = 0; l < aLabels.length; l++) { oUpdt.setString(2, aLabels[l]); oUpdt.setString(3, f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1).toLowerCase()); oUpdt.executeUpdate(); } oUpdt.close(); oUpdt = null; getConnection().commit(); } catch (SQLException sqle) { try { if (null != oUpdt) oUpdt.close(); } catch (SQLException ignore) { } try { getConnection().rollback(); } catch (SQLException ignore) { } throw new MessagingException(sqle.getMessage(), sqle); } return true; }
|
11
|
Code Sample 1:
private MimeTypesProvider() { File mimeTypesFile = new File(XPontusConstantsIF.XPONTUS_HOME_DIR, "mimes.properties"); try { if (!mimeTypesFile.exists()) { OutputStream os = null; InputStream is = getClass().getResourceAsStream("/net/sf/xpontus/configuration/mimetypes.properties"); os = FileUtils.openOutputStream(mimeTypesFile); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } provider = new XPontusMimetypesFileTypeMap(mimeTypesFile.getAbsolutePath()); MimetypesFileTypeMap.setDefaultFileTypeMap(provider); } catch (Exception err) { err.printStackTrace(); } }
Code Sample 2:
private void dumpFile(File repository, File copy) { try { if (copy.exists() && !copy.delete()) { throw new RuntimeException("can't delete copy: " + copy); } printFile("Real Archive File", repository); new ZipArchive(repository.getPath()); IOUtils.copyFiles(repository, copy); printFile("Copy Archive File", copy); new ZipArchive(copy.getPath()); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = null; ServletOutputStream outstream = null; try { String action = req.getParameter("nmrshiftdbaction"); String relativepath = ServletUtils.expandRelative(this.getServletConfig(), "/WEB-INF"); TurbineConfig tc = new TurbineConfig(relativepath + "..", relativepath + getServletConfig().getInitParameter("properties")); tc.init(); int spectrumId = -1; DBSpectrum spectrum = null; Export export = null; String format = req.getParameter("format"); if (action.equals("test")) { try { res.setContentType("text/plain"); out = res.getWriter(); List l = DBSpectrumPeer.executeQuery("select SPECTRUM_ID from SPECTRUM limit 1"); if (l.size() > 0) spectrumId = ((Record) l.get(0)).getValue(1).asInt(); out.write("success"); } catch (Exception ex) { out.write("failure"); } } else if (action.equals("rss")) { int numbertoexport = 10; out = res.getWriter(); if (req.getParameter("numbertoexport") != null) { try { numbertoexport = Integer.parseInt(req.getParameter("numbertoexport")); if (numbertoexport < 1 || numbertoexport > 20) throw new NumberFormatException("Number to small/large"); } catch (NumberFormatException ex) { out.println("The parameter <code>numbertoexport</code>must be an integer from 1 to 20"); } } res.setContentType("text/xml"); RssWriter rssWriter = new RssWriter(); rssWriter.setWriter(res.getWriter()); AtomContainerSet soac = new AtomContainerSet(); String query = "select distinct MOLECULE.MOLECULE_ID from MOLECULE, SPECTRUM where SPECTRUM.MOLECULE_ID = MOLECULE.MOLECULE_ID and SPECTRUM.REVIEW_FLAG =\"true\" order by MOLECULE.DATE desc;"; List l = NmrshiftdbUserPeer.executeQuery(query); for (int i = 0; i < numbertoexport; i++) { if (i == l.size()) break; DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(((Record) l.get(i)).getValue(1).asInt())); IMolecule cdkmol = mol.getAsCDKMoleculeAsEntered(1); soac.addAtomContainer(cdkmol); rssWriter.getLinkmap().put(cdkmol, mol.getEasylink(req)); rssWriter.getDatemap().put(cdkmol, mol.getDate()); rssWriter.getTitlemap().put(cdkmol, mol.getChemicalNamesAsOneStringWithFallback()); rssWriter.getCreatormap().put(cdkmol, mol.getNmrshiftdbUser().getUserName()); rssWriter.setCreator(GeneralUtils.getAdminEmail(getServletConfig())); Vector v = mol.getDBCanonicalNames(); for (int k = 0; k < v.size(); k++) { DBCanonicalName canonName = (DBCanonicalName) v.get(k); if (canonName.getDBCanonicalNameType().getCanonicalNameType() == "INChI") { rssWriter.getInchimap().put(cdkmol, canonName.getName()); break; } } rssWriter.setTitle("NMRShiftDB"); rssWriter.setLink("http://www.nmrshiftdb.org"); rssWriter.setDescription("NMRShiftDB is an open-source, open-access, open-submission, open-content web database for chemical structures and their nuclear magnetic resonance data"); rssWriter.setPublisher("NMRShiftDB.org"); rssWriter.setImagelink("http://www.nmrshiftdb.org/images/nmrshift-logo.gif"); rssWriter.setAbout("http://www.nmrshiftdb.org/NmrshiftdbServlet?nmrshiftdbaction=rss"); Collection coll = new ArrayList(); Vector spectra = mol.selectSpectra(null); for (int k = 0; k < spectra.size(); k++) { Element el = ((DBSpectrum) spectra.get(k)).getCmlSpect(); Element el2 = el.getChildElements().get(0); el.removeChild(el2); coll.add(el2); } rssWriter.getMultiMap().put(cdkmol, coll); } rssWriter.write(soac); } else if (action.equals("getattachment")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); DBSample sample = DBSamplePeer.retrieveByPK(new NumberKey(req.getParameter("sampleid"))); outstream.write(sample.getAttachment()); } else if (action.equals("createreport")) { res.setContentType("application/pdf"); outstream = res.getOutputStream(); boolean yearly = req.getParameter("style").equals("yearly"); int yearstart = Integer.parseInt(req.getParameter("yearstart")); int yearend = Integer.parseInt(req.getParameter("yearend")); int monthstart = 0; int monthend = 0; if (!yearly) { monthstart = Integer.parseInt(req.getParameter("monthstart")); monthend = Integer.parseInt(req.getParameter("monthend")); } int type = Integer.parseInt(req.getParameter("type")); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(relativepath + "/reports/" + (yearly ? "yearly" : "monthly") + "_report_" + type + ".jasper"); Map parameters = new HashMap(); if (yearly) parameters.put("HEADER", "Report for years " + yearstart + " - " + yearend); else parameters.put("HEADER", "Report for " + monthstart + "/" + yearstart + " - " + monthend + "/" + yearend); DBConnection dbconn = TurbineDB.getConnection(); Connection conn = dbconn.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = null; if (type == 1) { rs = stmt.executeQuery("select YEAR(DATE) as YEAR, " + (yearly ? "" : " MONTH(DATE) as MONTH, ") + "AFFILIATION_1, AFFILIATION_2, MACHINE.NAME as NAME, count(*) as C, sum(WISHED_SPECTRUM like '%13C%' or WISHED_SPECTRUM like '%variable temperature%' or WISHED_SPECTRUM like '%ID sel. NOE%' or WISHED_SPECTRUM like '%solvent suppression%' or WISHED_SPECTRUM like '%standard spectrum%') as 1_D, sum(WISHED_SPECTRUM like '%H,H-COSY%' or WISHED_SPECTRUM like '%NOESY%' or WISHED_SPECTRUM like '%HMQC%' or WISHED_SPECTRUM like '%HMBC%') as 2_D, sum(OTHER_WISHED_SPECTRUM!='') as SPECIAL, sum(OTHER_NUCLEI!='') as HETERO, sum(PROCESS='self') as SELF, sum(PROCESS='robot') as ROBOT, sum(PROCESS='worker') as OPERATOR from (SAMPLE join TURBINE_USER using (USER_ID)) join MACHINE on MACHINE.MACHINE_ID=SAMPLE.MACHINE where YEAR(DATE)>=" + yearstart + " and YEAR(DATE)<=" + yearend + " and LOGIN_NAME<>'testuser' group by YEAR, " + (yearly ? "" : "MONTH, ") + "AFFILIATION_1, AFFILIATION_2, MACHINE.NAME"); } else if (type == 2) { rs = stmt.executeQuery("select YEAR(DATE) as YEAR, " + (yearly ? "" : " MONTH(DATE) as MONTH, ") + "MACHINE.NAME as NAME, count(*) as C, sum(WISHED_SPECTRUM like '%13C%' or WISHED_SPECTRUM like '%variable temperature%' or WISHED_SPECTRUM like '%ID sel. NOE%' or WISHED_SPECTRUM like '%solvent suppression%' or WISHED_SPECTRUM like '%standard spectrum%') as 1_D, sum(WISHED_SPECTRUM like '%H,H-COSY%' or WISHED_SPECTRUM like '%NOESY%' or WISHED_SPECTRUM like '%HMQC%' or WISHED_SPECTRUM like '%HMBC%') as 2_D, sum(OTHER_WISHED_SPECTRUM!='') as SPECIAL, sum(OTHER_NUCLEI!='') as HETERO, sum(PROCESS='self') as SELF, sum(PROCESS='robot') as ROBOT, sum(PROCESS='worker') as OPERATOR from (SAMPLE join TURBINE_USER using (USER_ID)) join MACHINE on MACHINE.MACHINE_ID=SAMPLE.MACHINE group by YEAR, " + (yearly ? "" : "MONTH, ") + "MACHINE.NAME"); } JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JRResultSetDataSource(rs)); JasperExportManager.exportReportToPdfStream(jasperPrint, outstream); dbconn.close(); } else if (action.equals("exportcmlbyinchi")) { res.setContentType("text/xml"); out = res.getWriter(); String inchi = req.getParameter("inchi"); String spectrumtype = req.getParameter("spectrumtype"); Criteria crit = new Criteria(); crit.add(DBCanonicalNamePeer.NAME, inchi); crit.addJoin(DBCanonicalNamePeer.MOLECULE_ID, DBSpectrumPeer.MOLECULE_ID); crit.addJoin(DBSpectrumPeer.SPECTRUM_TYPE_ID, DBSpectrumTypePeer.SPECTRUM_TYPE_ID); crit.add(DBSpectrumTypePeer.NAME, spectrumtype); try { GeneralUtils.logToSql(crit.toString(), null); } catch (Exception ex) { } Vector spectra = DBSpectrumPeer.doSelect(crit); if (spectra.size() == 0) { out.write("No such molecule or spectrum"); } else { Element cmlElement = new Element("cml"); cmlElement.addAttribute(new Attribute("convention", "nmrshiftdb-convention")); cmlElement.setNamespaceURI("http://www.xml-cml.org/schema"); Element parent = ((DBSpectrum) spectra.get(0)).getDBMolecule().getCML(1); nu.xom.Node cmldoc = parent.getChild(0); ((Element) cmldoc).setNamespaceURI("http://www.xml-cml.org/schema"); parent.removeChildren(); cmlElement.appendChild(cmldoc); for (int k = 0; k < spectra.size(); k++) { Element parentspec = ((DBSpectrum) spectra.get(k)).getCmlSpect(); Node spectrumel = parentspec.getChild(0); parentspec.removeChildren(); cmlElement.appendChild(spectrumel); ((Element) spectrumel).setNamespaceURI("http://www.xml-cml.org/schema"); } out.write(cmlElement.toXML()); } } else if (action.equals("namelist")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(baos); Criteria crit = new Criteria(); crit.addJoin(DBMoleculePeer.MOLECULE_ID, DBSpectrumPeer.MOLECULE_ID); crit.add(DBSpectrumPeer.REVIEW_FLAG, "true"); Vector v = DBMoleculePeer.doSelect(crit); for (int i = 0; i < v.size(); i++) { if (i % 500 == 0) { if (i != 0) { zipout.write(new String("<p>The list is continued <a href=\"nmrshiftdb.names." + i + ".html\">here</a></p></body></html>").getBytes()); zipout.closeEntry(); } zipout.putNextEntry(new ZipEntry("nmrshiftdb.names." + i + ".html")); zipout.write(new String("<html><body><h1>This is a list of strcutures in <a href=\"http://www.nmrshiftdb.org\">NMRShiftDB</a>, starting at " + i + ", Its main purpose is to be found by search engines</h1>").getBytes()); } DBMolecule mol = (DBMolecule) v.get(i); zipout.write(new String("<p><a href=\"" + mol.getEasylink(req) + "\">").getBytes()); Vector cannames = mol.getDBCanonicalNames(); for (int k = 0; k < cannames.size(); k++) { zipout.write(new String(((DBCanonicalName) cannames.get(k)).getName() + " ").getBytes()); } Vector chemnames = mol.getDBChemicalNames(); for (int k = 0; k < chemnames.size(); k++) { zipout.write(new String(((DBChemicalName) chemnames.get(k)).getName() + " ").getBytes()); } zipout.write(new String("</a>. Information we have got: NMR spectra").getBytes()); Vector spectra = mol.selectSpectra(); for (int k = 0; k < spectra.size(); k++) { zipout.write(new String(((DBSpectrum) spectra.get(k)).getDBSpectrumType().getName() + ", ").getBytes()); } if (mol.hasAny3d()) zipout.write(new String("3D coordinates, ").getBytes()); zipout.write(new String("File formats: CML, mol, png, jpeg").getBytes()); zipout.write(new String("</p>").getBytes()); } zipout.write(new String("</body></html>").getBytes()); zipout.closeEntry(); zipout.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } else if (action.equals("predictor")) { if (req.getParameter("symbol") == null) { res.setContentType("text/plain"); out = res.getWriter(); out.write("please give the symbol to create the predictor for in the request with symbol=X (e. g. symbol=C"); } res.setContentType("application/zip"); outstream = res.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(baos); String filename = "org/openscience/nmrshiftdb/PredictionTool.class"; zipout.putNextEntry(new ZipEntry(filename)); JarInputStream jip = new JarInputStream(new FileInputStream(ServletUtils.expandRelative(getServletConfig(), "/WEB-INF/lib/nmrshiftdb-lib.jar"))); JarEntry entry = jip.getNextJarEntry(); while (entry.getName().indexOf("PredictionTool.class") == -1) { entry = jip.getNextJarEntry(); } for (int i = 0; i < entry.getSize(); i++) { zipout.write(jip.read()); } zipout.closeEntry(); zipout.putNextEntry(new ZipEntry("nmrshiftdb.csv")); int i = 0; org.apache.turbine.util.db.pool.DBConnection conn = TurbineDB.getConnection(); HashMap mapsmap = new HashMap(); while (true) { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select HOSE_CODE, VALUE, SYMBOL from HOSE_CODES where CONDITION_TYPE='m' and WITH_RINGS=0 and SYMBOL='" + req.getParameter("symbol") + "' limit " + (i * 1000) + ", 1000"); int m = 0; while (rs.next()) { String code = rs.getString(1); Double value = new Double(rs.getString(2)); String symbol = rs.getString(3); if (mapsmap.get(symbol) == null) { mapsmap.put(symbol, new HashMap()); } for (int spheres = 6; spheres > 0; spheres--) { StringBuffer hoseCodeBuffer = new StringBuffer(); StringTokenizer st = new StringTokenizer(code, "()/"); for (int k = 0; k < spheres; k++) { if (st.hasMoreTokens()) { String partcode = st.nextToken(); hoseCodeBuffer.append(partcode); } if (k == 0) { hoseCodeBuffer.append("("); } else if (k == 3) { hoseCodeBuffer.append(")"); } else { hoseCodeBuffer.append("/"); } } String hoseCode = hoseCodeBuffer.toString(); if (((HashMap) mapsmap.get(symbol)).get(hoseCode) == null) { ((HashMap) mapsmap.get(symbol)).put(hoseCode, new ArrayList()); } ((ArrayList) ((HashMap) mapsmap.get(symbol)).get(hoseCode)).add(value); } m++; } i++; stmt.close(); if (m == 0) break; } Set keySet = mapsmap.keySet(); Iterator it = keySet.iterator(); while (it.hasNext()) { String symbol = (String) it.next(); HashMap hosemap = ((HashMap) mapsmap.get(symbol)); Set keySet2 = hosemap.keySet(); Iterator it2 = keySet2.iterator(); while (it2.hasNext()) { String hoseCode = (String) it2.next(); ArrayList list = ((ArrayList) hosemap.get(hoseCode)); double[] values = new double[list.size()]; for (int k = 0; k < list.size(); k++) { values[k] = ((Double) list.get(k)).doubleValue(); } zipout.write(new String(symbol + "|" + hoseCode + "|" + Statistics.minimum(values) + "|" + Statistics.average(values) + "|" + Statistics.maximum(values) + "\r\n").getBytes()); } } zipout.closeEntry(); zipout.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); byte[] buf = new byte[32 * 1024]; int nRead = 0; i = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } else if (action.equals("exportspec") || action.equals("exportmol")) { if (spectrumId > -1) spectrum = DBSpectrumPeer.retrieveByPK(new NumberKey(spectrumId)); else spectrum = DBSpectrumPeer.retrieveByPK(new NumberKey(req.getParameter("spectrumid"))); export = new Export(spectrum); } else if (action.equals("exportmdl")) { res.setContentType("text/plain"); outstream = res.getOutputStream(); DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(req.getParameter("moleculeid"))); outstream.write(mol.getStructureFile(Integer.parseInt(req.getParameter("coordsetid")), false).getBytes()); } else if (action.equals("exportlastinputs")) { format = action; } else if (action.equals("printpredict")) { res.setContentType("text/html"); out = res.getWriter(); HttpSession session = req.getSession(); VelocityContext context = PredictPortlet.getContext(session, true, true, new StringBuffer(), getServletConfig(), req, true); StringWriter w = new StringWriter(); Velocity.mergeTemplate("predictprint.vm", "ISO-8859-1", context, w); out.println(w.toString()); } else { res.setContentType("text/html"); out = res.getWriter(); out.println("No valid action"); } if (format == null) format = ""; if (format.equals("pdf") || format.equals("rtf")) { res.setContentType("application/" + format); out = res.getWriter(); } if (format.equals("docbook")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); } if (format.equals("svg")) { res.setContentType("image/x-svg"); out = res.getWriter(); } if (format.equals("tiff")) { res.setContentType("image/tiff"); outstream = res.getOutputStream(); } if (format.equals("jpeg")) { res.setContentType("image/jpeg"); outstream = res.getOutputStream(); } if (format.equals("png")) { res.setContentType("image/png"); outstream = res.getOutputStream(); } if (format.equals("mdl") || format.equals("txt") || format.equals("cml") || format.equals("cmlboth") || format.indexOf("exsection") == 0) { res.setContentType("text/plain"); out = res.getWriter(); } if (format.equals("simplehtml") || format.equals("exportlastinputs")) { res.setContentType("text/html"); out = res.getWriter(); } if (action.equals("exportlastinputs")) { int numbertoexport = 4; if (req.getParameter("numbertoexport") != null) { try { numbertoexport = Integer.parseInt(req.getParameter("numbertoexport")); if (numbertoexport < 1 || numbertoexport > 20) throw new NumberFormatException("Number to small/large"); } catch (NumberFormatException ex) { out.println("The parameter <code>numbertoexport</code>must be an integer from 1 to 20"); } } NmrshiftdbUser user = null; try { user = NmrshiftdbUserPeer.getByName(req.getParameter("username")); } catch (NmrshiftdbException ex) { out.println("Seems <code>username</code> is not OK: " + ex.getMessage()); } if (user != null) { List l = NmrshiftdbUserPeer.executeQuery("SELECT LAST_DOWNLOAD_DATE FROM TURBINE_USER where LOGIN_NAME=\"" + user.getUserName() + "\";"); Date lastDownloadDate = ((Record) l.get(0)).getValue(1).asDate(); if (((new Date().getTime() - lastDownloadDate.getTime()) / 3600000) < 24) { out.println("Your last download was at " + lastDownloadDate + ". You may download your last inputs only once a day. Sorry for this, but we need to be carefull with resources. If you want to put your last inputs on your homepage best use some sort of cache (e. g. use wget for downlaod with crond and link to this static resource))!"); } else { NmrshiftdbUserPeer.executeStatement("UPDATE TURBINE_USER SET LAST_DOWNLOAD_DATE=NOW() where LOGIN_NAME=\"" + user.getUserName() + "\";"); Vector<String> parameters = new Vector<String>(); String query = "select distinct MOLECULE.MOLECULE_ID from MOLECULE, SPECTRUM where SPECTRUM.MOLECULE_ID = MOLECULE.MOLECULE_ID and SPECTRUM.REVIEW_FLAG =\"true\" and SPECTRUM.USER_ID=" + user.getUserId() + " order by MOLECULE.DATE desc;"; l = NmrshiftdbUserPeer.executeQuery(query); String url = javax.servlet.http.HttpUtils.getRequestURL(req).toString(); url = url.substring(0, url.length() - 17); for (int i = 0; i < numbertoexport; i++) { if (i == l.size()) break; DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(((Record) l.get(i)).getValue(1).asInt())); parameters.add(new String("<a href=\"" + url + "/portal/pane0/Results?nmrshiftdbaction=showDetailsFromHome&molNumber=" + mol.getMoleculeId() + "\"><img src=\"" + javax.servlet.http.HttpUtils.getRequestURL(req).toString() + "?nmrshiftdbaction=exportmol&spectrumid=" + ((DBSpectrum) mol.getDBSpectrums().get(0)).getSpectrumId() + "&format=jpeg&size=150x150&backcolor=12632256\"></a>")); } VelocityContext context = new VelocityContext(); context.put("results", parameters); StringWriter w = new StringWriter(); Velocity.mergeTemplate("lateststructures.vm", "ISO-8859-1", context, w); out.println(w.toString()); } } } if (action.equals("exportspec")) { if (format.equals("txt")) { String lastsearchtype = req.getParameter("lastsearchtype"); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { List l = ParseUtils.parseSpectrumFromSpecFile(req.getParameter("lastsearchvalues")); spectrum.initSimilarity(l, lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)); } Vector v = spectrum.getOptions(); DBMolecule mol = spectrum.getDBMolecule(); out.print(mol.getChemicalNamesAsOneString(false) + mol.getMolecularFormula(false) + "; " + mol.getMolecularWeight() + " Dalton\n\r"); out.print("\n\rAtom\t"); if (spectrum.getDBSpectrumType().getElementSymbol() == ("H")) out.print("Mult.\t"); out.print("Meas."); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\tInput\tDiff"); } out.print("\n\r"); out.print("No.\t"); if (spectrum.getDBSpectrumType().getElementSymbol() == ("H")) out.print("\t"); out.print("Shift"); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\tShift\tM-I"); } out.print("\n\r"); for (int i = 0; i < v.size(); i++) { out.print(((ValuesForVelocityBean) v.get(i)).getDisplayText() + "\t" + ((ValuesForVelocityBean) v.get(i)).getRange()); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\t" + ((ValuesForVelocityBean) v.get(i)).getNameForElements() + "\t" + ((ValuesForVelocityBean) v.get(i)).getDelta()); } out.print("\n\r"); } } if (format.equals("simplehtml")) { String i1 = export.getImage(false, "jpeg", ServletUtils.expandRelative(this.getServletConfig(), "/nmrshiftdbhtml") + "/tmp/" + System.currentTimeMillis(), true); export.pictures[0] = new File(i1).getName(); String i2 = export.getImage(true, "jpeg", ServletUtils.expandRelative(this.getServletConfig(), "/nmrshiftdbhtml") + "/tmp/" + System.currentTimeMillis(), true); export.pictures[1] = new File(i2).getName(); String docbook = export.getHtml(); out.print(docbook); } if (format.equals("pdf") || format.equals("rtf")) { String svgSpec = export.getSpecSvg(400, 200); String svgspecfile = relativepath + "/tmp/" + System.currentTimeMillis() + "s.svg"; new FileOutputStream(svgspecfile).write(svgSpec.getBytes()); export.pictures[1] = svgspecfile; String molSvg = export.getMolSvg(true); String svgmolfile = relativepath + "/tmp/" + System.currentTimeMillis() + "m.svg"; new FileOutputStream(svgmolfile).write(molSvg.getBytes()); export.pictures[0] = svgmolfile; String docbook = export.getDocbook("pdf", "SVG"); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new StreamSource("file:" + GeneralUtils.getNmrshiftdbProperty("docbookxslpath", getServletConfig()) + "/fo/docbook.xsl")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); transformer.transform(new StreamSource(new StringReader(docbook)), new StreamResult(baos)); FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); OutputStream out2 = new ByteArrayOutputStream(); Fop fop = fopFactory.newFop(format.equals("rtf") ? MimeConstants.MIME_RTF : MimeConstants.MIME_PDF, foUserAgent, out2); TransformerFactory factory = TransformerFactory.newInstance(); transformer = factory.newTransformer(); Source src = new StreamSource(new StringReader(baos.toString())); Result res2 = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res2); out.print(out2.toString()); } if (format.equals("docbook")) { String i1 = relativepath + "/tmp/" + System.currentTimeMillis() + ".svg"; new FileOutputStream(i1).write(export.getSpecSvg(300, 200).getBytes()); export.pictures[0] = new File(i1).getName(); String i2 = relativepath + "/tmp/" + System.currentTimeMillis() + ".svg"; new FileOutputStream(i2).write(export.getMolSvg(true).getBytes()); export.pictures[1] = new File(i2).getName(); String docbook = export.getDocbook("pdf", "SVG"); String docbookfile = relativepath + "/tmp/" + System.currentTimeMillis() + ".xml"; new FileOutputStream(docbookfile).write(docbook.getBytes()); ByteArrayOutputStream baos = export.makeZip(new String[] { docbookfile, i1, i2 }); outstream.write(baos.toByteArray()); } if (format.equals("svg")) { out.print(export.getSpecSvg(400, 200)); } if (format.equals("tiff") || format.equals("jpeg") || format.equals("png")) { InputStream is = new FileInputStream(export.getImage(false, format, relativepath + "/tmp/" + System.currentTimeMillis(), true)); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } if (format.equals("cml")) { out.print(spectrum.getCmlSpect().toXML()); } if (format.equals("cmlboth")) { Element cmlElement = new Element("cml"); cmlElement.addAttribute(new Attribute("convention", "nmrshiftdb-convention")); cmlElement.setNamespaceURI("http://www.xml-cml.org/schema"); Element parent = spectrum.getDBMolecule().getCML(1, spectrum.getDBSpectrumType().getName().equals("1H")); nu.xom.Node cmldoc = parent.getChild(0); ((Element) cmldoc).setNamespaceURI("http://www.xml-cml.org/schema"); parent.removeChildren(); cmlElement.appendChild(cmldoc); Element parentspec = spectrum.getCmlSpect(); Node spectrumel = parentspec.getChild(0); parentspec.removeChildren(); cmlElement.appendChild(spectrumel); ((Element) spectrumel).setNamespaceURI("http://www.xml-cml.org/schema"); out.write(cmlElement.toXML()); } if (format.indexOf("exsection") == 0) { StringTokenizer st = new StringTokenizer(format, "-"); st.nextToken(); String template = st.nextToken(); Criteria crit = new Criteria(); crit.add(DBSpectrumPeer.USER_ID, spectrum.getUserId()); Vector v = spectrum.getDBMolecule().getDBSpectrums(crit); VelocityContext context = new VelocityContext(); context.put("spectra", v); context.put("molecule", spectrum.getDBMolecule()); StringWriter w = new StringWriter(); Velocity.mergeTemplate("exporttemplates/" + template, "ISO-8859-1", context, w); out.write(w.toString()); } } if (action.equals("exportmol")) { int width = -1; int height = -1; if (req.getParameter("size") != null) { StringTokenizer st = new StringTokenizer(req.getParameter("size"), "x"); width = Integer.parseInt(st.nextToken()); height = Integer.parseInt(st.nextToken()); } boolean shownumbers = true; if (req.getParameter("shownumbers") != null && req.getParameter("shownumbers").equals("false")) { shownumbers = false; } if (req.getParameter("backcolor") != null) { export.backColor = new Color(Integer.parseInt(req.getParameter("backcolor"))); } if (req.getParameter("markatom") != null) { export.selected = Integer.parseInt(req.getParameter("markatom")) - 1; } if (format.equals("svg")) { out.print(export.getMolSvg(true)); } if (format.equals("tiff") || format.equals("jpeg") || format.equals("png")) { InputStream is = new FileInputStream(export.getImage(true, format, relativepath + "/tmp/" + System.currentTimeMillis(), width, height, shownumbers, null)); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } if (format.equals("mdl")) { out.println(spectrum.getDBMolecule().getStructureFile(1, false)); } if (format.equals("cml")) { out.println(spectrum.getDBMolecule().getCMLString(1)); } } if (out != null) out.flush(); else outstream.flush(); } catch (Exception ex) { ex.printStackTrace(); out.print(GeneralUtils.logError(ex, "NmrshiftdbServlet", null, true)); out.flush(); } }
Code Sample 2:
public static void insertTableData(Connection dest, TableMetaData tableMetaData) throws Exception { PreparedStatement ps = null; try { dest.setAutoCommit(false); String sql = "INSERT INTO " + tableMetaData.getSchema() + "." + tableMetaData.getTableName() + " ("; for (String columnName : tableMetaData.getColumnsNames()) { sql += columnName + ","; } sql = sql.substring(0, sql.length() - 1); sql += ") VALUES ("; for (String columnName : tableMetaData.getColumnsNames()) { sql += "?" + ","; } sql = sql.substring(0, sql.length() - 1); sql += ")"; IOHelper.writeInfo(sql); ps = dest.prepareStatement(sql); for (Row r : tableMetaData.getData()) { try { int param = 1; for (String columnName : tableMetaData.getColumnsNames()) { if (dest instanceof OracleConnection) { if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("BLOB")) { BLOB blob = new BLOB((OracleConnection) dest, (byte[]) r.getRowData().get(columnName)); ((OraclePreparedStatement) ps).setBLOB(param, blob); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("CLOB")) { ((OraclePreparedStatement) ps).setStringForClob(param, (String) r.getRowData().get(columnName)); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("LONG")) { ps.setBytes(param, (byte[]) r.getRowData().get(columnName)); } } else { IOHelper.writeInfo(columnName + " = " + r.getRowData().get(columnName)); ps.setObject(param, r.getRowData().get(columnName)); } param++; } if (ps.executeUpdate() != 1) { dest.rollback(); updateTableData(dest, tableMetaData, r); } } catch (Exception ex) { try { dest.rollback(); updateTableData(dest, tableMetaData, r); } catch (Exception ex2) { IOHelper.writeError("Error in update " + sql, ex2); } } ps.clearParameters(); } dest.commit(); dest.setAutoCommit(true); } finally { if (ps != null) ps.close(); } }
|
00
|
Code Sample 1:
public static IProject CreateJavaProject(String name, IPath classpath) throws CoreException { // Create and Open New Project in Workspace IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); IProject project = root.getProject(name); project.create(null); project.open(null); // Add Java Nature to new Project IProjectDescription desc = project.getDescription(); desc.setNatureIds(new String[] { JavaCore.NATURE_ID}); project.setDescription(desc, null); // Get Java Project Object IJavaProject javaProj = JavaCore.create(project); // Set Output Folder IFolder binDir = project.getFolder("bin"); IPath binPath = binDir.getFullPath(); javaProj.setOutputLocation(binPath, null); // Set Project's Classpath IClasspathEntry cpe = JavaCore.newLibraryEntry(classpath, null, null); javaProj.setRawClasspath(new IClasspathEntry[] {cpe}, null); return project; }
Code Sample 2:
public static String MD5Digest(String source) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(source.getBytes("UTF8")); byte[] hash = digest.digest(); String strHash = byteArrayToHexString(hash); return strHash; } catch (NoSuchAlgorithmException e) { String msg = "%s: %s"; msg = String.format(msg, e.getClass().getName(), e.getMessage()); logger.error(msg); return null; } catch (UnsupportedEncodingException e) { String msg = "%s: %s"; msg = String.format(msg, e.getClass().getName(), e.getMessage()); logger.error(msg); return null; } }
|
11
|
Code Sample 1:
private static void zip(ZipOutputStream aOutputStream, final File[] aFiles, final String sArchive, final URI aRootURI, final String sFilter) throws FileError { boolean closeStream = false; if (aOutputStream == null) try { aOutputStream = new ZipOutputStream(new FileOutputStream(sArchive)); closeStream = true; } catch (final FileNotFoundException e) { throw new FileError("Can't create ODF file!", e); } try { try { for (final File curFile : aFiles) { aOutputStream.putNextEntry(new ZipEntry(URLDecoder.decode(aRootURI.relativize(curFile.toURI()).toASCIIString(), "UTF-8"))); if (curFile.isDirectory()) { aOutputStream.closeEntry(); FileUtils.zip(aOutputStream, FileUtils.getFiles(curFile, sFilter), sArchive, aRootURI, sFilter); continue; } final FileInputStream inputStream = new FileInputStream(curFile); for (int i; (i = inputStream.read(FileUtils.BUFFER)) != -1; ) aOutputStream.write(FileUtils.BUFFER, 0, i); inputStream.close(); aOutputStream.closeEntry(); } } finally { if (closeStream && aOutputStream != null) aOutputStream.close(); } } catch (final IOException e) { throw new FileError("Can't zip file to archive!", e); } if (closeStream) DocumentController.getStaticLogger().fine(aFiles.length + " files and folders zipped as " + sArchive); }
Code Sample 2:
public static void main(String[] args) throws Exception { String linesep = System.getProperty("line.separator"); FileOutputStream fos = new FileOutputStream(new File("lib-licenses.txt")); fos.write(new String("JCP contains the following libraries. Please read this for comments on copyright etc." + linesep + linesep).getBytes()); fos.write(new String("Chemistry Development Kit, master version as of " + new Date().toString() + " (http://cdk.sf.net)" + linesep).getBytes()); fos.write(new String("Copyright 1997-2009 The CDK Development Team" + linesep).getBytes()); fos.write(new String("License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)" + linesep).getBytes()); fos.write(new String("Download: https://sourceforge.net/projects/cdk/files/" + linesep).getBytes()); fos.write(new String("Source available at: http://sourceforge.net/scm/?type=git&group_id=20024" + linesep + linesep).getBytes()); File[] files = new File(args[0]).listFiles(new JarFileFilter()); for (int i = 0; i < files.length; i++) { if (new File(files[i].getPath() + ".meta").exists()) { Map<String, Map<String, String>> metaprops = readProperties(new File(files[i].getPath() + ".meta")); Iterator<String> itsect = metaprops.keySet().iterator(); while (itsect.hasNext()) { String section = itsect.next(); fos.write(new String(metaprops.get(section).get("Library") + " " + metaprops.get(section).get("Version") + " (" + metaprops.get(section).get("Homepage") + ")" + linesep).getBytes()); fos.write(new String("Copyright " + metaprops.get(section).get("Copyright") + linesep).getBytes()); fos.write(new String("License: " + metaprops.get(section).get("License") + " (" + metaprops.get(section).get("LicenseURL") + ")" + linesep).getBytes()); fos.write(new String("Download: " + metaprops.get(section).get("Download") + linesep).getBytes()); fos.write(new String("Source available at: " + metaprops.get(section).get("SourceCode") + linesep + linesep).getBytes()); } } if (new File(files[i].getPath() + ".extra").exists()) { fos.write(new String("The author says:" + linesep).getBytes()); FileInputStream in = new FileInputStream(new File(files[i].getPath() + ".extra")); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } fos.write(linesep.getBytes()); } fos.close(); }
|
00
|
Code Sample 1:
public static final String convertPassword(final String srcPwd) { StringBuilder out; MessageDigest md; byte[] byteValues; byte singleChar = 0; try { md = MessageDigest.getInstance("MD5"); md.update(srcPwd.getBytes()); byteValues = md.digest(); if ((byteValues == null) || (byteValues.length <= 0)) { return null; } out = new StringBuilder(byteValues.length * 2); for (byte element : byteValues) { singleChar = (byte) (element & 0xF0); singleChar = (byte) (singleChar >>> 4); singleChar = (byte) (singleChar & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); singleChar = (byte) (element & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); } return out.toString(); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
Code Sample 2:
public static void copy(String inputFile, String outputFile) throws Exception { try { 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 e) { throw new Exception("Could not copy " + inputFile + " into " + outputFile + " because:\n" + e.getMessage()); } }
|
11
|
Code Sample 1:
public void copiarMidias(final File vidDir, final File imgDir) { for (int i = 0; i < getMidias().size(); i++) { try { FileChannel src = new FileInputStream(getMidias().get(i).getUrl().trim()).getChannel(); FileChannel dest; if (getMidias().get(i).getTipo().equals("video")) { FileChannel vidDest = new FileOutputStream(vidDir + "/" + processaString(getMidias().get(i).getTitulo()) + "." + retornaExtensaoMidia(getMidias().get(i))).getChannel(); dest = vidDest; } else { FileChannel midDest = new FileOutputStream(imgDir + "/" + processaString(getMidias().get(i).getTitulo()) + "." + retornaExtensaoMidia(getMidias().get(i))).getChannel(); dest = midDest; } dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (Exception e) { System.err.print(e.getMessage()); e.printStackTrace(); } } }
Code Sample 2:
public int procesar() { int mas = 0; String uriOntologia = "", source = "", uri = ""; String fichOrigenHTML = "", fichOrigenLN = ""; String ficheroOutOWL = ""; md5 firma = null; StringTokenV2 entra = null, entra2 = null, entra3 = null; FileInputStream lengNat = null; BufferedInputStream lengNat2 = null; DataInputStream entradaLenguajeNatural = null; FileWriter salOWL = null; BufferedWriter salOWL2 = null; PrintWriter salidaOWL = null; String sujeto = "", verbo = "", CD = "", CI = "", fraseOrigen = ""; StringTokenV2 token2; boolean bandera = false; OntClass c = null; OntClass cBak = null; String claseTrabajo = ""; String nombreClase = "", nombrePropiedad = "", variasPalabras = ""; int incre = 0, emergencia = 0; String lineaSalida = ""; String[] ontologia = new String[5]; ontologia[0] = "http://www.criado.info/owl/vertebrados_es.owl#"; ontologia[1] = "http://www.w3.org/2001/sw/WebOnt/guide-src/wine#"; ontologia[2] = "http://www.co-ode.org/ontologies/pizza/2005/10/18/pizza.owl#"; ontologia[3] = "http://www.w3.org/2001/sw/WebOnt/guide-src/food#"; ontologia[4] = "http://www.daml.org/2001/01/gedcom/gedcom#"; String[] ontologiaSource = new String[5]; ontologiaSource[0] = this.directorioMapeo + "\\" + "mapeo_vertebrados_es.xml"; ontologiaSource[1] = this.directorioMapeo + "\\" + "mapeo_wine_es.xml"; ontologiaSource[2] = this.directorioMapeo + "\\" + "mapeo_pizza_es.xml"; ontologiaSource[3] = this.directorioMapeo + "\\" + "mapeo_food_es.xml"; ontologiaSource[4] = this.directorioMapeo + "\\" + "mapeo_parentesco_es.xml"; mapeoIdiomas clasesOntologias; try { if ((entrada = entradaFichero.readLine()) != null) { if (entrada.trim().length() > 10) { entrada2 = new StringTokenV2(entrada.trim(), "\""); if (entrada2.isIncluidaSubcadena("<fichero ontologia=")) { ontologiaOrigen = entrada2.getToken(2); fichOrigenHTML = entrada2.getToken(4); fichOrigenLN = entrada2.getToken(6); if (ontologiaOrigen.equals("VERTEBRADOS")) { source = ontologiaSource[0]; uriOntologia = ontologia[0]; } if (ontologiaOrigen.equals("WINE")) { source = ontologiaSource[1]; uriOntologia = ontologia[1]; } if (ontologiaOrigen.equals("PIZZA")) { source = ontologiaSource[2]; uriOntologia = ontologia[2]; } if (ontologiaOrigen.equals("FOOD")) { source = ontologiaSource[3]; uriOntologia = ontologia[3]; } if (ontologiaOrigen.equals("PARENTESCOS")) { source = ontologiaSource[4]; uriOntologia = ontologia[4]; } firma = new md5(uriOntologia, false); clasesOntologias = new mapeoIdiomas(source); uri = ""; ficheroOutOWL = ""; entra2 = new StringTokenV2(fichOrigenHTML, "\\"); int numToken = entra2.getNumeroTokenTotales(); entra = new StringTokenV2(fichOrigenHTML, " "); if (entra.isIncluidaSubcadena(directorioLocal)) { entra = new StringTokenV2(entra.getQuitar(directorioLocal) + "", " "); uri = entra.getCambiar("\\", "/"); uri = entra.getQuitar(entra2.getToken(numToken)) + ""; entra3 = new StringTokenV2(entra2.getToken(numToken), "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; uri = urlPatron + uri + ficheroOutOWL; } entra3 = new StringTokenV2(fichOrigenHTML, "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; lineaSalida = "<vistasemantica origen=\"" + fichOrigenLN + "\" destino=\"" + uri + "\" />"; lengNat = new FileInputStream(fichOrigenLN); lengNat2 = new BufferedInputStream(lengNat); entradaLenguajeNatural = new DataInputStream(lengNat2); salOWL = new FileWriter(ficheroOutOWL); salOWL2 = new BufferedWriter(salOWL); salidaOWL = new PrintWriter(salOWL2); while ((entradaInstancias = entradaLenguajeNatural.readLine()) != null) { sujeto = ""; verbo = ""; CD = ""; CI = ""; fraseOrigen = ""; if (entradaInstancias.trim().length() > 10) { entrada2 = new StringTokenV2(entradaInstancias.trim(), "\""); if (entrada2.isIncluidaSubcadena("<oracion sujeto=")) { sujeto = entrada2.getToken(2).trim(); verbo = entrada2.getToken(4).trim(); CD = entrada2.getToken(6).trim(); CI = entrada2.getToken(8).trim(); fraseOrigen = entrada2.getToken(10).trim(); if (sujeto.length() > 0 & verbo.length() > 0 & CD.length() > 0) { bandera = false; c = null; cBak = null; nombreClase = clasesOntologias.getClaseInstancia(CD); if (nombreClase.length() > 0) { bandera = true; } if (bandera) { if (incre == 0) { salidaOWL.write(" <rdf:RDF " + "\n"); salidaOWL.write(" xmlns:j.0=\"" + uriOntologia + "\"" + "\n"); salidaOWL.write(" xmlns:protege=\"http://protege.stanford.edu/plugins/owl/protege#\"" + "\n"); salidaOWL.write(" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"" + "\n"); salidaOWL.write(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"" + "\n"); salidaOWL.write(" xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"" + "\n"); salidaOWL.write(" xmlns:owl=\"http://www.w3.org/2002/07/owl#\" " + "\n"); salidaOWL.write(" xmlns=\"" + uri + "#\"" + "\n"); salidaOWL.write(" xml:base=\"" + uri + "\">" + "\n"); salidaOWL.write(" <owl:Ontology rdf:about=\"\">" + "\n"); salidaOWL.write(" <owl:imports rdf:resource=\"" + uriOntologia + "\"/>" + "\n"); salidaOWL.write(" </owl:Ontology>" + "\n"); salidaOWL.flush(); salida.write(lineaSalida + "\n"); salida.flush(); incre = 1; } salidaOWL.write(" <j.0:" + nombreClase + " rdf:ID=\"" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" <owl:AllDifferent>" + "\n"); salidaOWL.write(" <owl:distinctMembers rdf:parseType=\"Collection\">" + "\n"); salidaOWL.write(" <" + nombreClase + " rdf:about=\"#" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" </owl:distinctMembers>" + "\n"); salidaOWL.write(" </owl:AllDifferent>" + "\n"); salidaOWL.flush(); bandera = false; } } } } } salidaOWL.write(" </rdf:RDF>" + "\n" + "\n"); salidaOWL.write("<!-- Creado por [html2ws] http://www.luis.criado.org -->" + "\n"); salidaOWL.flush(); } } mas = 1; } else { salida.write("</listaVistasSemanticas>\n"); salida.flush(); salida.close(); bw2.close(); fw2.close(); salidaOWL.close(); entradaFichero.close(); ent2.close(); ent1.close(); mas = -1; } } catch (Exception e) { mas = -2; salida.write("No se encuentra: " + fichOrigen + "\n"); salida.flush(); } return mas; }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.