label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: private PrecomputedAnimatedModel loadPrecomputedModel_(URL url) { if (precompCache.containsKey(url.toExternalForm())) { return (precompCache.get(url.toExternalForm()).copy()); } TextureLoader.getInstance().getTexture(""); List<SharedGroup> frames = new ArrayList<SharedGroup>(); Map<String, Animation> animations = new Hashtable<String, Animation>(); if (url.toExternalForm().endsWith(".amo")) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String objFileName = reader.readLine(); objFileName = url.toExternalForm().substring(0, url.toExternalForm().lastIndexOf("/")) + "/" + objFileName; frames = loadOBJFrames(objFileName); String line; while ((line = reader.readLine()) != null) { StringTokenizer tokenizer = new StringTokenizer(line); String animName = tokenizer.nextToken(); int from = Integer.valueOf(tokenizer.nextToken()); int to = Integer.valueOf(tokenizer.nextToken()); tokenizer.nextToken(); animations.put(animName, new Animation(animName, from, to)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { frames = loadOBJFrames(url.toExternalForm()); } PrecomputedAnimatedModel precompModel = new PrecomputedAnimatedModel(frames, animations); precompCache.put(url.toExternalForm(), precompModel); return (precompModel); } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private static String doGetForSessionKey(String authCode) throws Exception { String sessionKey = ""; HttpClient hc = new DefaultHttpClient(); HttpGet hg = new HttpGet(Common.TEST_SESSION_HOST + Common.TEST_SESSION_PARAM + authCode); HttpResponse hr = hc.execute(hg); BufferedReader br = new BufferedReader(new InputStreamReader(hr.getEntity().getContent())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } String result = sb.toString(); Log.i("sessionKeyMessages", result); Map<String, String> map = Util.handleURLParameters(result); sessionKey = map.get(Common.TOP_SESSION); String topParameters = map.get(Common.TOP_PARAMETERS); String decTopParameters = Util.decodeBase64(topParameters); Log.i("base64", decTopParameters); map = Util.handleURLParameters(decTopParameters); Log.i("nick", map.get(Common.VISITOR_NICK)); CachePool.put(Common.VISITOR_NICK, map.get(Common.VISITOR_NICK)); return sessionKey; } Code Sample 2: public String getPassword(URI uri) { if (_getPassword(uri) != null) return _getPassword(uri); String result = null; try { String sUri = scrubURI(uri); URL url = new URL(TEMP_PASSWORD_SERVICE_URL + "?SID=" + sessionId + "&ruri=" + URLEncoder.encode(sUri, "UTF-8")); JSONObject jsonObject = null; URLConnection conn = url.openConnection(); InputStream istream = conn.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(istream)); if ((result = in.readLine()) != null) { jsonObject = new JSONObject(result); } if (jsonObject.has("success")) { if (jsonObject.get("success").toString().equals("false")) { if (jsonObject.has("error")) { logger.log("Returned error message from temporary password service is: " + jsonObject.get("error")); } return null; } } if (jsonObject.has("temppass")) { result = (String) jsonObject.get("temppass"); } } catch (java.io.FileNotFoundException fe) { logger.log("Could not find temporary password service. " + fe); fe.printStackTrace(); } catch (Exception e) { logger.log("Exception getting temporary password. " + e); e.printStackTrace(); } if (result == null) return null; return result; }
00
Code Sample 1: protected final void loadLogFile(String filename) throws IOException { cleanUp(true, false); InputStream is = null; OutputStream os = null; File f = File.createTempFile("log", null); try { is = getClass().getResourceAsStream(filename); Assert.isTrue(is != null, "File not found: " + filename); os = new FileOutputStream(f); IOUtils.copy(is, os); setLogFile(f); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } Code Sample 2: public synchronized FTPClient getFTPClient(String User, String Password) throws IOException { if (logger.isDebugEnabled()) { logger.debug("getFTPClient(String, String) - start"); } while ((counter >= maxClients)) { try { wait(); } catch (InterruptedException e) { logger.error("getFTPClient(String, String)", e); e.printStackTrace(); } } FTPClient result = null; String key = User.concat(Password); logger.debug("versuche vorhandenen FTPClient aus Liste zu lesen"); if (Clients != null) { if (Clients.containsKey(key)) { LinkedList ClientList = (LinkedList) Clients.get(key); if (!ClientList.isEmpty()) do { result = (FTPClient) ClientList.getLast(); logger.debug("-- hole einen Client aus der Liste: " + result.toString()); ClientList.removeLast(); if (!result.isConnected()) { logger.debug("---- nicht mehr verbunden."); result = null; } else { try { result.changeWorkingDirectory("/"); } catch (IOException e) { logger.debug("---- schmei�t Exception bei Zugriff."); result = null; } } } while (result == null && !ClientList.isEmpty()); if (ClientList.isEmpty()) { Clients.remove(key); } } else { } } else logger.debug("-- keine Liste vorhanden."); if (result == null) { logger.debug("Kein FTPCLient verf�gbar, erstelle einen neuen."); result = new FTPClient(); logger.debug("-- Versuche Connect"); result.connect(Host); logger.debug("-- Versuche Login"); result.login(User, Password); result.setFileType(FTPClient.BINARY_FILE_TYPE); if (counter == maxClients - 1) { RemoveBufferedClient(); } } logger.debug("OK: neuer FTPClient ist " + result.toString()); ; counter++; if (logger.isDebugEnabled()) { logger.debug("getFTPClient(String, String) - end"); } return result; }
11
Code Sample 1: public static void downloadFile(HttpServletResponse response, String file) throws IOException { response.setContentType(FileUtils.getContentType(file)); response.setContentLength(FileUtils.getContentLength(file)); response.setHeader("Content-type", ResponseUtils.DOWNLOAD_CONTENT_TYPE); response.setHeader("Content-Disposition", "attachment; filename=\"" + FileUtils.getFileName(file) + "\""); response.setHeader("Content-Length", Integer.toString(FileUtils.getContentLength(file))); InputStream input = new FileInputStream(file); OutputStream output = response.getOutputStream(); IOUtils.copy(input, output, true); } Code Sample 2: public void includeJs(Group group, Writer out, PageContext pageContext) throws IOException { includeResource(pageContext, out, RetentionHelper.buildRootRetentionFilePath(group, ".js"), JS_BEGIN_TAG, JS_END_TAG); ByteArrayOutputStream outtmp = new ByteArrayOutputStream(); if (AbstractGroupBuilder.getInstance().buildGroupJsIfNeeded(group, outtmp, pageContext.getServletContext())) { FileOutputStream fileStream = new FileOutputStream(new File(RetentionHelper.buildFullRetentionFilePath(group, ".js"))); IOUtils.copy(new ByteArrayInputStream(outtmp.toByteArray()), fileStream); fileStream.close(); } }
00
Code Sample 1: private void sendLocal() throws Exception { if (validParameters()) { URL url = new URL(storageUrlString); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); RequestUtils requestUtils = new RequestUtils(); requestUtils.preRequestAddParameter("senderObj", "QuotaSender"); requestUtils.preRequestAddParameter("beanNumbers", new String().valueOf(quotaBeans.size())); for (int vPos = 0; vPos < quotaBeans.size(); vPos++) { QuotaBean bean = (QuotaBean) quotaBeans.get(vPos); requestUtils.preRequestAddParameter("" + vPos + "#portalID", bean.getPortalID()); requestUtils.preRequestAddParameter("" + vPos + "#userID", bean.getUserID()); requestUtils.preRequestAddParameter("" + vPos + "#workflowID", bean.getWorkflowID()); requestUtils.preRequestAddParameter("" + vPos + "#runtimeID", bean.getRuntimeID()); requestUtils.preRequestAddParameter("" + vPos + "#plussQuotaSize", bean.getPlussQuotaSize().toString()); } requestUtils.preRequestAddFile("zipFileName", "dummyZipFileName.zip"); requestUtils.createPostRequest(); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + requestUtils.getBoundary()); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); try { httpURLConnection.connect(); OutputStream out = httpURLConnection.getOutputStream(); byte[] preBytes = requestUtils.getPreRequestStringBytes(); out.write(preBytes); out.flush(); out.write(new String("dummyFile").getBytes()); byte[] postBytes = requestUtils.getPostRequestStringBytes(); out.write(postBytes); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); in.readLine(); in.close(); if (HttpURLConnection.HTTP_OK != httpURLConnection.getResponseCode()) { throw new Exception("response not HTTP_OK !"); } } catch (Exception e) { e.printStackTrace(); throw new Exception("Cannot connect to: " + storageUrlString, e); } } else { throw new Exception("Not valid parameters: quotaBeans !"); } } Code Sample 2: public Controller(String m_hostname, String team, boolean m_shouldexit) throws InternalException { m_received_messages = new ConcurrentLinkedQueue<ReceivedMessage>(); m_fragmsgs = new ArrayList<String>(); m_customizedtaunts = new HashMap<Integer, String>(); m_nethandler = new CachingNetHandler(); m_drawingpanel = GLDrawableFactory.getFactory().createGLCanvas(new GLCapabilities()); m_user = System.getProperty("user.name"); m_chatbuffer = new StringBuffer(); this.m_shouldexit = m_shouldexit; isChatPaused = false; isRunning = true; m_lastbullet = 0; try { BufferedReader in = new BufferedReader(new FileReader(HogsConstants.FRAGMSGS_FILE)); String str; while ((str = in.readLine()) != null) { m_fragmsgs.add(str); } in.close(); } catch (IOException e) { e.printStackTrace(); } String newFile = PathFinder.getCustsFile(); boolean exists = (new File(newFile)).exists(); Reader reader = null; if (exists) { try { reader = new FileReader(newFile); } catch (FileNotFoundException e3) { e3.printStackTrace(); } } else { Object[] options = { "Yes, create a .hogsrc file", "No, use default taunts" }; int n = JOptionPane.showOptionDialog(m_window, "You do not have customized taunts in your home\n " + "directory. Would you like to create a customizable file?", "Hogs Customization", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if (n == 0) { try { FileChannel srcChannel = new FileInputStream(HogsConstants.CUSTS_TEMPLATE).getChannel(); FileChannel dstChannel; dstChannel = new FileOutputStream(newFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); reader = new FileReader(newFile); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { try { reader = new FileReader(HogsConstants.CUSTS_TEMPLATE); } catch (FileNotFoundException e3) { e3.printStackTrace(); } } } try { m_netengine = NetEngine.forHost(m_user, m_hostname, 1820, m_nethandler); m_netengine.start(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (NetException e) { e.printStackTrace(); } m_gamestate = m_netengine.getCurrentState(); m_gamestate.setInChatMode(false); m_gamestate.setController(this); try { readFromFile(reader); } catch (NumberFormatException e3) { e3.printStackTrace(); } catch (IOException e3) { e3.printStackTrace(); } catch (InternalException e3) { e3.printStackTrace(); } GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice m_graphicsdevice = ge.getDefaultScreenDevice(); m_window = new GuiFrame(m_drawingpanel, m_gamestate); m_graphics = null; try { m_graphics = new GraphicsEngine(m_drawingpanel, m_gamestate); } catch (InternalException e1) { e1.printStackTrace(); System.exit(0); } m_drawingpanel.addGLEventListener(m_graphics); m_physics = new Physics(); if (team == null) { team = HogsConstants.TEAM_NONE; } if (!(team.toLowerCase().equals(HogsConstants.TEAM_NONE) || team.toLowerCase().equals(HogsConstants.TEAM_RED) || team.toLowerCase().equals(HogsConstants.TEAM_BLUE))) { throw new InternalException("Invalid team name!"); } String orig_team = team; Craft local_craft = m_gamestate.getLocalCraft(); if (m_gamestate.getNumCrafts() == 0) { local_craft.setTeamname(team); } else if (m_gamestate.isInTeamMode()) { if (team == HogsConstants.TEAM_NONE) { int red_craft = m_gamestate.getNumOnTeam(HogsConstants.TEAM_RED); int blue_craft = m_gamestate.getNumOnTeam(HogsConstants.TEAM_BLUE); String new_team; if (red_craft > blue_craft) { new_team = HogsConstants.TEAM_BLUE; } else if (red_craft < blue_craft) { new_team = HogsConstants.TEAM_RED; } else { new_team = Math.random() > 0.5 ? HogsConstants.TEAM_BLUE : HogsConstants.TEAM_RED; } m_gamestate.getLocalCraft().setTeamname(new_team); } else { local_craft.setTeamname(team); } } else { local_craft.setTeamname(HogsConstants.TEAM_NONE); if (orig_team != null) { m_window.displayText("You cannot join a team, this is an individual game."); } } if (!local_craft.getTeamname().equals(HogsConstants.TEAM_NONE)) { m_window.displayText("You are joining the " + local_craft.getTeamname() + " team."); } m_drawingpanel.setSize(m_drawingpanel.getWidth(), m_drawingpanel.getHeight()); m_middlepos = new java.awt.Point(m_drawingpanel.getWidth() / 2, m_drawingpanel.getHeight() / 2); m_curpos = new java.awt.Point(m_drawingpanel.getWidth() / 2, m_drawingpanel.getHeight() / 2); GuiKeyListener k_listener = new GuiKeyListener(); GuiMouseListener m_listener = new GuiMouseListener(); m_window.addKeyListener(k_listener); m_drawingpanel.addKeyListener(k_listener); m_window.addMouseListener(m_listener); m_drawingpanel.addMouseListener(m_listener); m_window.addMouseMotionListener(m_listener); m_drawingpanel.addMouseMotionListener(m_listener); m_drawingpanel.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { m_window.setMouseTrapped(false); m_window.returnMouseToCenter(); } }); m_window.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { m_window.setMouseTrapped(false); m_window.returnMouseToCenter(); } }); m_window.requestFocus(); }
00
Code Sample 1: public String process(URL url) throws IOException { String line, results = ""; InputStream is = url.openStream(); BufferedReader dis = new BufferedReader(new InputStreamReader(is)); while ((line = dis.readLine()) != null) { results += line + "\n"; } System.out.println(results); return results; } Code Sample 2: public FTPClient sample2(String server, String username, String password) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException { FTPClient ftpClient = new FTPClient(); ftpClient.connect(server); ftpClient.login(username, password); return ftpClient; }
00
Code Sample 1: public void testIntegrityViolation() throws Exception { if (getDialect() instanceof MySQLMyISAMDialect) { reportSkip("MySQL (ISAM) does not support FK violation checking", "exception conversion"); return; } SQLExceptionConverter converter = getDialect().buildSQLExceptionConverter(); Session session = openSession(); session.beginTransaction(); Connection connection = session.connection(); PreparedStatement ps = null; try { ps = connection.prepareStatement("INSERT INTO T_MEMBERSHIP (user_id, group_id) VALUES (?, ?)"); ps.setLong(1, 52134241); ps.setLong(2, 5342); ps.executeUpdate(); fail("INSERT should have failed"); } catch (SQLException sqle) { JDBCExceptionReporter.logExceptions(sqle, "Just output!!!!"); JDBCException jdbcException = converter.convert(sqle, null, null); assertEquals("Bad conversion [" + sqle.getMessage() + "]", ConstraintViolationException.class, jdbcException.getClass()); ConstraintViolationException ex = (ConstraintViolationException) jdbcException; System.out.println("Violated constraint name: " + ex.getConstraintName()); } finally { if (ps != null) { try { ps.close(); } catch (Throwable ignore) { } } } session.getTransaction().rollback(); session.close(); } 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: private void prepareQueryResultData(ZipEntryRef zer, String nodeDir, String reportDir, Set<ZipEntryRef> statusZers) throws Exception { String jobDir = nodeDir + File.separator + "job_" + zer.getUri(); if (!WorkDirectory.isWorkingDirectoryValid(jobDir)) { throw new Exception("Cannot acces to " + jobDir); } File f = new File(jobDir + File.separator + "result.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to result file " + f.getAbsolutePath()); } String fcopyName = reportDir + File.separator + zer.getName() + ".xml"; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); zer.setUri(fcopyName); f = new File(jobDir + File.separator + "status.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to status file " + f.getAbsolutePath()); } fcopyName = reportDir + File.separator + zer.getName() + "_status.xml"; bis = new BufferedInputStream(new FileInputStream(f)); bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); statusZers.add(new ZipEntryRef(ZipEntryRef.SINGLE_FILE, zer.getName(), fcopyName, ZipEntryRef.WITH_REL)); } Code Sample 2: public String postEvent(EventDocument eventDoc, Map attachments) { if (eventDoc == null || eventDoc.getEvent() == null) return null; if (queue == null) { sendEvent(eventDoc, attachments); return eventDoc.getEvent().getEventId(); } if (attachments != null) { Iterator iter = attachments.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); if (entry.getValue() instanceof DataHandler) { File file = new File(attachmentStorge + "/" + GuidUtil.generate() + entry.getKey()); try { IOUtils.copy(((DataHandler) entry.getValue()).getInputStream(), new FileOutputStream(file)); entry.setValue(file); } catch (IOException err) { err.printStackTrace(); } } } } InternalEventObject eventObj = new InternalEventObject(); eventObj.setEventDocument(eventDoc); eventObj.setAttachments(attachments); eventObj.setSessionContext(SessionContextUtil.getCurrentContext()); eventDoc.getEvent().setEventId(GuidUtil.generate()); getQueue().post(eventObj); return eventDoc.getEvent().getEventId(); }
00
Code Sample 1: public void testDoubleNaN() { double value = 0; boolean wasEqual = false; String message = "DB operation completed"; String ddl1 = "DROP TABLE t1 IF EXISTS;" + "CREATE TABLE t1 ( d DECIMAL, f DOUBLE, l BIGINT, i INTEGER, s SMALLINT, t TINYINT, " + "dt DATE DEFAULT CURRENT_DATE, ti TIME DEFAULT CURRENT_TIME, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP );"; try { stmnt.execute(ddl1); PreparedStatement ps = connection.prepareStatement("INSERT INTO t1 (d,f,l,i,s,t,dt,ti,ts) VALUES (?,?,?,?,?,?,?,?,?)"); ps.setString(1, "0.2"); ps.setDouble(2, 0.2); ps.setLong(3, java.lang.Long.MAX_VALUE); ps.setInt(4, Integer.MAX_VALUE); ps.setInt(5, Short.MAX_VALUE); ps.setInt(6, 0); ps.setDate(7, new java.sql.Date(System.currentTimeMillis())); ps.setTime(8, new java.sql.Time(System.currentTimeMillis())); ps.setTimestamp(9, new java.sql.Timestamp(System.currentTimeMillis())); ps.execute(); ps.setInt(1, 0); ps.setDouble(2, java.lang.Double.NaN); ps.setLong(3, java.lang.Long.MIN_VALUE); ps.setInt(4, Integer.MIN_VALUE); ps.setInt(5, Short.MIN_VALUE); ps.setInt(6, 0); ps.setTimestamp(7, new java.sql.Timestamp(System.currentTimeMillis() + 1)); ps.setTime(8, new java.sql.Time(System.currentTimeMillis() + 1)); ps.setDate(9, new java.sql.Date(System.currentTimeMillis() + 1)); ps.execute(); ps.setInt(1, 0); ps.setDouble(2, java.lang.Double.POSITIVE_INFINITY); ps.setInt(4, Integer.MIN_VALUE); ps.setObject(5, Boolean.TRUE); ps.setBoolean(5, true); ps.setObject(5, new Short((short) 2), Types.SMALLINT); ps.setObject(6, new Integer(2), Types.TINYINT); ps.setObject(7, new java.sql.Date(System.currentTimeMillis() + 2)); ps.setObject(8, new java.sql.Time(System.currentTimeMillis() + 2)); ps.setObject(9, new java.sql.Timestamp(System.currentTimeMillis() + 2)); ps.execute(); ps.setObject(1, new Float(0), Types.INTEGER); ps.setObject(4, new Float(1), Types.INTEGER); ps.setDouble(2, java.lang.Double.NEGATIVE_INFINITY); ps.execute(); ResultSet rs = stmnt.executeQuery("SELECT d, f, l, i, s*2, t FROM t1"); boolean result = rs.next(); value = rs.getDouble(2); int integerValue = rs.getInt(4); if (rs.next()) { value = rs.getDouble(2); wasEqual = Double.isNaN(value); integerValue = rs.getInt(4); integerValue = rs.getInt(1); } if (rs.next()) { value = rs.getDouble(2); wasEqual = wasEqual && value == Double.POSITIVE_INFINITY; } if (rs.next()) { value = rs.getDouble(2); wasEqual = wasEqual && value == Double.NEGATIVE_INFINITY; } rs = stmnt.executeQuery("SELECT MAX(i) FROM t1"); if (rs.next()) { int max = rs.getInt(1); System.out.println("Max value for i: " + max); } { stmnt.execute("drop table CDTYPE if exists"); rs = stmnt.executeQuery("CREATE TABLE cdType (ID INTEGER NOT NULL, name VARCHAR(50), PRIMARY KEY(ID))"); rs = stmnt.executeQuery("SELECT MAX(ID) FROM cdType"); if (rs.next()) { int max = rs.getInt(1); System.out.println("Max value for ID: " + max); } else { System.out.println("Max value for ID not returned"); } stmnt.executeUpdate("INSERT INTO cdType VALUES (10,'Test String');"); stmnt.executeQuery("CALL IDENTITY();"); try { stmnt.executeUpdate("INSERT INTO cdType VALUES (10,'Test String');"); } catch (SQLException e1) { stmnt.execute("ROLLBACK"); connection.rollback(); } } } catch (SQLException e) { fail(e.getMessage()); } System.out.println("testDoubleNaN complete"); assertEquals(true, wasEqual); } Code Sample 2: public Vector<Question> reload() throws IOException { Vector<Question> questions = new Vector<Question>(); InputStream is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); shortName = br.readLine(); if (shortName != null && shortName.equals("SHORTNAME")) { shortName = br.readLine(); author = br.readLine(); if (author != null && author.equals("AUTHOR")) { author = br.readLine(); description = br.readLine(); if (description != null && description.equals("DESCRIPTION")) { description = br.readLine(); try { questions = QuestionLoader.getQuestions(br); } catch (IOException ioe) { ioe.printStackTrace(); throw ioe; } finally { br.close(); is.close(); } } else { throw new IllegalArgumentException(); } } else { throw new IllegalArgumentException(); } } else { throw new IllegalArgumentException(); } return questions; }
00
Code Sample 1: @Override public void checkConnection(byte[] options) throws Throwable { Properties opts = PropertiesUtils.deserializeProperties(options); String server = opts.getProperty(TRANSFER_OPTION_SERVER); String username = opts.getProperty(TRANSFER_OPTION_USERNAME); String password = opts.getProperty(TRANSFER_OPTION_PASSWORD); String filePath = opts.getProperty(TRANSFER_OPTION_FILEPATH); URL url = new URL(PROTOCOL_PREFIX + username + ":" + password + "@" + server + filePath + ";type=i"); URLConnection urlc = url.openConnection(BackEnd.getProxy(Proxy.Type.SOCKS)); urlc.setConnectTimeout(Preferences.getInstance().preferredTimeOut * 1000); urlc.setReadTimeout(Preferences.getInstance().preferredTimeOut * 1000); urlc.connect(); } Code Sample 2: public static void copyFile4(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copy(in, out); in.close(); out.close(); }
00
Code Sample 1: public String getIpAddress() { try { URL url = new URL("http://checkip.dyndns.org"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String linha; String rtn = ""; while ((linha = in.readLine()) != null) rtn += linha; ; in.close(); return filtraRetorno(rtn); } catch (IOException ex) { Logger.getLogger(ExternalIp.class.getName()).log(Level.SEVERE, null, ex); return "ERRO."; } } 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: public static String hash(final String s) { if (s == null || s.length() == 0) return null; try { final MessageDigest hashEngine = MessageDigest.getInstance("SHA-1"); hashEngine.update(s.getBytes("iso-8859-1"), 0, s.length()); return convertToHex(hashEngine.digest()); } catch (final Exception e) { return null; } } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5; StringBuilder sbValueBeforeHash = new StringBuilder(); try { md5 = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new ApplicationIllegalArgumentException(e); } long time = System.nanoTime(); long rand = 0; if (secure) { rand = MySecureRand.nextLong(); } else { rand = MyRand.nextLong(); } sbValueBeforeHash.append(SId); sbValueBeforeHash.append(":"); sbValueBeforeHash.append(Long.toString(time)); sbValueBeforeHash.append(":"); sbValueBeforeHash.append(Long.toString(rand)); valueBeforeHash = sbValueBeforeHash.toString(); md5.update(valueBeforeHash.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b)); } valueAfterHash = sb.toString(); }
00
Code Sample 1: private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } } Code Sample 2: private void onDhReply(final SshDhReply msg) throws GeneralSecurityException, IOException { if ((this.keyPair == null) || this.connection.isServer()) throw new SshException("%s: unexpected %s", this.connection.uri, msg.getType()); final BigInteger k; { final DHPublicKeySpec remoteKeySpec = new DHPublicKeySpec(new BigInteger(msg.f), P1, G); final KeyFactory dhKeyFact = KeyFactory.getInstance("DH"); final DHPublicKey remotePubKey = (DHPublicKey) dhKeyFact.generatePublic(remoteKeySpec); final KeyAgreement dhKex = KeyAgreement.getInstance("DH"); dhKex.init(this.keyPair.getPrivate()); dhKex.doPhase(remotePubKey, true); k = new BigInteger(dhKex.generateSecret()); } final MessageDigest md = createMessageDigest(); final byte[] h; { updateByteArray(md, SshVersion.LOCAL.toString().getBytes()); updateByteArray(md, this.connection.getRemoteSshVersion().toString().getBytes()); updateByteArray(md, this.keyExchangeInitLocal.getPayload()); updateByteArray(md, this.keyExchangeInitRemote.getPayload()); updateByteArray(md, msg.hostKey); updateByteArray(md, ((DHPublicKey) this.keyPair.getPublic()).getY().toByteArray()); updateByteArray(md, msg.f); updateBigInt(md, k); h = md.digest(); } if (this.sessionId == null) this.sessionId = h; this.keyExchangeInitLocal = null; this.keyExchangeInitRemote = null; this.h = h; this.k = k; this.connection.send(new SshKeyExchangeNewKeys()); }
11
Code Sample 1: public boolean update(int idPartida, partida partidaModificada) { int intResult = 0; String sql = "UPDATE partida " + "SET torneo_idTorneo = ?, " + " jugador_idJugadorNegras = ?, jugador_idJugadorBlancas = ?, " + " fecha = ?, " + " resultado = ?, " + " nombreBlancas = ?, nombreNegras = ?, eloBlancas = ?, eloNegras = ?, idApertura = ? " + " WHERE idPartida = " + idPartida; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement2(partidaModificada); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); } Code Sample 2: public void importarHistoricoDeProventos(File pArquivoXLS, boolean pFiltrarPelaDataDeCorteDoCabecalho, Andamento pAndamento) throws IOException, SQLException, InvalidFormatException { int iLinha = -1; String nomeDaColuna = ""; Statement stmtLimpezaInicialDestino = null; OraclePreparedStatement stmtDestino = null; try { Workbook arquivo = WorkbookFactory.create(new FileInputStream(pArquivoXLS)); Sheet plan1 = arquivo.getSheetAt(0); int QUANTIDADE_DE_REGISTROS_DE_METADADOS = 2; int quantidadeDeRegistrosEstimada = plan1.getPhysicalNumberOfRows() - QUANTIDADE_DE_REGISTROS_DE_METADADOS; String vNomeDePregao, vTipoDaAcao, vDataDaAprovacao, vTipoDoProvento, vDataDoUltimoPrecoCom; BigDecimal vValorDoProvento, vUltimoPrecoCom, vProventoPorPreco; int vProventoPor1Ou1000Acoes, vPrecoPor1Ou1000Acoes; java.sql.Date vUltimoDiaCom; DateFormat formatadorData = new SimpleDateFormat("yyyyMMdd"); DateFormat formatadorPadraoData = DateFormat.getDateInstance(); Row registro; Cell celula; java.util.Date dataLimite = plan1.getRow(0).getCell(CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.ordinal()).getDateCellValue(); Cell celulaUltimoDiaCom; java.util.Date tmpUltimoDiaCom; stmtLimpezaInicialDestino = conDestino.createStatement(); String sql = "TRUNCATE TABLE TMP_TB_PROVENTO_EM_DINHEIRO"; stmtLimpezaInicialDestino.executeUpdate(sql); sql = "INSERT INTO TMP_TB_PROVENTO_EM_DINHEIRO(NOME_DE_PREGAO, TIPO_DA_ACAO, DATA_DA_APROVACAO, VALOR_DO_PROVENTO, PROVENTO_POR_1_OU_1000_ACOES, TIPO_DO_PROVENTO, ULTIMO_DIA_COM, DATA_DO_ULTIMO_PRECO_COM, ULTIMO_PRECO_COM, PRECO_POR_1_OU_1000_ACOES, PERC_PROVENTO_POR_PRECO) VALUES(:NOME_DE_PREGAO, :TIPO_DA_ACAO, :DATA_DA_APROVACAO, :VALOR_DO_PROVENTO, :PROVENTO_POR_1_OU_1000_ACOES, :TIPO_DO_PROVENTO, :ULTIMO_DIA_COM, :DATA_DO_ULTIMO_PRECO_COM, :ULTIMO_PRECO_COM, :PRECO_POR_1_OU_1000_ACOES, :PERC_PROVENTO_POR_PRECO)"; stmtDestino = (OraclePreparedStatement) conDestino.prepareStatement(sql); stmtDestino.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosImportados = 0; final int NUMERO_DA_LINHA_INICIAL = 1; for (iLinha = NUMERO_DA_LINHA_INICIAL; true; iLinha++) { registro = plan1.getRow(iLinha); if (registro != null) { nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_DIA_COM.toString(); celulaUltimoDiaCom = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_DIA_COM.ordinal()); if (celulaUltimoDiaCom != null) { if (celulaUltimoDiaCom.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpUltimoDiaCom = celulaUltimoDiaCom.getDateCellValue(); if (tmpUltimoDiaCom.compareTo(dataLimite) <= 0 || !pFiltrarPelaDataDeCorteDoCabecalho) { vUltimoDiaCom = new java.sql.Date(celulaUltimoDiaCom.getDateCellValue().getTime()); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.toString(); vNomeDePregao = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DA_ACAO.toString(); vTipoDaAcao = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DA_ACAO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.DATA_DA_APROVACAO.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.DATA_DA_APROVACAO.ordinal()); try { java.util.Date tmpDataDaAprovacao; if (celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpDataDaAprovacao = celula.getDateCellValue(); } else { tmpDataDaAprovacao = formatadorPadraoData.parse(celula.getStringCellValue()); } vDataDaAprovacao = formatadorData.format(tmpDataDaAprovacao); } catch (ParseException ex) { vDataDaAprovacao = celula.getStringCellValue(); } nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.VALOR_DO_PROVENTO.toString(); vValorDoProvento = new BigDecimal(String.valueOf(registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.VALOR_DO_PROVENTO.ordinal()).getNumericCellValue())); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_1_OU_1000_ACOES.toString(); vProventoPor1Ou1000Acoes = (int) registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_1_OU_1000_ACOES.ordinal()).getNumericCellValue(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DO_PROVENTO.toString(); vTipoDoProvento = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DO_PROVENTO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.DATA_DO_ULTIMO_PRECO_COM.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.DATA_DO_ULTIMO_PRECO_COM.ordinal()); if (celula != null) { try { java.util.Date tmpDataDoUltimoPrecoCom; if (celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpDataDoUltimoPrecoCom = celula.getDateCellValue(); } else { tmpDataDoUltimoPrecoCom = formatadorPadraoData.parse(celula.getStringCellValue()); } vDataDoUltimoPrecoCom = formatadorData.format(tmpDataDoUltimoPrecoCom); } catch (ParseException ex) { vDataDoUltimoPrecoCom = celula.getStringCellValue().trim(); } } else { vDataDoUltimoPrecoCom = ""; } nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_PRECO_COM.toString(); vUltimoPrecoCom = new BigDecimal(String.valueOf(registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_PRECO_COM.ordinal()).getNumericCellValue())); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PRECO_POR_1_OU_1000_ACOES.toString(); vPrecoPor1Ou1000Acoes = (int) registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PRECO_POR_1_OU_1000_ACOES.ordinal()).getNumericCellValue(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_PRECO.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_PRECO.ordinal()); if (celula != null && celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { vProventoPorPreco = new BigDecimal(String.valueOf(celula.getNumericCellValue())); } else { vProventoPorPreco = null; } stmtDestino.clearParameters(); stmtDestino.setStringAtName("NOME_DE_PREGAO", vNomeDePregao); stmtDestino.setStringAtName("TIPO_DA_ACAO", vTipoDaAcao); stmtDestino.setStringAtName("DATA_DA_APROVACAO", vDataDaAprovacao); stmtDestino.setBigDecimalAtName("VALOR_DO_PROVENTO", vValorDoProvento); stmtDestino.setIntAtName("PROVENTO_POR_1_OU_1000_ACOES", vProventoPor1Ou1000Acoes); stmtDestino.setStringAtName("TIPO_DO_PROVENTO", vTipoDoProvento); stmtDestino.setDateAtName("ULTIMO_DIA_COM", vUltimoDiaCom); stmtDestino.setStringAtName("DATA_DO_ULTIMO_PRECO_COM", vDataDoUltimoPrecoCom); stmtDestino.setBigDecimalAtName("ULTIMO_PRECO_COM", vUltimoPrecoCom); stmtDestino.setIntAtName("PRECO_POR_1_OU_1000_ACOES", vPrecoPor1Ou1000Acoes); stmtDestino.setBigDecimalAtName("PERC_PROVENTO_POR_PRECO", vProventoPorPreco); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportados++; } } } else { break; } double percentualCompleto = (double) quantidadeDeRegistrosImportados / quantidadeDeRegistrosEstimada * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } else { break; } } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); ProblemaNaImportacaoDeArquivo problemaDetalhado = new ProblemaNaImportacaoDeArquivo(); problemaDetalhado.nomeDoArquivo = pArquivoXLS.getName(); problemaDetalhado.linhaProblematicaDoArquivo = iLinha + 1; problemaDetalhado.colunaProblematicaDoArquivo = nomeDaColuna; problemaDetalhado.detalhesSobreOProblema = ex; throw problemaDetalhado; } finally { pAndamento.setPercentualCompleto(100); if (stmtLimpezaInicialDestino != null && (!stmtLimpezaInicialDestino.isClosed())) { stmtLimpezaInicialDestino.close(); } if (stmtDestino != null && (!stmtDestino.isClosed())) { stmtDestino.close(); } } }
00
Code Sample 1: static String fetchURLComposeExternPackageList(String urlpath, String pkglisturlpath) { String link = pkglisturlpath + "package-list"; try { boolean relative = isRelativePath(urlpath); readPackageList((new URL(link)).openStream(), urlpath, relative); } catch (MalformedURLException exc) { return getText("doclet.MalformedURL", link); } catch (IOException exc) { return getText("doclet.URL_error", link); } return null; } Code Sample 2: protected void init() throws MXQueryException { String add = getStringValueOrEmpty(subIters[0]); if (add == null) { currentToken = BooleanToken.FALSE_TOKEN; return; } URI uri; if (!TypeLexicalConstraints.isValidURI(add)) throw new DynamicException(ErrorCodes.F0017_INVALID_ARGUMENT_TO_FN_DOC, "Invalid URI given to fn:doc-available", loc); try { if (TypeLexicalConstraints.isAbsoluteURI(add)) { uri = new URI(add); } else { uri = new URI(IOLib.convertToAndroid(add)); } } catch (URISyntaxException se) { throw new DynamicException(ErrorCodes.F0017_INVALID_ARGUMENT_TO_FN_DOC, "Invalid URI given to fn:doc-available", loc); } if (add.startsWith("http://")) { URL url; try { url = uri.toURL(); } catch (MalformedURLException e) { throw new DynamicException(ErrorCodes.F0017_INVALID_ARGUMENT_TO_FN_DOC, "Invalid URI given to fn:doc-available", loc); } try { InputStream in = url.openStream(); in.close(); } catch (IOException e) { currentToken = BooleanToken.FALSE_TOKEN; return; } currentToken = BooleanToken.TRUE_TOKEN; } else { try { BufferedReader in = new BufferedReader(new InputStreamReader(MXQuery.getContext().openFileInput(uri.toString()))); currentToken = BooleanToken.TRUE_TOKEN; } catch (FileNotFoundException e) { currentToken = BooleanToken.FALSE_TOKEN; } catch (IOException e) { currentToken = BooleanToken.FALSE_TOKEN; } } }
11
Code Sample 1: @RequestMapping(value = "/image/{fileName}", method = RequestMethod.GET) public void getImage(@PathVariable String fileName, HttpServletRequest req, HttpServletResponse res) throws Exception { File file = new File(STORAGE_PATH + fileName + ".jpg"); res.setHeader("Cache-Control", "no-store"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); res.setContentType("image/jpg"); ServletOutputStream ostream = res.getOutputStream(); IOUtils.copy(new FileInputStream(file), ostream); ostream.flush(); ostream.close(); } Code Sample 2: protected static void copyFile(File from, File to) throws IOException { if (!from.isFile() || !to.isFile()) { throw new IOException("Both parameters must be files. from is " + from.isFile() + ", to is " + to.isFile()); } FileChannel in = (new FileInputStream(from)).getChannel(); FileChannel out = (new FileOutputStream(to)).getChannel(); in.transferTo(0, from.length(), out); in.close(); out.close(); }
00
Code Sample 1: private void copyTemplate(String resource, OutputStream outputStream) throws IOException { URL url = Tools.getResource(resource); if (url == null) { throw new IOException("could not find resource"); } BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF-8"))); String line = null; do { line = reader.readLine(); if (line != null) { writer.write(line); writer.newLine(); } } while (line != null); reader.close(); writer.close(); } 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:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</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()); }
11
Code Sample 1: private static void copy(File source, File dest) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(source); FileOutputStream output = new FileOutputStream(dest); System.out.println("Copying " + source + " to " + dest); IOUtils.copy(input, output); output.close(); input.close(); dest.setLastModified(source.lastModified()); } Code Sample 2: private static void _checkConfigFile() throws Exception { try { String filePath = getUserManagerConfigPath() + "user_manager_config.properties"; boolean copy = false; File from = new java.io.File(filePath); if (!from.exists()) { Properties properties = new Properties(); properties.put(Config.getStringProperty("ADDITIONAL_INFO_MIDDLE_NAME_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_MIDDLE_NAME_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_DATE_OF_BIRTH_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_DATE_OF_BIRTH_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_CELL_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_CELL_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_CATEGORIES_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_CATEGORIES_VISIBILITY")); Company comp = PublicCompanyFactory.getDefaultCompany(); int numberGenericVariables = Config.getIntProperty("MAX_NUMBER_VARIABLES_TO_SHOW"); for (int i = 1; i <= numberGenericVariables; i++) { properties.put(LanguageUtil.get(comp.getCompanyId(), comp.getLocale(), "user.profile.var" + i).replace(" ", "_"), Config.getStringProperty("ADDITIONAL_INFO_DEFAULT_VISIBILITY")); } try { properties.store(new java.io.FileOutputStream(filePath), null); } catch (Exception e) { Logger.error(UserManagerPropertiesFactory.class, e.getMessage(), e); } from = new java.io.File(filePath); copy = true; } String tmpFilePath = UtilMethods.getTemporaryDirPath() + "user_manager_config_properties.tmp"; File to = new java.io.File(tmpFilePath); if (!to.exists()) { to.createNewFile(); copy = true; } if (copy) { FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } catch (IOException e) { Logger.error(UserManagerPropertiesFactory.class, "_checkLanguagesFiles:Property File Copy Failed " + e, e); } }
11
Code Sample 1: private final long test(final boolean applyFilter, final int executionCount) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException, RuleLoadingException { final boolean stripHtmlEnabled = true; final boolean injectSecretTokensEnabled = true; final boolean encryptQueryStringsEnabled = true; final boolean protectParamsAndFormsEnabled = true; final boolean applyExtraProtectionForDisabledFormFields = true; final boolean applyExtraProtectionForReadonlyFormFields = false; final boolean applyExtraProtectionForRequestParamValueCount = false; final ContentInjectionHelper helper = new ContentInjectionHelper(); final RuleFileLoader ruleFileLoaderModificationExcludes = new ClasspathZipRuleFileLoader(); ruleFileLoaderModificationExcludes.setPath(WebCastellumFilter.MODIFICATION_EXCLUDES_DEFAULT); final ContentModificationExcludeDefinitionContainer containerModExcludes = new ContentModificationExcludeDefinitionContainer(ruleFileLoaderModificationExcludes); containerModExcludes.parseDefinitions(); helper.setContentModificationExcludeDefinitions(containerModExcludes); final AttackHandler attackHandler = new AttackHandler(null, 123, 600000, 100000, 300000, 300000, null, "MOCK", false, false, 0, false, false, Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), true); final SessionCreationTracker sessionCreationTracker = new SessionCreationTracker(attackHandler, 0, 600000, 300000, 0, "", "", "", ""); final RequestWrapper request = new RequestWrapper(new RequestMock(), helper, sessionCreationTracker, "123.456.789.000", false, true, true); final RuleFileLoader ruleFileLoaderResponseModifications = new ClasspathZipRuleFileLoader(); ruleFileLoaderResponseModifications.setPath(WebCastellumFilter.RESPONSE_MODIFICATIONS_DEFAULT); final ResponseModificationDefinitionContainer container = new ResponseModificationDefinitionContainer(ruleFileLoaderResponseModifications); container.parseDefinitions(); final ResponseModificationDefinition[] responseModificationDefinitions = downCast(container.getAllEnabledRequestDefinitions()); final List tmpPatternsToExcludeCompleteTag = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeCompleteScript = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeCompleteTag = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeCompleteScript = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpGroupNumbersToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpGroupNumbersToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); for (int i = 0; i < responseModificationDefinitions.length; i++) { final ResponseModificationDefinition responseModificationDefinition = responseModificationDefinitions[i]; if (responseModificationDefinition.isMatchesScripts()) { tmpPatternsToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPattern()); tmpPrefiltersToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPrefilter()); tmpPatternsToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinScripts.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } if (responseModificationDefinition.isMatchesTags()) { tmpPatternsToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPattern()); tmpPrefiltersToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPrefilter()); tmpPatternsToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinTags.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } } final Matcher[] matchersToExcludeCompleteTag = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteTag); final Matcher[] matchersToExcludeCompleteScript = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteScript); final Matcher[] matchersToExcludeLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinScripts); final Matcher[] matchersToExcludeLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinTags); final Matcher[] matchersToCaptureLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinScripts); final Matcher[] matchersToCaptureLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinTags); final WordDictionary[] prefiltersToExcludeCompleteTag = (WordDictionary[]) tmpPrefiltersToExcludeCompleteTag.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeCompleteScript = (WordDictionary[]) tmpPrefiltersToExcludeCompleteScript.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinTags = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinTags.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinTags = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinTags.toArray(new WordDictionary[0]); final int[][] groupNumbersToCaptureLinksWithinScripts = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinScripts); final int[][] groupNumbersToCaptureLinksWithinTags = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinTags); final Cipher cipher = CryptoUtils.getCipher(); final CryptoKeyAndSalt key = CryptoUtils.generateRandomCryptoKeyAndSalt(false); Cipher.getInstance("AES"); MessageDigest.getInstance("SHA-1"); final ResponseWrapper response = new ResponseWrapper(new ResponseMock(), request, attackHandler, helper, false, "___ENCRYPTED___", cipher, key, "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", false, false, false, false, "123.456.789.000", new HashSet(), prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, false, true, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false, false); final List durations = new ArrayList(); for (int i = 0; i < executionCount; i++) { final long start = System.currentTimeMillis(); Reader reader = null; Writer writer = null; try { reader = new BufferedReader(new FileReader(this.htmlFile)); writer = new FileWriter(this.outputFile); if (applyFilter) { writer = new ResponseFilterWriter(writer, true, "http://127.0.0.1/test/sample", "/test", "/test", "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", cipher, key, helper, "___ENCRYPTED___", request, response, stripHtmlEnabled, injectSecretTokensEnabled, protectParamsAndFormsEnabled, encryptQueryStringsEnabled, applyExtraProtectionForDisabledFormFields, applyExtraProtectionForReadonlyFormFields, applyExtraProtectionForRequestParamValueCount, prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, true, false, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false); writer = new BufferedWriter(writer); } char[] chars = new char[16 * 1024]; int read; while ((read = reader.read(chars)) != -1) { if (read > 0) { writer.write(chars, 0, read); } } durations.add(new Long(System.currentTimeMillis() - start)); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } if (writer != null) { try { writer.close(); } catch (IOException ignored) { } } } } long sum = 0; for (final Iterator iter = durations.iterator(); iter.hasNext(); ) { Long value = (Long) iter.next(); sum += value.longValue(); } return sum / durations.size(); } Code Sample 2: public void generateReport(AllTestsResult atr, AllConvsResult acr, File nwbConvGraph) { ConvResult[] convs = acr.getConvResults(); BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(nwbConvGraph)); writer = new BufferedWriter(new FileWriter(this.annotatedNWBGraph)); String line = null; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.startsWith("id*int")) { writer.write(line + " isTrusted*int chanceCorrect*float isConverter*int \r\n"); } else if (line.matches(NODE_LINE)) { String[] parts = line.split(" "); String rawConvName = parts[1]; String convName = rawConvName.replaceAll("\"", ""); boolean wroteAttributes = false; for (int ii = 0; ii < convs.length; ii++) { ConvResult cr = convs[ii]; if (cr.getShortName().equals(convName)) { int trusted; if (cr.isTrusted()) { trusted = 1; } else { trusted = 0; } writer.write(line + " " + trusted + " " + FormatUtil.formatToPercent(cr.getChanceCorrect()) + " 1 " + "\r\n"); wroteAttributes = true; break; } } if (!wroteAttributes) { writer.write(line + " 1 100.0 0" + "\r\n"); } } else { writer.write(line + "\r\n"); } } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to generate Graph Report.", e); try { if (reader != null) reader.close(); } catch (IOException e2) { this.log.log(LogService.LOG_ERROR, "Unable to close graph report stream", e); } } finally { try { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to close either graph report reader or " + "writer.", e); e.printStackTrace(); } } }
00
Code Sample 1: @Override public HttpResponse execute() throws IOException { if (this.method == HttpMethod.GET) { String url = this.toString(); if (url.length() > this.cutoff) { if (log.isLoggable(Level.FINER)) log.finer("URL length " + url.length() + " too long, converting GET to POST: " + url); String rebase = this.baseURL + "?method=GET"; return this.execute(HttpMethod.POST, rebase); } } return super.execute(); } Code Sample 2: public static void bubble(double[] a) { for (int i = a.length - 1; i > 0; i--) for (int j = 0; j < i; j++) if (a[j] > a[j + 1]) { double temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } }
00
Code Sample 1: public static void reset() throws Exception { Session session = DataStaticService.getHibernateSessionFactory().openSession(); try { Connection connection = session.connection(); try { Statement statement = connection.createStatement(); try { statement.executeUpdate("delete from Post"); connection.commit(); } finally { statement.close(); } } catch (HibernateException e) { connection.rollback(); throw new Exception(e); } catch (SQLException e) { connection.rollback(); throw new Exception(e); } } catch (SQLException e) { throw new Exception(e); } finally { session.close(); } } Code Sample 2: public static String SHA(String s) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(s.getBytes(), 0, s.getBytes().length); byte[] hash = md.digest(); StringBuilder sb = new StringBuilder(); int msb; int lsb = 0; int i; for (i = 0; i < hash.length; i++) { msb = ((int) hash[i] & 0x000000FF) / 16; lsb = ((int) hash[i] & 0x000000FF) % 16; sb.append(hexChars[msb]); sb.append(hexChars[lsb]); } return sb.toString(); } catch (NoSuchAlgorithmException e) { return null; } }
11
Code Sample 1: private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException { FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(srcFile); FileChannel iChannel = is.getChannel(); os = new FileOutputStream(destFile, false); FileChannel oChannel = os.getChannel(); long doneBytes = 0L; long todoBytes = srcFile.length(); while (todoBytes != 0L) { long iterationBytes = Math.min(todoBytes, chunkSize); long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes); if (iterationBytes != transferredLength) { throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only " + transferredLength + " bytes copied."); } doneBytes += transferredLength; todoBytes -= transferredLength; } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified()); if (!successTimestampOp) { log.warn("Could not change timestamp for {}. Index synchronization may be slow.", destFile); } } Code Sample 2: 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(); }
11
Code Sample 1: private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(inputStream, outputStream); } finally { outputStream.close(); inputStream.close(); } } Code Sample 2: public static void unzip(final File file, final ZipFile zipFile, final File targetDirectory) throws PtException { LOG.info("Unzipping zip file '" + file.getAbsolutePath() + "' to directory " + "'" + targetDirectory.getAbsolutePath() + "'."); assert (file.exists() && file.isFile()); if (targetDirectory.exists() == false) { LOG.debug("Creating target directory."); if (targetDirectory.mkdirs() == false) { throw new PtException("Could not create target directory at " + "'" + targetDirectory.getAbsolutePath() + "'!"); } } ZipInputStream zipin = null; try { zipin = new ZipInputStream(new FileInputStream(file)); ZipEntry nextZipEntry = zipin.getNextEntry(); while (nextZipEntry != null) { LOG.debug("Unzipping entry '" + nextZipEntry.getName() + "'."); if (nextZipEntry.isDirectory()) { LOG.debug("Skipping directory."); continue; } final File targetFile = new File(targetDirectory, nextZipEntry.getName()); final File parentTargetFile = targetFile.getParentFile(); if (parentTargetFile.exists() == false) { LOG.debug("Creating directory '" + parentTargetFile.getAbsolutePath() + "'."); if (parentTargetFile.mkdirs() == false) { throw new PtException("Could not create target directory at " + "'" + parentTargetFile.getAbsolutePath() + "'!"); } } InputStream input = null; FileOutputStream output = null; try { input = zipFile.getInputStream(nextZipEntry); if (targetFile.createNewFile() == false) { throw new PtException("Could not create target file " + "'" + targetFile.getAbsolutePath() + "'!"); } output = new FileOutputStream(targetFile); byte[] buffer = new byte[BUFFER_SIZE]; int readBytes = input.read(buffer, 0, buffer.length); while (readBytes > 0) { output.write(buffer, 0, readBytes); readBytes = input.read(buffer, 0, buffer.length); } } finally { PtCloseUtil.close(input, output); } nextZipEntry = zipin.getNextEntry(); } } catch (IOException e) { throw new PtException("Could not unzip file '" + file.getAbsolutePath() + "'!", e); } finally { PtCloseUtil.close(zipin); } }
11
Code Sample 1: private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); ServletContext ctx = getServletContext(); RequestDispatcher rd = ctx.getRequestDispatcher(SETUP_JSP); HttpSession session = request.getSession(false); if (session == null) { session = request.getSession(true); session.setAttribute(ERROR_TAG, "You need to have run the Sniffer before running " + "the Grinder. Go to <a href=\"/index.jsp\">the start page</a> " + " to run the Sniffer."); rd = ctx.getRequestDispatcher(ERROR_JSP); } else { session.setMaxInactiveInterval(-1); String pValue = request.getParameter(ACTION_TAG); if (pValue != null && pValue.equals(START_TAG)) { rd = ctx.getRequestDispatcher(WAIT_JSP); int p = 1; int t = 1; int c = 1; try { p = Integer.parseInt(request.getParameter("procs")); p = p > MAX_PROCS ? MAX_PROCS : p; } catch (NumberFormatException e) { } try { t = Integer.parseInt(request.getParameter("threads")); t = t > MAX_THREADS ? MAX_THREADS : t; } catch (NumberFormatException e) { } try { c = Integer.parseInt(request.getParameter("cycles")); c = c > MAX_CYCLES ? MAX_CYCLES : c; } catch (NumberFormatException e) { } try { String dirname = (String) session.getAttribute(OUTPUT_TAG); File workdir = new File(dirname); (new File(dirname + File.separator + LOG_DIR)).mkdir(); FileInputStream gpin = new FileInputStream(GPROPS); FileOutputStream gpout = new FileOutputStream(dirname + File.separator + GPROPS); copyBytes(gpin, gpout); gpin.close(); InitialContext ictx = new InitialContext(); Boolean isSecure = (Boolean) session.getAttribute(SECURE_TAG); if (isSecure.booleanValue()) { gpout.write(("grinder.plugin=" + "net.grinder.plugin.http.HttpsPlugin" + "\n").getBytes()); String certificate = (String) ictx.lookup(CERTIFICATE); String password = (String) ictx.lookup(PASSWORD); gpout.write(("grinder.plugin.parameter.clientCert=" + certificate + "\n").getBytes()); gpout.write(("grinder.plugin.parameter.clientCertPassword=" + password + "\n").getBytes()); } else { gpout.write(("grinder.plugin=" + "net.grinder.plugin.http.HttpPlugin\n").getBytes()); } gpout.write(("grinder.processes=" + p + "\n").getBytes()); gpout.write(("grinder.threads=" + t + "\n").getBytes()); gpout.write(("grinder.cycles=" + c + "\n").getBytes()); gpin = new FileInputStream(dirname + File.separator + SNIFFOUT); copyBytes(gpin, gpout); gpin.close(); gpout.close(); String classpath = (String) ictx.lookup(CLASSPATH); String cmd[] = new String[JAVA_PROCESS.length + 1 + GRINDER_PROCESS.length]; int i = 0; int n = JAVA_PROCESS.length; System.arraycopy(JAVA_PROCESS, 0, cmd, i, n); cmd[n] = classpath; i = n + 1; n = GRINDER_PROCESS.length; System.arraycopy(GRINDER_PROCESS, 0, cmd, i, n); for (int j = 0; j < cmd.length; ++j) { System.out.print(cmd[j] + " "); } Process proc = Runtime.getRuntime().exec(cmd, null, workdir); session.setAttribute(PROCESS_TAG, proc); } catch (NamingException e) { e.printStackTrace(); session.setAttribute(ERROR_MSG_TAG, e.toString()); session.setMaxInactiveInterval(TIMEOUT); rd = ctx.getRequestDispatcher(ERROR_JSP); } catch (Throwable e) { e.printStackTrace(response.getWriter()); throw new IOException(e.getMessage()); } } else if (pValue != null && pValue.equals(CHECK_TAG)) { boolean finished = true; try { Process p = (Process) session.getAttribute(PROCESS_TAG); int result = p.exitValue(); } catch (IllegalThreadStateException e) { finished = false; } if (finished) { session.setMaxInactiveInterval(TIMEOUT); rd = ctx.getRequestDispatcher(RESULTS_JSP); } else { rd = ctx.getRequestDispatcher(WAIT_JSP); } } try { rd.forward(request, response); } catch (ServletException e) { e.printStackTrace(response.getWriter()); throw new IOException(e.getMessage()); } } } Code Sample 2: public static void main(String[] args) throws IOException { long start = System.currentTimeMillis(); FileResourceManager frm = CommonsTransactionContext.configure(new File("C:/tmp")); try { frm.start(); } catch (ResourceManagerSystemException e) { throw new RuntimeException(e); } FileInputStream is = new FileInputStream("C:/Alfresco/WCM_Eval_Guide2.0.pdf"); CommonsTransactionOutputStream os = new CommonsTransactionOutputStream(new Ownerr()); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); try { frm.stop(FileResourceManager.SHUTDOWN_MODE_NORMAL); } catch (ResourceManagerSystemException e) { throw new RuntimeException(e); } System.out.println(System.currentTimeMillis() - start); }
00
Code Sample 1: public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } } try { digest.update(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e); } return encodeHex(digest.digest()); } Code Sample 2: public void insertArchiveEntries(ArchiveEntry entries[]) throws WeatherMonitorException { String sql = null; try { Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rslt = null; con.setAutoCommit(false); for (int i = 0; i < entries.length; i++) { if (!sanityCheck(entries[i])) { } else { sql = getSelectSql(entries[i]); rslt = stmt.executeQuery(sql); if (rslt.next()) { if (rslt.getInt(1) == 0) { sql = getInsertSql(entries[i]); if (stmt.executeUpdate(sql) != 1) { con.rollback(); System.out.println("rolling back sql"); throw new WeatherMonitorException("exception on insert"); } } } } } con.commit(); stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new WeatherMonitorException(e.getMessage()); } }
00
Code Sample 1: Bitmap downloadImage(String uri) { try { mGetMethod.setURI(new URI(uri)); HttpResponse resp = mClient.execute(mGetMethod); if (resp.getStatusLine().getStatusCode() < 400) { InputStream is = resp.getEntity().getContent(); String tmp = convertStreamToString(is); Log.d(TAG, "hoge" + tmp); is.close(); return null; } } catch (Exception e) { e.printStackTrace(); } return null; } Code Sample 2: public void deleteSynchrnServerFile(SynchrnServerVO synchrnServerVO) throws Exception { FTPClient ftpClient = new FTPClient(); ftpClient.setControlEncoding("euc-kr"); if (!EgovWebUtil.isIPAddress(synchrnServerVO.getServerIp())) { throw new RuntimeException("IP is needed. (" + synchrnServerVO.getServerIp() + ")"); } InetAddress host = InetAddress.getByName(synchrnServerVO.getServerIp()); ftpClient.connect(host, Integer.parseInt(synchrnServerVO.getServerPort())); ftpClient.login(synchrnServerVO.getFtpId(), synchrnServerVO.getFtpPassword()); FTPFile[] fTPFile = null; try { ftpClient.changeWorkingDirectory(synchrnServerVO.getSynchrnLc()); fTPFile = ftpClient.listFiles(synchrnServerVO.getSynchrnLc()); for (int i = 0; i < fTPFile.length; i++) { if (synchrnServerVO.getDeleteFileNm().equals(fTPFile[i].getName())) ftpClient.deleteFile(fTPFile[i].getName()); } SynchrnServer synchrnServer = new SynchrnServer(); synchrnServer.setServerId(synchrnServerVO.getServerId()); synchrnServer.setReflctAt("N"); synchrnServerDAO.processSynchrn(synchrnServer); } catch (Exception e) { System.out.println(e); } finally { ftpClient.logout(); } }
00
Code Sample 1: public static void copyAll(URL url, StringBuilder ret) { Reader in = null; try { in = new InputStreamReader(new BufferedInputStream(url.openStream())); copyAll(in, ret); } catch (IOException e) { throw new RuntimeException(e); } finally { close(in); } } Code Sample 2: private static long saveAndClosePDFDocument(PDDocument document, OutputStreamProvider outProvider) throws IOException, COSVisitorException { File tempFile = null; InputStream in = null; OutputStream out = null; try { tempFile = File.createTempFile("temp", "pdf"); OutputStream tempFileOut = new FileOutputStream(tempFile); tempFileOut = new BufferedOutputStream(tempFileOut); document.save(tempFileOut); document.close(); tempFileOut.close(); long length = tempFile.length(); in = new BufferedInputStream(new FileInputStream(tempFile)); out = new BufferedOutputStream(outProvider.getOutputStream()); IOUtils.copy(in, out); return length; } finally { if (in != null) { IOUtils.closeQuietly(in); } if (out != null) { IOUtils.closeQuietly(out); } if (tempFile != null && !FileUtils.deleteQuietly(tempFile)) { tempFile.deleteOnExit(); } } }
00
Code Sample 1: private ShaderProgram loadShaderProgram() { ShaderProgram sp = null; String vertexProgram = null; String fragmentProgram = null; Shader[] shaders = new Shader[2]; try { ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("Shaders/simple.vert"); System.out.println("url " + url); InputStream inputSteam = cl.getResourceAsStream("Shaders/simple.vert"); Reader reader = null; if (inputSteam != null) { reader = new InputStreamReader(inputSteam); } else { File file = new File("lib"); URL url2 = new URL("jar:file:" + file.getAbsolutePath() + "/j3d-vrml97-i3mainz.jar!/Shaders/simple.vert"); InputStream inputSteam2 = url2.openStream(); reader = new InputStreamReader(inputSteam2); } char[] buffer = new char[10000]; int len = reader.read(buffer); vertexProgram = new String(buffer); vertexProgram = vertexProgram.substring(0, len); } catch (Exception e) { System.err.println("could'nt load simple.vert"); e.printStackTrace(); } try { ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("Shaders/simple.frag"); System.out.println("url " + url); InputStream inputSteam = cl.getResourceAsStream("Shaders/simple.frag"); Reader reader = null; if (inputSteam != null) { reader = new InputStreamReader(inputSteam); } else { File file = new File("lib"); URL url2 = new URL("jar:file:" + file.getAbsolutePath() + "/j3d-vrml97-i3mainz.jar!/Shaders/simple.frag"); InputStream inputSteam2 = url2.openStream(); reader = new InputStreamReader(inputSteam2); } char[] buffer = new char[10000]; int len = reader.read(buffer); fragmentProgram = new String(buffer); fragmentProgram = fragmentProgram.substring(0, len); } catch (Exception e) { System.err.println("could'nt load simple.frag"); e.printStackTrace(); } if (vertexProgram != null && fragmentProgram != null) { shaders[0] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_VERTEX, vertexProgram); shaders[1] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_FRAGMENT, fragmentProgram); sp = new GLSLShaderProgram(); sp.setShaders(shaders); } return sp; } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public 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; } Code Sample 2: String chooseHGVersion(String version) { String line = ""; try { URL connectURL = new URL("http://genome.ucsc.edu/cgi-bin/hgGateway?db=" + version); InputStream urlStream = connectURL.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlStream)); while ((line = reader.readLine()) != null) { if (line.indexOf("hgsid") != -1) { line = line.substring(line.indexOf("hgsid")); line = line.substring(line.indexOf("VALUE=\"") + 7); line = line.substring(0, line.indexOf("\"")); return line; } } } catch (Exception e) { e.printStackTrace(); } return line; }
11
Code Sample 1: public void saveProjectFile(File aFile) { SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"); File destDir = new File(theProjectsDirectory, sdf.format(Calendar.getInstance().getTime())); if (destDir.mkdirs()) { File outFile = new File(destDir, "project.xml"); try { FileChannel sourceChannel = new FileInputStream(aFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(outFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException e) { e.printStackTrace(); } finally { aFile.delete(); } } } Code Sample 2: private static boolean genMovieRatingFile(String completePath, String masterFile, String CustLocationsFileName, String MovieRatingFileName) { try { File inFile1 = new File(completePath + fSep + "SmartGRAPE" + fSep + masterFile); FileChannel inC1 = new FileInputStream(inFile1).getChannel(); int fileSize1 = (int) inC1.size(); int totalNoDataRows = fileSize1 / 7; ByteBuffer mappedBuffer = inC1.map(FileChannel.MapMode.READ_ONLY, 0, fileSize1); System.out.println("Loaded master binary file"); File inFile2 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustLocationsFileName); FileChannel inC2 = new FileInputStream(inFile2).getChannel(); int fileSize2 = (int) inC2.size(); System.out.println(fileSize2); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieRatingFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); for (int i = 0; i < 1; i++) { ByteBuffer locBuffer = inC2.map(FileChannel.MapMode.READ_ONLY, i * fileSize2, fileSize2); System.out.println("Loaded cust location file chunk: " + i); while (locBuffer.hasRemaining()) { int locationToRead = locBuffer.getInt(); mappedBuffer.position((locationToRead - 1) * 7); short movieName = mappedBuffer.getShort(); int customer = mappedBuffer.getInt(); byte rating = mappedBuffer.get(); ByteBuffer outBuf = ByteBuffer.allocate(3); outBuf.putShort(movieName); outBuf.put(rating); outBuf.flip(); outC.write(outBuf); } } mappedBuffer.clear(); inC1.close(); inC2.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } }
11
Code Sample 1: private File Gzip(File f) throws IOException { if (f == null || !f.exists()) return null; File dest_dir = f.getParentFile(); String dest_filename = f.getName() + ".gz"; File zipfile = new File(dest_dir, dest_filename); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(zipfile)); FileInputStream in = new FileInputStream(f); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.finish(); try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } try { f.delete(); } catch (Exception e) { } return zipfile; } Code Sample 2: private void copy(File fin, File fout) throws IOException { FileOutputStream out = null; FileInputStream in = null; try { out = new FileOutputStream(fout); in = new FileInputStream(fin); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } } catch (IOException _e) { throw _e; } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: public void bubbleSort(int[] arr) { BasicProcessor.getInstance().getStartBlock(); BasicProcessor.getInstance().getVarDeclaration(); boolean swapped = true; BasicProcessor.getInstance().getVarDeclaration(); int j = 0; BasicProcessor.getInstance().getVarDeclaration(); int tmp; { BasicProcessor.getInstance().getWhileStatement(); while (swapped) { BasicProcessor.getInstance().getStartBlock(); swapped = false; j++; { BasicProcessor.getInstance().getForStatement(); for (int i = 0; i < arr.length - j; i++) { BasicProcessor.getInstance().getStartBlock(); { BasicProcessor.getInstance().getIfStatement(); if (arr[i] > arr[i + 1]) { BasicProcessor.getInstance().getStartBlock(); tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } Code Sample 2: public static void main(String[] argv) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (Exception e) { e.printStackTrace(); } md.update("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".getBytes(), 0, 56); String exp = "84983E441C3BD26EBAAE4AA1F95129E5E54670F1"; String result = toString(md.digest()); System.out.println(exp); System.out.println(result); if (!exp.equals(result)) System.out.println("NOT EQUAL!"); }
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 File extract(File source, String filename, File target) { if (source.exists() == false || filename == null || filename.trim().length() < 1 || target == null) return null; boolean isDirectory = (filename.lastIndexOf("/") == filename.length() - 1); try { Map contents = (Map) jarContents.get(source.getPath()); if (contents == null) { contents = new HashMap(); jarContents.put(source.getPath(), contents); ZipInputStream input = new ZipInputStream(new FileInputStream(source)); ZipEntry zipEntry = null; while ((zipEntry = input.getNextEntry()) != null) { if (zipEntry.isDirectory()) continue; contents.put(zipEntry.getName(), zipEntry); } input.close(); } if (isDirectory) { Iterator it = contents.keySet().iterator(); while (it.hasNext()) { String next = (String) it.next(); if (next.startsWith(filename)) { ZipEntry zipEntry = (ZipEntry) contents.get(next); int n = filename.length(); File newTarget = new File(target, zipEntry.getName().substring(n)); extract(source, next, newTarget); } } return target; } ZipEntry entry = (ZipEntry) contents.get(filename); ZipFile input = new ZipFile(source); InputStream in = input.getInputStream(entry); target.getParentFile().mkdirs(); int bytesRead; byte[] buffer = new byte[1024]; FileOutputStream output = new FileOutputStream(target); while ((bytesRead = in.read(buffer)) != -1) output.write(buffer, 0, bytesRead); output.close(); input.close(); return target; } catch (Exception ex) { ex.printStackTrace(); } return null; }
00
Code Sample 1: static String fetchURLComposeExternPackageList(String urlpath, String pkglisturlpath) { String link = pkglisturlpath + "package-list"; try { boolean relative = isRelativePath(urlpath); readPackageList((new URL(link)).openStream(), urlpath, relative); } catch (MalformedURLException exc) { return getText("doclet.MalformedURL", link); } catch (IOException exc) { return getText("doclet.URL_error", link); } return null; } Code Sample 2: public static String remove_tag(String sessionid, String absolutePathForTheSpesificTag) { String resultJsonString = "some problem existed inside the create_new_tag() function if you see this string"; try { Log.d("current running function name:", "remove_tag"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "remove_tag")); nameValuePairs.add(new BasicNameValuePair("absolute_tags", absolutePathForTheSpesificTag)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); resultJsonString = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", resultJsonString); return resultJsonString; } catch (Exception e) { e.printStackTrace(); } return resultJsonString; }
00
Code Sample 1: private String mkSid() { String temp = toString(); MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } messagedigest.update(temp.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } return chk.toString(); } Code Sample 2: public BufferedImage processUsingTemp(InputStream input, DjatokaDecodeParam params) throws DjatokaException { File in; try { in = File.createTempFile("tmp", ".jp2"); FileOutputStream fos = new FileOutputStream(in); in.deleteOnExit(); IOUtils.copyStream(input, fos); } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } BufferedImage bi = process(in.getAbsolutePath(), params); if (in != null) in.delete(); return bi; }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: private void transform(CommandLine commandLine) throws IOException { Reader reader; if (commandLine.hasOption('i')) { reader = createFileReader(commandLine.getOptionValue('i')); } else { reader = createStandardInputReader(); } Writer writer; if (commandLine.hasOption('o')) { writer = createFileWriter(commandLine.getOptionValue('o')); } else { writer = createStandardOutputWriter(); } String mapRule = commandLine.getOptionValue("m"); try { SrxTransformer transformer = new SrxAnyTransformer(); Map<String, Object> parameterMap = new HashMap<String, Object>(); if (mapRule != null) { parameterMap.put(Srx1Transformer.MAP_RULE_NAME, mapRule); } transformer.transform(reader, writer, parameterMap); } finally { cleanupReader(reader); cleanupWriter(writer); } }
11
Code Sample 1: private static boolean prepareQualifyingFile(String completePath, String outputFile) { try { File inFile = new File(completePath + fSep + "qualifying.txt"); FileChannel inC = new FileInputStream(inFile).getChannel(); BufferedReader br = new BufferedReader(new FileReader(inFile)); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + outputFile); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); boolean endOfFile = true; short movieName = 0; int customer = 0; while (endOfFile) { String line = br.readLine(); if (line != null) { if (line.indexOf(":") >= 0) { movieName = new Short(line.substring(0, line.length() - 1)).shortValue(); } else { customer = new Integer(line.substring(0, line.indexOf(","))).intValue(); ByteBuffer outBuf = ByteBuffer.allocate(6); outBuf.putShort(movieName); outBuf.putInt(customer); outBuf.flip(); outC.write(outBuf); } } else endOfFile = false; } br.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } } Code Sample 2: public static void copy(File src, File dest) throws IOException { if (!src.exists()) { throw new IOException(StaticUtils.format(OStrings.getString("LFC_ERROR_FILE_DOESNT_EXIST"), new Object[] { src.getAbsolutePath() })); } FileInputStream fis = new FileInputStream(src); dest.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(dest); byte[] b = new byte[BUFSIZE]; int readBytes; while ((readBytes = fis.read(b)) > 0) fos.write(b, 0, readBytes); fis.close(); fos.close(); }
00
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static Image getPluginImage(Object plugin, String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; }
00
Code Sample 1: public void login(String a_username, String a_password) throws GB_SecurityException { Exception l_exception = null; try { if (clientFtp == null) { clientFtp = new FTPClient(); clientFtp.connect("ftp://" + ftp); } boolean b = clientFtp.login(a_username, a_password); if (b) { username = a_username; password = a_password; return; } } catch (Exception ex) { l_exception = ex; } String l_msg = "Cannot login to ftp server with user [{1}], {2}"; String[] l_replaces = new String[] { a_username, ftp }; l_msg = STools.replace(l_msg, l_replaces); throw new GB_SecurityException(l_msg, l_exception); } Code Sample 2: private static BundleInfo[] getBundleInfoArray(String location) throws IOException { URL url = new URL(location + BUNDLE_LIST_FILE); BufferedReader br = null; List<BundleInfo> list = new ArrayList<BundleInfo>(); try { br = new BufferedReader(new InputStreamReader(url.openStream())); while (true) { String line = br.readLine(); if (line == null) { break; } int pos1 = line.indexOf('='); if (pos1 < 0) { continue; } BundleInfo info = new BundleInfo(); info.bundleSymbolicName = line.substring(0, pos1); info.location = line.substring(pos1 + 1); list.add(info); } if (!setBundleInfoName(location + BUNDLE_NAME_LIST_FILE + "_" + Locale.getDefault().getLanguage(), list)) { setBundleInfoName(location + BUNDLE_NAME_LIST_FILE, list); } return list.toArray(BUNDLE_INFO_EMPTY_ARRAY); } finally { if (br != null) { br.close(); } } }
11
Code Sample 1: public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("GET REQUEST OR RESPONSE - Send content: " + file.getAbsolutePath()); FileInputStream in = null; try { in = new FileInputStream(file); int bytes = IOUtils.copy(in, out); LOGGER.debug("wrote bytes: " + bytes); out.flush(); } finally { IOUtils.closeQuietly(in); } } Code Sample 2: 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(); } }
00
Code Sample 1: private void bokActionPerformed(java.awt.event.ActionEvent evt) { if (this.tfGeneralSubDivision.getText().trim().equals("")) { this.showWarningMessage("Enter general sub division"); } else { String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds(); String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveGeneralSubDivision("1", this.tfGeneralSubDivision.getText(), patlib); System.out.println(xmlreq); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SubDivisionServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); if (rootelement.getChild("Error") == null) { this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase")); } else { this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor")); } } catch (Exception e) { System.out.println(e); } } } Code Sample 2: 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 OutputStream getAsOutputStream() throws IOException { OutputStream out; if (contentStream != null) { File tmp = File.createTempFile(getId(), null); out = new FileOutputStream(tmp); IOUtils.copy(contentStream, out); } else { out = new ByteArrayOutputStream(); out.write(getContent()); } return out; } Code Sample 2: @Test public void testLargePut() throws Throwable { int size = CommonParameters.BLOCK_SIZE; InputStream is = new FileInputStream(_fileName); RepositoryFileOutputStream ostream = new RepositoryFileOutputStream(_nodeName, _putHandle, CommonParameters.local); int readLen = 0; int writeLen = 0; byte[] buffer = new byte[CommonParameters.BLOCK_SIZE]; while ((readLen = is.read(buffer, 0, size)) != -1) { ostream.write(buffer, 0, readLen); writeLen += readLen; } ostream.close(); CCNStats stats = _putHandle.getNetworkManager().getStats(); Assert.assertEquals(0, stats.getCounter("DeliverInterestFailed")); }
00
Code Sample 1: @Override protected Set<DataRecord> retrieveRecords(DataTemplate template) { String query = template.getQuery(); if (query == null) { query = topic; } String select = prefix + " SELECT ?resource WHERE { { ?resource rdf:type " + "<http://dbpedia.org/class/yago/" + StringUtils.toCamelCase(query) + "> } UNION { ?resource skos:subject <http://dbpedia.org/resource/Category:" + query.replaceAll(" ", "_") + "> } }"; Document doc = null; HashSet<DataRecord> recs = new HashSet<DataRecord>(); try { URL url = new URL(queryBase + URLEncoder.encode(select, "UTF-8")); InputStream inStream = url.openStream(); doc = docBuild.parse(inStream); HashSet<String> resourceNames = new HashSet<String>(); Element table = doc.getDocumentElement(); NodeList rows = table.getElementsByTagName("tr"); for (int i = 0; i < rows.getLength(); i++) { Element row = (Element) rows.item(i); NodeList cols = row.getElementsByTagName("td"); if (cols.getLength() > 0) { Element elem = (Element) cols.item(0); String resource = ((Text) elem.getFirstChild()).getData(); resourceNames.add(resource); } } inStream.close(); for (String resource : resourceNames) { MultiValueMap<String> resRecord = queryResource(resource); if (resource != null) { DataRecord rec = parseResource(resRecord, template); if (rec != null) { recs.add(rec); } } } } catch (IOException exc) { exc.printStackTrace(); } catch (SAXException exc) { exc.printStackTrace(); } return recs; } Code Sample 2: public static String getRefCatastral(String pURL) { String result = new String(); String iniPC1 = "<pc1>"; String iniPC2 = "<pc2>"; String finPC1 = "</pc1>"; String finPC2 = "</pc2>"; String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; boolean error = false; int ini, fin; try { URL url = new URL(pURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { if (str.contains(iniCuerr)) { ini = str.indexOf(iniCuerr) + iniCuerr.length(); fin = str.indexOf(finCuerr); if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true; } if (error) { if (str.contains(iniDesErr)) { ini = str.indexOf(iniDesErr) + iniDesErr.length(); fin = str.indexOf(finDesErr); throw (new Exception(str.substring(ini, fin))); } } else { if (str.contains(iniPC1)) { ini = str.indexOf(iniPC1) + iniPC1.length(); fin = str.indexOf(finPC1); result = str.substring(ini, fin); } if (str.contains(iniPC2)) { ini = str.indexOf(iniPC2) + iniPC2.length(); fin = str.indexOf(finPC2); result = result.concat(str.substring(ini, fin)); } } } in.close(); } catch (Exception e) { System.err.println(e); } return result; }
00
Code Sample 1: public static void executa(String arquivo, String filial, String ip) { String drive = arquivo.substring(0, 2); if (drive.indexOf(":") == -1) drive = ""; Properties p = Util.lerPropriedades(arquivo); String servidor = p.getProperty("servidor"); String impressora = p.getProperty("fila"); String arqRel = new String(drive + p.getProperty("arquivo")); String copias = p.getProperty("copias"); if (filial.equalsIgnoreCase(servidor)) { Socket s = null; int tentativas = 0; boolean conectado = false; while (!conectado) { try { tentativas++; System.out.println("Tentando conectar " + ip + " (" + tentativas + ")"); s = new Socket(ip, 7000); conectado = s.isConnected(); } catch (ConnectException ce) { System.err.println(ce.getMessage()); System.err.println(ce.getCause()); } catch (UnknownHostException uhe) { System.err.println(uhe.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } } FileInputStream in = null; BufferedOutputStream out = null; try { in = new FileInputStream(new File(arqRel)); out = new BufferedOutputStream(new GZIPOutputStream(s.getOutputStream())); } catch (FileNotFoundException e3) { e3.printStackTrace(); } catch (IOException e3) { e3.printStackTrace(); } String arqtr = arqRel.substring(2); System.out.println("Proximo arquivo: " + arqRel + " ->" + arqtr); while (arqtr.length() < 30) arqtr += " "; while (impressora.length() < 30) impressora += " "; byte aux[] = new byte[30]; byte cop[] = new byte[2]; try { aux = arqtr.getBytes("UTF8"); out.write(aux); aux = impressora.getBytes("UTF8"); out.write(aux); cop = copias.getBytes("UTF8"); out.write(cop); out.flush(); } catch (UnsupportedEncodingException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } byte b[] = new byte[1024]; int nBytes; try { while ((nBytes = in.read(b)) != -1) out.write(b, 0, nBytes); out.flush(); out.close(); in.close(); s.close(); } catch (IOException e1) { e1.printStackTrace(); } System.out.println("Arquivo " + arqRel + " foi transmitido. \n\n"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } SimpleDateFormat dfArq = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat dfLog = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String arqLog = "log" + filial + dfArq.format(new Date()) + ".txt"; PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(arqLog, true)); } catch (IOException e) { e.printStackTrace(); } pw.println("Arquivo: " + arquivo + " " + dfLog.format(new Date())); pw.flush(); pw.close(); File f = new File(arquivo); while (!f.delete()) { System.out.println("Erro apagando " + arquivo); } } } Code Sample 2: private void importUrl(String str) throws Exception { URL url = new URL(str); InputStream xmlStream = url.openStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); MessageHolder messages = MessageHolder.getInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(xmlStream); Element rootElement = document.getDocumentElement(); EntrySetParser entrySetParser = new EntrySetParser(); EntrySetTag entrySet = entrySetParser.process(rootElement); UpdateProteinsI proteinFactory = new UpdateProteins(); BioSourceFactory bioSourceFactory = new BioSourceFactory(); ControlledVocabularyRepository.check(); EntrySetChecker.check(entrySet, proteinFactory, bioSourceFactory); if (messages.checkerMessageExists()) { MessageHolder.getInstance().printCheckerReport(System.err); } else { EntrySetPersister.persist(entrySet); if (messages.checkerMessageExists()) { MessageHolder.getInstance().printPersisterReport(System.err); } else { System.out.println("The data have been successfully saved in your Intact node."); } } }
11
Code Sample 1: private void refreshCacheFile(RepositoryFile file, File cacheFile) throws FileNotFoundException, IOException { FileOutputStream fos = new FileOutputStream(cacheFile); InputStream is = file.getInputStream(); int count = IOUtils.copy(is, fos); logger.debug("===========================================================> wrote bytes to cache " + count); fos.flush(); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(file.getInputStream()); } Code Sample 2: public static void main(String[] args) throws Exception { SocketConnector socketConnector = new SocketConnector(); socketConnector.setPort(6080); SslSocketConnector sslSocketConnector = new SslSocketConnector(); sslSocketConnector.setPort(6443); String serverKeystore = MockHttpListenerWithAuthentication.class.getClassLoader().getResource("cert/serverkeystore.jks").getPath(); sslSocketConnector.setKeystore(serverKeystore); sslSocketConnector.setKeyPassword("serverpass"); String serverTruststore = MockHttpListenerWithAuthentication.class.getClassLoader().getResource("cert/servertruststore.jks").getPath(); sslSocketConnector.setTruststore(serverTruststore); sslSocketConnector.setTrustPassword("serverpass"); server.addConnector(socketConnector); server.addConnector(sslSocketConnector); SecurityHandler securityHandler = createBasicAuthenticationSecurityHandler(); HandlerList handlerList = new HandlerList(); handlerList.addHandler(securityHandler); handlerList.addHandler(new AbstractHandler() { @Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + httpServletRequest.getQueryString()); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + baos.toString()); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); } }); server.addHandler(handlerList); server.start(); }
11
Code Sample 1: public void deleteSingle(String tbName, String idFld, String id) throws Exception { String tmp = ""; PreparedStatement prepStmt = null; try { if (tbName == null || tbName.length() == 0 || id == null || id.length() == 0) throw new Exception("Invalid parameter"); con = database.getConnection(); String delSQL = "delete from " + tbName + " where " + idFld + "='" + id + "'"; con.setAutoCommit(false); prepStmt = con.prepareStatement(delSQL); 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: public int next() { int sequenceValue = current(); try { Update update = dbi.getUpdate(); update.setTableName(sequenceTable); update.assignValue("SEQUENCE_VALUE", --sequenceValue); Search search = new Search(); search.addAttributeCriteria(sequenceTable, "SEQUENCE_NAME", Search.EQUAL, sequenceName); update.where(search); int affectedRows = dbi.getConnection().createStatement().executeUpdate(update.toString()); if (affectedRows == 1) { dbi.getConnection().commit(); } else { dbi.getConnection().rollback(); } } catch (SQLException sqle) { System.err.println("SQLException occurred in current(): " + sqle.getMessage()); } return sequenceValue; }
11
Code Sample 1: public void testRoundTrip_1(String resource) throws Exception { long start1 = System.currentTimeMillis(); File originalFile = File.createTempFile("RoundTripTest", "testRoundTrip_1"); FileOutputStream fos = new FileOutputStream(originalFile); IOUtils.copy(getClass().getResourceAsStream(resource), fos); fos.close(); long start2 = System.currentTimeMillis(); IsoFile isoFile = new IsoFile(new FileInputStream(originalFile).getChannel()); long start3 = System.currentTimeMillis(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel wbc = Channels.newChannel(baos); long start4 = System.currentTimeMillis(); Walk.through(isoFile); long start5 = System.currentTimeMillis(); isoFile.getBox(wbc); wbc.close(); long start6 = System.currentTimeMillis(); System.err.println("Preparing tmp copy took: " + (start2 - start1) + "ms"); System.err.println("Parsing took : " + (start3 - start2) + "ms"); System.err.println("Writing took : " + (start6 - start3) + "ms"); System.err.println("Walking took : " + (start5 - start4) + "ms"); byte[] a = IOUtils.toByteArray(getClass().getResourceAsStream(resource)); byte[] b = baos.toByteArray(); Assert.assertArrayEquals(a, b); } Code Sample 2: protected void assignListeners() { groupsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent event) { refreshInfo(); } }); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JFileChooser fileDialog = new JFileChooser("."); fileDialog.setFileFilter(ReaderData.mkExtensionFileFilter(".grp", "Group Files")); int outcome = fileDialog.showSaveDialog((Frame) null); if (outcome == JFileChooser.APPROVE_OPTION) { assert (fileDialog.getCurrentDirectory() != null); assert (fileDialog.getSelectedFile() != null); String fileName = fileDialog.getCurrentDirectory().toString() + File.separator + fileDialog.getSelectedFile().getName(); try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); ReaderWriterGroup.write(out, writer); System.err.println("Wrote groups informations to output '" + fileName + "'."); out.close(); } catch (IOException e) { System.err.println("error while writing (GroupManager.saveClt):"); e.printStackTrace(); } } else if (outcome == JFileChooser.CANCEL_OPTION) { } } }); loadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { JFileChooser fileDialog = new JFileChooser("."); fileDialog.setFileFilter(ReaderData.mkExtensionFileFilter(".grp", "Group Files")); int outcome = fileDialog.showOpenDialog((Frame) null); if (outcome == JFileChooser.APPROVE_OPTION) { assert (fileDialog.getCurrentDirectory() != null); assert (fileDialog.getSelectedFile() != null); String fileName = fileDialog.getCurrentDirectory().toString() + File.separator + fileDialog.getSelectedFile().getName(); BufferedReader fileReader = null; try { fileReader = new BufferedReader(new FileReader(fileName)); ReaderWriterGroup.read(fileReader, writer); fileReader.close(); } catch (Exception e) { System.err.println("Exception while reading from file '" + fileName + "'."); System.err.println(e); } } else if (outcome == JFileChooser.CANCEL_OPTION) { } } }); ItemListener propItemListener = new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { int[] indices = groupsList.getSelectedIndices(); for (int index : indices) { Group group = getGroupFromListIndex(index); if (group != null) { if (event.getSource() instanceof JComboBox) { JComboBox eventSource = (JComboBox) event.getSource(); if (eventSource == colorComboBox) { Color color = colorComboBox.getSelectedColor(); assert (color != null); group.setColor(color); shapeComboBox.setColor(color); } else if (eventSource == shapeComboBox) { Shape shape = shapeComboBox.getSelectedShape(); assert (shape != null); group.setShape(shape); } } else if (event.getSource() instanceof JCheckBox) { JCheckBox eventSource = (JCheckBox) event.getSource(); if (eventSource == showGroupCheckBox) { group.visible = showGroupCheckBox.isSelected(); } else if (eventSource == showGraphicInfoCheckBox) { group.info = showGraphicInfoCheckBox.isSelected(); } } } } graph.notifyAboutGroupsChange(null); } }; colorComboBox.addItemListener(propItemListener); shapeComboBox.addItemListener(propItemListener); showGroupCheckBox.addItemListener(propItemListener); showGraphicInfoCheckBox.addItemListener(propItemListener); showGroupfreeNodesCheckBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { graph.getGroup(0).visible = showGroupfreeNodesCheckBox.isSelected(); graph.notifyAboutGroupsChange(null); } }); ActionListener propActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JButton botton = (JButton) event.getSource(); Group group = getGroupFromListIndex(groupsList.getSelectedIndex()); if (group != null) { for (GraphVertex graphVertex : group) { if (botton == showLabelsButton) { graphVertex.setShowName(NameVisibility.Priority.GROUPS, true); } else if (botton == hideLabelsButton) { graphVertex.setShowName(NameVisibility.Priority.GROUPS, false); } } graph.notifyAboutGroupsChange(null); } } }; showLabelsButton.addActionListener(propActionListener); hideLabelsButton.addActionListener(propActionListener); newButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { String newGroupName = JOptionPane.showInputDialog(null, "Enter a name", "Name of the new group", JOptionPane.QUESTION_MESSAGE); if (newGroupName != null) { if (graph.getGroup(newGroupName) == null) { graph.addGroup(new Group(newGroupName, graph)); } } } }); editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { Group group = getGroupFromListIndex(groupsList.getSelectedIndex()); if (group != null) { DialogEditGroup dialog = new DialogEditGroup(graph, group); dialog.setModal(true); dialog.setVisible(true); } } }); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index > 0 && index < graph.getNumberOfGroups() - 1) { graph.removeGroup(index); } } }); upButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index < graph.getNumberOfGroups() - 1) { graph.moveGroupUp(index); groupsList.setSelectedIndex(index - 1); } } }); downButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index < graph.getNumberOfGroups() - 1) { graph.moveGroupDown(index); groupsList.setSelectedIndex(index + 1); } } }); }
11
Code Sample 1: public static void DecodeMapFile(String mapFile, String outputFile) throws Exception { byte magicKey = 0; byte[] buffer = new byte[2048]; int nread; InputStream map; OutputStream output; try { map = new FileInputStream(mapFile); } catch (Exception e) { throw new Exception("Map file error", e); } try { output = new FileOutputStream(outputFile); } catch (Exception e) { throw new Exception("Map file error", e); } while ((nread = map.read(buffer, 0, 2048)) != 0) { for (int i = 0; i < nread; ++i) { buffer[i] ^= magicKey; magicKey += 43; } output.write(buffer, 0, nread); } map.close(); output.close(); } Code Sample 2: private void putAlgosFromJar(File jarfile, AlgoDir dir, Model model) throws FileNotFoundException, IOException { URLClassLoader urlLoader = new URLClassLoader(new URL[] { jarfile.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(jarfile)); JarEntry entry = jis.getNextJarEntry(); String name = null; String tmpdir = System.getProperty("user.dir") + File.separator + Application.getProperty("dir.tmp") + File.separator; byte[] buffer = new byte[1000]; while (entry != null) { name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); try { Class<?> cls = urlLoader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && ((cls.getModifiers() & Modifier.ABSTRACT) == 0)) { dir.addAlgorithm(cls); model.putClass(cls.getName(), cls); } else if (ISerializable.class.isAssignableFrom(cls)) { model.putClass(cls.getName(), cls); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else if (Constants.isAllowedImageType(name)) { int lastSep = name.lastIndexOf("/"); if (lastSep != -1) { String dirs = tmpdir + name.substring(0, lastSep); File d = new File(dirs); if (!d.exists()) d.mkdirs(); } String filename = tmpdir + name; File f = new File(filename); if (!f.exists()) { f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); int read = -1; while ((read = jis.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.close(); } } entry = jis.getNextJarEntry(); } }
00
Code Sample 1: public String obfuscateString(String string) { String obfuscatedString = null; try { MessageDigest md = MessageDigest.getInstance(ENCRYPTION_ALGORITHM); md.update(string.getBytes()); byte[] digest = md.digest(); obfuscatedString = new String(Base64.encode(digest)).replace(DELIM_PATH, '='); } catch (NoSuchAlgorithmException e) { StatusHandler.log("SHA not available", null); obfuscatedString = LABEL_FAILED_TO_OBFUSCATE; } return obfuscatedString; } Code Sample 2: private String loadSchemas() { StringWriter writer = new StringWriter(); try { IOUtils.copy(CoreOdfValidator.class.getResourceAsStream("schema_list.properties"), writer); } catch (IOException e) { e.printStackTrace(); } return writer.toString(); }
00
Code Sample 1: public static String readFromURL(String urlStr) throws IOException { URL url = new URL(urlStr); StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } in.close(); return sb.toString(); } Code Sample 2: public static int best(int r, int n, int s) { if ((n <= 0) || (r < 0) || (r > n) || (s < 0)) return 0; int[] rolls = new int[n]; for (int i = 0; i < n; i++) rolls[i] = d(s); boolean found; do { found = false; for (int x = 0; x < n - 1; x++) { if (rolls[x] < rolls[x + 1]) { int t = rolls[x]; rolls[x] = rolls[x + 1]; rolls[x + 1] = t; found = true; } } } while (found); int sum = 0; for (int i = 0; i < r; i++) sum += rolls[i]; return sum; }
00
Code Sample 1: public void run() { FileInputStream src; FileOutputStream dest; try { dest = new FileOutputStream(srcName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileChannel destC = dest.getChannel(); FileChannel srcC; ByteBuffer buf = ByteBuffer.allocateDirect(BUFFER_SIZE); try { int fileNo = 0; while (true) { int i = 1; String destName = srcName + "_" + fileNo; src = new FileInputStream(destName); srcC = src.getChannel(); while ((i > 0)) { i = srcC.read(buf); buf.flip(); destC.write(buf); buf.compact(); } srcC.close(); src.close(); fileNo++; } } catch (IOException e1) { e1.printStackTrace(); return; } } Code Sample 2: public void parseFile(String dataurl, URL documentBase) { DataInputStream in; if (_debug > 2) System.out.println("PlotBox: parseFile(" + dataurl + " " + documentBase + ") _dataurl = " + _dataurl + " " + _documentBase); if (dataurl == null || dataurl.length() == 0) { in = new DataInputStream(System.in); } else { try { URL url; if (documentBase == null && _documentBase != null) { documentBase = _documentBase; } if (documentBase == null) { url = new URL(_dataurl); } else { try { url = new URL(documentBase, dataurl); } catch (NullPointerException e) { url = new URL(_dataurl); } } in = new DataInputStream(url.openStream()); } catch (MalformedURLException e) { try { in = new DataInputStream(new FileInputStream(dataurl)); } catch (FileNotFoundException me) { _errorMsg = new String[2]; _errorMsg[0] = "File not found: " + dataurl; _errorMsg[1] = me.getMessage(); return; } catch (SecurityException me) { _errorMsg = new String[2]; _errorMsg[0] = "Security Exception: " + dataurl; _errorMsg[1] = me.getMessage(); return; } } catch (IOException ioe) { _errorMsg = new String[2]; _errorMsg[0] = "Failure opening URL: " + dataurl; _errorMsg[1] = ioe.getMessage(); return; } } _newFile(); try { if (_binary) { _parseBinaryStream(in); } else { String line = in.readLine(); while (line != null) { _parseLine(line); line = in.readLine(); } } } catch (MalformedURLException e) { _errorMsg = new String[2]; _errorMsg[0] = "Malformed URL: " + dataurl; _errorMsg[1] = e.getMessage(); return; } catch (IOException e) { _errorMsg = new String[2]; _errorMsg[0] = "Failure reading data: " + dataurl; _errorMsg[1] = e.getMessage(); } catch (PlotDataException e) { _errorMsg = new String[2]; _errorMsg[0] = "Incorrectly formatted plot data in " + dataurl; _errorMsg[1] = e.getMessage(); } finally { try { in.close(); } catch (IOException me) { } } }
11
Code Sample 1: private String getStoreName() { try { final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(protectionDomain.getBytes()); final byte[] bs = digest.digest(); final StringBuffer sb = new StringBuffer(bs.length * 2); for (int i = 0; i < bs.length; i++) { final String s = Integer.toHexString(bs[i] & 0xff); if (s.length() < 2) sb.append('0'); sb.append(s); } return sb.toString(); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Can't save credentials: digest method MD5 unavailable."); } } Code Sample 2: private boolean authenticate(String reply) { String user = reply.substring(0, reply.indexOf(" ")); String resp = reply.substring(reply.indexOf(" ") + 1); if (!module.users.contains(user)) { error = "so such user " + user; return false; } try { LineNumberReader secrets = new LineNumberReader(new FileReader(module.secretsFile)); String line; while ((line = secrets.readLine()) != null) { if (line.startsWith(user + ":")) { MessageDigest md4 = MessageDigest.getInstance("BrokenMD4"); md4.update(new byte[4]); md4.update(line.substring(line.indexOf(":") + 1).getBytes("US-ASCII")); md4.update(challenge.getBytes("US-ASCII")); String hash = Util.base64(md4.digest()); if (hash.equals(resp)) { secrets.close(); return true; } } } secrets.close(); } catch (Exception e) { logger.fatal(e.toString()); error = "server configuration error"; return false; } error = "authentication failure for module " + module.name; return false; }
11
Code Sample 1: private void copyFile(File dir, File fileToAdd) { try { byte[] readBuffer = new byte[1024]; File file = new File(dir.getCanonicalPath() + File.separatorChar + fileToAdd.getName()); if (file.createNewFile()) { FileInputStream fis = new FileInputStream(fileToAdd); FileOutputStream fos = new FileOutputStream(file); int bytesRead; do { bytesRead = fis.read(readBuffer); fos.write(readBuffer, 0, bytesRead); } while (bytesRead == 0); fos.flush(); fos.close(); fis.close(); } else { logger.severe("unable to create file:" + file.getAbsolutePath()); } } catch (IOException ioe) { logger.severe("unable to create file:" + ioe); } } Code Sample 2: public TempFileBinaryBody(InputStream is) throws IOException { TempPath tempPath = TempStorage.getInstance().getRootTempPath(); tempFile = tempPath.createTempFile("attachment", ".bin"); OutputStream out = tempFile.getOutputStream(); IOUtils.copy(is, out); out.close(); }
11
Code Sample 1: private File getTempFile(DigitalObject object, String pid) throws Exception { File directory = new File(tmpDir, object.getId()); File target = new File(directory, pid); if (!target.exists()) { target.getParentFile().mkdirs(); target.createNewFile(); } Payload payload = object.getPayload(pid); InputStream in = payload.open(); FileOutputStream out = null; try { out = new FileOutputStream(target); IOUtils.copyLarge(in, out); } catch (Exception ex) { close(out); target.delete(); payload.close(); throw ex; } close(out); payload.close(); return target; } Code Sample 2: public void init(String[] arguments) { if (arguments.length < 1) { printHelp(); return; } String[] valid_args = new String[] { "device*", "d*", "help", "h", "speed#", "s#", "file*", "f*", "gpsd*", "nmea", "n", "garmin", "g", "sirf", "i", "rawdata", "downloadtracks", "downloadwaypoints", "downloadroutes", "deviceinfo", "printposonce", "printpos", "p", "printalt", "printspeed", "printheading", "printsat", "template*", "outfile*", "screenshot*", "printdefaulttemplate", "helptemplate", "nmealogfile*", "l", "uploadtracks", "uploadroutes", "uploadwaypoints", "infile*" }; CommandArguments args = null; try { args = new CommandArguments(arguments, valid_args); } catch (CommandArgumentException cae) { System.err.println("Invalid arguments: " + cae.getMessage()); printHelp(); return; } String filename = null; String serial_port_name = null; boolean gpsd = false; String gpsd_host = "localhost"; int gpsd_port = 2947; int serial_port_speed = -1; GPSDataProcessor gps_data_processor; String nmea_log_file = null; if (args.isSet("help") || (args.isSet("h"))) { printHelp(); return; } if (args.isSet("helptemplate")) { printHelpTemplate(); } if (args.isSet("printdefaulttemplate")) { System.out.println(DEFAULT_TEMPLATE); } if (args.isSet("device")) { serial_port_name = (String) args.getValue("device"); } else if (args.isSet("d")) { serial_port_name = (String) args.getValue("d"); } if (args.isSet("speed")) { serial_port_speed = ((Integer) args.getValue("speed")).intValue(); } else if (args.isSet("s")) { serial_port_speed = ((Integer) args.getValue("s")).intValue(); } if (args.isSet("file")) { filename = (String) args.getValue("file"); } else if (args.isSet("f")) { filename = (String) args.getValue("f"); } if (args.isSet("gpsd")) { gpsd = true; String gpsd_host_port = (String) args.getValue("gpsd"); if (gpsd_host_port != null && gpsd_host_port.length() > 0) { String[] params = gpsd_host_port.split(":"); gpsd_host = params[0]; if (params.length > 0) { gpsd_port = Integer.parseInt(params[1]); } } } if (args.isSet("garmin") || args.isSet("g")) { gps_data_processor = new GPSGarminDataProcessor(); serial_port_speed = 9600; if (filename != null) { System.err.println("ERROR: Cannot read garmin data from file, only serial port supported!"); return; } } else if (args.isSet("sirf") || args.isSet("i")) { gps_data_processor = new GPSSirfDataProcessor(); serial_port_speed = 19200; if (filename != null) { System.err.println("ERROR: Cannot read sirf data from file, only serial port supported!"); return; } } else { gps_data_processor = new GPSNmeaDataProcessor(); serial_port_speed = 4800; } if (args.isSet("nmealogfile") || (args.isSet("l"))) { if (args.isSet("nmealogfile")) nmea_log_file = args.getStringValue("nmealogfile"); else nmea_log_file = args.getStringValue("l"); } if (args.isSet("rawdata")) { gps_data_processor.addGPSRawDataListener(new GPSRawDataListener() { public void gpsRawDataReceived(char[] data, int offset, int length) { System.out.println("RAWLOG: " + new String(data, offset, length)); } }); } GPSDevice gps_device; Hashtable environment = new Hashtable(); if (filename != null) { environment.put(GPSFileDevice.PATH_NAME_KEY, filename); gps_device = new GPSFileDevice(); } else if (gpsd) { environment.put(GPSNetworkGpsdDevice.GPSD_HOST_KEY, gpsd_host); environment.put(GPSNetworkGpsdDevice.GPSD_PORT_KEY, new Integer(gpsd_port)); gps_device = new GPSNetworkGpsdDevice(); } else { if (serial_port_name != null) environment.put(GPSSerialDevice.PORT_NAME_KEY, serial_port_name); if (serial_port_speed > -1) environment.put(GPSSerialDevice.PORT_SPEED_KEY, new Integer(serial_port_speed)); gps_device = new GPSSerialDevice(); } try { gps_device.init(environment); gps_data_processor.setGPSDevice(gps_device); gps_data_processor.open(); gps_data_processor.addProgressListener(this); if ((nmea_log_file != null) && (nmea_log_file.length() > 0)) { gps_data_processor.addGPSRawDataListener(new GPSRawDataFileLogger(nmea_log_file)); } if (args.isSet("deviceinfo")) { System.out.println("GPSInfo:"); String[] infos = gps_data_processor.getGPSInfo(); for (int index = 0; index < infos.length; index++) { System.out.println(infos[index]); } } if (args.isSet("screenshot")) { FileOutputStream out = new FileOutputStream((String) args.getValue("screenshot")); BufferedImage image = gps_data_processor.getScreenShot(); ImageIO.write(image, "PNG", out); } boolean print_waypoints = args.isSet("downloadwaypoints"); boolean print_routes = args.isSet("downloadroutes"); boolean print_tracks = args.isSet("downloadtracks"); if (print_waypoints || print_routes || print_tracks) { VelocityContext context = new VelocityContext(); if (print_waypoints) { List waypoints = gps_data_processor.getWaypoints(); if (waypoints != null) context.put("waypoints", waypoints); else print_waypoints = false; } if (print_tracks) { List tracks = gps_data_processor.getTracks(); if (tracks != null) context.put("tracks", tracks); else print_tracks = false; } if (print_routes) { List routes = gps_data_processor.getRoutes(); if (routes != null) context.put("routes", routes); else print_routes = false; } context.put("printwaypoints", new Boolean(print_waypoints)); context.put("printtracks", new Boolean(print_tracks)); context.put("printroutes", new Boolean(print_routes)); Writer writer; Reader reader; if (args.isSet("template")) { String template_file = (String) args.getValue("template"); reader = new FileReader(template_file); } else { reader = new StringReader(DEFAULT_TEMPLATE); } if (args.isSet("outfile")) writer = new FileWriter((String) args.getValue("outfile")); else writer = new OutputStreamWriter(System.out); addDefaultValuesToContext(context); boolean result = printTemplate(context, reader, writer); } boolean read_waypoints = (args.isSet("uploadwaypoints") && args.isSet("infile")); boolean read_routes = (args.isSet("uploadroutes") && args.isSet("infile")); boolean read_tracks = (args.isSet("uploadtracks") && args.isSet("infile")); if (read_waypoints || read_routes || read_tracks) { ReadGPX reader = new ReadGPX(); String in_file = (String) args.getValue("infile"); reader.parseFile(in_file); if (read_waypoints) gps_data_processor.setWaypoints(reader.getWaypoints()); if (read_routes) gps_data_processor.setRoutes(reader.getRoutes()); if (read_tracks) gps_data_processor.setTracks(reader.getTracks()); } if (args.isSet("printposonce")) { GPSPosition pos = gps_data_processor.getGPSPosition(); System.out.println("Current Position: " + pos); } if (args.isSet("printpos") || args.isSet("p")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.LOCATION, this); } if (args.isSet("printalt")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.ALTITUDE, this); } if (args.isSet("printspeed")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.SPEED, this); } if (args.isSet("printheading")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.HEADING, this); } if (args.isSet("printsat")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.NUMBER_SATELLITES, this); gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.SATELLITE_INFO, this); } if (args.isSet("printpos") || args.isSet("p") || args.isSet("printalt") || args.isSet("printsat") || args.isSet("printspeed") || args.isSet("printheading")) { gps_data_processor.startSendPositionPeriodically(1000L); try { System.in.read(); } catch (IOException ignore) { } } gps_data_processor.close(); } catch (GPSException e) { e.printStackTrace(); } catch (FileNotFoundException fnfe) { System.err.println("ERROR: File not found: " + fnfe.getMessage()); } catch (IOException ioe) { System.err.println("ERROR: I/O Error: " + ioe.getMessage()); } }
11
Code Sample 1: private static int ejecutaUpdate(String database, String SQL) throws Exception { int i = 0; DBConnectionManager dbm = null; Connection bd = null; try { dbm = DBConnectionManager.getInstance(); bd = dbm.getConnection(database); Statement st = bd.createStatement(); i = st.executeUpdate(SQL); bd.commit(); st.close(); dbm.freeConnection(database, bd); } catch (Exception e) { log.error("SQL error: " + SQL, e); Exception excep; if (dbm == null) excep = new Exception("Could not obtain pool object DbConnectionManager"); else if (bd == null) excep = new Exception("The Db connection pool could not obtain a database connection"); else { bd.rollback(); excep = new Exception("SQL Error: " + SQL + " error: " + e); dbm.freeConnection(database, bd); } throw excep; } return i; } Code Sample 2: static void test() throws SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; Savepoint sp = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); st = conn.createStatement(); String sql = "update user set money=money-10 where id=1"; st.executeUpdate(sql); sp = conn.setSavepoint(); sql = "update user set money=money-10 where id=3"; st.executeUpdate(sql); sql = "select money from user where id=2"; rs = st.executeQuery(sql); float money = 0.0f; if (rs.next()) { money = rs.getFloat("money"); } if (money > 300) throw new RuntimeException("�Ѿ��������ֵ��"); sql = "update user set money=money+10 where id=2"; st.executeUpdate(sql); conn.commit(); } catch (RuntimeException e) { if (conn != null && sp != null) { conn.rollback(sp); conn.commit(); } throw e; } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { JdbcUtils.free(rs, st, conn); } }
11
Code Sample 1: public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(""); fc.setMultiSelectionEnabled(false); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); int option = 0; boolean save = m_data != null; if (save) option = fc.showSaveDialog(this); else option = fc.showOpenDialog(this); if (option != JFileChooser.APPROVE_OPTION) return; File file = fc.getSelectedFile(); if (file == null) return; log.info(file.toString()); try { if (save) { FileOutputStream os = new FileOutputStream(file); byte[] buffer = (byte[]) m_data; os.write(buffer); os.flush(); os.close(); log.config("Save to " + file + " #" + buffer.length); } else { FileInputStream is = new FileInputStream(file); ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 8]; int length = -1; while ((length = is.read(buffer)) != -1) os.write(buffer, 0, length); is.close(); byte[] data = os.toByteArray(); m_data = data; log.config("Load from " + file + " #" + data.length); os.close(); } } catch (Exception ex) { log.log(Level.WARNING, "Save=" + save, ex); } try { fireVetoableChange(m_columnName, null, m_data); } catch (PropertyVetoException pve) { } } Code Sample 2: public static void copyFile(File in, File out, boolean read, boolean write, boolean execute) throws FileNotFoundException, IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); File outFile = null; if (out.isDirectory()) { outFile = new File(out.getAbsolutePath() + File.separator + in.getName()); } else { outFile = out; } FileChannel outChannel = new FileOutputStream(outFile).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } outFile.setReadable(read); outFile.setWritable(write); outFile.setExecutable(execute); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: public GGProvinces getListProvinces() throws IllegalStateException, GGException, Exception { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("method", "gg.photos.geo.getListProvinces")); qparams.add(new BasicNameValuePair("key", this.key)); String url = REST_URL + "?" + URLEncodedUtils.format(qparams, "UTF-8"); URI uri = new URI(url); HttpGet httpget = new HttpGet(uri); HttpResponse response = httpClient.execute(httpget); int status = response.getStatusLine().getStatusCode(); errorCheck(response, status); InputStream content = response.getEntity().getContent(); GGProvinces provinces = JAXB.unmarshal(content, GGProvinces.class); return provinces; } Code Sample 2: public void readHTMLFromURL(URL url) throws IOException { InputStream in = url.openStream(); try { readHTMLFromStream(new InputStreamReader(in)); } finally { try { in.close(); } catch (IOException ex) { Logger.getLogger(HTMLTextAreaModel.class.getName()).log(Level.SEVERE, "Exception while closing InputStream", ex); } } }
11
Code Sample 1: public static File jar(File in, String outArc, File tempDir, PatchConfigXML conf) { FileOutputStream arcFile = null; JarOutputStream jout = null; DirectoryScanner ds = null; ds = new DirectoryScanner(); ds.setCaseSensitive(true); ds.setBasedir(in); ds.scan(); ds.setCaseSensitive(true); String[] names = ds.getIncludedFiles(); ArrayList exName = new ArrayList(); if (names == null || names.length < 1) return null; File tempArc = new File(tempDir, outArc.substring(0, outArc.length())); try { Manifest mf = null; List v = new ArrayList(); for (int i = 0; i < names.length; i++) { if (names[i].toUpperCase().indexOf("MANIFEST.MF") > -1) { FileInputStream fis = new FileInputStream(in.getAbsolutePath() + "/" + names[i].replace('\\', '/')); mf = new Manifest(fis); } else v.add(names[i]); } String[] toJar = new String[v.size()]; v.toArray(toJar); tempArc.createNewFile(); arcFile = new FileOutputStream(tempArc); if (mf == null) jout = new JarOutputStream(arcFile); else jout = new JarOutputStream(arcFile, mf); byte[] buffer = new byte[1024]; for (int i = 0; i < toJar.length; i++) { if (conf != null) { if (!conf.allowFileAction(toJar[i], PatchConfigXML.OP_CREATE)) { exName.add(toJar[i]); continue; } } String currentPath = in.getAbsolutePath() + "/" + toJar[i]; String entryName = toJar[i].replace('\\', '/'); JarEntry currentEntry = new JarEntry(entryName); jout.putNextEntry(currentEntry); FileInputStream fis = new FileInputStream(currentPath); int len; while ((len = fis.read(buffer)) >= 0) jout.write(buffer, 0, len); fis.close(); jout.closeEntry(); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { jout.close(); arcFile.close(); } catch (IOException e1) { throw new RuntimeException(e1); } } return tempArc; } Code Sample 2: private void addAuditDatastream() throws ObjectIntegrityException, StreamIOException { if (m_obj.getAuditRecords().size() == 0) { return; } String dsId = m_pid.toURI() + "/AUDIT"; String dsvId = dsId + "/" + DateUtility.convertDateToString(m_obj.getCreateDate()); Entry dsEntry = m_feed.addEntry(); dsEntry.setId(dsId); dsEntry.setTitle("AUDIT"); dsEntry.setUpdated(m_obj.getCreateDate()); dsEntry.addCategory(MODEL.STATE.uri, "A", null); dsEntry.addCategory(MODEL.CONTROL_GROUP.uri, "X", null); dsEntry.addCategory(MODEL.VERSIONABLE.uri, "false", null); dsEntry.addLink(dsvId, Link.REL_ALTERNATE); Entry dsvEntry = m_feed.addEntry(); dsvEntry.setId(dsvId); dsvEntry.setTitle("AUDIT.0"); dsvEntry.setUpdated(m_obj.getCreateDate()); ThreadHelper.addInReplyTo(dsvEntry, m_pid.toURI() + "/AUDIT"); dsvEntry.addCategory(MODEL.FORMAT_URI.uri, AUDIT1_0.uri, null); dsvEntry.addCategory(MODEL.LABEL.uri, "Audit Trail for this object", null); if (m_format.equals(ATOM_ZIP1_1)) { String name = "AUDIT.0.xml"; try { m_zout.putNextEntry(new ZipEntry(name)); Reader r = new StringReader(DOTranslationUtility.getAuditTrail(m_obj)); IOUtils.copy(r, m_zout, m_encoding); m_zout.closeEntry(); r.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); dsvEntry.setSummary("AUDIT.0"); dsvEntry.setContent(iri, "text/xml"); } else { dsvEntry.setContent(DOTranslationUtility.getAuditTrail(m_obj), "text/xml"); } }
00
Code Sample 1: protected Source getStylesheetSource(Resource stylesheetLocation) throws ApplicationContextException { if (logger.isDebugEnabled()) { logger.debug("Loading XSLT stylesheet from " + stylesheetLocation); } try { URL url = stylesheetLocation.getURL(); String urlPath = url.toString(); String systemId = urlPath.substring(0, urlPath.lastIndexOf('/') + 1); return new StreamSource(url.openStream(), systemId); } catch (IOException ex) { throw new ApplicationContextException("Can't load XSLT stylesheet from " + stylesheetLocation, ex); } } Code Sample 2: private static String processRequest(String request, HttpMethod method) { SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory(); URI uri = null; try { uri = new URI(request); ClientHttpRequest clientHttpRequest = simpleClientHttpRequestFactory.createRequest(uri, method); ClientHttpResponse response = clientHttpRequest.execute(); InputStream bodyInputStream = response.getBody(); String body = org.apache.commons.io.IOUtils.toString(bodyInputStream); return body; } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
00
Code Sample 1: void copyFileOnPeer(String path, RServerInfo peerserver, boolean allowoverwrite) throws IOException { RFile file = new RFile(path); OutputStream out = null; FileInputStream in = null; try { in = fileManager.openFileRead(path); out = localClient.openWrite(file, false, WriteMode.TRANSACTED, 1, peerserver, !allowoverwrite); IOUtils.copyLarge(in, out); out.close(); out = null; } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (out != null) { try { out.close(); } catch (Throwable t) { } } } } Code Sample 2: public void run() { waiting(200); try { URL url = new URL(urlAddress); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); XMLHandlerSingleAlbum myXMLHandler = new XMLHandlerSingleAlbum(); xr.setContentHandler(myXMLHandler); xr.parse(new InputSource(url.openStream())); statuscode = myXMLHandler.statuscode; if (statuscode != 200 && statuscode != 206) { throw new Exception(); } genre = myXMLHandler.genre; genreId = myXMLHandler.genreId; labelId = myXMLHandler.labelId; label = myXMLHandler.label; date = myXMLHandler.releaseDate; rating = myXMLHandler.rating; imageURL = myXMLHandler.imageURL; artist = myXMLHandler.artist; artistId = myXMLHandler.artistId; numberOfTracks = myXMLHandler.nItems; trackNames = myXMLHandler.tracks; handlerSetContent.sendEmptyMessage(0); dialog.dismiss(); updateImage(); } catch (Exception e) { final Exception ef = e; nameTextView.post(new Runnable() { public void run() { nameTextView.setText(R.string.couldnt_get_album_info); } }); } if (dialog.isShowing()) { dialog.dismiss(); } handlerDoneLoading.sendEmptyMessage(0); }
00
Code Sample 1: private void bokActionPerformed(java.awt.event.ActionEvent evt) { if (this.tfGeneralSubDivision.getText().trim().equals("")) { this.showWarningMessage("Enter general sub division"); } else { String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds(); String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveGeneralSubDivision("1", this.tfGeneralSubDivision.getText(), patlib); System.out.println(xmlreq); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SubDivisionServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); if (rootelement.getChild("Error") == null) { this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase")); } else { this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor")); } } catch (Exception e) { System.out.println(e); } } } Code Sample 2: public static String md5(String text, String charset) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } msgDigest.update(text.getBytes()); byte[] bytes = msgDigest.digest(); byte tb; char low; char high; char tmpChar; String md5Str = new String(); for (int i = 0; i < bytes.length; i++) { tb = bytes[i]; tmpChar = (char) ((tb >>> 4) & 0x000f); if (tmpChar >= 10) { high = (char) (('a' + tmpChar) - 10); } else { high = (char) ('0' + tmpChar); } md5Str += high; tmpChar = (char) (tb & 0x000f); if (tmpChar >= 10) { low = (char) (('a' + tmpChar) - 10); } else { low = (char) ('0' + tmpChar); } md5Str += low; } return md5Str; }
00
Code Sample 1: public void widgetSelected(SelectionEvent event) { try { URL url = new URL(PKBMain.PRODUCT_WEBSITE + "/latest-version.txt"); Properties prop = new Properties(); prop.load(url.openStream()); Package currentPackage = Package.getPackage("org.sf.pkb.gui"); String version = currentPackage.getImplementationVersion(); if (version == null) { version = ""; } String remoteVersion = prop.getProperty("version") + " b" + prop.getProperty("build"); if (remoteVersion.trim().compareTo(version.trim()) != 0) { StringBuffer buf = new StringBuffer(); buf.append("<HTML><BODY>").append("<h3 style='color: #0033FF'>You do not have the latest version. <br/> ").append("The latest version is PKB ").append(prop.getProperty("version") + " b" + prop.getProperty("build")).append(".</h3><A HREF='").append(prop.getProperty("url")).append("' TARGET='_BLANK'>Please download here </a> <br/><br/>").append("<B>It is strongly suggested to backup your knowledge base before install or unzip the new package!</B>").append("</BODY></HTML>"); MainScreen.Widget.getKnowledgeContentPanel().showTextInBrowser(buf.toString()); } else { StringBuffer buf = new StringBuffer(); buf.append("<HTML><BODY>").append("<h3 style='color: #0033FF'>You already had the latest version - ALEX PKB ").append(prop.getProperty("version") + " b" + prop.getProperty("build")).append(".</h3>").append("</BODY></HTML>"); MainScreen.Widget.getKnowledgeContentPanel().showTextInBrowser(buf.toString()); } } catch (Exception ex) { ex.printStackTrace(); } shell.close(); } Code Sample 2: public static void loadPlugins() { Logger.trace("Loading plugins"); Enumeration<URL> urls = null; try { urls = Play.classloader.getResources("play.plugins"); } catch (Exception e) { } while (urls != null && urls.hasMoreElements()) { URL url = urls.nextElement(); Logger.trace("Found one plugins descriptor, %s", url); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; while ((line = reader.readLine()) != null) { String[] infos = line.split(":"); PlayPlugin plugin = (PlayPlugin) Play.classloader.loadClass(infos[1].trim()).newInstance(); Logger.trace("Loaded plugin %s", plugin); plugin.index = Integer.parseInt(infos[0]); plugins.add(plugin); } } catch (Exception ex) { Logger.error(ex, "Cannot load %s", url); } } Collections.sort(plugins); for (PlayPlugin plugin : new ArrayList<PlayPlugin>(plugins)) { plugin.onLoad(); } }
11
Code Sample 1: @Test public void testCopy_readerToOutputStream_Encoding_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null, "UTF16"); fail(); } catch (NullPointerException ex) { } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } Code Sample 2: private void doUpload(UploadKind uploadKind, WriteKind writeKind) throws Exception { int n = 512 * 1024; AtomicInteger total = new AtomicInteger(0); ServerSocket ss = startSinkServer(total); URL url = new URL("http://localhost:" + ss.getLocalPort() + "/test1"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); if (uploadKind == UploadKind.CHUNKED) { conn.setChunkedStreamingMode(-1); } else { conn.setFixedLengthStreamingMode(n); } OutputStream out = conn.getOutputStream(); if (writeKind == WriteKind.BYTE_BY_BYTE) { for (int i = 0; i < n; ++i) { out.write('x'); } } else { byte[] buf = new byte[writeKind == WriteKind.SMALL_BUFFERS ? 256 : 64 * 1024]; Arrays.fill(buf, (byte) 'x'); for (int i = 0; i < n; i += buf.length) { out.write(buf, 0, Math.min(buf.length, n - i)); } } out.close(); assertTrue(conn.getResponseCode() > 0); assertEquals(uploadKind == UploadKind.CHUNKED ? -1 : n, total.get()); }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: private static String fetchImageViaHttp(URL imgUrl) throws IOException { String sURL = imgUrl.toString(); String imgFile = imgUrl.getPath(); HttpURLConnection cnx = (HttpURLConnection) imgUrl.openConnection(); String uri = null; try { cnx.setAllowUserInteraction(false); cnx.setDoOutput(true); cnx.addRequestProperty("Cache-Control", "no-cache"); RequestContext ctx = RequestContext.get(); if (ctx != null) cnx.addRequestProperty("User-Agent", ctx.header("user-agent")); else cnx.addRequestProperty("User-Agent", user_agent); cnx.addRequestProperty("Referer", sURL.substring(0, sURL.indexOf('/', sURL.indexOf('.')) + 1)); cnx.connect(); if (cnx.getResponseCode() != HttpURLConnection.HTTP_OK) return null; InputStream imgData = cnx.getInputStream(); String ext = FilenameUtils.getExtension(imgFile).toLowerCase(); if (!Multimedia.isImageFile("aa." + ext)) ext = "jpg"; uri = FMT_FN.format(new Date()) + RandomStringUtils.randomAlphanumeric(4) + '.' + ext; File fileDest = new File(img_path + uri); if (!fileDest.getParentFile().exists()) fileDest.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(fileDest); try { IOUtils.copy(imgData, fos); } finally { IOUtils.closeQuietly(imgData); IOUtils.closeQuietly(fos); } } finally { cnx.disconnect(); } return RequestContext.get().contextPath() + "/uploads/img/" + uri; }
00
Code Sample 1: private void doDissemTest(String what, boolean redirectOK) throws Exception { final int num = 30; System.out.println("Getting " + what + " " + num + " times..."); int i = 0; try { URL url = new URL(BASE_URL + "/get/" + what); for (i = 0; i < num; i++) { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream in = conn.getInputStream(); in.read(); in.close(); conn.disconnect(); } } catch (Exception e) { fail("Dissemination of " + what + " failed on iter " + i + ": " + e.getMessage()); } } Code Sample 2: public List<String> extractUrlList(String url) throws IOException, XPathExpressionException { LinkedList<String> list = new LinkedList<String>(); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); Tidy tidy = new Tidy(); tidy.setErrout(new NullPrintWriter()); Document doc = tidy.parseDOM(conn.getInputStream(), null); int len = conn.getContentLength(); if (len <= 0) len = 32000; ByteArrayOutputStream bout = new ByteArrayOutputStream(len); PrintStream ps = new PrintStream(bout); tidy.pprint(doc, ps); ps.flush(); String content = bout.toString(); Pattern p = Pattern.compile("(http://[\\w\\\\\\./=&?;-]+)"); Matcher m = p.matcher(content); while (m.find()) { list.add(m.group()); } return list; }
11
Code Sample 1: @Override public void execute() throws BuildException { final String GC_USERNAME = "google-code-username"; final String GC_PASSWORD = "google-code-password"; if (StringUtils.isBlank(this.projectName)) throw new BuildException("undefined project"); if (this.file == null) throw new BuildException("undefined file"); if (!this.file.exists()) throw new BuildException("file not found :" + file); if (!this.file.isFile()) throw new BuildException("not a file :" + file); if (this.config == null) throw new BuildException("undefined config"); if (!this.config.exists()) throw new BuildException("file not found :" + config); if (!this.config.isFile()) throw new BuildException("not a file :" + config); PostMethod post = null; try { Properties cfg = new Properties(); FileInputStream fin = new FileInputStream(this.config); cfg.loadFromXML(fin); fin.close(); if (!cfg.containsKey(GC_USERNAME)) throw new BuildException("undefined " + GC_USERNAME + " in " + this.config); if (!cfg.containsKey(GC_PASSWORD)) throw new BuildException("undefined " + GC_PASSWORD + " in " + this.config); HttpClient client = new HttpClient(); post = new PostMethod("https://" + projectName + ".googlecode.com/files"); post.addRequestHeader("User-Agent", getClass().getName()); post.addRequestHeader("Authorization", "Basic " + Base64.encode(cfg.getProperty(GC_USERNAME) + ":" + cfg.getProperty(GC_PASSWORD))); List<Part> parts = new ArrayList<Part>(); String s = this.summary; if (StringUtils.isBlank(s)) { s = this.file.getName() + " (" + TimeUtils.toYYYYMMDD() + ")"; } parts.add(new StringPart("summary", s)); for (String lbl : this.labels.split("[, \t\n]+")) { if (StringUtils.isBlank(lbl)) continue; parts.add(new StringPart("label", lbl.trim())); } parts.add(new FilePart("filename", this.file)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()); post.setRequestEntity(requestEntity); int status = client.executeMethod(post); if (status != 201) { throw new BuildException("http status !=201 : " + post.getResponseBodyAsString()); } else { IOUtils.copyTo(post.getResponseBodyAsStream(), new NullOutputStream()); } } catch (BuildException e) { throw e; } catch (Exception e) { throw new BuildException(e); } finally { if (post != null) post.releaseConnection(); } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private String getLatestVersion(URL url) throws IOException { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(new BufferedInputStream(con.getInputStream()))); String lines = ""; String line = null; while ((line = br.readLine()) != null) { lines += line; } con.disconnect(); return lines; } Code Sample 2: public int[] bubbleSort(int[] data) { for (int i = 0; i < data.length; i++) { for (int j = 0; j < data.length - i - 1; j++) { if (data[j] > data[j + 1]) { int temp = data[j]; data[j] = data[j + 1]; data[j + 1] = temp; } } } return data; }
00
Code Sample 1: public void process() throws Exception { String searchXML = FileUtils.readFileToString(new File(getSearchRequestRelativeFilePath())); Map<String, String> parametersMap = new HashMap<String, String>(); parametersMap.put("searchXML", searchXML); String proxyHost = null; int proxyPort = -1; String serverUserName = null; String serverUserPassword = null; FileOutputStream fos = null; if (getUseProxy()) { serverUserName = getServerUserName(); serverUserPassword = getServerUserPassword(); } if (getUseProxy()) { proxyHost = getProxyHost(); proxyPort = getProxyPort(); } try { InputStream responseInputStream = URLUtils.getHttpResponse(getSearchBaseURL(), serverUserName, serverUserPassword, URLUtils.HTTP_POST_METHOD, proxyHost, proxyPort, parametersMap, -1); fos = new FileOutputStream(getSearchResponseRelativeFilePath()); IOUtils.copyLarge(responseInputStream, fos); } finally { if (null != fos) { fos.flush(); fos.close(); } } } Code Sample 2: private void initSerializerFiles(String fileName, HashSet<String> fileList, HashMap<Class, Class> classMap, Class type) { try { ClassLoader classLoader = getClassLoader(); if (classLoader == null) return; Enumeration iter; iter = classLoader.getResources(fileName); while (iter.hasMoreElements()) { URL url = (URL) iter.nextElement(); if (fileList.contains(url.toString())) continue; fileList.add(url.toString()); InputStream is = null; try { is = url.openStream(); Properties props = new Properties(); props.load(is); for (Map.Entry entry : props.entrySet()) { String apiName = (String) entry.getKey(); String serializerName = (String) entry.getValue(); Class apiClass = null; Class serializerClass = null; try { apiClass = Class.forName(apiName, false, classLoader); } catch (ClassNotFoundException e) { log.fine(url + ": " + apiName + " is not available in this context: " + getClassLoader()); continue; } try { serializerClass = Class.forName(serializerName, false, classLoader); } catch (ClassNotFoundException e) { log.fine(url + ": " + serializerName + " is not available in this context: " + getClassLoader()); continue; } if (!type.isAssignableFrom(serializerClass)) throw new HessianException(url + ": " + serializerClass.getName() + " is invalid because it does not implement " + type.getName()); classMap.put(apiClass, serializerClass); } } finally { if (is != null) is.close(); } } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new HessianException(e); } }
00
Code Sample 1: @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (log.isTraceEnabled()) { log.trace("doGet(requestURI=" + request.getRequestURI() + ")"); } ServletConfig sc = getServletConfig(); String uriPrefix = request.getContextPath() + "/" + request.getServletPath(); String resUri = request.getRequestURI().substring(uriPrefix.length()); if (log.isTraceEnabled()) { log.trace("Request for resource '" + resUri + "'"); } boolean allowAccess = true; String prefixesSpec = sc.getInitParameter(PARAM_ALLOWED_PREFIXES); if (null != prefixesSpec && prefixesSpec.length() > 0) { String[] prefixes = prefixesSpec.split(";"); allowAccess = false; if (log.isTraceEnabled()) { log.trace("allowedPrefixes specified; checking access"); } for (String prefix : prefixes) { if (log.isTraceEnabled()) { log.trace("Checking resource URI '" + resUri + "' against allowed prefix '" + prefix + "'"); } if (resUri.startsWith(prefix)) { if (log.isTraceEnabled()) { log.trace("Found matching prefix for resource URI '" + resUri + "': '" + prefix + "'"); } allowAccess = true; break; } } } if (!allowAccess) { if (log.isWarnEnabled()) { log.warn("Requested for resource that does not match with" + " allowed prefixes: " + resUri); } response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String resPrefix = sc.getInitParameter(PARAM_RESOURCE_PREFIX); if (null != resPrefix && resPrefix.length() > 0) { if (log.isTraceEnabled()) { log.trace("resourcePrefix specified: " + resPrefix); } if (resPrefix.endsWith("/")) { resUri = resPrefix + resUri; } else { resUri = resPrefix + "/" + resUri; } } resUri = resUri.replaceAll("\\/\\/+", "/"); if (log.isTraceEnabled()) { log.trace("Qualified (prefixed) resource URI: " + resUri); } String baseClassName = sc.getInitParameter(PARAM_BASE_CLASS); if (null == baseClassName || 0 == baseClassName.length()) { if (log.isTraceEnabled()) { log.trace("No baseClass initialization parameter specified; using default: " + ResourceLoaderServlet.class.getName()); } baseClassName = ResourceLoaderServlet.class.getName(); } else { if (log.isTraceEnabled()) { log.trace("Using baseClass: " + baseClassName); } } Class baseClass; try { baseClass = Class.forName(baseClassName); } catch (ClassNotFoundException ex) { throw new ServletException("Base class '" + baseClassName + "' not found", ex); } URL resUrl = baseClass.getResource(resUri); if (null != resUrl) { if (log.isTraceEnabled()) { log.trace("Sending resource: " + resUrl); } URLConnection urlc = resUrl.openConnection(); response.setContentType(urlc.getContentType()); response.setContentLength(urlc.getContentLength()); response.setStatus(HttpServletResponse.SC_OK); final byte[] buf = new byte[255]; int r = 0; InputStream in = new BufferedInputStream(urlc.getInputStream()); OutputStream out = new BufferedOutputStream(response.getOutputStream()); do { r = in.read(buf, 0, 255); if (r > 0) { out.write(buf, 0, r); } } while (r > 0); in.close(); out.flush(); out.close(); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource not found"); } } Code Sample 2: 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) { } } } }
00
Code Sample 1: private void sort() { for (int i = 0; i < density.length; i++) { for (int j = density.length - 2; j >= i; j--) { if (density[j] > density[j + 1]) { KDNode n = nonEmptyNodesArray[j]; nonEmptyNodesArray[j] = nonEmptyNodesArray[j + 1]; nonEmptyNodesArray[j + 1] = n; double d = density[j]; density[j] = density[j + 1]; density[j + 1] = d; } } } } Code Sample 2: public static JSONObject update(String name, String uid, double lat, double lon, boolean online) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpPost post = new HttpPost(UPDATE_URI); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("name", name)); parameters.add(new BasicNameValuePair("uid", uid)); parameters.add(new BasicNameValuePair("latitude", Double.toString(lat))); parameters.add(new BasicNameValuePair("longitude", Double.toString(lon))); parameters.add(new BasicNameValuePair("online", Boolean.toString(online))); post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8)); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); return new JSONObject(res); } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void 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(); }
11
Code Sample 1: public boolean verifySignature() { try { byte[] data = readFile(name + ".tmp1.bin"); if (data == null) return false; if (data[data.length - 0x104] != 'N' || data[data.length - 0x103] != 'G' || data[data.length - 0x102] != 'I' || data[data.length - 0x101] != 'S') return false; byte[] signature = new byte[0x100]; byte[] module = new byte[data.length - 0x104]; System.arraycopy(data, data.length - 0x100, signature, 0, 0x100); System.arraycopy(data, 0, module, 0, data.length - 0x104); BigIntegerEx power = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { 0x01, 0x00, 0x01, 0x00 }); BigIntegerEx mod = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { (byte) 0x6B, (byte) 0xCE, (byte) 0xF5, (byte) 0x2D, (byte) 0x2A, (byte) 0x7D, (byte) 0x7A, (byte) 0x67, (byte) 0x21, (byte) 0x21, (byte) 0x84, (byte) 0xC9, (byte) 0xBC, (byte) 0x25, (byte) 0xC7, (byte) 0xBC, (byte) 0xDF, (byte) 0x3D, (byte) 0x8F, (byte) 0xD9, (byte) 0x47, (byte) 0xBC, (byte) 0x45, (byte) 0x48, (byte) 0x8B, (byte) 0x22, (byte) 0x85, (byte) 0x3B, (byte) 0xC5, (byte) 0xC1, (byte) 0xF4, (byte) 0xF5, (byte) 0x3C, (byte) 0x0C, (byte) 0x49, (byte) 0xBB, (byte) 0x56, (byte) 0xE0, (byte) 0x3D, (byte) 0xBC, (byte) 0xA2, (byte) 0xD2, (byte) 0x35, (byte) 0xC1, (byte) 0xF0, (byte) 0x74, (byte) 0x2E, (byte) 0x15, (byte) 0x5A, (byte) 0x06, (byte) 0x8A, (byte) 0x68, (byte) 0x01, (byte) 0x9E, (byte) 0x60, (byte) 0x17, (byte) 0x70, (byte) 0x8B, (byte) 0xBD, (byte) 0xF8, (byte) 0xD5, (byte) 0xF9, (byte) 0x3A, (byte) 0xD3, (byte) 0x25, (byte) 0xB2, (byte) 0x66, (byte) 0x92, (byte) 0xBA, (byte) 0x43, (byte) 0x8A, (byte) 0x81, (byte) 0x52, (byte) 0x0F, (byte) 0x64, (byte) 0x98, (byte) 0xFF, (byte) 0x60, (byte) 0x37, (byte) 0xAF, (byte) 0xB4, (byte) 0x11, (byte) 0x8C, (byte) 0xF9, (byte) 0x2E, (byte) 0xC5, (byte) 0xEE, (byte) 0xCA, (byte) 0xB4, (byte) 0x41, (byte) 0x60, (byte) 0x3C, (byte) 0x7D, (byte) 0x02, (byte) 0xAF, (byte) 0xA1, (byte) 0x2B, (byte) 0x9B, (byte) 0x22, (byte) 0x4B, (byte) 0x3B, (byte) 0xFC, (byte) 0xD2, (byte) 0x5D, (byte) 0x73, (byte) 0xE9, (byte) 0x29, (byte) 0x34, (byte) 0x91, (byte) 0x85, (byte) 0x93, (byte) 0x4C, (byte) 0xBE, (byte) 0xBE, (byte) 0x73, (byte) 0xA9, (byte) 0xD2, (byte) 0x3B, (byte) 0x27, (byte) 0x7A, (byte) 0x47, (byte) 0x76, (byte) 0xEC, (byte) 0xB0, (byte) 0x28, (byte) 0xC9, (byte) 0xC1, (byte) 0xDA, (byte) 0xEE, (byte) 0xAA, (byte) 0xB3, (byte) 0x96, (byte) 0x9C, (byte) 0x1E, (byte) 0xF5, (byte) 0x6B, (byte) 0xF6, (byte) 0x64, (byte) 0xD8, (byte) 0x94, (byte) 0x2E, (byte) 0xF1, (byte) 0xF7, (byte) 0x14, (byte) 0x5F, (byte) 0xA0, (byte) 0xF1, (byte) 0xA3, (byte) 0xB9, (byte) 0xB1, (byte) 0xAA, (byte) 0x58, (byte) 0x97, (byte) 0xDC, (byte) 0x09, (byte) 0x17, (byte) 0x0C, (byte) 0x04, (byte) 0xD3, (byte) 0x8E, (byte) 0x02, (byte) 0x2C, (byte) 0x83, (byte) 0x8A, (byte) 0xD6, (byte) 0xAF, (byte) 0x7C, (byte) 0xFE, (byte) 0x83, (byte) 0x33, (byte) 0xC6, (byte) 0xA8, (byte) 0xC3, (byte) 0x84, (byte) 0xEF, (byte) 0x29, (byte) 0x06, (byte) 0xA9, (byte) 0xB7, (byte) 0x2D, (byte) 0x06, (byte) 0x0B, (byte) 0x0D, (byte) 0x6F, (byte) 0x70, (byte) 0x9E, (byte) 0x34, (byte) 0xA6, (byte) 0xC7, (byte) 0x31, (byte) 0xBE, (byte) 0x56, (byte) 0xDE, (byte) 0xDD, (byte) 0x02, (byte) 0x92, (byte) 0xF8, (byte) 0xA0, (byte) 0x58, (byte) 0x0B, (byte) 0xFC, (byte) 0xFA, (byte) 0xBA, (byte) 0x49, (byte) 0xB4, (byte) 0x48, (byte) 0xDB, (byte) 0xEC, (byte) 0x25, (byte) 0xF3, (byte) 0x18, (byte) 0x8F, (byte) 0x2D, (byte) 0xB3, (byte) 0xC0, (byte) 0xB8, (byte) 0xDD, (byte) 0xBC, (byte) 0xD6, (byte) 0xAA, (byte) 0xA6, (byte) 0xDB, (byte) 0x6F, (byte) 0x7D, (byte) 0x7D, (byte) 0x25, (byte) 0xA6, (byte) 0xCD, (byte) 0x39, (byte) 0x6D, (byte) 0xDA, (byte) 0x76, (byte) 0x0C, (byte) 0x79, (byte) 0xBF, (byte) 0x48, (byte) 0x25, (byte) 0xFC, (byte) 0x2D, (byte) 0xC5, (byte) 0xFA, (byte) 0x53, (byte) 0x9B, (byte) 0x4D, (byte) 0x60, (byte) 0xF4, (byte) 0xEF, (byte) 0xC7, (byte) 0xEA, (byte) 0xAC, (byte) 0xA1, (byte) 0x7B, (byte) 0x03, (byte) 0xF4, (byte) 0xAF, (byte) 0xC7 }); byte[] result = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, signature).modPow(power, mod).toByteArray(); byte[] digest; byte[] properResult = new byte[0x100]; for (int i = 0; i < properResult.length; i++) properResult[i] = (byte) 0xBB; MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(module); md.update("MAIEV.MOD".getBytes()); digest = md.digest(); System.arraycopy(digest, 0, properResult, 0, digest.length); for (int i = 0; i < result.length; i++) if (result[i] != properResult[i]) return false; return true; } catch (Exception e) { System.out.println("Failed to verify signature: " + e.toString()); } return false; } Code Sample 2: static String hash(String text) { try { StringBuffer plugins = new StringBuffer(); for (PlayPlugin plugin : Play.plugins) { plugins.append(plugin.getClass().getName()); } MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update((Play.version + plugins.toString() + text).getBytes("utf-8")); byte[] digest = messageDigest.digest(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < digest.length; ++i) { int value = digest[i]; if (value < 0) { value += 256; } builder.append(Integer.toHexString(value)); } return builder.toString(); } catch (Exception 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: @Test public void testCopy() throws IOException { final byte[] input = { 0x00, 0x01, 0x7F, 0x03, 0x40 }; final byte[] verification = input.clone(); Assert.assertNotSame("Expecting verification to be a new array.", input, verification); final ByteArrayInputStream in = new ByteArrayInputStream(input); final ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); final byte[] output = out.toByteArray(); Assert.assertTrue("Expecting input to be unchanged.", Arrays.equals(verification, input)); Assert.assertTrue("Expecting output to be like input.", Arrays.equals(verification, output)); Assert.assertNotSame("Expecting output to be a new array.", input, output); Assert.assertNotSame("Expecting output to be a new array.", verification, output); }
00
Code Sample 1: public void read() throws LogicException { try { File file = new File(filename); URL url = file.toURI().toURL(); source = new Source(url.openConnection()); } catch (Exception e) { throw new LogicException("Failed to read " + filename + " !", e); } ArrayList<Segment> segments = new ArrayList<Segment>(); List<Element> elements = source.getChildElements(); for (Element element : elements) { Segment segment = element.getContent(); Iterator<Segment> iterator = segment.getNodeIterator(); while (iterator.hasNext()) { Segment current = iterator.next(); if (isPlainText(current)) { segments.add(current); } } } texts.clear(); sentences.clear(); for (int i = 0; i < segments.size(); i++) { ArrayList<Segment> group = new ArrayList<Segment>(); group.add(segments.get(i)); while (i < (segments.size() - 1) && segments.get(i).getEnd() == segments.get(i + 1).getBegin()) { group.add(segments.get(i + 1)); i++; } texts.add(new Text(group, tokenizer)); } ArrayList<Token> tokens = new ArrayList<Token>(); for (Text text : texts) { tokens.addAll(text.getTokens()); } sentences = tokenizer.toSentences(tokens); } Code Sample 2: public static void loadMemcachedConfigFromURL(URL url, XMLInputFactory factory, List<MemcachedClientConfig> memcachedClientconfigs, List<MemcachedClientSocketPoolConfig> memcachedClientSocketPoolConfigs, List<MemcachedClientClusterConfig> memcachedClientClusterConfig) { MemcachedClientConfig node = null; MemcachedClientSocketPoolConfig socketnode = null; MemcachedClientClusterConfig clusternode = null; InputStream in = null; XMLEventReader r = null; try { in = url.openStream(); r = factory.createXMLEventReader(in); String servers = null; String weights = null; while (r.hasNext()) { XMLEvent event = r.nextEvent(); if (event.isStartElement()) { StartElement start = event.asStartElement(); String tag = start.getName().getLocalPart(); if (tag.equalsIgnoreCase("client")) { node = new MemcachedClientConfig(); if (start.getAttributeByName(new QName("", "name")) != null) node.setName(start.getAttributeByName(new QName("", "name")).getValue()); else throw new RuntimeException("memcached client name can't not be null!"); if (start.getAttributeByName(new QName("", "socketpool")) != null) node.setSocketPool(start.getAttributeByName(new QName("", "socketpool")).getValue()); else throw new RuntimeException("memcached client socketpool can't not be null!"); if (start.getAttributeByName(new QName("", "compressEnable")) != null) node.setCompressEnable(Boolean.parseBoolean(start.getAttributeByName(new QName("", "compressEnable")).getValue())); else node.setCompressEnable(true); if (start.getAttributeByName(new QName("", "defaultEncoding")) != null) node.setDefaultEncoding(start.getAttributeByName(new QName("", "defaultEncoding")).getValue()); else node.setDefaultEncoding("UTF-8"); continue; } if (tag.equalsIgnoreCase("errorHandler") && node != null) { event = r.peek(); if (event.isCharacters()) { node.setErrorHandler(event.asCharacters().getData()); r.nextEvent(); } continue; } if (tag.equalsIgnoreCase("socketpool")) { socketnode = new MemcachedClientSocketPoolConfig(); servers = null; weights = null; if (start.getAttributeByName(new QName("", "name")) != null) socketnode.setName(start.getAttributeByName(new QName("", "name")).getValue()); else throw new RuntimeException("memcached client socketpool name can't not be null!"); if (start.getAttributeByName(new QName("", "failover")) != null) socketnode.setFailover(Boolean.parseBoolean(start.getAttributeByName(new QName("", "failover")).getValue())); if (start.getAttributeByName(new QName("", "initConn")) != null) socketnode.setInitConn(Integer.parseInt(start.getAttributeByName(new QName("", "initConn")).getValue())); if (start.getAttributeByName(new QName("", "minConn")) != null) socketnode.setMinConn(Integer.parseInt(start.getAttributeByName(new QName("", "minConn")).getValue())); if (start.getAttributeByName(new QName("", "maxConn")) != null) socketnode.setMaxConn(Integer.parseInt(start.getAttributeByName(new QName("", "maxConn")).getValue())); if (start.getAttributeByName(new QName("", "maintSleep")) != null) socketnode.setMaintSleep(Integer.parseInt(start.getAttributeByName(new QName("", "maintSleep")).getValue())); if (start.getAttributeByName(new QName("", "nagle")) != null) socketnode.setNagle(Boolean.parseBoolean(start.getAttributeByName(new QName("", "nagle")).getValue())); if (start.getAttributeByName(new QName("", "socketTO")) != null) socketnode.setSocketTo(Integer.parseInt(start.getAttributeByName(new QName("", "socketTO")).getValue())); if (start.getAttributeByName(new QName("", "maxIdle")) != null) socketnode.setMaxIdle(Integer.parseInt(start.getAttributeByName(new QName("", "maxIdle")).getValue())); if (start.getAttributeByName(new QName("", "aliveCheck")) != null) socketnode.setAliveCheck(Boolean.parseBoolean(start.getAttributeByName(new QName("", "aliveCheck")).getValue())); continue; } if (tag.equalsIgnoreCase("servers") && socketnode != null) { event = r.peek(); if (event.isCharacters()) { servers = event.asCharacters().getData(); socketnode.setServers(servers); r.nextEvent(); } continue; } if (tag.equalsIgnoreCase("weights") && socketnode != null) { event = r.peek(); if (event.isCharacters()) { weights = event.asCharacters().getData(); socketnode.setWeights(weights); r.nextEvent(); } continue; } if (tag.equalsIgnoreCase("cluster")) { clusternode = new MemcachedClientClusterConfig(); if (start.getAttributeByName(new QName("", "name")) != null) clusternode.setName(start.getAttributeByName(new QName("", "name")).getValue()); else throw new RuntimeException("memcached cluster name can't not be null!"); if (start.getAttributeByName(new QName("", "mode")) != null) clusternode.setMode(start.getAttributeByName(new QName("", "mode")).getValue()); continue; } if (tag.equalsIgnoreCase("memCachedClients") && clusternode != null) { event = r.peek(); if (event.isCharacters()) { String clients = event.asCharacters().getData(); if (clients != null && !clients.equals("")) { clusternode.setMemCachedClients(clients.split(",")); } r.nextEvent(); } continue; } } if (event.isEndElement()) { EndElement end = event.asEndElement(); if (node != null && end.getName().getLocalPart().equalsIgnoreCase("client")) { memcachedClientconfigs.add(node); Logger.info(new StringBuilder().append(" add memcachedClient config :").append(node.getName())); continue; } if (socketnode != null && end.getName().getLocalPart().equalsIgnoreCase("socketpool")) { memcachedClientSocketPoolConfigs.add(socketnode); Logger.info(new StringBuilder().append(" add socketpool config :").append(socketnode.getName())); continue; } if (clusternode != null && end.getName().getLocalPart().equalsIgnoreCase("cluster")) { memcachedClientClusterConfig.add(clusternode); Logger.info(new StringBuilder().append(" add cluster config :").append(clusternode.getName())); continue; } } } } catch (Exception e) { Logger.error(new StringBuilder("MemcachedManager loadConfig error !").append(" config url :").append(url.getFile()).toString()); node = null; } finally { try { if (r != null) r.close(); if (in != null) in.close(); r = null; in = null; } catch (Exception ex) { throw new RuntimeException("processConfigURL error !", ex); } } }
11
Code Sample 1: private boolean saveLOBDataToFileSystem() { if ("".equals(m_attachmentPathRoot)) { log.severe("no attachmentPath defined"); return false; } if (m_items == null || m_items.size() == 0) { setBinaryData(null); return true; } final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.newDocument(); final Element root = document.createElement("attachments"); document.appendChild(root); document.setXmlStandalone(true); for (int i = 0; i < m_items.size(); i++) { log.fine(m_items.get(i).toString()); File entryFile = m_items.get(i).getFile(); final String path = entryFile.getAbsolutePath(); log.fine(path + " - " + m_attachmentPathRoot); if (!path.startsWith(m_attachmentPathRoot)) { log.fine("move file: " + path); FileChannel in = null; FileChannel out = null; try { final File destFolder = new File(m_attachmentPathRoot + File.separator + getAttachmentPathSnippet()); if (!destFolder.exists()) { if (!destFolder.mkdirs()) { log.warning("unable to create folder: " + destFolder.getPath()); } } final File destFile = new File(m_attachmentPathRoot + File.separator + getAttachmentPathSnippet() + File.separator + entryFile.getName()); in = new FileInputStream(entryFile).getChannel(); out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); if (entryFile.exists()) { if (!entryFile.delete()) { entryFile.deleteOnExit(); } } entryFile = destFile; } catch (IOException e) { e.printStackTrace(); log.severe("unable to copy file " + entryFile.getAbsolutePath() + " to " + m_attachmentPathRoot + File.separator + getAttachmentPathSnippet() + File.separator + entryFile.getName()); } finally { if (in != null && in.isOpen()) { in.close(); } if (out != null && out.isOpen()) { out.close(); } } } final Element entry = document.createElement("entry"); entry.setAttribute("name", getEntryName(i)); String filePathToStore = entryFile.getAbsolutePath(); filePathToStore = filePathToStore.replaceFirst(m_attachmentPathRoot.replaceAll("\\\\", "\\\\\\\\"), ATTACHMENT_FOLDER_PLACEHOLDER); log.fine(filePathToStore); entry.setAttribute("file", filePathToStore); root.appendChild(entry); } final Source source = new DOMSource(document); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final Result result = new StreamResult(bos); final Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(source, result); final byte[] xmlData = bos.toByteArray(); log.fine(bos.toString()); setBinaryData(xmlData); return true; } catch (Exception e) { log.log(Level.SEVERE, "saveLOBData", e); } setBinaryData(null); return false; } Code Sample 2: public void invoke() throws IOException { String[] command = new String[files.length + options.length + 2]; command[0] = chmod; System.arraycopy(options, 0, command, 1, options.length); command[1 + options.length] = perms; for (int i = 0; i < files.length; i++) { File file = files[i]; command[2 + options.length + i] = file.getAbsolutePath(); } Process p = Runtime.getRuntime().exec(command); try { p.waitFor(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (p.exitValue() != 0) { StringWriter writer = new StringWriter(); IOUtils.copy(p.getErrorStream(), writer); throw new IOException("Unable to chmod files: " + writer.toString()); } }
11
Code Sample 1: public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException { if (format != null && "gif".equals(format.toLowerCase())) { resize(originalFile, resizedFile, width, 1); return; } FileInputStream fis = new FileInputStream(originalFile); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int readLength = -1; int bufferSize = 1024; byte bytes[] = new byte[bufferSize]; while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) { byteStream.write(bytes, 0, readLength); } byte[] in = byteStream.toByteArray(); fis.close(); byteStream.close(); Image inputImage = Toolkit.getDefaultToolkit().createImage(in); waitForImage(inputImage); int imageWidth = inputImage.getWidth(null); if (imageWidth < 1) throw new IllegalArgumentException("image width " + imageWidth + " is out of range"); int imageHeight = inputImage.getHeight(null); if (imageHeight < 1) throw new IllegalArgumentException("image height " + imageHeight + " is out of range"); int height = -1; double scaleW = (double) imageWidth / (double) width; double scaleY = (double) imageHeight / (double) height; if (scaleW >= 0 && scaleY >= 0) { if (scaleW > scaleY) { height = -1; } else { width = -1; } } Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT); checkImage(outputImage); encode(new FileOutputStream(resizedFile), outputImage, format); } Code Sample 2: public void copy(File from, String to) throws SystemException { assert from != null; File dst = new File(folder, to); dst.getParentFile().mkdirs(); FileChannel in = null; FileChannel out = null; try { if (!dst.exists()) dst.createNewFile(); in = new FileInputStream(from).getChannel(); out = new FileOutputStream(dst).getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { throw new SystemException(e); } finally { try { if (in != null) in.close(); } catch (Exception e1) { } try { if (out != null) out.close(); } catch (Exception e1) { } } }
11
Code Sample 1: public static JSONObject doJSONQuery(String urlstr) throws IOException, MalformedURLException, JSONException, SolrException { URL url = new URL(urlstr); HttpURLConnection con = null; try { con = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuffer buffer = new StringBuffer(); String str; while ((str = in.readLine()) != null) { buffer.append(str + "\n"); } in.close(); JSONObject response = new JSONObject(buffer.toString()); return response; } catch (IOException e) { if (con != null) { try { int statusCode = con.getResponseCode(); if (statusCode >= 400) { throw (new SolrSelectUtils()).new SolrException(statusCode); } } catch (IOException exc) { } } throw (e); } } Code Sample 2: public static String createRecoveryContent(String password) { try { password = encryptGeneral1(password); String data = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); URL url = new URL("https://mypasswords-server.appspot.com/recovery_file"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder finalResult = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { finalResult.append(line); } wr.close(); rd.close(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new InputSource(new StringReader(finalResult.toString()))); document.normalizeDocument(); Element root = document.getDocumentElement(); String textContent = root.getTextContent(); return textContent; } catch (Exception e) { System.out.println(e.getMessage()); } return null; }
00
Code Sample 1: public String performRequest(TreeMap<String, String> params, boolean isAuthenticated) { params.put("format", "json"); try { URL url = new URL(getApiUrl(params, isAuthenticated)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); Reader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = ""; while (reader.ready()) { response += (char) reader.read(); } response = response.replaceFirst("jsonVimeoApi\\(", ""); response = response.substring(0, response.length() - 2); return response; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: protected Icon newIcon(String iconName) { URL url = Utils.getResource(getFullPath(iconName, "/"), getClass()); if (url == null) { if (getParent() != null) return getParent().getIcon(iconName); return null; } try { MethodCall getImage = new MethodCaller("org.apache.sanselan.Sanselan", null, "getBufferedImage", new Object[] { InputStream.class }).getMethodCall(); getImage.setArgumentValue(0, url.openStream()); return new ImageIcon((BufferedImage) getImage.call()); } catch (Throwable e) { return new ImageIcon(url); } } Code Sample 2: @Deprecated public boolean backupLuceneIndex(int indexLocation, int backupLocation) { boolean result = false; try { System.out.println("lucene backup started"); String indexPath = this.getIndexFolderPath(indexLocation); String backupPath = this.getIndexFolderPath(backupLocation); File inDir = new File(indexPath); boolean flag = true; if (inDir.exists() && inDir.isDirectory()) { File filesList[] = inDir.listFiles(); if (filesList != null) { File parDirBackup = new File(backupPath); if (!parDirBackup.exists()) parDirBackup.mkdir(); String date = this.getDate(); backupPath += "/" + date; File dirBackup = new File(backupPath); if (!dirBackup.exists()) dirBackup.mkdir(); else { File files[] = dirBackup.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i] != null) { files[i].delete(); } } } dirBackup.delete(); dirBackup.mkdir(); } for (int i = 0; i < filesList.length; i++) { if (filesList[i].isFile()) { try { File destFile = new File(backupPath + "/" + filesList[i].getName()); if (!destFile.exists()) destFile.createNewFile(); FileInputStream in = new FileInputStream(filesList[i]); FileOutputStream out = new FileOutputStream(destFile); FileChannel fcIn = in.getChannel(); FileChannel fcOut = out.getChannel(); fcIn.transferTo(0, fcIn.size(), fcOut); } catch (FileNotFoundException ex) { System.out.println("FileNotFoundException ---->" + ex); flag = false; } catch (IOException excIO) { System.out.println("IOException ---->" + excIO); flag = false; } } } } } System.out.println("lucene backup finished"); System.out.println("flag ========= " + flag); if (flag) { result = true; } } catch (Exception e) { System.out.println("Exception in backupLuceneIndex Method : " + e); e.printStackTrace(); } return result; }
11
Code Sample 1: private String fetchCompareContent() throws IOException { URL url = new URL(compareTo); StringWriter sw = new StringWriter(); IOUtils.copy(url.openStream(), sw); return sw.getBuffer().toString(); } Code Sample 2: public void jsFunction_addFile(ScriptableFile infile) throws IOException { if (!infile.jsFunction_exists()) throw new IllegalArgumentException("Cannot add a file that doesn't exists to an archive"); ZipArchiveEntry entry = new ZipArchiveEntry(infile.getName()); entry.setSize(infile.jsFunction_getSize()); out.putArchiveEntry(entry); try { InputStream inStream = infile.jsFunction_createInputStream(); IOUtils.copy(inStream, out); inStream.close(); } finally { out.closeArchiveEntry(); } }
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 static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { if (System.getProperty("os.name").toUpperCase().indexOf("WIN") != -1) { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } else { inChannel.transferTo(0, inChannel.size(), outChannel); } } finally { if (inChannel != null) try { inChannel.close(); } catch (Exception e) { } ; if (outChannel != null) try { outChannel.close(); } catch (Exception e) { } ; } }
00
Code Sample 1: public void testCommitRollback() throws Exception { Statement stmt = con.createStatement(); assertNotNull(stmt); assertTrue(con.getAutoCommit()); stmt.execute("CREATE TABLE #TESTCOMMIT (id int primary key)"); con.setAutoCommit(false); assertFalse(con.getAutoCommit()); assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (1)")); con.commit(); assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (2)")); assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (3)")); con.rollback(); assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (4)")); con.setAutoCommit(true); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM #TESTCOMMIT"); rs.next(); assertEquals("commit", 2, rs.getInt(1)); stmt.close(); } Code Sample 2: public static void copy(FileInputStream source, FileOutputStream target) throws IOException { FileChannel sourceChannel = source.getChannel(); FileChannel targetChannel = target.getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
11
Code Sample 1: public void format(File source, File target) { if (!source.exists()) { throw new IllegalArgumentException("Source '" + source + " doesn't exist"); } if (!source.isFile()) { throw new IllegalArgumentException("Source '" + source + " is not a file"); } target.mkdirs(); String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1); String _target = source.getName().replace(fileExtension, "html"); target = new File(target.getPath() + "/" + _target); try { Reader reader = new FileReader(source); Writer writer = new FileWriter(target); this.format(reader, writer); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void actionPerformed(ActionEvent ev) { if (fileChooser == null) { fileChooser = new JFileChooser(); ExtensionFileFilter fileFilter = new ExtensionFileFilter("Device profile (*.jar, *.zip)"); fileFilter.addExtension("jar"); fileFilter.addExtension("zip"); fileChooser.setFileFilter(fileFilter); } if (fileChooser.showOpenDialog(SwingSelectDevicePanel.this) == JFileChooser.APPROVE_OPTION) { String manifestDeviceName = null; URL[] urls = new URL[1]; ArrayList descriptorEntries = new ArrayList(); JarFile jar = null; try { jar = new JarFile(fileChooser.getSelectedFile()); 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); } } urls[0] = fileChooser.getSelectedFile().toURL(); } catch (IOException e) { Message.error("Error reading file: " + fileChooser.getSelectedFile().getName() + ", " + Message.getCauseMessage(e), e); return; } finally { if (jar != null) { try { jar.close(); } catch (IOException ignore) { } } } if (descriptorEntries.size() == 0) { Message.error("Cannot find any device profile in file: " + fileChooser.getSelectedFile().getName()); return; } if (descriptorEntries.size() > 1) { manifestDeviceName = null; } ClassLoader classLoader = Common.createExtensionsClassLoader(urls); HashMap devices = new HashMap(); for (Iterator it = descriptorEntries.iterator(); it.hasNext(); ) { String entryName = (String) it.next(); try { devices.put(entryName, DeviceImpl.create(emulatorContext, classLoader, entryName, J2SEDevice.class)); } catch (IOException e) { Message.error("Error parsing device profile, " + Message.getCauseMessage(e), e); return; } } for (Enumeration en = lsDevicesModel.elements(); en.hasMoreElements(); ) { DeviceEntry entry = (DeviceEntry) en.nextElement(); 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(), fileChooser.getSelectedFile().getName()); if (deviceFile.exists()) { deviceFile = File.createTempFile("device", ".jar", Config.getConfigPath()); } IOUtils.copyFile(fileChooser.getSelectedFile(), 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); } lsDevicesModel.addElement(entry); Config.addDeviceEntry(entry); } lsDevices.setSelectedValue(entry, true); } catch (IOException e) { Message.error("Error adding device profile, " + Message.getCauseMessage(e), e); return; } } }
11
Code Sample 1: public static void copy(File toCopy, File dest) throws IOException { FileInputStream src = new FileInputStream(toCopy); FileOutputStream out = new FileOutputStream(dest); try { while (src.available() > 0) { out.write(src.read()); } } finally { src.close(); out.close(); } } Code Sample 2: private static boolean copyFile(File src, File dest) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); for (int c = fis.read(); c != -1; c = fis.read()) fos.write(c); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (fis != null) try { fis.close(); } catch (IOException e) { e.printStackTrace(); } if (fos != null) try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
11
Code Sample 1: protected void copyFile(File src, File dest) throws Exception { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel(); long transferred = destChannel.transferFrom(srcChannel, 0, srcChannel.size()); if (transferred != srcChannel.size()) throw new Exception("Could not transfer entire file"); srcChannel.close(); destChannel.close(); } Code Sample 2: private static final void cloneFile(File origin, File target) throws IOException { FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(origin).getChannel(); destChannel = new FileOutputStream(target).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) srcChannel.close(); if (destChannel != null) destChannel.close(); } }
00
Code Sample 1: @Override public boolean exists() { if (local_file.exists()) { return true; } else { try { URLConnection c = remote_url.openConnection(); try { c.setConnectTimeout(CIO.getLoadingTimeOut()); c.connect(); return c.getContentLength() > 0; } catch (Exception err) { err.printStackTrace(); return false; } finally { if (c instanceof HttpURLConnection) { ((HttpURLConnection) c).disconnect(); } } } catch (IOException e) { e.printStackTrace(); return false; } } } Code Sample 2: public static String md5(String str) { if (str == null) { System.err.println("Stringx.md5 (String) : null string."); return ""; } String rt = ""; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes("gb2312")); byte[] bt = md5.digest(); String s = null; int l = 0; for (int i = 0; i < bt.length; i++) { s = Integer.toHexString(bt[i]); l = s.length(); if (l > 2) s = s.substring(l - 2, l); else if (l == 1) s = "0" + s; rt += s; } } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return rt; }
11
Code Sample 1: public static void makeLPKFile(String[] srcFilePath, String makeFilePath, LPKHeader header) { FileOutputStream os = null; DataOutputStream dos = null; try { LPKTable[] fileTable = new LPKTable[srcFilePath.length]; long fileOffset = outputOffset(header); for (int i = 0; i < srcFilePath.length; i++) { String sourceFileName = FileUtils.getFileName(srcFilePath[i]); long sourceFileSize = FileUtils.getFileSize(srcFilePath[i]); LPKTable ft = makeLPKTable(sourceFileName, sourceFileSize, fileOffset); fileOffset = outputNextOffset(sourceFileSize, fileOffset); fileTable[i] = ft; } File file = new File(makeFilePath); if (!file.exists()) { FileUtils.makedirs(file); } os = new FileOutputStream(file); dos = new DataOutputStream(os); dos.writeInt(header.getPAKIdentity()); writeByteArray(header.getPassword(), dos); dos.writeFloat(header.getVersion()); dos.writeLong(header.getTables()); for (int i = 0; i < fileTable.length; i++) { writeByteArray(fileTable[i].getFileName(), dos); dos.writeLong(fileTable[i].getFileSize()); dos.writeLong(fileTable[i].getOffSet()); } for (int i = 0; i < fileTable.length; i++) { File ftFile = new File(srcFilePath[i]); FileInputStream ftFis = new FileInputStream(ftFile); DataInputStream ftDis = new DataInputStream(ftFis); byte[] buff = new byte[256]; int readLength = 0; while ((readLength = ftDis.read(buff)) != -1) { makeBuffer(buff, readLength); dos.write(buff, 0, readLength); } ftDis.close(); ftFis.close(); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (dos != null) { try { dos.close(); dos = null; } catch (IOException e) { } } } } Code Sample 2: private void output(HttpServletResponse resp, InputStream is, long length, String fileName) throws Exception { resp.reset(); String mimeType = "image/jpeg"; resp.setContentType(mimeType); resp.setContentLength((int) length); resp.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\""); resp.setHeader("Cache-Control", "must-revalidate"); ServletOutputStream sout = resp.getOutputStream(); IOUtils.copy(is, sout); sout.flush(); resp.flushBuffer(); }
00
Code Sample 1: private void addPNMLFileToLibrary(File selected) { try { FileChannel srcChannel = new FileInputStream(selected.getAbsolutePath()).getChannel(); FileChannel dstChannel = new FileOutputStream(new File(matchingOrderXML).getParent() + "/" + selected.getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); order.add(new ComponentDescription(false, selected.getName().replaceAll(".pnml", ""), 1.0)); updateComponentList(); } catch (IOException ioe) { JOptionPane.showMessageDialog(dialog, "Could not add the PNML file " + selected.getName() + " to the library!"); } } Code Sample 2: public String parse() { try { URL url = new URL(mUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; boolean flag1 = false; while ((line = reader.readLine()) != null) { line = line.trim(); if (!flag1 && line.contains("</center>")) flag1 = true; if (flag1 && line.contains("<br><center>")) break; if (flag1) { mText.append(line); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return mText.toString(); }
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: protected void createDb() { File rootFolder = new File(dbFolderPath); if (!rootFolder.exists()) { rootFolder.mkdirs(); } openConnection(); try { Statement stat = connection.createStatement(); ResourceBundle bundle = ResourceBundle.getBundle("uTaggerDb"); for (String key : bundle.keySet()) { stat.executeUpdate(bundle.getString(key)); } commit(); } catch (SQLException e) { LOG.warn(e); rollback(); } }
00
Code Sample 1: protected void givenTestRepository(String repositoryId) throws Exception { HttpResponse response = executeDeleteWithResponse("/repositories/" + repositoryId); consume(response.getEntity()); response = executePost("/repositories", createRepositoryXml(repositoryId)); assertEquals(content(response), SC_CREATED, statusCode(response)); } Code Sample 2: public MapInfo getMap(double latitude, double longitude, double wanted_mapblast_scale, int image_width, int image_height, String file_path_wo_extension, ProgressListener progress_listener) throws IOException { try { if (web_request_ == null) { web_request_ = new HttpRequester(HOST_NAME); } int zoom_index = getZoomLevelIndex(wanted_mapblast_scale); int google_zoom_level = GOOGLE_ZOOM_LEVELS[zoom_index]; double mapblast_scale = POSSIBLE_GOOGLE_SCALES[zoom_index]; Tile tile = new Tile(latitude, longitude, google_zoom_level); SimplePoint coords = tile.getTileLatLong(); SimplePoint google_xy = tile.getTileCoord(); MapInfo map_info = new MapInfo(); map_info.setLatitude(coords.getX()); map_info.setLongitude(coords.getY()); map_info.setScale((float) mapblast_scale); map_info.setWidth(256); map_info.setHeight(256); map_info.setFilename(file_path_wo_extension + "png"); Object[] params = new Object[] { new Integer(google_xy.getX()), new Integer(google_xy.getY()), new Integer(google_zoom_level) }; MessageFormat message_format = new MessageFormat(GOOGLE_MAPS_URL, Locale.US); String url_string = message_format.format(params); URL url = new URL(url_string); if (Debug.DEBUG) Debug.println("map_download", "loading map from url: " + url); URLConnection connection = url.openConnection(); if (resources_.getBoolean(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_USE)) { String proxy_userid = resources_.getString(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_USERNAME); String proxy_password = resources_.getString(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_PASSWORD); String auth_string = proxy_userid + ":" + proxy_password; auth_string = "Basic " + new sun.misc.BASE64Encoder().encode(auth_string.getBytes()); connection.setRequestProperty("Proxy-Authorization", auth_string); } connection.connect(); String mime_type = connection.getContentType().toLowerCase(); if (!mime_type.startsWith("image")) { if (mime_type.startsWith("text")) { HTMLViewerFrame viewer = new HTMLViewerFrame(url); viewer.setSize(640, 480); viewer.setTitle("ERROR on loading url: " + url); viewer.setVisible(true); throw new IOException("Invalid mime type (expected 'image/*'): received " + mime_type + "\nPage is displayed in HTML frame."); } throw new IOException("Invalid mime type (expected 'image/*'): received " + mime_type); } int content_length = connection.getContentLength(); if (content_length < 0) progress_listener.actionStart(PROGRESS_LISTENER_ID, 0, Integer.MIN_VALUE); else progress_listener.actionStart(PROGRESS_LISTENER_ID, 0, content_length); String extension = mime_type.substring(mime_type.indexOf('/') + 1); String filename = file_path_wo_extension + extension; FileOutputStream out = new FileOutputStream(filename); byte[] buffer = new byte[BUFFER_SIZE]; BufferedInputStream in = new BufferedInputStream(connection.getInputStream(), BUFFER_SIZE); int sum_bytes = 0; int num_bytes = 0; while ((num_bytes = in.read(buffer)) != -1) { out.write(buffer, 0, num_bytes); sum_bytes += num_bytes; progress_listener.actionProgress(PROGRESS_LISTENER_ID, sum_bytes); } progress_listener.actionEnd(PROGRESS_LISTENER_ID); in.close(); out.close(); return (map_info); } catch (NoRouteToHostException nrhe) { nrhe.printStackTrace(); progress_listener.actionEnd(PROGRESS_LISTENER_ID); String message = nrhe.getMessage() + ":\n" + resources_.getString(DownloadMouseModeLayer.KEY_LOCALIZE_MESSAGE_DOWNLOAD_ERROR_NO_ROUTE_TO_HOST_MESSAGE); throw new IOException(message); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); progress_listener.actionEnd(PROGRESS_LISTENER_ID); String message = fnfe.getMessage() + ":\n" + resources_.getString(DownloadMouseModeLayer.KEY_LOCALIZE_MESSAGE_DOWNLOAD_ERROR_FILE_NOT_FOUND_MESSAGE); throw new IOException(message); } catch (Exception e) { progress_listener.actionEnd(PROGRESS_LISTENER_ID); e.printStackTrace(); String message = e.getMessage(); if (message == null) { Throwable cause = e.getCause(); if (cause != null) message = cause.getMessage(); } throw new IOException(message); } }
11
Code Sample 1: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } } Code Sample 2: @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: @Override public void onClick(View v) { Log.d(Config.SS_TAG, "Sending POST request to server..."); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(Config.RPC_SERVLET_URL); JSONObject requestJson = new JSONObject(); JSONArray callsJson = new JSONArray(); try { JSONObject callJson = new JSONObject(); callJson.put("method", "ping"); callJson.put("void", "null"); callsJson.put(0, callJson); requestJson.put("calls", callsJson); httpPost.setEntity(new StringEntity(requestJson.toString(), "UTF-8")); HttpResponse httpResponse = httpClient.execute(httpPost); final int responseStatusCode = httpResponse.getStatusLine().getStatusCode(); if (200 <= responseStatusCode && responseStatusCode < 300) { Log.d(Config.SS_TAG, "Successful ping - status code: " + responseStatusCode); BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } JSONTokener tokener = new JSONTokener(sb.toString()); JSONObject responseJson = new JSONObject(tokener); JSONArray resultsJson = responseJson.getJSONArray("results"); JSONObject result = resultsJson.getJSONObject(0); String returnValue = result.getJSONObject("data").getString("return"); Log.d(Config.SS_TAG, "Response message: " + returnValue); } else { Log.e(Config.SS_TAG, "Unsuccessful ping..."); } } catch (Exception e) { Log.e(Config.SS_TAG, "Error while trying to ping rpc servlet"); e.printStackTrace(); } } Code Sample 2: public void run() { try { URL url = new URL("http://mydiversite.appspot.com/version.html"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public void deleteRole(AuthSession authSession, RoleBean roleBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (roleBean.getRoleId() == null) throw new IllegalArgumentException("role id is null"); String sql = "delete from WM_AUTH_ACCESS_GROUP where ID_ACCESS_GROUP=? "; ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, roleBean.getRoleId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete role"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } Code Sample 2: public byte[] computeMD5(String plainText) throws VHException { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw new VHException("The MD5 hash algorithm is not available.", ex); } try { md.update(plainText.getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { throw new VHException("The UTF-8 encoding is not supported.", ex); } return md.digest(); }
00
Code Sample 1: private void copyTemplates(ProjectPath pPath) { String sourceAntPath = pPath.sourceAntPath(); final String moduleName = projectOperations.getFocusedTopLevelPackage().toString(); logger.info("Module Name: " + moduleName); String targetDirectory = pPath.canonicalFileSystemPath(projectOperations); logger.info("Moving into target Directory: " + targetDirectory); if (!targetDirectory.endsWith("/")) { targetDirectory += "/"; } if (!fileManager.exists(targetDirectory)) { fileManager.createDirectory(targetDirectory); } System.out.println("Target Directory: " + pPath.sourceAntPath()); String path = TemplateUtils.getTemplatePath(getClass(), sourceAntPath); Set<URL> urls = UrlFindingUtils.findMatchingClasspathResources(context.getBundleContext(), path); Assert.notNull(urls, "Could not search bundles for resources for Ant Path '" + path + "'"); if (urls.isEmpty()) { logger.info("URLS are empty stopping..."); } for (URL url : urls) { logger.info("Stepping into " + url.toExternalForm()); String fileName = url.getPath().substring(url.getPath().lastIndexOf("/") + 1); fileName = fileName.replace("-template", ""); String targetFilename = targetDirectory + fileName; logger.info("Handling " + targetFilename); if (!fileManager.exists(targetFilename)) { try { logger.info("Copied file"); String input = FileCopyUtils.copyToString(new InputStreamReader(url.openStream())); logger.info("TopLevelPackage: " + projectOperations.getFocusedTopLevelPackage()); logger.info("SegmentPackage: " + pPath.canonicalFileSystemPath(projectOperations)); String topLevelPackage = projectOperations.getFocusedTopLevelPackage().toString(); input = input.replace("__TOP_LEVEL_PACKAGE__", topLevelPackage); input = input.replace("__SEGMENT_PACKAGE__", pPath.segmentPackage()); input = input.replace("__PROJECT_NAME__", projectOperations.getFocusedProjectName()); input = input.replace("__ENTITY_NAME__", entityName); MutableFile mutableFile = fileManager.createFile(targetFilename); FileCopyUtils.copy(input.getBytes(), mutableFile.getOutputStream()); } catch (IOException ioe) { throw new IllegalStateException("Unable to create '" + targetFilename + "'", ioe); } } } } Code Sample 2: void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } }
00
Code Sample 1: public void alterar(Cliente cliente) throws Exception { Connection connection = criaConexao(false); String sql = "update cliente set nome = ?, sexo = ?, cod_cidade = ? where cod_cliente = ?"; PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); stmt.setString(1, cliente.getNome()); stmt.setString(2, cliente.getSexo()); stmt.setInt(3, cliente.getCidade().getCodCidade()); stmt.setLong(4, cliente.getId()); int retorno = stmt.executeUpdate(); if (retorno == 0) { connection.rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de alterar dados de cliente no banco!"); } connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { throw e; } } } Code Sample 2: public static String sha1(String in) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } byte[] data = new byte[40]; try { md.update(in.getBytes("iso-8859-1"), 0, in.length()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } data = md.digest(); return HexidecimalUtilities.convertFromByteArrayToHex(data); }
00
Code Sample 1: public static final long copyFile(final File srcFile, final File dstFile, final long cpySize) throws IOException { if ((null == srcFile) || (null == dstFile)) return (-1L); final File dstFolder = dstFile.getParentFile(); if ((!dstFolder.exists()) && (!dstFolder.mkdirs())) throw new IOException("Failed to created destination folder(s)"); FileChannel srcChannel = null, dstChannel = null; try { srcChannel = new FileInputStream(srcFile).getChannel(); dstChannel = new FileOutputStream(dstFile).getChannel(); final long srcLen = srcFile.length(), copyLen = dstChannel.transferFrom(srcChannel, 0, (cpySize < 0L) ? srcLen : cpySize); if ((cpySize < 0L) && (copyLen != srcLen)) return (-2L); return copyLen; } finally { FileUtil.closeAll(srcChannel, dstChannel); } } Code Sample 2: public static URL[] getURLsForAllJars(URL url, File tmpDir) { FileInputStream fin = null; InputStream in = null; ZipInputStream zin = null; try { ArrayList array = new ArrayList(); in = url.openStream(); String fileName = url.getFile(); int index = fileName.lastIndexOf('/'); if (index != -1) { fileName = fileName.substring(index + 1); } final File f = createTempFile(fileName, in, tmpDir); fin = (FileInputStream) org.apache.axis2.java.security.AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws FileNotFoundException { return new FileInputStream(f); } }); array.add(f.toURL()); zin = new ZipInputStream(fin); ZipEntry entry; String entryName; while ((entry = zin.getNextEntry()) != null) { entryName = entry.getName(); if ((entryName != null) && entryName.toLowerCase().startsWith("lib/") && entryName.toLowerCase().endsWith(".jar")) { String suffix = entryName.substring(4); File f2 = createTempFile(suffix, zin, tmpDir); array.add(f2.toURL()); } } return (URL[]) array.toArray(new URL[array.size()]); } catch (Exception e) { throw new RuntimeException(e); } finally { if (fin != null) { try { fin.close(); } catch (IOException e) { } } if (in != null) { try { in.close(); } catch (IOException e) { } } if (zin != null) { try { zin.close(); } catch (IOException 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 render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(s_contentType); response.setHeader("Cache-control", "no-cache"); InputStream graphStream = getGraphStream(request); OutputStream out = getOutputStream(response); IOUtils.copy(graphStream, out); out.flush(); }
11
Code Sample 1: private static void generateTIFF(Connection con, String category, String area_code, String topic_code, String timeseries, String diff_timeseries, Calendar time, String area_label, String raster_label, String image_label, String note, Rectangle2D bounds, Rectangle2D raster_bounds, String source_filename, String diff_filename, String legend_filename, String output_filename, int output_maximum_size) throws SQLException, IOException { Debug.println("ImageCropper.generateTIFF begin"); MapContext map_context = new MapContext("test", new Configuration()); try { Map map = new Map(map_context, area_label, new Configuration()); map.setCoordSys(ProjectionCategories.default_coordinate_system); map.setPatternOutline(new XPatternOutline(new XPatternPaint(Color.white))); String type = null; RasterLayer rlayer = getRasterLayer(map, raster_label, getLinuxPathEquivalent(source_filename), getLinuxPathEquivalent(diff_filename), type, getLinuxPathEquivalent(legend_filename)); map.addLayer(rlayer, true); map.setBounds2DImage(bounds, true); Dimension image_dim = null; image_dim = new Dimension((int) rlayer.raster.getDeviceBounds().getWidth() + 1, (int) rlayer.raster.getDeviceBounds().getHeight() + 1); if (output_maximum_size > 0) { double width_factor = image_dim.getWidth() / output_maximum_size; double height_factor = image_dim.getHeight() / output_maximum_size; double factor = Math.max(width_factor, height_factor); if (factor > 1.0) { image_dim.setSize(image_dim.getWidth() / factor, image_dim.getHeight() / factor); } } map.setImageDimension(image_dim); map.scale(); image_dim = new Dimension((int) map.getBounds2DImage().getWidth(), (int) map.getBounds2DImage().getHeight()); Image image = null; Graphics gr = null; image = ImageCreator.getImage(image_dim); gr = image.getGraphics(); try { map.paint(gr); } catch (Exception e) { Debug.println("map.paint error: " + e.getMessage()); } String tiff_filename = ""; try { tiff_filename = formatPath(category, timeseries, output_filename); new File(new_filename).mkdirs(); Debug.println("tiff_filename: " + tiff_filename); BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_BYTE_INDEXED); bi.createGraphics().drawImage(image, 0, 0, null); File f = new File(tiff_filename); FileOutputStream out = new FileOutputStream(f); TIFFEncodeParam param = new TIFFEncodeParam(); param.setCompression(TIFFEncodeParam.COMPRESSION_PACKBITS); TIFFImageEncoder encoder = (TIFFImageEncoder) TIFFCodec.createImageEncoder("tiff", out, param); encoder.encode(bi); out.close(); } catch (IOException e) { Debug.println("ImageCropper.generateTIFF TIFFCodec e: " + e.getMessage()); throw new IOException("GenerateTIFF.IOException: " + e); } PreparedStatement pstmt = null; try { String query = "select Proj_ID, AccessType_Code from project " + "where Proj_Code= '" + area_code.trim() + "'"; Statement stmt = null; ResultSet rs = null; int proj_id = -1; int access_code = -1; stmt = con.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { proj_id = rs.getInt(1); access_code = rs.getInt(2); } rs.close(); stmt.close(); String delete_raster = "delete from rasterlayer where " + "Raster_Name='" + tiff_name.trim() + "' and Group_Code='" + category.trim() + "' and Proj_ID =" + proj_id; Debug.println("***** delete_raster: " + delete_raster); pstmt = con.prepareStatement(delete_raster); boolean del = pstmt.execute(); pstmt.close(); String insert_raster = "insert into rasterlayer(Raster_Name, " + "Group_Code, Proj_ID, Raster_TimeCode, Raster_Xmin, " + "Raster_Ymin, Raster_Area_Xmin, Raster_Area_Ymin, " + "Raster_Visibility, Raster_Order, Raster_Path, " + "AccessType_Code, Raster_TimePeriod) values(?,?,?,?, " + "?,?,?,?,?,?,?,?,?)"; pstmt = con.prepareStatement(insert_raster); pstmt.setString(1, tiff_name); pstmt.setString(2, category); pstmt.setInt(3, proj_id); pstmt.setString(4, timeseries); pstmt.setDouble(5, raster_bounds.getX()); pstmt.setDouble(6, raster_bounds.getY()); pstmt.setDouble(7, raster_bounds.getWidth()); pstmt.setDouble(8, raster_bounds.getHeight()); pstmt.setString(9, "false"); int sequence = 0; if (tiff_name.endsWith("DP")) { sequence = 1; } else if (tiff_name.endsWith("DY")) { sequence = 2; } else if (tiff_name.endsWith("DA")) { sequence = 3; } pstmt.setInt(10, sequence); pstmt.setString(11, tiff_filename); pstmt.setInt(12, access_code); if (time == null) { pstmt.setNull(13, java.sql.Types.DATE); } else { pstmt.setDate(13, new java.sql.Date(time.getTimeInMillis())); } pstmt.executeUpdate(); } catch (SQLException e) { Debug.println("SQLException occurred e: " + e.getMessage()); con.rollback(); throw new SQLException("GenerateTIFF.SQLException: " + e); } finally { pstmt.close(); } } catch (Exception e) { Debug.println("ImageCropper.generateTIFF e: " + e.getMessage()); } Debug.println("ImageCropper.generateTIFF end"); } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
11
Code Sample 1: public static MMissing load(URL url) throws IOException { MMissing ret = new MMissing(); InputStream is = url.openStream(); try { Reader r = new InputStreamReader(is); BufferedReader br = new BufferedReader(r); String line; while ((line = br.readLine()) != null) { if (line.length() > 0) { ret.add(line); } } return ret; } finally { is.close(); } } Code Sample 2: @Override public void exec() { BufferedReader in = null; try { URL url = new URL(getUrl()); in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer result = new StringBuffer(); String str; while ((str = in.readLine()) != null) { result.append(str); } logger.info("received message: " + result); } catch (Exception e) { logger.error("HttpGetEvent could not execute", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("BufferedReader could not be closed", e); } } } }