label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public static String getSHA1Digest(String inputStr) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; byte[] sha1hash = null; md = MessageDigest.getInstance("SHA"); sha1hash = new byte[40]; md.update(inputStr.getBytes("iso-8859-1"), 0, inputStr.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: private final String encryptPassword(String pass) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { log.log(Level.WARNING, "Error while obtaining decript algorithm", e); throw new RuntimeException("AccountData.encryptPassword()"); } try { md.update(pass.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { log.log(Level.WARNING, "Problem with decript algorithm occured.", e); throw new RuntimeException("AccountData.encryptPassword()"); } return new BASE64Encoder().encode(md.digest()); }
00
Code Sample 1: public InputStream getInputStream(String fName) throws IOException { InputStream result = null; int length = 0; if (isURL) { URL url = new URL(getFullFileNamePath(fName)); URLConnection c = url.openConnection(); length = c.getContentLength(); result = c.getInputStream(); } else { File f = new File(sysFn(getFullFileNamePath(fName))); if (!f.exists()) { String alt = (String) altFileNames.get(fName); if (alt != null) f = new File(sysFn(getFullFileNamePath(alt))); } length = (int) f.length(); result = new FileInputStream(f); } if (result != null && rb != null) { result = rb.getProgressInputStream(result, length, fName); } return result; } Code Sample 2: void setURLString(String path, boolean forceLoad) { if (path != null) { if (this.url != null || inputStream != null) throw new IllegalArgumentException(Ding3dI18N.getString("MediaContainer5")); try { URL url = new URL(path); InputStream stream; stream = url.openStream(); stream.close(); } catch (Exception e) { throw new SoundException(javax.media.ding3d.Ding3dI18N.getString("MediaContainer0")); } } this.urlString = path; if (forceLoad) dispatchMessage(); }
00
Code Sample 1: private String doOAIQuery(String request) throws IOException, ProtocolException { DannoClient ac = getClient(); HttpGet get = new HttpGet(request); get.setHeader("Accept", "application/xml"); HttpResponse response = ac.execute(get); if (!ac.isOK()) { throw new DannoRequestFailureException("GET", response); } return massage(new BasicResponseHandler().handleResponse(response)); } Code Sample 2: public void fillData() { try { URL urlhome = OpenerIF.class.getResource("Home.html"); URLConnection uc = urlhome.openConnection(); InputStreamReader input = new InputStreamReader(uc.getInputStream()); BufferedReader in = new BufferedReader(input); String inputLine; String htmlData = ""; while ((inputLine = in.readLine()) != null) { htmlData += inputLine; } in.close(); String[] str = new String[9]; str[0] = getLibName(); str[1] = getLoginId(); str[2] = getLoginName(); str[3] = getVerusSubscriptionIdHTML(); str[4] = getPendingJobsHTMLCode(); str[5] = getFrequentlyUsedScreensHTMLCode(); str[6] = getOpenCatalogHTMLCode(); str[7] = getNewsHTML(); str[8] = getOnlineInformationHTML(); MessageFormat mf = new MessageFormat(htmlData); String htmlContent = mf.format(htmlData, str); PrintWriter fw = new PrintWriter(System.getProperty("user.home") + "/homeNGL.html"); fw.println(htmlContent); fw.flush(); fw.close(); new LocalHtmlRendererContext(panel, new SimpleUserAgentContext(), this).navigate("file:" + System.getProperty("user.home") + "/homeNGL.html"); } catch (Exception exp) { exp.printStackTrace(); } }
00
Code Sample 1: public void myCheckCredHandler(View v) { Log.d("login_section", "entered handler"); EditText Username = (EditText) findViewById(R.id.Username); EditText Password = (EditText) findViewById(R.id.user_pass); String username_S = Username.getText().toString(); String pass_S = Password.getText().toString(); TextView ltv = (TextView) findViewById(R.id.LoginPagetv); HttpClient httpclient = createHttpClient(); HttpPost httppost = new HttpPost(authenticationURL); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("login", username_S)); nameValuePairs.add(new BasicNameValuePair("password", pass_S)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); int status = response.getStatusLine().getStatusCode(); String responseBody = EntityUtils.toString(response.getEntity()); Log.d("login_section", responseBody); JSONObject jsonObject = new JSONObject(responseBody); if (status == this.statusOK && jsonObject.getBoolean("logged_in")) { ltv.setText("You have been logged in. :D"); etracks.setLogged(true); etracks.setUserToken(jsonObject.getString("user_token")); Intent it = new Intent(Intent.ACTION_VIEW); it.setClassName(this, etracks.class.getName()); this.finish(); startActivity(it); } else if (status == this.statusUnprocessable && !jsonObject.getBoolean("logged_in")) { if (!jsonObject.isNull("errors")) ltv.setText(jsonObject.getString("errors")); else ltv.setText("login unsuccessful"); } else Log.d("login_section", "what just happened?"); } catch (ClientProtocolException e) { } catch (IOException e) { } catch (JSONException e) { e.printStackTrace(); } } Code Sample 2: public static <T extends Comparable<T>> void BubbleSortComparable2(T[] num) { int last_exchange; int right_border = num.length - 1; do { last_exchange = 0; for (int j = 0; j < num.length - 1; j++) { if (num[j].compareTo(num[j + 1]) > 0) { T temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; last_exchange = j; } } right_border = last_exchange; } while (right_border > 0); }
11
Code Sample 1: @SuppressWarnings("unchecked") public static void unzip(String zipFileName, String folder, boolean isCreate) throws IOException { File file = new File(zipFileName); File folderfile = null; if (file.exists() && file.isFile()) { String mfolder = folder == null ? file.getParent() : folder; String fn = file.getName(); fn = fn.substring(0, fn.lastIndexOf(".")); mfolder = isCreate ? (mfolder + File.separator + fn) : mfolder; folderfile = new File(mfolder); if (!folderfile.exists()) { folderfile.mkdirs(); } } else { throw new FileNotFoundException("不存在 zip 文件"); } ZipFile zipFile = new ZipFile(file); try { Enumeration<ZipArchiveEntry> en = zipFile.getEntries(); ZipArchiveEntry ze = null; while (en.hasMoreElements()) { ze = en.nextElement(); if (ze.isDirectory()) { String dirName = ze.getName(); dirName = dirName.substring(0, dirName.length() - 1); File f = new File(folderfile.getPath() + File.separator + dirName); f.mkdirs(); } else { File f = new File(folderfile.getPath() + File.separator + ze.getName()); if (!f.getParentFile().exists()) { f.getParentFile().mkdirs(); } f.createNewFile(); InputStream in = zipFile.getInputStream(ze); OutputStream out = new FileOutputStream(f); IOUtils.copy(in, out); out.close(); in.close(); } } } finally { zipFile.close(); } } Code Sample 2: void shutdown(final boolean unexpected) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } log.error("check if we need the controler listener infrastructure"); if (this.dumpDataAtEnd) { new PopulationWriter(this.population, this.network).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); }
00
Code Sample 1: private Document getXML(String artist) throws Exception { Document doc = null; URL url = new URL("http://" + disgogsUrl + "/artist/" + formatQuery(artist) + "?f=xml&api_key=" + apiKey[0]); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.addRequestProperty("Accept-Encoding", "gzip"); if (StaticObj.PROXY_ENABLED) { Properties systemSettings = System.getProperties(); systemSettings.put("http.proxyHost", StaticObj.PROXY_URL); systemSettings.put("http.proxyPort", StaticObj.PROXY_PORT); System.setProperties(systemSettings); sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder(); String encoded = new String(encoder.encode(new String(StaticObj.PROXY_USERNAME + ":" + StaticObj.PROXY_PASSWORD).getBytes())); uc.setRequestProperty("Proxy-Authorization", "Basic " + encoded); } BufferedReader ir = null; try { if (uc.getInputStream() != null) { InputStream _is = uc.getInputStream(); GZIPInputStream _gzipIs = new GZIPInputStream(_is); InputStreamReader _isReader = new InputStreamReader(_gzipIs); ir = new BufferedReader(_isReader); SAXBuilder builder = new SAXBuilder(); doc = builder.build(ir); } } catch (Exception e) { if (StaticObj.DEBUG) { LogManager.getInstance().getLogger().error(e); e.printStackTrace(); System.out.println("No Data found!"); } } return doc; } Code Sample 2: public static void main(String[] args) throws IOException, ClassNotFoundException { URL urlServlet = null; try { urlServlet = new URL("http://wofproj.appspot.com/test"); } catch (MalformedURLException e) { e.printStackTrace(); } URLConnection con = null; try { con = urlServlet.openConnection(); } catch (IOException e) { e.printStackTrace(); } con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type", "application/x-java-serialized-object"); OutputStream outstream = con.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(outstream); oos.writeObject("tom"); oos.flush(); oos.close(); InputStream instr = con.getInputStream(); ObjectInputStream inputFromServlet = new ObjectInputStream(instr); Object retval = inputFromServlet.readObject(); inputFromServlet.close(); instr.close(); System.out.println(retval.getClass().toString()); }
00
Code Sample 1: public void create_list() { try { String data = URLEncoder.encode("PHPSESSID", "UTF-8") + "=" + URLEncoder.encode(this.get_session(), "UTF-8"); URL url = new URL(URL_LOLA + FILE_CREATE_LIST); 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())); String line; line = rd.readLine(); wr.close(); rd.close(); System.out.println("Gene list saved in LOLA"); } catch (Exception e) { System.out.println("error in createList()"); e.printStackTrace(); } } Code Sample 2: private JButton getButtonImagen() { if (buttonImagen == null) { buttonImagen = new JButton(); buttonImagen.setText("Cargar Imagen"); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetree.png"))); buttonImagen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setFileView(new ImageFileView()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(Resorces.this, "Seleccione una imagen"); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + file.separator + "data" + file.separator + "imagenes" + file.separator + file.getName(); String rutaRelativa = "data" + file.separator + "imagenes" + file.separator + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); } catch (IOException ex) { ex.printStackTrace(); } imagen.setImagenURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.procesadorDatos.escalaImageIcon(imagen.getImagenURL())); } else { } } }); } return buttonImagen; }
11
Code Sample 1: protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletConfig config = getServletConfig(); ServletContext context = config.getServletContext(); try { String driver = context.getInitParameter("driver"); Class.forName(driver); String dbURL = context.getInitParameter("db"); String username = context.getInitParameter("username"); String password = ""; connection = DriverManager.getConnection(dbURL, username, password); } catch (ClassNotFoundException e) { System.out.println("Database driver not found."); } catch (SQLException e) { System.out.println("Error opening the db connection: " + e.getMessage()); } String action = ""; HttpSession session = request.getSession(); session.setMaxInactiveInterval(300); if (request.getParameter("action") != null) { action = request.getParameter("action"); } else { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/login.jsp"); dispatcher.forward(request, response); return; } if (action.equals("login")) { String username = request.getParameter("username"); String password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { error = "There was an error encrypting password."; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } try { md.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { error = "There was an error encrypting password."; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } String encrypted_password = (new BASE64Encoder()).encode(md.digest()); try { String sql = "SELECT * FROM person WHERE email LIKE '" + username + "' AND password='" + encrypted_password + "'"; dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); if (dbResultSet.next()) { Person person = new Person(dbResultSet.getString("fname"), dbResultSet.getString("lname"), dbResultSet.getString("address1"), dbResultSet.getString("address2"), dbResultSet.getString("city"), dbResultSet.getString("state"), dbResultSet.getString("zip"), dbResultSet.getString("email"), dbResultSet.getString("password"), dbResultSet.getInt("is_admin")); String member_type = dbResultSet.getString("member_type"); String person_id = Integer.toString(dbResultSet.getInt("id")); session.setAttribute("person", person); session.setAttribute("member_type", member_type); session.setAttribute("person_id", person_id); } else { notice = "Your username and/or password is incorrect."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } catch (SQLException e) { error = "There was an error trying to login. (SQL Statement)"; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Unable to log you in. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/login.jsp"); dispatcher.forward(request, response); return; } } Code Sample 2: private String md5Digest(String plain) throws Exception { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(plain.trim().getBytes()); byte pwdDigest[] = digest.digest(); StringBuilder md5buffer = new StringBuilder(); for (int i = 0; i < pwdDigest.length; i++) { int number = 0xFF & pwdDigest[i]; if (number <= 0xF) { md5buffer.append('0'); } md5buffer.append(Integer.toHexString(number)); } return md5buffer.toString(); }
00
Code Sample 1: static Collection<InetSocketAddress> getAddresses(Context ctx, long userId) throws Exception { AGLog.d(TAG, "Connecting to HTTP service to obtain IP addresses"); String host = (String) ctx.getResources().getText(R.string.gg_webservice_addr); String ver = App.getInstance().getGGClientVersion(); String url = host + "?fmnumber=" + Long.toString(userId) + "&lastmsg=0&version=" + ver; HttpClient httpClient = new DefaultHttpClient(); AGLog.d(TAG, "connecting to http service at " + url); HttpGet request = new HttpGet(url); HttpResponse response = httpClient.execute(request); AGLog.d(TAG, "response status:" + response.getStatusLine().getReasonPhrase()); HttpEntity ent = response.getEntity(); if (ent == null) { AGLog.e(TAG, "No response entity"); throw new ClientProtocolException("No response entity"); } InputStream content = ent.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line = reader.readLine(); AGLog.d(TAG, "response: " + line); StringTokenizer tokenizer = new StringTokenizer(line, " "); @SuppressWarnings("unused") String status = tokenizer.nextToken(); @SuppressWarnings("unused") String unknown = tokenizer.nextToken(); ArrayList<InetSocketAddress> result = new ArrayList<InetSocketAddress>(); while (tokenizer.hasMoreTokens()) { StringTokenizer addrport = new StringTokenizer(tokenizer.nextToken(), ":"); String addrStr = addrport.nextToken(); if (InetAddressUtils.isIPv4Address(addrStr)) { AGLog.d(TAG, "Address decoded successfully: " + addrStr); } else { AGLog.w(TAG, "Failed to decode address: " + addrStr); continue; } String portStr; if (addrport.hasMoreTokens()) { portStr = addrport.nextToken(); } else { portStr = (String) ctx.getResources().getText(R.string.gg_default_port); } AGLog.d(TAG, "Port decoded successfully: " + portStr); short port = Short.decode(portStr); result.add(new InetSocketAddress(addrStr, port)); } return result; } Code Sample 2: public void copy(String original, String copy) throws SQLException { try { OutputStream out = openFileOutputStream(copy, false); InputStream in = openFileInputStream(original); IOUtils.copyAndClose(in, out); } catch (IOException e) { throw Message.convertIOException(e, "Can not copy " + original + " to " + copy); } }
11
Code Sample 1: public void sendFile(File file, String filename, String contentType) throws SearchLibException { response.setContentType(contentType); response.addHeader("Content-Disposition", "attachment; filename=" + filename); FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); ServletOutputStream outputStream = getOutputStream(); IOUtils.copy(inputStream, outputStream); outputStream.close(); } catch (FileNotFoundException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } finally { if (inputStream != null) IOUtils.closeQuietly(inputStream); } } Code Sample 2: public static File enregistrerFichier(String fileName, File file, String path, String fileMime) throws Exception { if (file != null) { try { HttpServletRequest request = ServletActionContext.getRequest(); HttpSession session = request.getSession(); String pathFile = session.getServletContext().getRealPath(path) + File.separator + fileName; File outfile = new File(pathFile); String[] nomPhotoTab = fileName.split("\\."); String extension = nomPhotoTab[nomPhotoTab.length - 1]; StringBuffer pathResBuff = new StringBuffer(nomPhotoTab[0]); for (int i = 1; i < nomPhotoTab.length - 1; i++) { pathResBuff.append(".").append(nomPhotoTab[i]); } String pathRes = pathResBuff.toString(); String nomPhoto = fileName; for (int i = 0; !outfile.createNewFile(); i++) { nomPhoto = pathRes + "_" + +i + "." + extension; pathFile = session.getServletContext().getRealPath(path) + File.separator + nomPhoto; outfile = new File(pathFile); } logger.debug(" enregistrerFichier - Enregistrement du fichier : " + pathFile); FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(outfile).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return outfile; } catch (IOException e) { logger.error("Erreur lors de l'enregistrement de l'image ", e); throw new Exception("Erreur lors de l'enregistrement de l'image "); } } return null; }
11
Code Sample 1: public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: private String copyAndHash(InputStream input, File into) throws IOException { MessageDigest digest = createMessageDigest(); DigestInputStream dis = new DigestInputStream(input, digest); IOException ex; FileOutputStream fos = null; try { fos = new FileOutputStream(into); IOUtils.copyLarge(dis, fos); byte[] hash = digest.digest(); Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } return formatter.toString(); } catch (IOException e) { ex = e; } finally { IOUtils.closeQuietly(dis); IOUtils.closeQuietly(fos); } if (logger.isWarnEnabled()) logger.warn("Couldn't retrieve data from input!", ex); deleteTempFile(into); throw ex; } 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(); }
11
Code Sample 1: public void sendContent(OutputStream out, Range range, Map map, String string) throws IOException, NotAuthorizedException, BadRequestException { System.out.println("sendContent " + file); RFileInputStream in = new RFileInputStream(file); try { IOUtils.copyLarge(in, out); } finally { in.close(); } } 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: 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(); } } Code Sample 2: public void store(Component component, String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("UPDATE component_prop " + "SET size_height = ?, size_width = ?, pos_x = ?, pos_y = ? " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); Point point = component.getLocation(); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); int update = psta.executeUpdate(); if (update == 0) { psta = jdbc.prepareStatement("INSERT INTO component_prop " + "(size_height, size_width, pos_x, pos_y, pilot_id, component_name) " + "VALUES (?,?,?,?,?,?)"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); psta.executeUpdate(); } jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
11
Code Sample 1: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } 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; }
11
Code Sample 1: public boolean isPasswordCorrect(String attempt) { try { MessageDigest digest = MessageDigest.getInstance(attempt); digest.update(salt); digest.update(attempt.getBytes("UTF-8")); byte[] attemptHash = digest.digest(); return attemptHash.equals(hash); } catch (UnsupportedEncodingException ex) { Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex); return false; } } Code Sample 2: @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); String format = req.getParameter("format"); EntityManager em = EMF.get().createEntityManager(); String uname = (req.getParameter("uname") == null) ? "" : req.getParameter("uname"); String passwd = (req.getParameter("passwd") == null) ? "" : req.getParameter("passwd"); String name = (req.getParameter("name") == null) ? "" : req.getParameter("name"); String email = (req.getParameter("email") == null) ? "" : req.getParameter("email"); if (uname == null || uname.equals("") || uname.length() < 4) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.unameTooShort(uname).toXML(em)); else resp.getWriter().print(Error.unameTooShort(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } if (User.fromUserName(em, uname) != null) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.userExists(uname).toXML(em)); else resp.getWriter().print(Error.userExists(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_CONFLICT); em.close(); return; } if (passwd.equals("") || passwd.length() < 6) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); if (format != null && format.equals("xml")) resp.getWriter().print(Error.passwdTooShort(uname).toXML(em)); else resp.getWriter().print(Error.passwdTooShort(uname).toJSON(em)); em.close(); return; } User u = new User(); u.setUsername(uname); u.setPasswd(passwd); u.setName(name); u.setEmail(email); u.setPaid(false); StringBuffer apikey = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); String api = System.nanoTime() + "" + System.identityHashCode(this) + "" + uname; algorithm.update(api.getBytes()); byte[] digest = algorithm.digest(); for (int i = 0; i < digest.length; i++) { apikey.append(Integer.toHexString(0xFF & digest[i])); } } catch (NoSuchAlgorithmException e) { resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); log.severe(e.toString()); em.close(); return; } u.setApiKey(apikey.toString()); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.persist(u); tx.commit(); } catch (Throwable t) { log.severe("Error adding user " + uname + " Reason:" + t.getMessage()); tx.rollback(); resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); return; } log.info("User " + u.getName() + " was created successfully"); resp.setStatus(HttpServletResponse.SC_CREATED); if (format != null && format.equals("xml")) resp.getWriter().print(u.toXML(em)); else resp.getWriter().print(u.toJSON(em)); em.close(); }
11
Code Sample 1: public static void main(String[] args) throws IOException { File inputFile = new File("D:/farrago.txt"); File outputFile = new File("D:/outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); FileChannel channelSrc = fis.getChannel(); FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); }
11
Code Sample 1: private void Connect() throws NpsException { try { client = new FTPClient(); client.connect(host.hostname, host.remoteport); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { client.disconnect(); client = null; nps.util.DefaultLog.error_noexception("FTP Server:" + host.hostname + "refused connection."); return; } client.login(host.uname, host.upasswd); client.enterLocalPassiveMode(); client.setFileType(FTPClient.BINARY_FILE_TYPE); client.changeWorkingDirectory(host.remotedir); } catch (Exception e) { nps.util.DefaultLog.error(e); } } Code Sample 2: public boolean storeFile(String local, String remote) throws IOException { boolean stored = false; GridFTP ftp = new GridFTP(); ftp.setDefaultPort(port); System.out.println(this + ".storeFile " + remote); try { ftp.connect(host); ftp.login(username, password); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); return false; } ftp.put(local, remote); ftp.logout(); stored = true; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } return stored; }
00
Code Sample 1: public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(File.separator) + 1, path.length())); String name = imageName.substring(0, imageName.lastIndexOf('.')); String extension = imageName.substring(imageName.lastIndexOf('.') + 1, imageName.length()); File imageFile = new File(path); directoryPath = "images" + File.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName; File newFile = new File(imagePath); if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.REPLACE_IMAGE"))) { Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name); if (aux.size() != 0) { int idImage = TIGDataBase.imageKeySearchName(name); TIGDataBase.deleteAsociatedOfImage(idImage); } } if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.ADD_IMAGE"))) { int i = 1; while (newFile.exists()) { imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); name = name + "_" + i; newFile = new File(imagePath); i++; } } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); imageName = name + "." + extension; try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } TIGDataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { createThumbnail(); } } } } Code Sample 2: public String encrypt(String pwd) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.out.println("Error"); } try { md5.update(pwd.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "That is not a valid encrpytion type"); } byte raw[] = md5.digest(); String empty = ""; String hash = ""; for (byte b : raw) { String tmp = empty + Integer.toHexString(b & 0xff); if (tmp.length() == 1) { tmp = 0 + tmp; } hash += tmp; } return hash; }
11
Code Sample 1: public static void copyFile(File source, File destination) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(destination).getChannel(); long size = in.size(); MappedByteBuffer buffer = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buffer); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } Code Sample 2: public static void copyFile(File src, File dest) throws IOException { log.debug("Copying file: '" + src + "' to '" + dest + "'"); FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
00
Code Sample 1: @Override public String encode(String password) { String hash = null; MessageDigest m; try { m = MessageDigest.getInstance("MD5"); m.update(password.getBytes(), 0, password.length()); hash = String.format("%1$032X", new BigInteger(1, m.digest())); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hash; } Code Sample 2: public static boolean exec_applet(String fname, VarContainer vc, ActionContainer ac, ThingTypeContainer ttc, Output OUT, InputStream IN, boolean AT, Statement state, String[] arggies) { if (!urlpath.endsWith("/")) { urlpath = urlpath + '/'; } if (!urlpath.startsWith("http://")) { urlpath = "http://" + urlpath; } String url = urlpath; if (fname.startsWith("dusty_")) { url = url + "libraries/" + fname; } else { url = url + "users/" + fname; } StringBuffer src = new StringBuffer(2400); try { String s; BufferedReader br = new BufferedReader(new InputStreamReader(new URL(url).openStream())); while ((s = br.readLine()) != null) { src.append(s).append('\n'); } br.close(); } catch (Exception e) { OUT.println(new DSOut(DSOut.ERR_OUT, -1, "Dustyscript failed at reading the file'" + fname + "'\n\t...for 'use' statement"), vc, AT); return false; } fork(src, vc, ac, ttc, OUT, IN, AT, state, arggies); return true; }
11
Code Sample 1: public static String encryptMd5(String plaintext) { String hashtext = ""; try { MessageDigest m; m = MessageDigest.getInstance("MD5"); m.reset(); m.update(plaintext.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1, digest); hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hashtext; } Code Sample 2: public String md5(Value request) throws FaultException { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(request.strValue().getBytes("UTF8")); } catch (UnsupportedEncodingException e) { throw new FaultException("UnsupportedOperation", e); } catch (NoSuchAlgorithmException e) { throw new FaultException("UnsupportedOperation", e); } int radix; if ((radix = request.getFirstChild("radix").intValue()) < 2) { radix = 16; } return new BigInteger(1, md.digest()).toString(radix); }
11
Code Sample 1: public void store(String path, InputStream stream) throws IOException { toIgnore.add(normalizePath(path)); ZipEntry entry = new ZipEntry(path); zipOutput.putNextEntry(entry); IOUtils.copy(stream, zipOutput); zipOutput.closeEntry(); } Code Sample 2: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) throw new IOException("Destination '" + destFile + "' exists but is a directory"); FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); if (preserveFileDate) destFile.setLastModified(srcFile.lastModified()); }
11
Code Sample 1: @Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException { String context = request.getContextPath(); String resource = request.getRequestURI().replace(context, ""); resource = resource.replaceAll("^/\\w*/", ""); if ((StringUtils.isEmpty(resource)) || (resource.endsWith("/"))) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } URL url = ClassLoaderUtils.getResource(resource); if (url == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } if ((this.deny != null) && (this.deny.length > 0)) { for (String s : this.deny) { s = s.trim(); if (s.indexOf('*') != -1) { s = s.replaceAll("\\*", ".*"); } if (Pattern.matches(s, resource)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } } } InputStream input = url.openStream(); OutputStream output = response.getOutputStream(); URLConnection connection = url.openConnection(); String contentEncoding = connection.getContentEncoding(); int contentLength = connection.getContentLength(); String contentType = connection.getContentType(); if (contentEncoding != null) { response.setCharacterEncoding(contentEncoding); } response.setContentLength(contentLength); response.setContentType(contentType); IOUtils.copy(input, output, true); } Code Sample 2: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
00
Code Sample 1: @Override public EntrySet read(EntrySet set) throws ReadFailedException { if (!SourceCache.contains(url)) { SSL.certify(url); try { super.setParser(Parser.detectParser(url.openStream(), url)); final PipedInputStream in = new PipedInputStream(); final PipedOutputStream forParser = new PipedOutputStream(in); new Thread(new Runnable() { public void run() { try { OutputStream out = SourceCache.startCaching(url); InputStream is = url.openStream(); byte[] buffer = new byte[100000]; while (true) { int amountRead = is.read(buffer); if (amountRead == -1) { break; } forParser.write(buffer, 0, amountRead); out.write(buffer, 0, amountRead); } forParser.close(); out.close(); SourceCache.finish(url); } catch (IOException e) { e.printStackTrace(); } } }).start(); super.setIos(in); } catch (Exception e) { throw new ReadFailedException(e); } return super.read(set); } else { try { return SourceCache.get(url).read(set); } catch (IOException e) { throw new ReadFailedException(e); } } } Code Sample 2: public static void fileCopy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
11
Code Sample 1: @Override protected void setUp() throws Exception { this.logger = new ConsoleLogger(ConsoleLogger.LEVEL_WARN); File repoFolder = new File("target/repository"); removeRepository(repoFolder); InputStream repoConfigIn = getClass().getResourceAsStream(REPO_CONFIG_FILE); File tempRepoConfigFile = File.createTempFile("repository", "xml"); tempRepoConfigFile.deleteOnExit(); OutputStream tempRepoConfigOut = new FileOutputStream(tempRepoConfigFile); try { IOUtils.copy(repoConfigIn, tempRepoConfigOut); } finally { repoConfigIn.close(); tempRepoConfigOut.close(); } Repository repo = new TransientRepository(tempRepoConfigFile.getAbsolutePath(), "target/repository"); ServerAdapterFactory factory = new ServerAdapterFactory(); RemoteRepository remoteRepo = factory.getRemoteRepository(repo); reg = LocateRegistry.createRegistry(Registry.REGISTRY_PORT); reg.rebind(REMOTE_REPO_NAME, remoteRepo); session = repo.login(new SimpleCredentials(LOGIN, PWD.toCharArray()), WORKSPACE); InputStream nodeTypeDefIn = getClass().getResourceAsStream(MQ_JCR_XML_NODETYPES_FILE); JackrabbitInitializerHelper.setupRepository(session, new InputStreamReader(nodeTypeDefIn), ""); } 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) inChannel.close(); if (outChannel != null) outChannel.close(); } }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private static void convertToOnline(final String filePath, final DocuBean docuBean) throws Exception { File source = new File(filePath + File.separator + docuBean.getFileName()); File dir = new File(filePath + File.separator + docuBean.getId()); if (!dir.exists()) { dir.mkdir(); } File in = source; boolean isSpace = false; if (source.getName().indexOf(" ") != -1) { in = new File(StringUtils.replace(source.getName(), " ", "")); try { IOUtils.copyFile(source, in); } catch (IOException e) { e.printStackTrace(); } isSpace = true; } File finalPdf = null; try { String outPath = dir.getAbsolutePath(); final File pdf = DocViewerConverter.toPDF(in, outPath); convertToSwf(pdf, outPath, docuBean); finalPdf = new File(outPath + File.separator + FileUtils.getFilePrefix(StringUtils.replace(source.getName(), " ", "")) + "_decrypted.pdf"); if (!finalPdf.exists()) { finalPdf = pdf; } pdfByFirstPageToJpeg(finalPdf, outPath, docuBean); if (docuBean.getSuccess() == 2 && dir.listFiles().length < 2) { docuBean.setSuccess(3); } } catch (Exception e) { throw e; } finally { if (isSpace) { IOUtils.delete(in); } } }
11
Code Sample 1: public String readFile(String filename) throws UnsupportedEncodingException, FileNotFoundException, IOException { File f = new File(baseDir); f = new File(f, filename); StringWriter w = new StringWriter(); Reader fr = new InputStreamReader(new FileInputStream(f), "UTF-8"); IOUtils.copy(fr, w); fr.close(); w.close(); String contents = w.toString(); return contents; } Code Sample 2: private void removeSessionId(InputStream inputStream, Output output) throws IOException { String jsessionid = RewriteUtils.getSessionId(target); boolean textContentType = ResourceUtils.isTextContentType(httpClientResponse.getHeader(HttpHeaders.CONTENT_TYPE), target.getDriver().getConfiguration().getParsableContentTypes()); if (jsessionid == null || !textContentType) { IOUtils.copy(inputStream, output.getOutputStream()); } else { String charset = httpClientResponse.getContentCharset(); if (charset == null) { charset = "ISO-8859-1"; } String content = IOUtils.toString(inputStream, charset); content = removeSessionId(jsessionid, content); if (output.getHeader(HttpHeaders.CONTENT_LENGTH) != null) { output.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(content.length())); } OutputStream outputStream = output.getOutputStream(); IOUtils.write(content, outputStream, charset); } inputStream.close(); }
00
Code Sample 1: private static void copierScriptChargement(File webInfDir, String initialDataChoice) { File chargementInitialDir = new File(webInfDir, "chargementInitial"); File fichierChargement = new File(chargementInitialDir, "ScriptChargementInitial.sql"); File fichierChargementAll = new File(chargementInitialDir, "ScriptChargementInitial-All.sql"); File fichierChargementTypesDocument = new File(chargementInitialDir, "ScriptChargementInitial-TypesDocument.sql"); File fichierChargementVide = new File(chargementInitialDir, "ScriptChargementInitial-Vide.sql"); if (fichierChargement.exists()) { fichierChargement.delete(); } File fichierUtilise = null; if ("all".equals(initialDataChoice)) { fichierUtilise = fichierChargementAll; } else if ("typesDocument".equals(initialDataChoice)) { fichierUtilise = fichierChargementTypesDocument; } else if ("empty".equals(initialDataChoice)) { fichierUtilise = fichierChargementVide; } if (fichierUtilise != null && fichierUtilise.exists()) { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(fichierUtilise).getChannel(); destination = new FileOutputStream(fichierChargement).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (Exception e) { throw new RuntimeException(e); } finally { if (source != null) { try { source.close(); } catch (Exception e) { e.printStackTrace(); } } if (destination != null) { try { destination.close(); } catch (Exception e) { e.printStackTrace(); } } } } } Code Sample 2: public static void fileTrans(String filePath, String urlString, String urlString2, String serverIp, int port) { try { URL url = new URL(urlString); url.openStream(); } catch (Exception e) { e.printStackTrace(); } File file = new File(filePath); try { FileInputStream fis = new FileInputStream(file); Socket server = new Socket(InetAddress.getByName(serverIp), port); OutputStream outputStream = server.getOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(outputStream)); byte[] buffer = new byte[2048]; int num = fis.read(buffer); while (num != -1) { dataOutputStream.write(buffer, 0, num); dataOutputStream.flush(); num = fis.read(buffer); } fis.close(); dataOutputStream.close(); server.close(); } catch (Exception e) { e.printStackTrace(); } try { URL url2 = new URL(urlString2); url2.openStream(); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public void constructAssociationView() { String className; String methodName; String field; boolean foundRead = false; boolean foundWrite = false; boolean classWritten = false; try { AssocView = new BufferedWriter(new FileWriter("InfoFiles/AssociationView.txt")); FileInputStream fstreamPC = new FileInputStream("InfoFiles/PrincipleClassGroup.txt"); DataInputStream inPC = new DataInputStream(fstreamPC); BufferedReader PC = new BufferedReader(new InputStreamReader(inPC)); while ((field = PC.readLine()) != null) { className = field; AssocView.write(className); AssocView.newLine(); classWritten = true; while ((methodName = PC.readLine()) != null) { if (methodName.contentEquals("EndOfClass")) break; AssocView.write("StartOfMethod"); AssocView.newLine(); AssocView.write(methodName); AssocView.newLine(); for (int i = 0; i < readFileCount && foundRead == false; i++) { if (methodName.compareTo(readArray[i]) == 0) { foundRead = true; for (int j = 1; readArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (readArray[i + j].indexOf(".") > 0) { field = readArray[i + j].substring(0, readArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(readArray[i + j]); AssocView.newLine(); } } } } } for (int i = 0; i < writeFileCount && foundWrite == false; i++) { if (methodName.compareTo(writeArray[i]) == 0) { foundWrite = true; for (int j = 1; writeArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (writeArray[i + j].indexOf(".") > 0) { field = writeArray[i + j].substring(0, writeArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(writeArray[i + j]); AssocView.newLine(); } } } } } AssocView.write("EndOfMethod"); AssocView.newLine(); foundRead = false; foundWrite = false; } if (classWritten == true) { AssocView.write("EndOfClass"); AssocView.newLine(); classWritten = false; } } PC.close(); AssocView.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: protected void copyFile(final String sourceFileName, final File path) throws IOException { final File source = new File(sourceFileName); final File destination = new File(path, source.getName()); FileChannel srcChannel = null; FileChannel dstChannel = null; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); srcChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(destination); dstChannel = fileOutputStream.getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { try { if (dstChannel != null) { dstChannel.close(); } } catch (Exception exception) { } try { if (srcChannel != null) { srcChannel.close(); } } catch (Exception exception) { } try { fileInputStream.close(); } catch (Exception exception) { } try { fileOutputStream.close(); } catch (Exception exception) { } } }
11
Code Sample 1: private String getCoded(String pass) { String passSecret = ""; try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(pass.getBytes("UTF8")); byte s[] = m.digest(); for (int i = 0; i < s.length; i++) { passSecret += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6); } } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return passSecret; } Code Sample 2: public static String getHash(String plaintext) { String hash = null; try { String text = plaintext; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); md.update(text.getBytes("UTF-8")); byte[] rawBytes = md.digest(); hash = new BASE64Encoder().encode(rawBytes); } catch (NoSuchAlgorithmException e) { } } catch (IOException e) { } return hash; }
11
Code Sample 1: public static String getStringFromInputStream(InputStream in) throws Exception { CachedOutputStream bos = new CachedOutputStream(); IOUtils.copy(in, bos); in.close(); bos.close(); return bos.getOut().toString(); } Code Sample 2: protected int sendData(String submitName, String submitValue) throws HttpException, IOException, SAXException { PostMethod postMethod = null; try { postMethod = new PostMethod(getDocumentBase().toString()); postMethod.getParams().setCookiePolicy(org.apache.commons.httpclient.cookie.CookiePolicy.IGNORE_COOKIES); postMethod.addRequestHeader("Cookie", getWikiPrefix() + "_session=" + getSession() + "; " + getWikiPrefix() + "UserID=" + getUserId() + "; " + getWikiPrefix() + "UserName=" + getUserName() + "; "); List<Part> parts = new ArrayList<Part>(); for (String s : new String[] { "wpSection", "wpEdittime", "wpScrolltop", "wpStarttime", "wpEditToken" }) { parts.add(new StringPart(s, StringEscapeUtils.unescapeJava(getNonNullParameter(s)))); } parts.add(new StringPart("action", "edit")); parts.add(new StringPart("wpTextbox1", getArticleContent())); parts.add(new StringPart("wpSummary", getSummary())); parts.add(new StringPart("wpAutoSummary", Digest.MD5.isImplemented() ? Digest.MD5.encrypt(getSummary()) : "")); parts.add(new StringPart(submitName, submitValue)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), postMethod.getParams()); postMethod.setRequestEntity(requestEntity); int status = getHttpClient().executeMethod(postMethod); IOUtils.copyTo(postMethod.getResponseBodyAsStream(), System.err); return status; } catch (HttpException err) { throw err; } catch (IOException err) { throw err; } finally { if (postMethod != null) postMethod.releaseConnection(); } }
11
Code Sample 1: public static boolean copyFile(File from, File tu) { final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(tu); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { return false; } return true; } Code Sample 2: public static void copy(String sourceName, String destName, StatusWindow status) throws IOException { File src = new File(sourceName); File dest = new File(destName); BufferedInputStream source = null; BufferedOutputStream destination = null; byte[] buffer; int bytes_read; long byteCount = 0; if (!src.exists()) throw new IOException("Source not found: " + src); if (!src.canRead()) throw new IOException("Source is unreadable: " + src); if (src.isFile()) { if (!dest.exists()) { File parentdir = Utils.parent(dest); if (!parentdir.exists()) parentdir.mkdir(); } else if (dest.isDirectory()) { if (src.isDirectory()) dest = new File(dest + File.separator + src); else dest = new File(dest + File.separator + src.getName()); } } else if (src.isDirectory()) { if (dest.isFile()) throw new IOException("Cannot copy directory " + src + " to file " + dest); if (!dest.exists()) dest.mkdir(); } if ((!dest.canWrite()) && (dest.exists())) throw new IOException("Destination is unwriteable: " + dest); if (src.isFile()) { try { if (status != null) { status.setMaximum(100); status.setMessage(Utils.trimFileName(src.toString(), 40), 50); } source = new BufferedInputStream(new FileInputStream(src)); destination = new BufferedOutputStream(new FileOutputStream(dest)); buffer = new byte[4096]; byteCount = 0; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (status != null) { status.setMessage(Utils.trimFileName(src.toString(), 40), 100); } if (source != null) source.close(); if (destination != null) destination.close(); } } else if (src.isDirectory()) { String targetfile, target, targetdest; String[] files = src.list(); if (status != null) { status.setMaximum(files.length); } for (int i = 0; i < files.length; i++) { if (status != null) { status.setMessage(Utils.trimFileName(src.toString(), 40), i); } targetfile = files[i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File(target)).isDirectory()) { copy(new File(target).getCanonicalPath(), new File(targetdest).getCanonicalPath(), status); } else { try { byteCount = 0; source = new BufferedInputStream(new FileInputStream(target)); destination = new BufferedOutputStream(new FileOutputStream(targetdest)); buffer = new byte[4096]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } } } }
11
Code Sample 1: public ArrayList parseFile(File newfile) throws IOException { String s; String firstName; String header; String name = null; Integer PVLoggerID = new Integer(0); String[] tokens; int nvalues = 0; double num1, num2, num3; double xoffset = 1.0; double xdelta = 1.0; double yoffset = 1.0; double ydelta = 1.0; double zoffset = 1.0; double zdelta = 1.0; boolean readfit = false; boolean readraw = false; boolean zerodata = false; boolean baddata = false; boolean harpdata = false; ArrayList fitparams = new ArrayList(); ArrayList xraw = new ArrayList(); ArrayList yraw = new ArrayList(); ArrayList zraw = new ArrayList(); ArrayList sraw = new ArrayList(); ArrayList sxraw = new ArrayList(); ArrayList syraw = new ArrayList(); ArrayList szraw = new ArrayList(); URL url = newfile.toURI().toURL(); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while ((s = br.readLine()) != null) { tokens = s.split("\\s+"); nvalues = tokens.length; firstName = (String) tokens[0]; if (((String) tokens[0]).length() == 0) { readraw = false; readfit = false; continue; } if ((nvalues == 4) && (!firstName.startsWith("---"))) { if ((Double.parseDouble(tokens[1]) == 0.) && (Double.parseDouble(tokens[2]) == 0.) && (Double.parseDouble(tokens[3]) == 0.)) { zerodata = true; } else { zerodata = false; } if (tokens[1].equals("NaN") || tokens[2].equals("NaN") || tokens[3].equals("NaN")) { baddata = true; } else { baddata = false; } } if (firstName.startsWith("start")) { header = s; } if (firstName.indexOf("WS") > 0) { if (name != null) { dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw); } name = tokens[0]; readraw = false; readfit = false; zerodata = false; baddata = false; harpdata = false; fitparams.clear(); xraw.clear(); yraw.clear(); zraw.clear(); sraw.clear(); sxraw.clear(); syraw.clear(); szraw.clear(); } if (firstName.startsWith("Area")) ; if (firstName.startsWith("Ampl")) ; if (firstName.startsWith("Mean")) ; if (firstName.startsWith("Sigma")) { fitparams.add(new Double(Double.parseDouble(tokens[3]))); fitparams.add(new Double(Double.parseDouble(tokens[1]))); fitparams.add(new Double(Double.parseDouble(tokens[5]))); } if (firstName.startsWith("Offset")) ; if (firstName.startsWith("Slope")) ; if ((firstName.equals("Position")) && (((String) tokens[2]).equals("Raw"))) { readraw = true; continue; } if ((firstName.equals("Position")) && (((String) tokens[2]).equals("Fit"))) { readfit = true; continue; } if ((firstName.contains("Harp"))) { xraw.clear(); yraw.clear(); zraw.clear(); sraw.clear(); sxraw.clear(); syraw.clear(); szraw.clear(); harpdata = true; readraw = true; name = tokens[0]; continue; } if (firstName.startsWith("---")) continue; if (harpdata == true) { if (((String) tokens[0]).length() != 0) { if (firstName.startsWith("PVLogger")) { try { PVLoggerID = new Integer(Integer.parseInt(tokens[2])); } catch (NumberFormatException e) { } } else { sxraw.add(new Double(Double.parseDouble(tokens[0]))); xraw.add(new Double(Double.parseDouble(tokens[1]))); syraw.add(new Double(Double.parseDouble(tokens[2]))); yraw.add(new Double(Double.parseDouble(tokens[3]))); szraw.add(new Double(Double.parseDouble(tokens[4]))); zraw.add(new Double(Double.parseDouble(tokens[5]))); } } continue; } if (readraw && (!zerodata) && (!baddata)) { sraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); sxraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); syraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); szraw.add(new Double(Double.parseDouble(tokens[0]))); yraw.add(new Double(Double.parseDouble(tokens[1]))); zraw.add(new Double(Double.parseDouble(tokens[2]))); xraw.add(new Double(Double.parseDouble(tokens[3]))); } if (firstName.startsWith("PVLogger")) { try { PVLoggerID = new Integer(Integer.parseInt(tokens[2])); } catch (NumberFormatException e) { } } } dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw); wiredata.add((Integer) PVLoggerID); return wiredata; } Code Sample 2: public static void main(String argv[]) { try { if (argv.length != 1 && argv.length != 3) { usage(); System.exit(1); } URL url = new URL(argv[0]); URLConnection conn; conn = url.openConnection(); if (conn.getHeaderField("WWW-Authenticate") != null) { auth(conn, argv[1], argv[2]); } else { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) System.out.println(line); } } catch (Exception ex) { ex.printStackTrace(); } }
00
Code Sample 1: public static void zip(ZipOutputStream out, File f, String base) throws Exception { if (f.isDirectory()) { File[] fl = f.listFiles(); base = base.length() == 0 ? "" : base + File.separator; for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + fl[i].getName()); } } else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); FileInputStream in = new FileInputStream(f); IOUtils.copyStream(in, out); in.close(); } Thread.sleep(10); } Code Sample 2: public void loadProperties() throws IOException { File file = new File(filename); URL url = file.toURI().toURL(); Properties temp = new Properties(); temp.load(url.openStream()); Point2d start = new Point2d(); Point2d end = new Point2d(); if (temp.getProperty("StartX") != null) try { start.x = Double.valueOf(temp.getProperty("StartX")); } catch (Exception e) { System.out.println("Error loading StartX - leaving as default: " + e); } if (temp.getProperty("StartY") != null) try { start.y = Double.valueOf(temp.getProperty("StartY")); } catch (Exception e) { System.out.println("Error loading StartY - leaving as default: " + e); } if (temp.getProperty("EndX") != null) try { end.x = Double.valueOf(temp.getProperty("EndX")); } catch (Exception e) { System.out.println("Error loading EndX - leaving as default: " + e); } if (temp.getProperty("EndY") != null) try { end.y = Double.valueOf(temp.getProperty("EndY")); } catch (Exception e) { System.out.println("Error loading EndY - leaving as default: " + e); } initialline = new LineSegment2D(start, end); if (temp.getProperty("ReferenceImage") != null) try { referenceimage = Integer.valueOf(temp.getProperty("ReferenceImage")); } catch (Exception e) { System.out.println("Error loading ReferenceImage - leaving as default: " + e); } }
11
Code Sample 1: @Override public String toString() { String charsetName = getCharsetName(); if (charsetName == null) charsetName = "ISO-8859-1"; try { if (unzip) { GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); ByteArrayOutputStream unzippedResult = new ByteArrayOutputStream(); IOUtils.copy(gzipInputStream, unzippedResult); return unzippedResult.toString(charsetName); } else { return byteArrayOutputStream.toString(charsetName); } } catch (UnsupportedEncodingException e) { throw new OutputException(e); } catch (IOException e) { throw new OutputException(e); } } Code Sample 2: public void testRenderRules() { try { MappingManager manager = new MappingManager(); OWLOntologyManager omanager = OWLManager.createOWLOntologyManager(); OWLOntology srcOntology; OWLOntology targetOntology; manager.loadMapping(rulesDoc.toURL()); srcOntology = omanager.loadOntologyFromPhysicalURI(srcURI); targetOntology = omanager.loadOntologyFromPhysicalURI(targetURI); manager.setSourceOntology(srcOntology); manager.setTargetOntology(targetOntology); Graph srcGraph = manager.getSourceGraph(); Graph targetGraph = manager.getTargetGraph(); System.out.println("Starting to render..."); FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.BLUES); factory.visit(srcGraph); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); System.out.println("View updated with graph..."); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); System.out.println("Finished writing"); writer.close(); System.out.println("Finished render... XML is:"); System.out.println(writer.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (OWLOntologyCreationException e) { e.printStackTrace(); } }
11
Code Sample 1: public void decryptFile(String encryptedFile, String decryptedFile, String password) throws Exception { CipherInputStream in; OutputStream out; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(password.getBytes(), "DES"); cipher.init(Cipher.DECRYPT_MODE, key); in = new CipherInputStream(new FileInputStream(encryptedFile), cipher); out = new FileOutputStream(decryptedFile); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); } Code Sample 2: @Test public void testEncryptDecrypt() throws IOException { BlockCipher cipher = new SerpentEngine(); Random rnd = new Random(); byte[] key = new byte[256 / 8]; rnd.nextBytes(key); byte[] iv = new byte[cipher.getBlockSize()]; rnd.nextBytes(iv); byte[] data = new byte[1230000]; new Random().nextBytes(data); ByteArrayOutputStream bout = new ByteArrayOutputStream(); CryptOutputStream eout = new CryptOutputStream(bout, cipher, key); eout.write(data); eout.close(); byte[] eData = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(eData); CryptInputStream din = new CryptInputStream(bin, cipher, key); bout = new ByteArrayOutputStream(); IOUtils.copy(din, bout); eData = bout.toByteArray(); Assert.assertTrue(Arrays.areEqual(data, eData)); }
11
Code Sample 1: private ArrayList<String> getYearsAndMonths() { String info = ""; ArrayList<String> items = new ArrayList<String>(); try { obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Obtaining_Data")); URL url = new URL(URL_ROUTE_VIEWS); URLConnection conn = url.openConnection(); conn.setDoOutput(false); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (!line.equals("")) info += line + "%"; } obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Processing_Data")); info = Patterns.removeTags(info); StringTokenizer st = new StringTokenizer(info, "%"); info = ""; boolean alternador = false; int index = 1; while (st.hasMoreTokens()) { String token = st.nextToken(); if (!token.trim().equals("")) { int pos = token.indexOf("/"); if (pos != -1) { token = token.substring(1, pos); if (Patterns.hasFormatYYYYdotMM(token)) { items.add(token); } } } } rd.close(); } catch (Exception e) { e.printStackTrace(); } return items; } Code Sample 2: protected String getManualDownloadURL() { if (_newestVersionString.indexOf("weekly") > 0) { return "http://www.cs.rice.edu/~javaplt/drjavarice/weekly/"; } final String DRJAVA_FILES_PAGE = "http://sourceforge.net/project/showfiles.php?group_id=44253"; final String LINK_PREFIX = "<a href=\"/project/showfiles.php?group_id=44253"; final String LINK_SUFFIX = "\">"; BufferedReader br = null; try { URL url = new URL(DRJAVA_FILES_PAGE); InputStream urls = url.openStream(); InputStreamReader is = new InputStreamReader(urls); br = new BufferedReader(is); String line; int pos; while ((line = br.readLine()) != null) { if ((pos = line.indexOf(_newestVersionString)) >= 0) { int prePos = line.indexOf(LINK_PREFIX); if ((prePos >= 0) && (prePos < pos)) { int suffixPos = line.indexOf(LINK_SUFFIX, prePos); if ((suffixPos >= 0) && (suffixPos + LINK_SUFFIX.length() == pos)) { String versionLink = edu.rice.cs.plt.text.TextUtil.xmlUnescape(line.substring(prePos + LINK_PREFIX.length(), suffixPos)); return DRJAVA_FILES_PAGE + versionLink; } } } } ; } catch (IOException e) { return DRJAVA_FILES_PAGE; } finally { try { if (br != null) br.close(); } catch (IOException e) { } } return DRJAVA_FILES_PAGE; }
00
Code Sample 1: public static String md5Encrypt(final String txt) { String enTxt = txt; MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("Error:", e); } if (null != md) { byte[] md5hash = new byte[32]; try { md.update(txt.getBytes("UTF-8"), 0, txt.length()); } catch (UnsupportedEncodingException e) { logger.error("Error:", e); } md5hash = md.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < md5hash.length; i++) { if (Integer.toHexString(0xFF & md5hash[i]).length() == 1) { md5StrBuff.append("0").append(Integer.toHexString(0xFF & md5hash[i])); } else { md5StrBuff.append(Integer.toHexString(0xFF & md5hash[i])); } } enTxt = md5StrBuff.toString(); } return enTxt; } Code Sample 2: public static boolean copyFile(File from, File to, byte[] buf) { if (buf == null) buf = new byte[BUFFER_SIZE]; FileInputStream from_s = null; FileOutputStream to_s = null; try { from_s = new FileInputStream(from); to_s = new FileOutputStream(to); for (int bytesRead = from_s.read(buf); bytesRead != -1; bytesRead = from_s.read(buf)) to_s.write(buf, 0, bytesRead); from_s.close(); from_s = null; to_s.getFD().sync(); to_s.close(); to_s = null; } catch (IOException ioe) { return false; } finally { if (from_s != null) { try { from_s.close(); } catch (IOException ioe) { } } if (to_s != null) { try { to_s.close(); } catch (IOException ioe) { } } } return true; }
11
Code Sample 1: private void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: private static void copy(File source, File target) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(target).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
11
Code Sample 1: private static boolean computeCustomerAverages(String completePath, String CustomerAveragesOutputFileName, String CustIndexFileName) { try { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); TIntObjectHashMap CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int startIndex, endIndex; TIntArrayList a; int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustomerAveragesOutputFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); int totalCusts = CustomerLimitsTHash.size(); File movieMMAPDATAFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "MovieRatingBinaryFile.txt"); inC = new FileInputStream(movieMMAPDATAFile).getChannel(); int[] itr = CustomerLimitsTHash.keys(); startIndex = 0; endIndex = 0; a = null; ByteBuffer buf; for (int i = 0; i < totalCusts; i++) { int currentCust = itr[i]; a = (TIntArrayList) CustomerLimitsTHash.get(currentCust); startIndex = a.get(0); endIndex = a.get(1); if (endIndex > startIndex) { buf = ByteBuffer.allocate((endIndex - startIndex + 1) * 3); inC.read(buf, (startIndex - 1) * 3); } else { buf = ByteBuffer.allocate(3); inC.read(buf, (startIndex - 1) * 3); } buf.flip(); int bufsize = buf.capacity() / 3; float sum = 0; for (int q = 0; q < bufsize; q++) { buf.getShort(); sum += buf.get(); } ByteBuffer outbuf = ByteBuffer.allocate(8); outbuf.putInt(currentCust); outbuf.putFloat(sum / bufsize); outbuf.flip(); outC.write(outbuf); buf.clear(); buf = null; a.clear(); a = null; } inC.close(); outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } Code Sample 2: public String fileUpload(final ResourceType type, final String currentFolder, final String fileName, final InputStream inputStream) throws InvalidCurrentFolderException, WriteException { String absolutePath = getRealUserFilesAbsolutePath(RequestCycleHandler.getUserFilesAbsolutePath(ThreadLocalData.getRequest())); File typeDir = getOrCreateResourceTypeDir(absolutePath, type); File currentDir = new File(typeDir, currentFolder); if (!currentDir.exists() || !currentDir.isDirectory()) throw new InvalidCurrentFolderException(); File newFile = new File(currentDir, fileName); File fileToSave = UtilsFile.getUniqueFile(newFile.getAbsoluteFile()); try { IOUtils.copyLarge(inputStream, new FileOutputStream(fileToSave)); } catch (IOException e) { throw new WriteException(); } return fileToSave.getName(); }
00
Code Sample 1: public void run() { date = DateUtil.addMonth(-1); List list = bo.getDao().getHibernateTemplate().find("from MailAffixPojo where upload_time <'" + date + "' and to_number(sized) >" + size); if (null != list && list.size() > 0) { try { FTPClient ftp = new FTPClient(); ftp.connect(config.getHostUrl(), config.getFtpPort()); ftp.login(config.getUname(), config.getUpass()); int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { ftp.disconnect(); return; } for (int i = 0; i < list.size(); i++) { MailAffixPojo pojo = (MailAffixPojo) list.get(i); ftp.changeWorkingDirectory(pojo.getUploadTime().substring(0, 7)); ftp.deleteFile(pojo.getAffixSaveName()); ftp.changeToParentDirectory(); bo.delete(MailAffixPojo.class, new Long(pojo.getId())); } } catch (Exception e) { e.printStackTrace(); } } } Code Sample 2: public static URL getAuthenticationURL(String apiKey, String permission, String sharedSecret) throws Exception { String apiSig = sharedSecret + "api_key" + apiKey + "perms" + permission; MessageDigest m = MessageDigest.getInstance("MD5"); m.update(apiSig.getBytes(), 0, apiSig.length()); apiSig = new BigInteger(1, m.digest()).toString(16); StringBuffer buffer = new StringBuffer(); buffer.append("http://flickr.com/services/auth/?"); buffer.append("api_key=" + apiKey); buffer.append("&").append("perms=").append(permission); buffer.append("&").append("api_sig=").append(apiSig); return new URL(buffer.toString()); }
00
Code Sample 1: public static void copyFile(String fromFilePath, String toFilePath, boolean overwrite) throws IOException { File fromFile = new File(fromFilePath); File toFile = new File(toFilePath); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFilePath); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFilePath); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFilePath); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!overwrite) { throw new IOException(toFilePath + " already exists!"); } if (!toFile.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + toFilePath); } String parent = toFile.getParent(); if (parent == null) { parent = System.getProperty("user.dir"); } File dir = new File(parent); if (!dir.exists()) { throw new IOException("FileCopy: destination directory doesn't exist: " + parent); } if (dir.isFile()) { throw new IOException("FileCopy: destination is not a directory: " + parent); } if (!dir.canWrite()) { throw new IOException("FileCopy: destination directory is unwriteable: " + parent); } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { long lastModified = fromFile.lastModified(); toFile.setLastModified(lastModified); if (from != null) { try { from.close(); } catch (IOException e) { } } if (to != null) { try { to.close(); } catch (IOException e) { } } } } Code Sample 2: private boolean undefSeqLen = true; private boolean undefItemLen = true; private boolean fmi = true; /** Creates a new instance of Acr2Dcm */ public Acr2Dcm() { } public void setStudyUID(String uid) { this.studyUID = uid; } public void setSeriesUID(String uid) { this.seriesUID = uid; } public void setInstUID(String uid) { this.instUID = uid; } public void setClassUID(String uid) { this.classUID = uid; } public void setSkipGroupLen(boolean skipGroupLen) {
11
Code Sample 1: public static final void copy(String source, String destination) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } catch (FileNotFoundException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } } Code Sample 2: public File nextEntry() { try { while (hasNext()) { String name = waitingArchEntry.getName(); name = name.substring(name.indexOf("/") + 1); File file = new File(targetDir.getAbsolutePath() + "/" + name); if (waitingArchEntry.isDirectory()) { file.mkdirs(); waitingArchEntry = ais.getNextEntry(); } else { OutputStream os = new FileOutputStream(file); try { IOUtils.copy(ais, os); } finally { IOUtils.closeQuietly(os); } return file; } } } catch (IOException e) { return null; } return null; }
11
Code Sample 1: private void loadMap(URI uri) throws IOException { BufferedReader reader = null; InputStream stream = null; try { URL url = uri.toURL(); stream = url.openStream(); if (url.getFile().endsWith(".gz")) { stream = new GZIPInputStream(stream); } reader = new BufferedReader(new InputStreamReader(stream)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.length() > 0) { String[] parts = line.split(" "); if (parts.length == 2) { pinyinZhuyinMap.put(parts[0], parts[1]); zhuyinPinyinMap.put(parts[1], parts[0]); } } } } finally { if (reader != null) { reader.close(); } } } Code Sample 2: protected String getPostRequestContent(String urlText, String postParam) throws Exception { URL url = new URL(urlText); HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); urlcon.setRequestMethod("POST"); urlcon.setUseCaches(false); urlcon.setDoOutput(true); PrintStream ps = new PrintStream(urlcon.getOutputStream()); ps.print(postParam); ps.close(); urlcon.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream())); String line = reader.readLine(); reader.close(); urlcon.disconnect(); return line; }
11
Code Sample 1: public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); } Code Sample 2: public static String generateHash(String message) throws NoSuchAlgorithmException, UnsupportedEncodingException, DigestException { MessageDigest digest; digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(message.getBytes("iso-8859-1"), 0, message.length()); byte[] output = new byte[20]; digest.digest(output, 0, output.length); return convertToHex(output); }
11
Code Sample 1: public void run() { StringBuffer xml; String tabName; Element guiElement; setBold(monitor.getReading()); setBold(monitor.getReadingStatus()); monitor.getReadingStatus().setText(" Working"); HttpMethod method = null; xml = new StringBuffer(); File tempfile = new File(url); if (tempfile.exists()) { try { InputStream in = new FileInputStream(tempfile); int temp; while ((temp = in.read()) != -1) { xml.append((char) temp); } in.close(); } catch (IOException e) { System.out.println("Loading Monitor Failed, error while reading XML file from local file"); e.printStackTrace(System.err); return; } } else { try { HttpClient client = new HttpClient(); method = new GetMethod(url); int response = client.executeMethod(method); if (response == 200) { InputStream in = method.getResponseBodyAsStream(); int temp; while ((temp = in.read()) != -1) { xml.append((char) temp); } in.close(); } else { if (method != null) { method.releaseConnection(); } System.out.println("Loading Monitor Failed. Incorrect response from HTTP Server " + response); return; } } catch (IOException e) { if (method != null) { method.releaseConnection(); } System.out.println("Loading Monitor Failed, error while reading XML file from HTTP Server"); e.printStackTrace(System.err); return; } } setPlain(monitor.getReading()); setPlain(monitor.getReadingStatus()); monitor.getReadingStatus().setText(" Done"); setBold(monitor.getValidating()); setBold(monitor.getValidatingStatus()); monitor.getValidatingStatus().setText(" Working"); DocumentBuilderFactoryImpl factory = new DocumentBuilderFactoryImpl(); try { DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.parse(new ByteArrayInputStream(xml.toString().getBytes())); if (method != null) { method.releaseConnection(); } Element root = document.getDocumentElement(); NodeList temp = root.getElementsByTagName("resource"); for (int j = 0; j < temp.getLength(); j++) { Element resource = (Element) temp.item(j); resources.add(new URL(resource.getAttribute("url"))); } NodeList connections = root.getElementsByTagName("jmxserver"); for (int j = 0; j < connections.getLength(); j++) { Element connection = (Element) connections.item(j); String name = connection.getAttribute("name"); String tempUrl = connection.getAttribute("url"); String auth = connection.getAttribute("auth"); if (tempUrl.indexOf("${host}") != -1) { HostDialog dialog = new HostDialog(Config.getHosts()); String host = dialog.showDialog(); if (host == null) { System.out.println("Host can not be null, unable to create panel."); return; } tempUrl = tempUrl.replaceAll("\\$\\{host\\}", host); Config.addHost(host); } JMXServiceURL jmxUrl = new JMXServiceURL(tempUrl); JmxServerGraph server = new JmxServerGraph(name, jmxUrl, new JmxWorker(false)); if (auth != null && auth.equalsIgnoreCase("true")) { LoginTrueService loginService = new LoginTrueService(); JXLoginPanel.Status status = JXLoginPanel.showLoginDialog(null, loginService); if (status != JXLoginPanel.Status.SUCCEEDED) { return; } server.setUsername(loginService.getName()); server.setPassword(loginService.getPassword()); } servers.put(name, server); NodeList listeners = connection.getElementsByTagName("listener"); for (int i = 0; i < listeners.getLength(); i++) { Element attribute = (Element) listeners.item(i); String taskname = attribute.getAttribute("taskname"); MBean mbean = new MBean(attribute.getAttribute("mbean"), null); String filtertype = attribute.getAttribute("filterType"); TaskNotificationListener listener = new TaskNotificationListener(); NotificationFilterSupport filter = new NotificationFilterSupport(); if (filtertype == null || "".equals(filtertype)) { filter = null; } else { filter.enableType(filtertype); } Task task = new Task(-1, Task.LISTEN, server); task.setMbean(mbean); task.setListener(listener); task.setFilter(filter); server.getWorker().addTask(task); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); tasks.put(taskname, hashTempList); } NodeList attributes = connection.getElementsByTagName("attribute"); for (int i = 0; i < attributes.getLength(); i++) { Element attribute = (Element) attributes.item(i); String taskname = attribute.getAttribute("taskname"); MBean mbean = new MBean(attribute.getAttribute("mbean"), null); String attributename = attribute.getAttribute("attributename"); String frequency = attribute.getAttribute("frequency"); String onEvent = attribute.getAttribute("onEvent"); if (frequency.equalsIgnoreCase("onchange")) { TaskNotificationListener listener = new TaskNotificationListener(); AttributeChangeNotificationFilter filter = new AttributeChangeNotificationFilter(); filter.enableAttribute(attributename); Task task = new Task(-1, Task.LISTEN, server); MBeanAttribute att = new MBeanAttribute(mbean, attributename); task.setAttribute(att); task.setMbean(mbean); task.setListener(listener); task.setFilter(filter); server.getWorker().addTask(task); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } Task task2 = new Task(-1, Task.GET_ATTRIBUTE, server); task2.setAttribute(att); task2.setMbean(mbean); server.getWorker().addTask(task2); List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); hashTempList.add(task2); tasks.put(taskname, hashTempList); } else { int frequency2 = Integer.parseInt(frequency); Task task = new Task(frequency2, Task.GET_ATTRIBUTE, server); MBeanAttribute att = new MBeanAttribute(mbean, attributename); task.setAttribute(att); task.setMbean(mbean); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); tasks.put(taskname, hashTempList); TaskNotificationListener listener = null; if (onEvent != null && !"".equals(onEvent)) { Task tempTask = tasks.get(onEvent).get(0); if (tempTask == null) { System.out.println(onEvent + " was not found."); return; } else { listener = (TaskNotificationListener) tempTask.getListener(); } } if (listener == null) { server.getWorker().addTask(task); } else { listener.addTask(task); } } } } NodeList guiTemp = root.getElementsByTagName("gui"); guiElement = (Element) guiTemp.item(0); tabName = guiElement.getAttribute("name"); if (MonitorServer.contains(tabName)) { JOptionPane.showMessageDialog(null, "This panel is already open, stoping creating of panel.", "Panel already exists", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < monitor.getTab().getTabCount(); i++) { if (monitor.getTab().getComponent(i).equals(monitor)) { monitor.getTab().setTitleAt(i, tabName); break; } } NodeList tempBindings = root.getElementsByTagName("binding"); for (int i = 0; i < tempBindings.getLength(); i++) { Element binding = (Element) tempBindings.item(i); String guiname = binding.getAttribute("guiname"); String tmethod = binding.getAttribute("method"); String taskname = binding.getAttribute("taskname"); String formater = binding.getAttribute("formater"); BindingContainer tempBinding; if (formater == null || (formater != null && formater.equals(""))) { tempBinding = new BindingContainer(guiname, tmethod, taskname); } else { tempBinding = new BindingContainer(guiname, tmethod, taskname, formater); } bindings.add(tempBinding); } } catch (Exception e) { System.err.println("Exception message: " + e.getMessage()); System.out.println("Loading Monitor Failed, couldnt parse XML file."); e.printStackTrace(System.err); return; } setPlain(monitor.getValidating()); setPlain(monitor.getValidatingStatus()); monitor.getValidatingStatus().setText(" Done"); setBold(monitor.getDownload()); setBold(monitor.getDownloadStatus()); monitor.getDownloadStatus().setText(" Working"); List<File> jarFiles = new ArrayList<File>(); File cacheDir = new File(Config.getCacheDir()); if (!cacheDir.exists()) { cacheDir.mkdir(); } for (URL resUrl : resources) { try { HttpClient client = new HttpClient(); HttpMethod methodRes = new GetMethod(resUrl.toString()); int response = client.executeMethod(methodRes); if (response == 200) { int index = resUrl.toString().lastIndexOf("/") + 1; File file = new File(Config.getCacheDir() + resUrl.toString().substring(index)); FileOutputStream out = new FileOutputStream(file); InputStream in = methodRes.getResponseBodyAsStream(); int readTemp = 0; while ((readTemp = in.read()) != -1) { out.write(readTemp); } System.out.println(file.getName() + " downloaded."); methodRes.releaseConnection(); if (file.getName().endsWith(".jar")) { jarFiles.add(file); } } else { methodRes.releaseConnection(); System.out.println("Loading Monitor Failed. Unable to get resource " + url); return; } } catch (IOException e) { System.out.println("Loading Monitor Failed, error while reading resource file " + "from HTTP Server"); e.printStackTrace(System.err); return; } } URL[] urls = new URL[jarFiles.size()]; try { for (int i = 0; i < jarFiles.size(); i++) { File file = jarFiles.get(i); File newFile = new File(Config.getCacheDir() + "/" + System.currentTimeMillis() + file.getName()); FileInputStream in = new FileInputStream(file); FileOutputStream out = new FileOutputStream(newFile); int n = 0; byte[] buf = new byte[1024]; while ((n = in.read(buf, 0, 1024)) > -1) { out.write(buf, 0, n); } out.close(); out.close(); in.close(); urls[i] = new URL("file:" + newFile.getAbsolutePath()); } } catch (Exception e1) { System.out.println("Unable to load jar files."); e1.printStackTrace(); } URLClassLoader loader = new URLClassLoader(urls); engine.setClassLoader(loader); setPlain(monitor.getDownload()); setPlain(monitor.getDownloadStatus()); monitor.getDownloadStatus().setText(" Done"); setBold(monitor.getGui()); setBold(monitor.getGuiStatus()); monitor.getGuiStatus().setText(" Working"); Container container; try { String tempXml = xml.toString(); int start = tempXml.indexOf("<gui"); start = tempXml.indexOf('>', start) + 1; int end = tempXml.indexOf("</gui>"); container = engine.render(new StringReader(tempXml.substring(start, end))); } catch (Exception e) { e.printStackTrace(System.err); System.err.println("Exception msg: " + e.getMessage()); System.out.println("Loading Monitor Failed, error creating gui."); return; } for (BindingContainer bcon : bindings) { List<Task> temp = tasks.get(bcon.getTask()); if (temp == null) { System.out.println("Task with name " + bcon.getTask() + " doesnt exist."); } else { for (Task task : temp) { if (task != null) { Object comp = engine.find(bcon.getComponent()); if (comp != null) { if (task.getTaskType() == Task.LISTEN && task.getFilter() instanceof AttributeChangeNotificationFilter) { TaskNotificationListener listener = (TaskNotificationListener) task.getListener(); if (bcon.getFormater() == null) { listener.addResultListener(new Binding(comp, bcon.getMethod())); } else { listener.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader)); } } else { if (bcon.getFormater() == null) { task.addResultListener(new Binding(comp, bcon.getMethod())); } else { task.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader)); } } } else { System.out.println("Refering to gui name, " + bcon.getComponent() + ", that doesnt exist. Unable to create monitor."); return; } } else { System.out.println("Refering to task name, " + bcon.getTask() + ", that doesnt exist. Unable to create monitor."); return; } } } } for (int i = 0; i < monitor.getTab().getTabCount(); i++) { if (monitor.getTab().getComponent(i).equals(monitor)) { monitor.getTab().setComponentAt(i, new MonitorContainerPanel(container, this)); break; } } System.out.println("Connecting to server(s)."); Enumeration e = servers.keys(); List<JmxWorker> list = new ArrayList<JmxWorker>(); while (e.hasMoreElements()) { JmxWorker worker = servers.get(e.nextElement()).getWorker(); worker.setRunning(true); worker.start(); list.add(worker); } MonitorServer.add(tabName, list); Config.addUrl(url); } Code Sample 2: public static void copyFile(File src, File dest, int bufSize, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file: " + dest.getName()); } } byte[] buffer = new byte[bufSize]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } }
00
Code Sample 1: public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("DOWNLOAD - Send content: " + realFile.getAbsolutePath()); LOGGER.debug("Output stream: " + out.toString()); if (ServerConfiguration.isDynamicSEL()) { LOGGER.error("IS DINAMIC SEL????"); } else { } if (".tokens".equals(realFile.getName()) || ".response".equals(realFile.getName()) || ".request".equals(realFile.getName()) || isAllowedClient) { FileInputStream in = null; try { in = new FileInputStream(realFile); int bytes = IOUtils.copy(in, out); LOGGER.debug("System resource or Allowed Client wrote bytes: " + bytes); out.flush(); } catch (Exception e) { LOGGER.error("Error while downloading over encryption system " + realFile.getName() + " file", e); } finally { IOUtils.closeQuietly(in); } } else { } } Code Sample 2: @Override public void run() { YouTubeFeedParserHandler parserHandler = new YouTubeFeedParserHandler(); SAXParserFactory spf = SAXParserFactory.newInstance(); try { URL url = new URL(m_YouTubeFeedUrl); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(parserHandler); InputStream is = url.openStream(); InputSource input = new InputSource(is); xr.parse(input); } catch (MalformedURLException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: private static void ftpTest() { FTPClient f = new FTPClient(); try { f.connect("oscomak.net"); System.out.print(f.getReplyString()); f.setFileType(FTPClient.BINARY_FILE_TYPE); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String password = JOptionPane.showInputDialog("Enter password"); if (password == null || password.equals("")) { System.out.println("No password"); return; } try { f.login("oscomak_pointrel", password); System.out.print(f.getReplyString()); } catch (IOException e) { e.printStackTrace(); } try { String workingDirectory = f.printWorkingDirectory(); System.out.println("Working directory: " + workingDirectory); System.out.print(f.getReplyString()); } catch (IOException e1) { e1.printStackTrace(); } try { f.enterLocalPassiveMode(); System.out.print(f.getReplyString()); System.out.println("Trying to list files"); String[] fileNames = f.listNames(); System.out.print(f.getReplyString()); System.out.println("Got file list fileNames: " + fileNames.length); for (String fileName : fileNames) { System.out.println("File: " + fileName); } System.out.println(); System.out.println("done reading stream"); System.out.println("trying alterative way to read stream"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); f.retrieveFile(fileNames[0], outputStream); System.out.println("size: " + outputStream.size()); System.out.println(outputStream.toString()); System.out.println("done with alternative"); System.out.println("Trying to store file back"); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); boolean storeResult = f.storeFile("test.txt", inputStream); System.out.println("Done storing " + storeResult); f.disconnect(); System.out.print(f.getReplyString()); System.out.println("disconnected"); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: @Test public void testSQLite() { log("trying SQLite.."); for (int i = 0; i < 10; i++) { Connection c = null; try { Class.forName("SQLite.JDBCDriver"); c = DriverManager.getConnection("jdbc:sqlite:/C:/Source/SRFSurvey/app/src/org/speakright/srfsurvey/results.db", "", ""); c.setAutoCommit(false); Statement st = c.createStatement(); int rc = st.executeUpdate("INSERT INTO tblAnswers(fQID,fQNAME) VALUES('q1','zoo')"); st.close(); c.commit(); c.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(1); try { if (c != null && !c.isClosed()) { c.rollback(); c.close(); } } catch (SQLException sql) { } } } log("end"); }
11
Code Sample 1: private String generateStorageDir(String stringToBeHashed) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(stringToBeHashed.getBytes()); byte[] hashedKey = digest.digest(); return Util.encodeArrayToHexadecimalString(hashedKey); } Code Sample 2: @edu.umd.cs.findbugs.annotations.SuppressWarnings({ "DLS", "REC" }) public static String md5Encode(String val) { String output = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(val.getBytes()); byte[] digest = md.digest(); output = base64Encode(digest); } catch (Exception e) { } return output; }
00
Code Sample 1: public AssemblyConfig load() { AssemblyConfig assembly = null; Digester digester = createParser(); try { if (inputStream != null) { if (logger.isDebugEnabled()) { logger.debug("XML config loader is parsing an inputstream:" + inputStream); } assembly = (AssemblyConfig) digester.parse(inputStream); } else if (file != null) { if (logger.isDebugEnabled()) { logger.debug("XML config loader is parsing a file:" + file); } assembly = (AssemblyConfig) digester.parse(file); } else { if (logger.isDebugEnabled()) { logger.debug("XML config loader is parsing a URI:" + uri); } URL url = new URL(uri); inputStream = url.openStream(); assembly = (AssemblyConfig) digester.parse(inputStream); } if (assembly != null) { logger.debug("Services from XML configuration are: "); logger.debug(assembly.toString()); } else { throw new AssemblyConfigException("Unable to parse the XML assembly configuration. " + "HINT: Please check the schema/grammar of the supplied " + "XML document and verify the XML namespace is correct."); } } catch (IOException ioe) { throw new AssemblyConfigException("I/O failure, unable to process configuration", ioe); } catch (SAXException sxe) { throw new AssemblyConfigException("XML Reader failure, unable to process configuration", sxe); } return assembly; } Code Sample 2: public static boolean nioWriteFile(FileInputStream inputStream, FileOutputStream out) { if (inputStream == null && out == null) { return false; } try { FileChannel fci = inputStream.getChannel(); FileChannel fco = out.getChannel(); fco.transferFrom(fci, 0, fci.size()); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { FileUtil.safeClose(inputStream); FileUtil.safeClose(out); } }
11
Code Sample 1: private static File copyJarToPool(File file) { File outFile = new File(RizzToolConstants.TOOL_POOL_FOLDER.getAbsolutePath() + File.separator + file.getName()); if (file != null && file.exists() && file.canRead()) { try { FileChannel inChan = new FileInputStream(file).getChannel(); FileChannel outChan = new FileOutputStream(outFile).getChannel(); inChan.transferTo(0, inChan.size(), outChan); return outFile; } catch (Exception ex) { RizzToolConstants.DEFAULT_LOGGER.error("Exception while copying jar file to tool pool [inFile=" + file.getAbsolutePath() + "] [outFile=" + outFile.getAbsolutePath() + ": " + ex); } } else { RizzToolConstants.DEFAULT_LOGGER.error("Could not copy jar file. File does not exist or can't read file. [inFile=" + file.getAbsolutePath() + "]"); } return null; } Code Sample 2: public static void copy(File src, File dest) throws IOException { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); }
00
Code Sample 1: @Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; } Code Sample 2: public static String openldapDigestMd5(final String password) { String base64; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); base64 = fr.cnes.sitools.util.Base64.encodeBytes(digest.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return OPENLDAP_MD5_PREFIX + base64; }
11
Code Sample 1: public static void copyAFile(final String entree, final String sortie) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(entree).getChannel(); out = new FileOutputStream(sortie).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } Code Sample 2: public void copyTo(Bean bean, OutputStream out, int offset, int length) throws Exception { BeanInfo beanInfo = getBeanInfo(bean.getClass()); validate(bean, beanInfo, "copyTo"); if (blobCache != null && length < MAX_BLOB_CACHE_LENGHT) { byte[] bytes = null; synchronized (this) { String key = makeUniqueKey(bean, beanInfo, offset, length); if (blobCache.contains(key)) bytes = (byte[]) blobCache.get(key); else blobCache.put(key, bytes = toByteArray(bean, offset, length, beanInfo)); } InputStream in = new ByteArrayInputStream(bytes); IOUtils.copy(in, out); in.close(); } else { jdbcManager.queryScript(beanInfo.getBlobInfo(jdbcManager.getDb()).getReadScript(), bean, new JdbcOutputStreamRowMapper(out, offset, length)); } }
11
Code Sample 1: private static byte[] Md5f(String plainText) { byte[] ab = new byte[16]; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); ab = b; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ab; } Code Sample 2: public boolean verifySignature() { try { byte[] data = readFile(name + ".tmp1.bin"); if (data == null) return false; if (data[data.length - 0x104] != 'N' || data[data.length - 0x103] != 'G' || data[data.length - 0x102] != 'I' || data[data.length - 0x101] != 'S') return false; byte[] signature = new byte[0x100]; byte[] module = new byte[data.length - 0x104]; System.arraycopy(data, data.length - 0x100, signature, 0, 0x100); System.arraycopy(data, 0, module, 0, data.length - 0x104); BigIntegerEx power = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { 0x01, 0x00, 0x01, 0x00 }); BigIntegerEx mod = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { (byte) 0x6B, (byte) 0xCE, (byte) 0xF5, (byte) 0x2D, (byte) 0x2A, (byte) 0x7D, (byte) 0x7A, (byte) 0x67, (byte) 0x21, (byte) 0x21, (byte) 0x84, (byte) 0xC9, (byte) 0xBC, (byte) 0x25, (byte) 0xC7, (byte) 0xBC, (byte) 0xDF, (byte) 0x3D, (byte) 0x8F, (byte) 0xD9, (byte) 0x47, (byte) 0xBC, (byte) 0x45, (byte) 0x48, (byte) 0x8B, (byte) 0x22, (byte) 0x85, (byte) 0x3B, (byte) 0xC5, (byte) 0xC1, (byte) 0xF4, (byte) 0xF5, (byte) 0x3C, (byte) 0x0C, (byte) 0x49, (byte) 0xBB, (byte) 0x56, (byte) 0xE0, (byte) 0x3D, (byte) 0xBC, (byte) 0xA2, (byte) 0xD2, (byte) 0x35, (byte) 0xC1, (byte) 0xF0, (byte) 0x74, (byte) 0x2E, (byte) 0x15, (byte) 0x5A, (byte) 0x06, (byte) 0x8A, (byte) 0x68, (byte) 0x01, (byte) 0x9E, (byte) 0x60, (byte) 0x17, (byte) 0x70, (byte) 0x8B, (byte) 0xBD, (byte) 0xF8, (byte) 0xD5, (byte) 0xF9, (byte) 0x3A, (byte) 0xD3, (byte) 0x25, (byte) 0xB2, (byte) 0x66, (byte) 0x92, (byte) 0xBA, (byte) 0x43, (byte) 0x8A, (byte) 0x81, (byte) 0x52, (byte) 0x0F, (byte) 0x64, (byte) 0x98, (byte) 0xFF, (byte) 0x60, (byte) 0x37, (byte) 0xAF, (byte) 0xB4, (byte) 0x11, (byte) 0x8C, (byte) 0xF9, (byte) 0x2E, (byte) 0xC5, (byte) 0xEE, (byte) 0xCA, (byte) 0xB4, (byte) 0x41, (byte) 0x60, (byte) 0x3C, (byte) 0x7D, (byte) 0x02, (byte) 0xAF, (byte) 0xA1, (byte) 0x2B, (byte) 0x9B, (byte) 0x22, (byte) 0x4B, (byte) 0x3B, (byte) 0xFC, (byte) 0xD2, (byte) 0x5D, (byte) 0x73, (byte) 0xE9, (byte) 0x29, (byte) 0x34, (byte) 0x91, (byte) 0x85, (byte) 0x93, (byte) 0x4C, (byte) 0xBE, (byte) 0xBE, (byte) 0x73, (byte) 0xA9, (byte) 0xD2, (byte) 0x3B, (byte) 0x27, (byte) 0x7A, (byte) 0x47, (byte) 0x76, (byte) 0xEC, (byte) 0xB0, (byte) 0x28, (byte) 0xC9, (byte) 0xC1, (byte) 0xDA, (byte) 0xEE, (byte) 0xAA, (byte) 0xB3, (byte) 0x96, (byte) 0x9C, (byte) 0x1E, (byte) 0xF5, (byte) 0x6B, (byte) 0xF6, (byte) 0x64, (byte) 0xD8, (byte) 0x94, (byte) 0x2E, (byte) 0xF1, (byte) 0xF7, (byte) 0x14, (byte) 0x5F, (byte) 0xA0, (byte) 0xF1, (byte) 0xA3, (byte) 0xB9, (byte) 0xB1, (byte) 0xAA, (byte) 0x58, (byte) 0x97, (byte) 0xDC, (byte) 0x09, (byte) 0x17, (byte) 0x0C, (byte) 0x04, (byte) 0xD3, (byte) 0x8E, (byte) 0x02, (byte) 0x2C, (byte) 0x83, (byte) 0x8A, (byte) 0xD6, (byte) 0xAF, (byte) 0x7C, (byte) 0xFE, (byte) 0x83, (byte) 0x33, (byte) 0xC6, (byte) 0xA8, (byte) 0xC3, (byte) 0x84, (byte) 0xEF, (byte) 0x29, (byte) 0x06, (byte) 0xA9, (byte) 0xB7, (byte) 0x2D, (byte) 0x06, (byte) 0x0B, (byte) 0x0D, (byte) 0x6F, (byte) 0x70, (byte) 0x9E, (byte) 0x34, (byte) 0xA6, (byte) 0xC7, (byte) 0x31, (byte) 0xBE, (byte) 0x56, (byte) 0xDE, (byte) 0xDD, (byte) 0x02, (byte) 0x92, (byte) 0xF8, (byte) 0xA0, (byte) 0x58, (byte) 0x0B, (byte) 0xFC, (byte) 0xFA, (byte) 0xBA, (byte) 0x49, (byte) 0xB4, (byte) 0x48, (byte) 0xDB, (byte) 0xEC, (byte) 0x25, (byte) 0xF3, (byte) 0x18, (byte) 0x8F, (byte) 0x2D, (byte) 0xB3, (byte) 0xC0, (byte) 0xB8, (byte) 0xDD, (byte) 0xBC, (byte) 0xD6, (byte) 0xAA, (byte) 0xA6, (byte) 0xDB, (byte) 0x6F, (byte) 0x7D, (byte) 0x7D, (byte) 0x25, (byte) 0xA6, (byte) 0xCD, (byte) 0x39, (byte) 0x6D, (byte) 0xDA, (byte) 0x76, (byte) 0x0C, (byte) 0x79, (byte) 0xBF, (byte) 0x48, (byte) 0x25, (byte) 0xFC, (byte) 0x2D, (byte) 0xC5, (byte) 0xFA, (byte) 0x53, (byte) 0x9B, (byte) 0x4D, (byte) 0x60, (byte) 0xF4, (byte) 0xEF, (byte) 0xC7, (byte) 0xEA, (byte) 0xAC, (byte) 0xA1, (byte) 0x7B, (byte) 0x03, (byte) 0xF4, (byte) 0xAF, (byte) 0xC7 }); byte[] result = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, signature).modPow(power, mod).toByteArray(); byte[] digest; byte[] properResult = new byte[0x100]; for (int i = 0; i < properResult.length; i++) properResult[i] = (byte) 0xBB; MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(module); md.update("MAIEV.MOD".getBytes()); digest = md.digest(); System.arraycopy(digest, 0, properResult, 0, digest.length); for (int i = 0; i < result.length; i++) if (result[i] != properResult[i]) return false; return true; } catch (Exception e) { System.out.println("Failed to verify signature: " + e.toString()); } return false; }
11
Code Sample 1: public void testCodingFromFileSmaller() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff;"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); } Code Sample 2: public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
11
Code Sample 1: public String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UploadFileForm vo = (UploadFileForm) form; FormFile file = vo.getFile(); String inforId = request.getParameter("inforId"); System.out.println("inforId=" + inforId); if (file != null) { String realpath = getServlet().getServletContext().getRealPath("/"); realpath = realpath.replaceAll("\\\\", "/"); String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); String strAppend = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); if (file.getFileSize() != 0) { file.getInputStream(); String name = file.getFileName(); String fullPath = realpath + "attach/" + strAppend + name; t_attach attach = new t_attach(); attach.setAttach_fullname(fullPath); attach.setAttach_name(name); attach.setInfor_id(Integer.parseInt(inforId)); attach.setInsert_day(new Date()); attach.setUpdate_day(new Date()); t_attach_EditMap attachEdit = new t_attach_EditMap(); attachEdit.add(attach); File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(file.getInputStream(), out); out.close(); System.out.println("file name is :" + name); } } request.setAttribute("operating-status", "�����ɹ�! ��ӭ����ʹ�á�"); System.out.println("in the end...."); return "aftersave"; } Code Sample 2: public static void printResource(OutputStream os, String resourceName) throws IOException { InputStream is = null; try { is = ResourceLoader.loadResource(resourceName); if (is == null) { throw new IOException("Given resource not found!"); } IOUtils.copy(is, os); } finally { IOUtils.closeQuietly(is); } }
00
Code Sample 1: public static void main(String[] argv) throws IOException { int i; for (i = 0; i < argv.length; i++) { if (argv[i].charAt(0) != '-') break; ++i; switch(argv[i - 1].charAt(1)) { case 'b': try { flag_predict_probability = (atoi(argv[i]) != 0); } catch (NumberFormatException e) { exit_with_help(); } break; default: System.err.printf("unknown option: -%d%n", argv[i - 1].charAt(1)); exit_with_help(); break; } } if (i >= argv.length || argv.length <= i + 2) { exit_with_help(); } BufferedReader reader = null; Writer writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(argv[i]), Linear.FILE_CHARSET)); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(argv[i + 2]), Linear.FILE_CHARSET)); Model model = Linear.loadModel(new File(argv[i + 1])); doPredict(reader, writer, model); } finally { closeQuietly(reader); closeQuietly(writer); } } Code Sample 2: public String gen() { String plainText = this.password; MessageDigest mdAlgorithm; StringBuffer hexString = new StringBuffer(); try { mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(plainText.getBytes()); byte[] digest = mdAlgorithm.digest(); for (int i = 0; i < digest.length; i++) { plainText = Integer.toHexString(0xFF & digest[i]); if (plainText.length() < 2) plainText = "0" + plainText; hexString.append(plainText); } } catch (NoSuchAlgorithmException ex) { } return hexString.toString(); }
00
Code Sample 1: public static boolean isSameHttpContent(final String url, final File localFile, UsernamePasswordCredentials creds) throws IOException { if (localFile.isFile()) { long localContentLength = localFile.length(); long localLastModified = localFile.lastModified() / 1000; long contentLength = -1; long lastModified = -1; HttpClient httpclient = createHttpClient(creds); try { HttpHead httphead = new HttpHead(url); HttpResponse response = httpclient.execute(httphead); if (response != null) { StatusLine statusLine = response.getStatusLine(); int status = statusLine.getStatusCode() / 100; if (status == 2) { Header lastModifiedHeader = response.getFirstHeader("Last-Modified"); Header contentLengthHeader = response.getFirstHeader("Content-Length"); if (contentLengthHeader != null) { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (lastModifiedHeader != null) { SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); formatter.setDateFormatSymbols(new DateFormatSymbols(Locale.US)); try { lastModified = formatter.parse(lastModifiedHeader.getValue()).getTime() / 1000; } catch (ParseException e) { logger.error(e); } } } else { return true; } } } finally { httpclient.getConnectionManager().shutdown(); } if (logger.isDebugEnabled()) { logger.debug("local:" + localContentLength + " " + localLastModified); logger.debug("remote:" + contentLength + " " + lastModified); } if (contentLength != -1 && localContentLength != contentLength) return false; if (lastModified != -1 && lastModified != localLastModified) return false; if (contentLength == -1 && lastModified == -1) return false; return true; } return false; } Code Sample 2: public void run() { LogPrinter.log(Level.FINEST, "Started Download at : {0, date, long}", new Date()); if (!PipeConnected) { throw new IllegalStateException("You should connect the pipe before with getInputStream()"); } InputStream ins = null; if (IsAlreadyDownloaded) { LogPrinter.log(Level.FINEST, "The file already Exists open and foward the byte"); try { ContentLength = (int) TheAskedFile.length(); ContentType = URLConnection.getFileNameMap().getContentTypeFor(TheAskedFile.getName()); ins = new FileInputStream(TheAskedFile); byte[] buffer = new byte[BUFFER_SIZE]; int read = ins.read(buffer); while (read >= 0) { Pipe.write(buffer, 0, read); read = ins.read(buffer); } } catch (IOException e) { e.printStackTrace(); } finally { if (ins != null) { try { ins.close(); } catch (IOException e) { } } } } else { LogPrinter.log(Level.FINEST, "the file does not exist locally so we try to download the thing"); File theDir = TheAskedFile.getParentFile(); if (!theDir.exists()) { theDir.mkdirs(); } for (URL url : ListFastest) { FileOutputStream fout = null; boolean OnError = false; long timestart = System.currentTimeMillis(); long bytecount = 0; try { URL newUrl = new URL(url.toString() + RequestedFile); LogPrinter.log(Level.FINEST, "the download URL = {0}", newUrl); URLConnection conn = newUrl.openConnection(); ContentType = conn.getContentType(); ContentLength = conn.getContentLength(); ins = conn.getInputStream(); fout = new FileOutputStream(TheAskedFile); byte[] buffer = new byte[BUFFER_SIZE]; int read = ins.read(buffer); while (read >= 0) { fout.write(buffer, 0, read); Pipe.write(buffer, 0, read); read = ins.read(buffer); bytecount += read; } Pipe.flush(); } catch (IOException e) { OnError = true; } finally { if (ins != null) { try { ins.close(); } catch (IOException e) { } } if (fout != null) { try { fout.close(); } catch (IOException e) { } } } long timeend = System.currentTimeMillis(); if (OnError) { continue; } else { long timetook = timeend - timestart; BigDecimal speed = new BigDecimal(bytecount).multiply(new BigDecimal(1000)).divide(new BigDecimal(timetook), MathContext.DECIMAL32); for (ReportCalculatedStatistique report : Listener) { report.reportUrlStat(url, speed, timetook); } break; } } } LogPrinter.log(Level.FINEST, "download finished at {0,date,long}", new Date()); if (Pipe != null) { try { Pipe.close(); } catch (IOException e) { e.printStackTrace(); } } }
11
Code Sample 1: private String copyAndHash(InputStream input, File into) throws IOException { MessageDigest digest = createMessageDigest(); DigestInputStream dis = new DigestInputStream(input, digest); IOException ex; FileOutputStream fos = null; try { fos = new FileOutputStream(into); IOUtils.copyLarge(dis, fos); byte[] hash = digest.digest(); Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } return formatter.toString(); } catch (IOException e) { ex = e; } finally { IOUtils.closeQuietly(dis); IOUtils.closeQuietly(fos); } if (logger.isWarnEnabled()) logger.warn("Couldn't retrieve data from input!", ex); deleteTempFile(into); throw ex; } Code Sample 2: private void trainDepParser(byte flag, JarArchiveOutputStream zout) throws Exception { AbstractDepParser parser = null; OneVsAllDecoder decoder = null; if (flag == ShiftPopParser.FLAG_TRAIN_LEXICON) { System.out.println("\n* Save lexica"); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, s_featureXml); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, s_featureXml); } else if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE) { System.out.println("\n* Print training instances"); System.out.println("- loading lexica"); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, t_xml, ENTRY_LEXICA); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, t_xml, ENTRY_LEXICA); } else if (flag == ShiftPopParser.FLAG_TRAIN_BOOST) { System.out.println("\n* Train conditional"); decoder = new OneVsAllDecoder(m_model); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, t_xml, t_map, decoder); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, t_xml, t_map, decoder); } AbstractReader<DepNode, DepTree> reader = null; DepTree tree; int n; if (s_format.equals(AbstractReader.FORMAT_DEP)) reader = new DepReader(s_trainFile, true); else if (s_format.equals(AbstractReader.FORMAT_CONLLX)) reader = new CoNLLXReader(s_trainFile, true); parser.setLanguage(s_language); reader.setLanguage(s_language); for (n = 0; (tree = reader.nextTree()) != null; n++) { parser.parse(tree); if (n % 1000 == 0) System.out.printf("\r- parsing: %dK", n / 1000); } System.out.println("\r- parsing: " + n); if (flag == ShiftPopParser.FLAG_TRAIN_LEXICON) { System.out.println("- saving"); parser.saveTags(ENTRY_LEXICA); t_xml = parser.getDepFtrXml(); } else if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE || flag == ShiftPopParser.FLAG_TRAIN_BOOST) { a_yx = parser.a_trans; zout.putArchiveEntry(new JarArchiveEntry(ENTRY_PARSER)); PrintStream fout = new PrintStream(zout); fout.print(s_depParser); fout.flush(); zout.closeArchiveEntry(); zout.putArchiveEntry(new JarArchiveEntry(ENTRY_FEATURE)); IOUtils.copy(new FileInputStream(s_featureXml), zout); zout.closeArchiveEntry(); zout.putArchiveEntry(new JarArchiveEntry(ENTRY_LEXICA)); IOUtils.copy(new FileInputStream(ENTRY_LEXICA), zout); zout.closeArchiveEntry(); if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE) t_map = parser.getDepFtrMap(); } }
00
Code Sample 1: public void adicionaCliente(ClienteBean cliente) { PreparedStatement pstmt = null; ResultSet rs = null; String sql = "insert into cliente(nome,cpf,telefone,cursoCargo,bloqueado,ativo,tipo) values(?,?,?,?,?,?,?)"; try { pstmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstmt.setString(1, cliente.getNome()); pstmt.setString(2, cliente.getCPF()); pstmt.setString(3, cliente.getTelefone()); pstmt.setString(4, cliente.getCursoCargo()); pstmt.setString(5, cliente.getBloqueado()); pstmt.setString(6, cliente.getAtivo()); pstmt.setString(7, cliente.getTipo()); pstmt.executeUpdate(); rs = pstmt.getGeneratedKeys(); if (rs.next()) { cliente.setIdCliente(rs.getLong(1)); } connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (SQLException ex1) { throw new RuntimeException("Erro ao inserir cliente.", ex1); } throw new RuntimeException("Erro ao inserir cliente.", ex); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); } catch (SQLException ex) { throw new RuntimeException("Ocorreu um erro no banco de dados.", ex); } } } Code Sample 2: protected byte[] getBytesForWebPageUsingHTTPClient(String urlString) throws ClientProtocolException, IOException { log("Retrieving url: " + urlString); DefaultHttpClient httpclient = new DefaultHttpClient(); if (this.archiveAccessSpecification.getUserID() != null) { httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(this.archiveAccessSpecification.getUserID(), this.archiveAccessSpecification.getUserPassword())); } HttpGet httpget = new HttpGet(urlString); log("about to do request: " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); log("-------------- Request results --------------"); log("Status line: " + response.getStatusLine()); if (entity != null) { log("Response content length: " + entity.getContentLength()); } log("contents"); byte[] bytes = null; if (entity != null) { bytes = getBytesFromInputStream(entity.getContent()); entity.consumeContent(); } log("Status code :" + response.getStatusLine().getStatusCode()); log(response.getStatusLine().getReasonPhrase()); if (response.getStatusLine().getStatusCode() != 200) return null; return bytes; }
00
Code Sample 1: public Reader getReader() throws Exception { if (url_base == null) { return new FileReader(file); } else { URL url = new URL(url_base + file.getName()); return new InputStreamReader(url.openConnection().getInputStream()); } } Code Sample 2: private void createSoundbank(String testSoundbankFileName) throws Exception { System.out.println("Create soundbank"); File packageDir = new File("testsoundbank"); if (packageDir.exists()) { for (File file : packageDir.listFiles()) assertTrue(file.delete()); assertTrue(packageDir.delete()); } packageDir.mkdir(); String sourceFileName = "testsoundbank/TestSoundBank.java"; File sourceFile = new File(sourceFileName); FileWriter writer = new FileWriter(sourceFile); writer.write("package testsoundbank;\n" + "public class TestSoundBank extends com.sun.media.sound.ModelAbstractOscillator { \n" + " @Override public int read(float[][] buffers, int offset, int len) throws java.io.IOException { \n" + " return 0;\n" + " }\n" + " @Override public String getVersion() {\n" + " return \"" + (soundbankRevision++) + "\";\n" + " }\n" + "}\n"); writer.close(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File("."))); compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile))).call(); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testSoundbankFileName)); ZipEntry ze = new ZipEntry("META-INF/services/javax.sound.midi.Soundbank"); zos.putNextEntry(ze); zos.write("testsoundbank.TestSoundBank".getBytes()); ze = new ZipEntry("testsoundbank/TestSoundBank.class"); zos.putNextEntry(ze); FileInputStream fis = new FileInputStream("testsoundbank/TestSoundBank.class"); int b = fis.read(); while (b != -1) { zos.write(b); b = fis.read(); } zos.close(); }
00
Code Sample 1: private void writeFile(FileInputStream inFile, FileOutputStream outFile) throws IOException { byte[] buf = new byte[2048]; int read; while ((read = inFile.read(buf)) > 0) outFile.write(buf, 0, read); inFile.close(); } Code Sample 2: public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { GrammarPool grammarpool = (GrammarPool) config.getProperty(XMLReaderObjectFactory.GRAMMER_POOL); if (isCalledAs("clear-grammar-cache")) { Sequence result = new ValueSequence(); int before = countTotalNumberOfGrammar(grammarpool); LOG.debug("Clearing " + before + " grammars"); clearGrammarPool(grammarpool); int after = countTotalNumberOfGrammar(grammarpool); LOG.debug("Remained " + after + " grammars"); int delta = before - after; result.add(new IntegerValue(delta)); return result; } else if (isCalledAs("show-grammar-cache")) { MemTreeBuilder builder = context.getDocumentBuilder(); NodeImpl result = writeReport(grammarpool, builder); return result; } else if (isCalledAs("pre-parse-grammar")) { if (args[0].isEmpty()) return Sequence.EMPTY_SEQUENCE; XMLGrammarPreparser parser = new XMLGrammarPreparser(); parser.registerPreparser(TYPE_XSD, null); List<Grammar> allGrammars = new ArrayList<Grammar>(); for (SequenceIterator i = args[0].iterate(); i.hasNext(); ) { String url = i.nextItem().getStringValue(); if (url.startsWith("/")) { url = "xmldb:exist://" + url; } LOG.debug("Parsing " + url); try { if (url.endsWith(".xsd")) { InputStream is = new URL(url).openStream(); XMLInputSource xis = new XMLInputSource(null, url, url, is, null); Grammar schema = parser.preparseGrammar(TYPE_XSD, xis); is.close(); allGrammars.add(schema); } else { throw new XPathException(this, "Only XMLSchemas can be preparsed."); } } catch (IOException ex) { LOG.debug(ex); throw new XPathException(this, ex); } catch (Exception ex) { LOG.debug(ex); throw new XPathException(this, ex); } } LOG.debug("Successfully parsed " + allGrammars.size() + " grammars."); Grammar grammars[] = new Grammar[allGrammars.size()]; grammars = allGrammars.toArray(grammars); grammarpool.cacheGrammars(TYPE_XSD, grammars); ValueSequence result = new ValueSequence(); for (Grammar one : grammars) { result.add(new StringValue(one.getGrammarDescription().getNamespace())); } return result; } else { LOG.error("function not found error"); throw new XPathException(this, "function not found"); } }
11
Code Sample 1: public static void main(String[] args) throws IOException { long readfilelen = 0; BufferedRandomAccessFile brafReadFile, brafWriteFile; brafReadFile = new BufferedRandomAccessFile("C:\\WINNT\\Fonts\\STKAITI.TTF"); readfilelen = brafReadFile.initfilelen; brafWriteFile = new BufferedRandomAccessFile(".\\STKAITI.001", "rw", 10); byte buf[] = new byte[1024]; int readcount; long start = System.currentTimeMillis(); while ((readcount = brafReadFile.read(buf)) != -1) { brafWriteFile.write(buf, 0, readcount); } brafWriteFile.close(); brafReadFile.close(); System.out.println("BufferedRandomAccessFile Copy & Write File: " + brafReadFile.filename + " FileSize: " + java.lang.Integer.toString((int) readfilelen >> 1024) + " (KB) " + "Spend: " + (double) (System.currentTimeMillis() - start) / 1000 + "(s)"); java.io.FileInputStream fdin = new java.io.FileInputStream("C:\\WINNT\\Fonts\\STKAITI.TTF"); java.io.BufferedInputStream bis = new java.io.BufferedInputStream(fdin, 1024); java.io.DataInputStream dis = new java.io.DataInputStream(bis); java.io.FileOutputStream fdout = new java.io.FileOutputStream(".\\STKAITI.002"); java.io.BufferedOutputStream bos = new java.io.BufferedOutputStream(fdout, 1024); java.io.DataOutputStream dos = new java.io.DataOutputStream(bos); start = System.currentTimeMillis(); for (int i = 0; i < readfilelen; i++) { dos.write(dis.readByte()); } dos.close(); dis.close(); System.out.println("DataBufferedios Copy & Write File: " + brafReadFile.filename + " FileSize: " + java.lang.Integer.toString((int) readfilelen >> 1024) + " (KB) " + "Spend: " + (double) (System.currentTimeMillis() - start) / 1000 + "(s)"); } Code Sample 2: private Document saveFile(Document document, File file) throws Exception { List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { preference = preferences.get(0); } SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); String repo = preference.getRepository(); Calendar calendar = Calendar.getInstance(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(sdf.format(calendar.getTime())); sbFolder.append(File.separator).append(calendar.get(Calendar.HOUR_OF_DAY)); File folder = new File(sbRepo.append(sbFolder).toString()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()); StringBuffer fname = new StringBuffer(document.getId().toString()); fname.append(".").append(document.getExt()); sbFile.append(File.separator).append(fname); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } return document; }
11
Code Sample 1: private static void addFile(File file, ZipArchiveOutputStream zaos) throws IOException { String filename = null; filename = file.getName(); ZipArchiveEntry zae = new ZipArchiveEntry(filename); zae.setSize(file.length()); zaos.putArchiveEntry(zae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, zaos); zaos.closeArchiveEntry(); } Code Sample 2: private int mergeFiles(Merge merge) throws MojoExecutionException { String encoding = DEFAULT_ENCODING; if (merge.getEncoding() != null && merge.getEncoding().length() > 0) { encoding = merge.getEncoding(); } int numMergedFiles = 0; Writer ostream = null; FileOutputStream fos = null; try { fos = new FileOutputStream(merge.getTargetFile(), true); ostream = new OutputStreamWriter(fos, encoding); BufferedWriter output = new BufferedWriter(ostream); for (String orderingName : this.orderingNames) { List<File> files = this.orderedFiles.get(orderingName); if (files != null) { getLog().info("Appending: " + files.size() + " files that matched the name: " + orderingName + " to the target file: " + merge.getTargetFile().getAbsolutePath() + "..."); for (File file : files) { String fileName = file.getName(); getLog().info("Appending file: " + fileName + " to the target file: " + merge.getTargetFile().getAbsolutePath() + "..."); InputStream input = null; try { input = new FileInputStream(file); if (merge.getSeparator() != null && merge.getSeparator().trim().length() > 0) { String replaced = merge.getSeparator().trim(); replaced = replaced.replace("\n", ""); replaced = replaced.replace("\t", ""); replaced = replaced.replace("#{file.name}", fileName); replaced = replaced.replace("#{parent.name}", file.getParentFile() != null ? file.getParentFile().getName() : ""); replaced = replaced.replace("\\n", "\n"); replaced = replaced.replace("\\t", "\t"); getLog().debug("Appending separator: " + replaced); IOUtils.copy(new StringReader(replaced), output); } IOUtils.copy(input, output, encoding); } catch (IOException ioe) { throw new MojoExecutionException("Failed to append file: " + fileName + " to output file", ioe); } finally { IOUtils.closeQuietly(input); } numMergedFiles++; } } } output.flush(); } catch (IOException ioe) { throw new MojoExecutionException("Failed to open stream file to output file: " + merge.getTargetFile().getAbsolutePath(), ioe); } finally { if (fos != null) { IOUtils.closeQuietly(fos); } if (ostream != null) { IOUtils.closeQuietly(ostream); } } return numMergedFiles; }
11
Code Sample 1: private void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public static void getResponseAsStream(String _url, Object _stringOrStream, OutputStream _stream, Map<String, String> _headers, Map<String, String> _params, String _contentType, int _timeout) throws IOException { if (_url == null || _url.length() <= 0) throw new IllegalArgumentException("Url can not be null."); String temp = _url.toLowerCase(); if (!temp.startsWith("http://") && !temp.startsWith("https://")) _url = "http://" + _url; _url = encodeURL(_url); HttpMethod method = null; if (_stringOrStream == null && (_params == null || _params.size() <= 0)) method = new GetMethod(_url); else method = new PostMethod(_url); HttpMethodParams methodParams = ((HttpMethodBase) method).getParams(); if (methodParams == null) { methodParams = new HttpMethodParams(); ((HttpMethodBase) method).setParams(methodParams); } if (_timeout < 0) methodParams.setSoTimeout(0); else methodParams.setSoTimeout(_timeout); if (_contentType != null && _contentType.length() > 0) { if (_headers == null) _headers = new HashMap<String, String>(); _headers.put("Content-Type", _contentType); } if (_headers == null || !_headers.containsKey("User-Agent")) { if (_headers == null) _headers = new HashMap<String, String>(); _headers.put("User-Agent", DEFAULT_USERAGENT); } if (_headers != null) { Iterator<Map.Entry<String, String>> iter = _headers.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); method.setRequestHeader((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof PostMethod && (_params != null && _params.size() > 0)) { Iterator<Map.Entry<String, String>> iter = _params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); ((PostMethod) method).addParameter((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof EntityEnclosingMethod && _stringOrStream != null) { if (_stringOrStream instanceof InputStream) { RequestEntity entity = new InputStreamRequestEntity((InputStream) _stringOrStream); ((EntityEnclosingMethod) method).setRequestEntity(entity); } else { RequestEntity entity = new StringRequestEntity(_stringOrStream.toString(), _contentType, null); ((EntityEnclosingMethod) method).setRequestEntity(entity); } } HttpClient httpClient = new HttpClient(new org.apache.commons.httpclient.SimpleHttpConnectionManager()); httpClient.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); InputStream instream = null; try { int status = httpClient.executeMethod(method); if (status != HttpStatus.SC_OK) { LOG.warn("Http Satus:" + status + ",Url:" + _url); if (status >= 500 && status < 600) throw new IOException("Remote service<" + _url + "> respose a error, status:" + status); } instream = method.getResponseBodyAsStream(); IOUtils.copy(instream, _stream); } catch (IOException err) { LOG.error("Failed to access " + _url, err); throw err; } finally { IOUtils.closeQuietly(instream); if (method != null) method.releaseConnection(); } }
00
Code Sample 1: protected boolean validateCaptcha(HttpServletRequest request) { String captchaID = request.getSession().getId(); String challengeResponse = StringUtils.upperCase(request.getParameter(JCaptchaEngine.CAPTCHA_INPUT_NAME)); try { String urlString = "eadefakiaHR0cDovL3d3dy5zaG9weHgubmV0L2NlcnRpZmljYXRlLmFjdGlvbj9zaG9wVXJsPQ"; BASE64Decoder bASE64Decoder = new BASE64Decoder(); urlString = new String(bASE64Decoder.decodeBuffer(StringUtils.substring(urlString, 8) + "==")); URL url = new URL(urlString + SystemConfigUtil.getSystemConfig().getShopUrl()); URLConnection urlConnection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection) urlConnection; httpConnection.getResponseCode(); } catch (IOException e) { } return captchaService.validateResponseForID(captchaID, challengeResponse); } Code Sample 2: public static byte[] read(URL url) throws IOException { byte[] bytes; InputStream is = null; try { is = url.openStream(); bytes = readAllBytes(is); } finally { if (is != null) { is.close(); } } return bytes; }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void main(String args[]) throws Exception { FileInputStream fin = new FileInputStream("D:/work/test.txt"); FileOutputStream fout = new FileOutputStream("D:/work/output.txt"); FileChannel inChannel = fin.getChannel(); FileChannel outChannel = fout.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int ret = inChannel.read(buffer); if (ret == -1) break; buffer.flip(); outChannel.write(buffer); buffer.clear(); } }
00
Code Sample 1: private static void copierScriptChargement(File webInfDir, String initialDataChoice) { File chargementInitialDir = new File(webInfDir, "chargementInitial"); File fichierChargement = new File(chargementInitialDir, "ScriptChargementInitial.sql"); File fichierChargementAll = new File(chargementInitialDir, "ScriptChargementInitial-All.sql"); File fichierChargementTypesDocument = new File(chargementInitialDir, "ScriptChargementInitial-TypesDocument.sql"); File fichierChargementVide = new File(chargementInitialDir, "ScriptChargementInitial-Vide.sql"); if (fichierChargement.exists()) { fichierChargement.delete(); } File fichierUtilise = null; if ("all".equals(initialDataChoice)) { fichierUtilise = fichierChargementAll; } else if ("typesDocument".equals(initialDataChoice)) { fichierUtilise = fichierChargementTypesDocument; } else if ("empty".equals(initialDataChoice)) { fichierUtilise = fichierChargementVide; } if (fichierUtilise != null && fichierUtilise.exists()) { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(fichierUtilise).getChannel(); destination = new FileOutputStream(fichierChargement).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (Exception e) { throw new RuntimeException(e); } finally { if (source != null) { try { source.close(); } catch (Exception e) { e.printStackTrace(); } } if (destination != null) { try { destination.close(); } catch (Exception e) { e.printStackTrace(); } } } } } Code Sample 2: private void createTree(DefaultMutableTreeNode top) throws MalformedURLException, ParserConfigurationException, SAXException, IOException { InputStream stream; URL url = new URL(SHIPS_URL + view.getBaseurl()); try { stream = url.openStream(); } catch (Exception e) { stream = getClass().getResourceAsStream("ships.xml"); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(stream); NodeList races = doc.getElementsByTagName("race"); for (int i = 0; i < races.getLength(); i++) { Element race = (Element) races.item(i); top.add(buildRaceTree(race)); } top.setUserObject("Ships"); view.getShipTree().repaint(); view.getShipTree().expandRow(0); }
00
Code Sample 1: public static Object transmitObject(String servletURL, Object obj) throws IOException { URL url; URLConnection conn; InputStream is; OutputStream os; try { if (servletURL.startsWith("https") || servletURL.startsWith("HTTPS")) { System.out.println(Jvm.class.getName() + ".transmitObject is initializing ssl"); Jvm.initSSL(); } } catch (Throwable t) { System.out.println(Jvm.class.getName() + ".transmitObject could not initialize ssl"); } url = new URL(servletURL); conn = url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Content-Type", "application/octet-stream"); conn.setUseCaches(false); os = conn.getOutputStream(); writeSerial(obj, os); os.flush(); os.close(); try { is = conn.getInputStream(); Object rcvObj = readSerial(is); is.close(); return rcvObj; } catch (IOException x2) { x2.printStackTrace(); return null; } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); return null; } } Code Sample 2: @Override public void run() { log.debug("Now running...."); log.debug("Current env. variables:"); try { this.infoNotifiers("Environment parameters after modifications:"); this.logEnvironment(); this.infoNotifiers("Dump thread will now run..."); this.endNotifiers(); this.process = this.pb.start(); this.process.waitFor(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } List<String> cmd = new LinkedList<String>(); cmd.add("gzip"); cmd.add(info.getDumpFileName()); File basePath = this.pb.directory(); this.pb = new ProcessBuilder(cmd); this.pb.directory(basePath); log.debug("Executing: " + StringUtils.join(cmd.iterator(), ' ')); this.process = this.pb.start(); this.process.waitFor(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump GZip Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } info.setDumpFileName(info.getDumpFileName() + ".gz"); info.setMD5SumFileName(info.getDumpFileName() + ".md5sum"); cmd = new LinkedList<String>(); cmd.add("md5sum"); cmd.add("-b"); cmd.add(info.getDumpFileName()); log.debug("Executing: " + StringUtils.join(cmd.iterator(), ' ')); this.pb = new ProcessBuilder(cmd); this.pb.directory(basePath); this.process = this.pb.start(); BufferedOutputStream md5sumFileOut = new BufferedOutputStream(new FileOutputStream(basePath.getAbsolutePath() + File.separatorChar + info.getMD5SumFileName())); IOUtils.copy(this.process.getInputStream(), md5sumFileOut); this.process.waitFor(); md5sumFileOut.flush(); md5sumFileOut.close(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump GZip MD5Sum Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } else { this.startNotifiers(); this.infoNotifiers("Dump, gzip and md5sum sucessfuly completed."); this.endNotifiers(); } } catch (IOException e) { String message = "IOException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } catch (InterruptedException e) { String message = "InterruptedException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } catch (IntegrationException e) { String message = "IntegrationException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } }
00
Code Sample 1: @Override public List<String> getNamedEntitites(String sentence) { List<String> namedEntities = new ArrayList<String>(); try { URL url = new URL(SERVICE_URL + "text=" + URLEncoder.encode(sentence, "UTF-8") + "&confidence=" + CONFIDENCE + "&support=" + SUPPORT); URLConnection conn = url.openConnection(); conn.setRequestProperty("accept", "application/json"); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); JSONObject json = new JSONObject(sb.toString()); if (!json.isNull("Resources")) { JSONArray array = json.getJSONArray("Resources"); JSONObject entityObject; for (int i = 0; i < array.length(); i++) { entityObject = array.getJSONObject(i); System.out.println("Entity: " + entityObject.getString("@surfaceForm")); System.out.println("DBpedia URI: " + entityObject.getString("@URI")); System.out.println("Types: " + entityObject.getString("@types")); namedEntities.add(entityObject.getString("@surfaceForm")); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return namedEntities; } Code Sample 2: public static void decompressGZIP(File gzip, File to, long skip) throws IOException { GZIPInputStream gis = null; BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(to)); FileInputStream fis = new FileInputStream(gzip); fis.skip(skip); gis = new GZIPInputStream(fis); final byte[] buffer = new byte[IO_BUFFER]; int read = -1; while ((read = gis.read(buffer)) != -1) { bos.write(buffer, 0, read); } } finally { try { gis.close(); } catch (Exception nope) { } try { bos.flush(); } catch (Exception nope) { } try { bos.close(); } catch (Exception nope) { } } }
00
Code Sample 1: public static void main(String[] args) throws Exception { PatternLayout pl = new PatternLayout("%d{ISO8601} %-5p %c: %m\n"); ConsoleAppender ca = new ConsoleAppender(pl); Logger.getRoot().addAppender(ca); Logger.getRoot().setLevel(Level.INFO); Options options = new Options(); options.addOption("p", "put", false, "put a file in the DHT overlay"); options.addOption("g", "get", false, "get a file from the DHT"); options.addOption("r", "remove", false, "remove a file from the DHT"); options.addOption("u", "update", false, "updates the lease"); options.addOption("j", "join", false, "join the DHT overlay"); options.addOption("c", "config", true, "the configuration file"); options.addOption("k", "key", true, "the key to read a file from"); options.addOption("f", "file", true, "the file to read or write"); options.addOption("a", "app", true, "the application ID"); options.addOption("s", "secret", true, "the secret used to hide data"); options.addOption("t", "ttl", true, "how long in seconds data should persist"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); String configFile = null; String mode = null; String secretStr = null; int ttl = 9999; String keyStr = null; String file = null; int appId = 0; if (cmd.hasOption("j")) { mode = "join"; } if (cmd.hasOption("p")) { mode = "put"; } if (cmd.hasOption("g")) { mode = "get"; } if (cmd.hasOption("r")) { mode = "remove"; } if (cmd.hasOption("u")) { mode = "update"; } if (cmd.hasOption("c")) { configFile = cmd.getOptionValue("c"); } if (cmd.hasOption("k")) { keyStr = cmd.getOptionValue("k"); } if (cmd.hasOption("f")) { file = cmd.getOptionValue("f"); } if (cmd.hasOption("s")) { secretStr = cmd.getOptionValue("s"); } if (cmd.hasOption("t")) { ttl = Integer.parseInt(cmd.getOptionValue("t")); } if (cmd.hasOption("a")) { appId = Integer.parseInt(cmd.getOptionValue("a")); } if (mode == null) { System.err.println("ERROR: --put or --get or --remove or --join or --update is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (configFile == null) { System.err.println("ERROR: --config is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } Properties conf = new Properties(); conf.load(new FileInputStream(configFile)); DHT dht = new DHT(conf); if (mode.equals("join")) { dht.join(); } else if (mode.equals("put")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("putting file " + file); FileInputStream in = new FileInputStream(file); byte[] tmp = new byte[1000000]; int num = in.read(tmp); byte[] value = new byte[num]; System.arraycopy(tmp, 0, value, 0, num); in.close(); if (dht.put((short) appId, keyStr.getBytes(), value, ttl, secretStr.getBytes()) < 0) { logger.info("There was an error while putting a key-value."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("get")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("getting file " + file); ArrayList<byte[]> values = new ArrayList<byte[]>(); if (dht.get((short) appId, keyStr.getBytes(), Integer.MAX_VALUE, values) < 0) { logger.info("There was an error while getting a value."); System.exit(0); } if (values.size() == 0 || values == null) { System.out.println("No values returned."); System.exit(0); } FileOutputStream out = new FileOutputStream(file); System.out.println("Found " + values.size() + " values -- saving the first one only."); out.write(values.get(0)); out.close(); System.out.println("Ok!"); } else if (mode.equals("remove")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("removing <key,value> for key=" + keyStr); if (dht.remove((short) appId, keyStr.getBytes(), secretStr.getBytes()) < 0) { logger.info("There was an error while removing a key."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("update")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("updating <key,value> for key=" + keyStr); if (dht.updateLease((short) appId, keyStr.getBytes(), ttl) < 0) { logger.info("There was an error while updating data lease."); System.exit(0); } System.out.println("Ok!"); } DHT.getInstance().stop(); } Code Sample 2: public synchronized void deleteDocument(final String file) throws IOException { SQLException ex = null; try { PreparedStatement findFileStmt = con.prepareStatement("SELECT ID AS \"ID\" FROM File_ WHERE Name = ?"); findFileStmt.setString(1, file); ResultSet rs = findFileStmt.executeQuery(); if (null != rs && rs.next()) { int fileId = rs.getInt("ID"); rs.close(); rs = null; PreparedStatement deleteTokensStmt = con.prepareStatement("DELETE FROM Token_ WHERE FieldID IN ( SELECT ID FROM Field_ WHERE FileID = ? )"); deleteTokensStmt.setInt(1, fileId); deleteTokensStmt.executeUpdate(); PreparedStatement deleteFieldsStmt = con.prepareStatement("DELETE FROM Field_ WHERE FileID = ?"); deleteFieldsStmt.setInt(1, fileId); deleteFieldsStmt.executeUpdate(); PreparedStatement deleteFileStmt = con.prepareStatement("DELETE FROM File_ WHERE ID = ?"); deleteFileStmt.setInt(1, fileId); deleteFileStmt.executeUpdate(); deleteFileStmt.close(); deleteFileStmt = null; deleteFieldsStmt.close(); deleteFieldsStmt = null; deleteTokensStmt.close(); deleteTokensStmt = null; } findFileStmt.close(); findFileStmt = null; } catch (SQLException e) { e.printStackTrace(); ex = e; try { this.con.rollback(); } catch (SQLException e2) { } } finally { try { this.con.setAutoCommit(true); } catch (SQLException e2) { } } if (null != ex) throw new IOException(ex.getMessage()); }
11
Code Sample 1: private static void includePodDependencies(Curnit curnit, JarOutputStream jarout) throws IOException { Properties props = new Properties(); Collection<Pod> pods = curnit.getReferencedPods(); for (Pod pod : pods) { PodUuid podId = pod.getPodId(); URL weburl = PodArchiveResolver.getSystemResolver().getUrl(podId); String urlString = ""; if (weburl != null) { String uriPath = weburl.getPath(); String zipPath = CurnitFile.WITHINCURNIT_BASEPATH + uriPath; jarout.putNextEntry(new JarEntry(zipPath)); IOUtils.copy(weburl.openStream(), jarout); jarout.closeEntry(); urlString = CurnitFile.WITHINCURNIT_PROTOCOL + uriPath; } props.put(podId.toString(), urlString); } jarout.putNextEntry(new JarEntry(CurnitFile.PODSREFERENCED_NAME)); props.store(jarout, "pod dependencies"); jarout.closeEntry(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public void filter(File source, File destination, MNamespace mNamespace) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(source)); BufferedWriter writer = new BufferedWriter(new FileWriter(destination)); int line = 0; int column = 0; Stack parseStateStack = new Stack(); parseStateStack.push(new ParseState(mNamespace)); for (Iterator i = codePieces.iterator(); i.hasNext(); ) { NamedCodePiece cp = (NamedCodePiece) i.next(); while (line < cp.getStartLine()) { line++; column = 0; writer.write(reader.readLine()); writer.newLine(); } while (column < cp.getStartPosition()) { writer.write(reader.read()); column++; } cp.write(writer, parseStateStack, column); while (line < cp.getEndLine()) { line++; column = 0; reader.readLine(); } while (column < cp.getEndPosition()) { column++; reader.read(); } } String data; while ((data = reader.readLine()) != null) { writer.write(data); writer.newLine(); } reader.close(); writer.close(); } Code Sample 2: static void cleanFile(File file) { final Counter cnt = new Counter(); final File out = new File(FileUtils.appendToFileName(file.getAbsolutePath(), ".cleaned")); final SAMFileReader reader = new SAMFileReader(file); final SAMRecordIterator it = reader.iterator(); final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), true, out); if (!it.hasNext()) return; log.info("Cleaning file " + file + " to " + out.getName()); SAMRecord last = it.next(); writer.addAlignment(last); while (it.hasNext()) { final SAMRecord now = it.next(); final int start1 = last.getAlignmentStart(); final int start2 = now.getAlignmentStart(); final int end1 = last.getAlignmentEnd(); final int end2 = now.getAlignmentEnd(); if (start1 == start2 && end1 == end2) { log.debug("Discarding record " + now.toString()); cnt.count(); continue; } writer.addAlignment(now); last = now; } writer.close(); reader.close(); log.info(file + " done, discarded " + cnt.getCount() + " reads"); exe.shutdown(); }
11
Code Sample 1: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } Code Sample 2: public void onUploadClicked(Event event) { Media[] medias = null; try { medias = Fileupload.get("Select one or more files to upload to " + "the current directory.", "Upload Files", 5); } catch (Exception e) { log.error("An exception occurred when displaying the file " + "upload dialog", e); } if (medias == null) { return; } for (Media media : medias) { String name = media.getName(); CSPath potentialFile = model.getPathForFile(name); if (media.isBinary()) { CSPathOutputStream writer = null; try { potentialFile.createNewFile(); if (potentialFile.exists()) { writer = new CSPathOutputStream(potentialFile); IOUtils.copy(media.getStreamData(), writer); } } catch (IOException e) { displayError("An error occurred when uploading the file " + name + ": " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } else { CSPathWriter writer = null; try { potentialFile.createNewFile(); if (potentialFile.exists()) { writer = new CSPathWriter(potentialFile); IOUtils.write(media.getStringData(), writer); } } catch (IOException e) { displayError("An error occurred when uploading the file " + name + ": " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } model.fileCleanup(potentialFile); updateFileGrid(); } }
00
Code Sample 1: public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); URL url; URLConnection urlConn; DataOutputStream cgiInput; url = new URL("http://localhost:8080/ListeOnLine/Target"); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); cgiInput = new DataOutputStream(urlConn.getOutputStream()); String content = "param1=" + URLEncoder.encode("first parameter") + "&param2=" + URLEncoder.encode("the second one..."); cgiInput.writeBytes(content); cgiInput.flush(); cgiInput.close(); BufferedReader cgiOutput = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); PrintWriter servletOutput = response.getWriter(); servletOutput.print("<html><body><h1>This is the Source Servlet</h1><p />"); String line = null; while (null != (line = cgiOutput.readLine())) { servletOutput.println(line); } cgiOutput.close(); servletOutput.print("</body></html>"); servletOutput.close(); } Code Sample 2: public void prepareOutput(HttpServletRequest req) { EaasyStreet.logTrace(METHOD_IN + className + OUTPUT_METHOD); super.prepareOutput(req); String content = Constants.EMPTY_STRING; String rawContent = null; List parts = null; try { URL url = new URL(sourceUrl); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; StringBuffer buffer = new StringBuffer(); while ((line = input.readLine()) != null) { buffer.append(line); buffer.append(Constants.LF); } rawContent = buffer.toString(); } catch (FileNotFoundException nf) { req.setAttribute(Constants.RAK_SYSTEM_ACTION, Constants.SYSTEM_ACTION_BACK); EaasyStreet.handleSafeEvent(req, new Event(Constants.EAA0012I, new String[] { "URL", nf.getMessage(), nf.toString() })); } catch (Exception e) { req.setAttribute(Constants.RAK_SYSTEM_ACTION, Constants.SYSTEM_ACTION_BACK); EaasyStreet.handleSafeEvent(req, new Event(Constants.EAA0012I, new String[] { "URL", e.getMessage(), e.toString() })); } if (rawContent != null) { if (startDelimiter != null) { parts = StringUtils.split(rawContent, startDelimiter); if (parts != null && parts.size() > 1) { rawContent = (String) parts.get(1); if (parts.size() > 2) { for (int x = 2; x < parts.size(); x++) { rawContent += startDelimiter; rawContent += parts.get(x); } } } else { rawContent = null; } } } if (rawContent != null) { if (endDelimiter != null) { parts = StringUtils.split(rawContent, endDelimiter); if (parts != null && parts.size() > 0) { rawContent = (String) parts.get(0); } else { rawContent = null; } } } if (rawContent != null) { if (replacementValues != null && !replacementValues.isEmpty()) { for (int x = 0; x < replacementValues.size(); x++) { LabelValueBean bean = (LabelValueBean) replacementValues.get(x); rawContent = StringUtils.replace(rawContent, bean.getLabel(), bean.getValue()); } } } if (rawContent != null) { content = rawContent; } req.setAttribute(getFormName(), content); EaasyStreet.logTrace(METHOD_OUT + className + OUTPUT_METHOD); }
11
Code Sample 1: public static boolean joinFiles(File dest, Collection<File> sources) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fos = new FileOutputStream(dest); for (File source : sources) { fis = new FileInputStream(source); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; } fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("error joining files to " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; } Code Sample 2: private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { TestLogger.error(e); } } catch (FileNotFoundException e) { TestLogger.error(e); } }
11
Code Sample 1: public String generateFilename() { MessageDigest md; byte[] sha1hash = new byte[40]; Random r = new Random(); String fileName = ""; String token = ""; while (true) { token = Long.toString(Math.abs(r.nextLong()), 36) + Long.toString(System.currentTimeMillis()); try { md = MessageDigest.getInstance("SHA-1"); md.update(token.getBytes("iso-8859-1"), 0, token.length()); sha1hash = md.digest(); } catch (Exception e) { log.log(Level.WARNING, e.getMessage(), e); } fileName = convertToHex(sha1hash); if (!new File(Configuration.ImageUploadPath + fileName).exists()) { break; } } return fileName; } Code Sample 2: public static String getHash(String password, String salt) { try { MessageDigest messageDigest = null; messageDigest = MessageDigest.getInstance(SHA_512); messageDigest.reset(); messageDigest.update(salt.getBytes("UTF-8")); messageDigest.update(password.getBytes("UTF-8")); byte[] input = messageDigest.digest(); for (int i = 0; i < 1000; i++) { messageDigest.reset(); input = messageDigest.digest(input); } Formatter formatter = new Formatter(); for (byte i : input) { formatter.format("%02x", i); } return formatter.toString(); } catch (NoSuchAlgorithmException e) { return ""; } catch (UnsupportedEncodingException e) { return ""; } }
00
Code Sample 1: public String getHtml(String path) throws Exception { URL url = new URL(path); URLConnection conn = url.openConnection(); conn.setDoOutput(true); InputStream inputStream = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8"); StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(isr); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } String result = sb.toString(); return result; } 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); } }
00
Code Sample 1: public void testClickToCallOutDirection() throws Exception { init(); SipCall[] receiverCalls = new SipCall[receiversCount]; receiverCalls[0] = sipPhoneReceivers[0].createSipCall(); receiverCalls[1] = sipPhoneReceivers[1].createSipCall(); receiverCalls[0].listenForIncomingCall(); receiverCalls[1].listenForIncomingCall(); logger.info("Trying to reach url : " + CLICK2DIAL_URL + CLICK2DIAL_PARAMS); URL url = new URL(CLICK2DIAL_URL + CLICK2DIAL_PARAMS); InputStream in = url.openConnection().getInputStream(); byte[] buffer = new byte[10000]; int len = in.read(buffer); String httpResponse = ""; for (int q = 0; q < len; q++) httpResponse += (char) buffer[q]; logger.info("Received the follwing HTTP response: " + httpResponse); receiverCalls[0].waitForIncomingCall(timeout); assertTrue(receiverCalls[0].sendIncomingCallResponse(Response.RINGING, "Ringing", 0)); assertTrue(receiverCalls[0].sendIncomingCallResponse(Response.OK, "OK", 0)); receiverCalls[1].waitForIncomingCall(timeout); assertTrue(receiverCalls[1].sendIncomingCallResponse(Response.RINGING, "Ringing", 0)); assertTrue(receiverCalls[1].sendIncomingCallResponse(Response.OK, "OK", 0)); assertTrue(receiverCalls[1].waitForAck(timeout)); assertTrue(receiverCalls[0].waitForAck(timeout)); assertTrue(receiverCalls[0].disconnect()); assertTrue(receiverCalls[1].waitForDisconnect(timeout)); assertTrue(receiverCalls[1].respondToDisconnect()); } Code Sample 2: public boolean uploadFromServlet(InputStream is, String serverFileName, String serverPath, String serverUrl, int serverPort, String userName, String passWord) throws IOException { FTPClient ftp = new FTPClient(); FTPClientConfig conf = new FTPClientConfig(); conf.setServerLanguageCode("zh_CN"); conf.setServerTimeZoneId("Asia/Chongqing"); try { ftp.configure(conf); int reply; ftp.setDefaultPort(serverPort); ftp.connect(serverUrl); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("FTP server refused connection."); } } catch (IOException e) { disconnectFtp(ftp); } try { if (!ftp.login(userName, passWord)) { throw new IOException("Can not log in with given username and password."); } if (!ftp.changeWorkingDirectory(serverPath)) { throw new IOException("Can not change to working directory."); } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (!ftp.storeFile(serverFileName, is)) { throw new IOException("Can not store file to FTP server."); } is.close(); } catch (SocketException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (ftp != null && ftp.isConnected()) { try { ftp.logout(); ftp.disconnect(); } catch (IOException e) { e.printStackTrace(); return false; } } } return true; }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { LogUtil.d(TAG, "Copying file %s to %s", src, dst); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(src).getChannel(); outChannel = new FileOutputStream(dst).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { closeSafe(inChannel); closeSafe(outChannel); } } Code Sample 2: private boolean write(File file) { String filename = file.getPath(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PrintStream out = new PrintStream(byteArrayOutputStream); try { StringBuffer xml = null; if (MainFrame.getInstance().getAnimation() != null) { MainFrame.getInstance().getAnimation().xml(out, "\t"); } else { xml = MainFrame.getInstance().getModel().xml("\t"); } if (file.exists()) { BufferedReader reader = new BufferedReader(new FileReader(filename)); BufferedWriter writer = new BufferedWriter(new FileWriter(filename + "~")); char[] buffer = new char[65536]; int charsRead = 0; while ((charsRead = reader.read(buffer)) > 0) writer.write(buffer, 0, charsRead); reader.close(); writer.close(); } BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writer.write("<jpatch version=\"" + VersionInfo.ver + "\">\n"); if (xml != null) writer.write(xml.toString()); else writer.write(byteArrayOutputStream.toString()); writer.write("</jpatch>\n"); writer.close(); MainFrame.getInstance().getUndoManager().setChange(false); if (MainFrame.getInstance().getAnimation() != null) MainFrame.getInstance().getAnimation().setFile(file); else MainFrame.getInstance().getModel().setFile(file); MainFrame.getInstance().setFilename(file.getName()); return true; } catch (IOException ioException) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "Unable to save file \"" + filename + "\"\n" + ioException, "Error", JOptionPane.ERROR_MESSAGE); return false; } }
00
Code Sample 1: public int delete(BusinessObject o) throws DAOException { int delete = 0; Bill bill = (Bill) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_BILL")); pst.setInt(1, bill.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; } Code Sample 2: public Document parse(InputSource is) throws SAXException, IOException { LSInput input = ls.createLSInput(); String systemId = is.getSystemId(); InputStream in = is.getByteStream(); if (in != null) { input.setByteStream(in); } else { Reader reader = is.getCharacterStream(); if (reader != null) { input.setCharacterStream(reader); } else { URL url = new URL(systemId); input.setByteStream(url.openStream()); } } input.setPublicId(is.getPublicId()); input.setSystemId(systemId); input.setEncoding(is.getEncoding()); return parser.parse(input); }
11
Code Sample 1: public static void main(String[] args) throws ParseException, FileNotFoundException, IOException { InputStream input = new BufferedInputStream(UpdateLanguages.class.getResourceAsStream("definition_template")); Translator t = new Translator(input, "UTF8"); Node template = Translator.Start(); File langs = new File("support/support/translate/languages"); for (File f : langs.listFiles()) { if (f.getName().endsWith(".lng")) { input = new BufferedInputStream(new FileInputStream(f)); try { Translator.ReInit(input, "UTF8"); } catch (java.lang.NullPointerException e) { new Translator(input, "UTF8"); } Node newFile = Translator.Start(); ArrayList<Addition> additions = new ArrayList<Addition>(); syncKeys(template, newFile, additions); ArrayList<String> fileLines = new ArrayList<String>(); Scanner scanner = new Scanner(new BufferedReader(new FileReader(f))); while (scanner.hasNextLine()) { fileLines.add(scanner.nextLine()); } int offset = 0; for (Addition a : additions) { System.out.println("Key added " + a + " to " + f.getName()); if (a.afterLine < 0 || a.afterLine >= fileLines.size()) { fileLines.add(a.getAddition(0)); } else { fileLines.add(a.afterLine + (offset++) + 1, a.getAddition(0)); } } f.delete(); Writer writer = new BufferedWriter(new FileWriter(f)); for (String s : fileLines) writer.write(s + "\n"); writer.close(); System.out.println("Language " + f.getName() + " had " + additions.size() + " additions"); } } File defFile = new File(langs, "language.lng"); defFile.delete(); defFile.createNewFile(); InputStream copyStream = new BufferedInputStream(UpdateLanguages.class.getResourceAsStream("definition_template")); OutputStream out = new BufferedOutputStream(new FileOutputStream(defFile)); int c = 0; while ((c = copyStream.read()) >= 0) out.write(c); out.close(); System.out.println("Languages updated."); } Code Sample 2: public static boolean copyFileToContentFolder(String source, LearningDesign learningDesign) { File inputFile = new File(source); File outputFile = new File(getRootFilePath(learningDesign) + inputFile.getName()); FileReader in; try { in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
00
Code Sample 1: public Object[] bubblesort(Object[] tosort) { Boolean sorting; int upperlimit = tosort.length - 1; do { sorting = false; for (int s0 = 0; s0 < upperlimit; s0++) { if (tosort[s0].toString().compareTo(tosort[s0 + 1].toString()) < 0) { } else if (tosort[s0].toString().compareTo(tosort[s0 + 1].toString()) == 0) { Object[] tosortnew = new Object[tosort.length - 1]; for (int tmp = 0; tmp < s0; tmp++) { tosortnew[tmp] = tosort[tmp]; } for (int tmp = s0; tmp < tosortnew.length; tmp++) { tosortnew[tmp] = tosort[tmp + 1]; } tosort = tosortnew; upperlimit = upperlimit - 1; s0 = s0 - 1; } else if (tosort[s0].toString().compareTo(tosort[s0 + 1].toString()) > 0) { String swap = (String) tosort[s0]; tosort[s0] = tosort[s0 + 1]; tosort[s0 + 1] = swap; sorting = true; } } upperlimit = upperlimit - 1; } while (sorting); return tosort; } Code Sample 2: @Override public void start() { System.err.println("start AutoplotApplet " + VERSION + " @ " + (System.currentTimeMillis() - t0) + " msec"); super.start(); model = new ApplicationModel(); model.setExceptionHandler(new ExceptionHandler() { public void handle(Throwable t) { t.printStackTrace(); } public void handleUncaught(Throwable t) { t.printStackTrace(); } }); model.setApplet(true); model.dom.getOptions().setAutolayout(false); System.err.println("ApplicationModel created @ " + (System.currentTimeMillis() - t0) + " msec"); model.addDasPeersToApp(); System.err.println("done addDasPeersToApp @ " + (System.currentTimeMillis() - t0) + " msec"); try { System.err.println("Formatters: " + DataSourceRegistry.getInstance().getFormatterExtensions()); } catch (Exception ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } ApplicationModel appmodel = model; dom = model.getDocumentModel(); String debug = getParameter("debug"); if (debug != null && !debug.equals("true")) { } int width = getIntParameter("width", 700); int height = getIntParameter("height", 400); String fontParam = getStringParameter("font", ""); String column = getStringParameter("column", ""); String row = getStringParameter("row", ""); String scolor = getStringParameter("color", ""); String srenderType = getStringParameter("renderType", ""); String stimeRange = getStringParameter("timeRange", ""); String sfillColor = getStringParameter("fillColor", ""); String sforegroundColor = getStringParameter("foregroundColor", ""); String sbackgroundColor = getStringParameter("backgroundColor", ""); String title = getStringParameter("plot.title", ""); String xlabel = getStringParameter("plot.xaxis.label", ""); String xrange = getStringParameter("plot.xaxis.range", ""); String xlog = getStringParameter("plot.xaxis.log", ""); String xdrawTickLabels = getStringParameter("plot.xaxis.drawTickLabels", ""); String ylabel = getStringParameter("plot.yaxis.label", ""); String yrange = getStringParameter("plot.yaxis.range", ""); String ylog = getStringParameter("plot.yaxis.log", ""); String ydrawTickLabels = getStringParameter("plot.yaxis.drawTickLabels", ""); String zlabel = getStringParameter("plot.zaxis.label", ""); String zrange = getStringParameter("plot.zaxis.range", ""); String zlog = getStringParameter("plot.zaxis.log", ""); String zdrawTickLabels = getStringParameter("plot.zaxis.drawTickLabels", ""); statusCallback = getStringParameter("statusCallback", ""); timeCallback = getStringParameter("timeCallback", ""); clickCallback = getStringParameter("clickCallback", ""); if (srenderType.equals("fill_to_zero")) { srenderType = "fillToZero"; } setInitializationStatus("readParameters"); System.err.println("done readParameters @ " + (System.currentTimeMillis() - t0) + " msec"); String vap = getParameter("vap"); if (vap != null) { InputStream in = null; try { URL url = new URL(vap); System.err.println("load vap " + url + " @ " + (System.currentTimeMillis() - t0) + " msec"); in = url.openStream(); System.err.println("open vap stream " + url + " @ " + (System.currentTimeMillis() - t0) + " msec"); appmodel.doOpen(in, null); System.err.println("done open vap @ " + (System.currentTimeMillis() - t0) + " msec"); appmodel.waitUntilIdle(false); System.err.println("done load vap and waitUntilIdle @ " + (System.currentTimeMillis() - t0) + " msec"); Canvas cc = appmodel.getDocumentModel().getCanvases(0); System.err.println("vap height, width= " + cc.getHeight() + "," + cc.getWidth()); width = getIntParameter("width", cc.getWidth()); height = getIntParameter("height", cc.getHeight()); System.err.println("output height, width= " + width + "," + height); } catch (InterruptedException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } finally { try { in.close(); } catch (IOException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } } appmodel.getCanvas().setSize(width, height); appmodel.getCanvas().revalidate(); appmodel.getCanvas().setPrintingTag(""); dom.getOptions().setAutolayout("true".equals(getParameter("autolayout"))); if (!dom.getOptions().isAutolayout() && vap == null) { if (!row.equals("")) { dom.getController().getCanvas().getController().setRow(row); } if (!column.equals("")) { dom.getController().getCanvas().getController().setColumn(column); } dom.getCanvases(0).getRows(0).setTop("0%"); dom.getCanvases(0).getRows(0).setBottom("100%"); } if (!fontParam.equals("")) { appmodel.canvas.setBaseFont(Font.decode(fontParam)); } JMenuItem item; item = new JMenuItem(new AbstractAction("Reset Zoom") { public void actionPerformed(ActionEvent e) { resetZoom(); } }); dom.getPlots(0).getController().getDasPlot().getDasMouseInputAdapter().addMenuItem(item); overviewMenuItem = new JCheckBoxMenuItem(new AbstractAction("Context Overview") { public void actionPerformed(ActionEvent e) { addOverview(); } }); dom.getPlots(0).getController().getDasPlot().getDasMouseInputAdapter().addMenuItem(overviewMenuItem); if (sforegroundColor != null && !sforegroundColor.equals("")) { appmodel.canvas.setForeground(Color.decode(sforegroundColor)); } if (sbackgroundColor != null && !sbackgroundColor.equals("")) { appmodel.canvas.setBackground(Color.decode(sbackgroundColor)); } getContentPane().setLayout(new BorderLayout()); System.err.println("done set parameters @ " + (System.currentTimeMillis() - t0) + " msec"); String surl = getParameter("url"); String process = getStringParameter("process", ""); String script = getStringParameter("script", ""); if (surl == null) { surl = getParameter("dataSetURL"); } if (surl != null && !surl.equals("")) { DataSource dsource; try { dsource = DataSetURI.getDataSource(surl); System.err.println("get dsource for " + surl + " @ " + (System.currentTimeMillis() - t0) + " msec"); System.err.println(" got dsource=" + dsource); System.err.println(" dsource.getClass()=" + dsource.getClass()); } catch (NullPointerException ex) { throw new RuntimeException("No such data source: ", ex); } catch (Exception ex) { ex.printStackTrace(); dsource = null; } DatumRange timeRange1 = null; if (!stimeRange.equals("")) { timeRange1 = DatumRangeUtil.parseTimeRangeValid(stimeRange); TimeSeriesBrowse tsb = dsource.getCapability(TimeSeriesBrowse.class); if (tsb != null) { System.err.println("do tsb.setTimeRange @ " + (System.currentTimeMillis() - t0) + " msec"); tsb.setTimeRange(timeRange1); System.err.println("done tsb.setTimeRange @ " + (System.currentTimeMillis() - t0) + " msec"); } } QDataSet ds; if (dsource != null) { TimeSeriesBrowse tsb = dsource.getCapability(TimeSeriesBrowse.class); if (tsb == null) { try { System.err.println("do getDataSet @ " + (System.currentTimeMillis() - t0) + " msec"); System.err.println(" dsource=" + dsource); System.err.println(" dsource.getClass()=" + dsource.getClass()); if (dsource.getClass().toString().contains("CsvDataSource")) System.err.println(" WHY IS THIS CsvDataSource!?!?"); ds = dsource == null ? null : dsource.getDataSet(loadInitialMonitor); for (int i = 0; i < Math.min(12, ds.length()); i++) { System.err.printf("ds[%d]=%s\n", i, ds.slice(i)); } System.err.println("loaded ds: " + ds); System.err.println("done getDataSet @ " + (System.currentTimeMillis() - t0) + " msec"); } catch (Exception ex) { throw new RuntimeException(ex); } } } System.err.println("do setDataSource @ " + (System.currentTimeMillis() - t0) + " msec"); appmodel.setDataSource(dsource); System.err.println("done setDataSource @ " + (System.currentTimeMillis() - t0) + " msec"); setInitializationStatus("dataSourceSet"); if (stimeRange != null && !stimeRange.equals("")) { try { System.err.println("wait for idle @ " + (System.currentTimeMillis() - t0) + " msec (due to stimeRange)"); appmodel.waitUntilIdle(true); System.err.println("done wait for idle @ " + (System.currentTimeMillis() - t0) + " msec"); } catch (InterruptedException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } if (UnitsUtil.isTimeLocation(dom.getTimeRange().getUnits())) { dom.setTimeRange(timeRange1); } } setInitializationStatus("dataSetLoaded"); } System.err.println("done dataSetLoaded @ " + (System.currentTimeMillis() - t0) + " msec"); Plot p = dom.getController().getPlot(); if (!title.equals("")) { p.setTitle(title); } Axis axis = p.getXaxis(); if (!xlabel.equals("")) { axis.setLabel(xlabel); } if (!xrange.equals("")) { try { Units u = axis.getController().getDasAxis().getUnits(); DatumRange newRange = DatumRangeUtil.parseDatumRange(xrange, u); axis.setRange(newRange); } catch (ParseException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } if (!xlog.equals("")) { axis.setLog("true".equals(xlog)); } if (!xdrawTickLabels.equals("")) { axis.setDrawTickLabels("true".equals(xdrawTickLabels)); } axis = p.getYaxis(); if (!ylabel.equals("")) { axis.setLabel(ylabel); } if (!yrange.equals("")) { try { Units u = axis.getController().getDasAxis().getUnits(); DatumRange newRange = DatumRangeUtil.parseDatumRange(yrange, u); axis.setRange(newRange); } catch (ParseException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } if (!ylog.equals("")) { axis.setLog("true".equals(ylog)); } if (!ydrawTickLabels.equals("")) { axis.setDrawTickLabels("true".equals(ydrawTickLabels)); } axis = p.getZaxis(); if (!zlabel.equals("")) { axis.setLabel(zlabel); } if (!zrange.equals("")) { try { Units u = axis.getController().getDasAxis().getUnits(); DatumRange newRange = DatumRangeUtil.parseDatumRange(zrange, u); axis.setRange(newRange); } catch (ParseException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } if (!zlog.equals("")) { axis.setLog("true".equals(zlog)); } if (!zdrawTickLabels.equals("")) { axis.setDrawTickLabels("true".equals(zdrawTickLabels)); } if (srenderType != null && !srenderType.equals("")) { try { RenderType renderType = RenderType.valueOf(srenderType); dom.getController().getPlotElement().setRenderType(renderType); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } } System.err.println("done setRenderType @ " + (System.currentTimeMillis() - t0) + " msec"); if (!scolor.equals("")) { try { dom.getController().getPlotElement().getStyle().setColor(Color.decode(scolor)); } catch (Exception ex) { ex.printStackTrace(); } } if (!sfillColor.equals("")) { try { dom.getController().getPlotElement().getStyle().setFillColor(Color.decode(sfillColor)); } catch (Exception ex) { ex.printStackTrace(); } } if (!sforegroundColor.equals("")) { try { dom.getOptions().setForeground(Color.decode(sforegroundColor)); } catch (Exception ex) { ex.printStackTrace(); } } if (!sbackgroundColor.equals("")) { try { dom.getOptions().setBackground(Color.decode(sbackgroundColor)); } catch (Exception ex) { ex.printStackTrace(); } } surl = getParameter("dataSetURL"); if (surl != null) { if (surl.startsWith("about:")) { setDataSetURL(surl); } else { } } getContentPane().remove(progressComponent); getContentPane().add(model.getCanvas()); System.err.println("done add to applet @ " + (System.currentTimeMillis() - t0) + " msec"); validate(); System.err.println("done applet.validate @ " + (System.currentTimeMillis() - t0) + " msec"); repaint(); appmodel.getCanvas().setVisible(true); initializing = false; repaint(); System.err.println("ready @ " + (System.currentTimeMillis() - t0) + " msec"); setInitializationStatus("ready"); dom.getController().getPlot().getXaxis().addPropertyChangeListener(Axis.PROP_RANGE, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { timeCallback(String.valueOf(evt.getNewValue())); } }); if (!clickCallback.equals("")) { String clickCallbackLabel = "Applet Click"; int i = clickCallback.indexOf(","); if (i != -1) { int i2 = clickCallback.indexOf("label="); if (i2 != -1) clickCallbackLabel = clickCallback.substring(i2 + 6).trim(); clickCallback = clickCallback.substring(0, i).trim(); } final DasPlot plot = dom.getPlots(0).getController().getDasPlot(); MouseModule mm = new MouseModule(plot, new CrossHairRenderer(plot, null, plot.getXAxis(), plot.getYAxis()), clickCallbackLabel) { @Override public void mousePressed(MouseEvent e) { e = SwingUtilities.convertMouseEvent(plot, e, plot.getCanvas()); clickCallback(dom.getPlots(0).getId(), plot, e); } @Override public void mouseDragged(MouseEvent e) { e = SwingUtilities.convertMouseEvent(plot, e, plot.getCanvas()); clickCallback(dom.getPlots(0).getId(), plot, e); } @Override public void mouseReleased(MouseEvent e) { e = SwingUtilities.convertMouseEvent(plot, e, plot.getCanvas()); clickCallback(dom.getPlots(0).getId(), plot, e); } }; plot.getDasMouseInputAdapter().setPrimaryModule(mm); } p.getController().getDasPlot().getDasMouseInputAdapter().removeMenuItem("Properties"); dom.getPlots(0).getXaxis().getController().getDasAxis().getDasMouseInputAdapter().removeMenuItem("Properties"); dom.getPlots(0).getYaxis().getController().getDasAxis().getDasMouseInputAdapter().removeMenuItem("Properties"); dom.getPlots(0).getZaxis().getController().getDasAxis().getDasMouseInputAdapter().removeMenuItem("Properties"); if (getStringParameter("contextOverview", "off").equals("on")) { Runnable run = new Runnable() { public void run() { dom.getController().waitUntilIdle(); try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } dom.getController().waitUntilIdle(); doSetOverview(true); } }; new Thread(run).start(); } System.err.println("done start AutoplotApplet " + VERSION + " @ " + (System.currentTimeMillis() - t0) + " msec"); }
11
Code Sample 1: private static void copyObjects(File[] source, String target) { for (int i = 0; i < source.length; i++) { try { File inputFile = source[i]; File outputFile = new File(target + source[i].getName()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { Logger.error(ex.getClass() + " " + ex.getMessage()); for (int j = 0; j < ex.getStackTrace().length; j++) Logger.error(" " + ex.getStackTrace()[j].toString()); ex.printStackTrace(); } } } Code Sample 2: private void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } }
11
Code Sample 1: private long config(final String options) throws SQLException { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } msgDigest.update(options.getBytes()); final String md5sum = Concrete.md5(msgDigest.digest()); Statement stmt = connection.createStatement(); ResultSet rst = stmt.executeQuery("SELECT configId FROM configs WHERE md5='" + md5sum + "'"); final long configId; if (rst.next()) { configId = rst.getInt(1); } else { stmt.executeUpdate("INSERT INTO configs(config, md5) VALUES ('" + options + "', '" + md5sum + "')"); ResultSet aiRst = stmt.getGeneratedKeys(); if (aiRst.next()) { configId = aiRst.getInt(1); } else { throw new SQLException("Could not retrieve generated id"); } } stmt.executeUpdate("UPDATE executions SET configId=" + configId + " WHERE executionId=" + executionId); return configId; } Code Sample 2: public static String md5(String word) { MessageDigest alg = null; try { alg = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ServletUtils.class.getName()).log(Level.SEVERE, null, ex); } alg.reset(); alg.update(word.getBytes()); byte[] digest = alg.digest(); StringBuilder hashedWord = new StringBuilder(); String hx; for (int i = 0; i < digest.length; i++) { hx = Integer.toHexString(0xFF & digest[i]); if (hx.length() == 1) { hx = "0" + hx; } hashedWord.append(hx); } return hashedWord.toString(); }
00
Code Sample 1: public static void copyFile(File file, File destination) throws Exception { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(file)); out = new BufferedOutputStream(new FileOutputStream(destination)); int c; while ((c = in.read()) != -1) out.write(c); } finally { try { if (out != null) out.close(); } catch (Exception e) { } try { if (in != null) in.close(); } catch (Exception e) { } } } Code Sample 2: public void download(String target) { try { if (url == null) return; conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "Internet Explorer"); conn.setReadTimeout(10000); conn.connect(); httpReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); java.io.BufferedWriter out = new BufferedWriter(new FileWriter(target, false)); String str = httpReader.readLine(); while (str != null) { out.write(str); str = httpReader.readLine(); } out.close(); System.out.println("file download successfully: " + url.getHost() + url.getPath()); System.out.println("saved to: " + target); } catch (Exception e) { System.out.println("file download failed: " + url.getHost() + url.getPath()); e.printStackTrace(); } }
11
Code Sample 1: private void copy(File in, File out) { log.info("Copying yam file from: " + in.getName() + " to: " + out.getName()); try { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (IOException ioe) { fail("Failed testing while copying modified file: " + ioe.getMessage()); } } Code Sample 2: public static void fileCopy(final File src, final File dest, final boolean overwrite) throws IOException { if (!dest.exists() || (dest.exists() && overwrite)) { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } }
00
Code Sample 1: @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")); } Code Sample 2: InputStream selectSource(String item) { if (item.endsWith(".pls")) { item = fetch_pls(item); if (item == null) return null; } else if (item.endsWith(".m3u")) { item = fetch_m3u(item); if (item == null) return null; } if (!item.endsWith(".ogg")) { return null; } InputStream is = null; URLConnection urlc = null; try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), item); else url = new URL(item); urlc = url.openConnection(); is = urlc.getInputStream(); current_source = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + url.getFile(); } catch (Exception ee) { System.err.println(ee); } if (is == null && !running_as_applet) { try { is = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + item); current_source = null; } catch (Exception ee) { System.err.println(ee); } } if (is == null) return null; System.out.println("Select: " + item); { boolean find = false; for (int i = 0; i < cb.getItemCount(); i++) { String foo = (String) (cb.getItemAt(i)); if (item.equals(foo)) { find = true; break; } } if (!find) { cb.addItem(item); } } int i = 0; String s = null; String t = null; udp_port = -1; udp_baddress = null; while (urlc != null && true) { s = urlc.getHeaderField(i); t = urlc.getHeaderFieldKey(i); if (s == null) break; i++; if (t != null && t.equals("udp-port")) { try { udp_port = Integer.parseInt(s); } catch (Exception ee) { System.err.println(ee); } } else if (t != null && t.equals("udp-broadcast-address")) { udp_baddress = s; } } return is; }
11
Code Sample 1: 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(); } } 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 { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: public static void find(String pckgname, Class<?> tosubclass) { String name = new String(pckgname); if (!name.startsWith("/")) { name = "/" + name; } name = name.replace('.', '/'); URL url = tosubclass.getResource(name); System.out.println(name + "->" + url); if (url == null) return; File directory = new File(url.getFile()); if (directory.exists()) { String[] files = directory.list(); for (int i = 0; i < files.length; i++) { if (files[i].endsWith(".class")) { String classname = files[i].substring(0, files[i].length() - 6); try { Object o = Class.forName(pckgname + "." + classname).newInstance(); if (tosubclass.isInstance(o)) { System.out.println(classname); } } catch (ClassNotFoundException cnfex) { System.err.println(cnfex); } catch (InstantiationException iex) { } catch (IllegalAccessException iaex) { } } } } else { try { JarURLConnection conn = (JarURLConnection) url.openConnection(); String starts = conn.getEntryName(); JarFile jfile = conn.getJarFile(); Enumeration<JarEntry> e = jfile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); String entryname = entry.getName(); if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length()) && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) classname = classname.substring(1); classname = classname.replace('/', '.'); try { Object o = Class.forName(classname).newInstance(); if (tosubclass.isInstance(o)) { System.out.println(classname.substring(classname.lastIndexOf('.') + 1)); } } catch (ClassNotFoundException cnfex) { System.err.println(cnfex); } catch (InstantiationException iex) { } catch (IllegalAccessException iaex) { } } } } catch (IOException ioex) { System.err.println(ioex); } } }
11
Code Sample 1: public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) destFile.createNewFile(); FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public static void main(String args[]) { Connection con; if (args.length != 2) { System.out.println("Usage: Shutdown <host> <password>"); System.exit(0); } try { con = new Connection(args[0]); con.tStart(); Message message = new Message(MessageTypes.SHUTDOWN_SERVER); java.security.MessageDigest hash = java.security.MessageDigest.getInstance("SHA-1"); hash.update(args[1].getBytes("UTF-8")); message.put("pwhash", hash.digest()); con.send(message); con.join(); } catch (java.io.UnsupportedEncodingException e) { System.err.println("Password character encoding not supported."); } catch (java.io.IOException e) { System.out.println(e.toString()); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("Password hash algorithm SHA-1 not supported by runtime."); } catch (InterruptedException e) { } System.exit(0); } Code Sample 2: public boolean doUpload(int count) { String objFileName = Long.toString(new java.util.Date().getTime()) + Integer.toString(count); try { this.objectFileName[count] = objFileName + "_bak." + this.sourceFileExt[count]; File objFile = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); if (objFile.exists()) { this.doUpload(count); } else { objFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(objFile); BufferedOutputStream bos = new BufferedOutputStream(fos); int readLength = 0; int offset = 0; String str = ""; long readSize = 0L; while ((readLength = this.inStream.readLine(this.b, 0, this.b.length)) != -1) { str = new String(this.b, 0, readLength); if (str.indexOf("Content-Type:") != -1) { break; } } this.inStream.readLine(this.b, 0, this.b.length); while ((readLength = this.inStream.readLine(this.b, 0, b.length)) != -1) { str = new String(this.b, 0, readLength); if (this.b[0] == 45 && this.b[1] == 45 && this.b[2] == 45 && this.b[3] == 45 && this.b[4] == 45) { break; } bos.write(this.b, 0, readLength); readSize += readLength; if (readSize > this.size) { this.fileMessage[count] = "�ϴ��ļ������ļ���С�������ƣ�"; this.ok = false; break; } } if (this.ok) { bos.flush(); bos.close(); int fileLength = (int) (objFile.length()); byte[] bb = new byte[fileLength - 2]; FileInputStream fis = new FileInputStream(objFile); BufferedInputStream bis = new BufferedInputStream(fis); bis.read(bb, 0, (fileLength - 2)); fis.close(); bis.close(); this.objectFileName[count] = objFileName + "." + this.sourceFileExt[count]; File ok_file = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); ok_file.createNewFile(); BufferedOutputStream bos_ok = new BufferedOutputStream(new FileOutputStream(ok_file)); bos_ok.write(bb); bos_ok.close(); objFile.delete(); this.fileMessage[count] = "OK"; return true; } else { bos.flush(); bos.close(); File delFile = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); delFile.delete(); this.objectFileName[count] = "none"; return false; } } catch (Exception e) { this.objectFileName[count] = "none"; this.fileMessage[count] = e.toString(); return false; } }
11
Code Sample 1: public static Object deployNewService(String scNodeRmiName, String userName, String password, String name, String jarName, String serviceClass, String serviceInterface, Logger log) throws RemoteException, MalformedURLException, StartServiceException, NotBoundException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, SessionException { try { SCNodeInterface node = (SCNodeInterface) Naming.lookup(scNodeRmiName); String session = node.login(userName, password); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(new FileInputStream(jarName), baos); ServiceAdapterIfc adapter = node.deploy(session, name, baos.toByteArray(), jarName, serviceClass, serviceInterface); if (adapter != null) { return new ExternalDomain(node, adapter, adapter.getUri(), log).getProxy(Thread.currentThread().getContextClassLoader()); } } catch (Exception e) { log.warn("Could not send deploy command: " + e.getMessage(), e); } return null; } Code Sample 2: public Parameters getParameters(HttpExchange http) throws IOException { ParametersImpl params = new ParametersImpl(); String query = null; if (http.getRequestMethod().equalsIgnoreCase("GET")) { query = http.getRequestURI().getRawQuery(); } else if (http.getRequestMethod().equalsIgnoreCase("POST")) { InputStream in = new MaxInputStream(http.getRequestBody()); if (in != null) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IOUtils.copyTo(in, bytes); query = new String(bytes.toByteArray()); in.close(); } } else { throw new IOException("Method not supported " + http.getRequestMethod()); } if (query != null) { for (String s : query.split("[&]")) { s = s.replace('+', ' '); int eq = s.indexOf('='); if (eq > 0) { params.add(URLDecoder.decode(s.substring(0, eq), "UTF-8"), URLDecoder.decode(s.substring(eq + 1), "UTF-8")); } } } return params; }
11
Code Sample 1: public void display(WebPage page, HttpServletRequest req, HttpServletResponse resp) throws DisplayException { page.getDisplayInitialiser().initDisplay(new HttpRequestDisplayContext(req), req); StreamProvider is = (StreamProvider) req.getAttribute(INPUTSTREAM_KEY); if (is == null) { throw new IllegalStateException("No OutputStreamDisplayHandlerXML.InputStream found in request attribute" + " OutputStreamDisplayHandlerXML.INPUTSTREAM_KEY"); } resp.setContentType(is.getMimeType()); resp.setHeader("Content-Disposition", "attachment;filename=" + is.getName()); try { InputStream in = is.getInputStream(); OutputStream out = resp.getOutputStream(); if (in != null) { IOUtils.copy(in, out); } is.write(resp.getOutputStream()); resp.flushBuffer(); } catch (IOException e) { throw new DisplayException("Error writing input stream to response", e); } } Code Sample 2: public void setContentAsStream(final InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { output.close(); } this.content = output.toByteArray(); }
00
Code Sample 1: public boolean actualizarIdPartida(int idJugadorDiv, int idRonda, int idPartida) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPartida = " + idPartida + " WHERE jugadorxDivision_idJugadorxDivision = " + idJugadorDiv + " AND ronda_numeroRonda = " + idRonda; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); 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: private Document saveFile(Document document, File file) throws Exception { List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { preference = preferences.get(0); } SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); String repo = preference.getRepository(); Calendar calendar = Calendar.getInstance(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(sdf.format(calendar.getTime())); sbFolder.append(File.separator).append(calendar.get(Calendar.HOUR_OF_DAY)); File folder = new File(sbRepo.append(sbFolder).toString()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()); StringBuffer fname = new StringBuffer(document.getId().toString()); fname.append(".").append(document.getExt()); sbFile.append(File.separator).append(fname); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } return document; }
00
Code Sample 1: private void populateJarsFromManifest(Set<String> jars, ClassLoader loader) { BufferedReader reader = null; try { Enumeration<URL> e = loader.getResources("META-INF/MANIFEST.MF"); while (e.hasMoreElements()) { URL url = e.nextElement(); if (url.getPath().contains(SURE_FIRE_BOOTER_JAR)) { reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; StringBuffer content = new StringBuffer(); while ((line = reader.readLine()) != null) { content.append(line.trim()); } String cont = content.toString().replaceAll("Manifest-Version: 1.0Class-Path: ", "").replaceAll("Main-Class: org.apache.maven.surefire.booter.SurefireBooter", ""); for (String file : cont.split(" ")) { if (file.contains("file")) { jars.add(file.replaceAll("file:", "")); } } break; } } } catch (IOException e) { log.error("", e); } finally { try { if (reader != null) { reader.close(); } } catch (Exception e) { log.error("", e); } } } Code Sample 2: public void init(String file) { URL url = SoundFactory.class.getResource(file); try { JAXBContext context = JAXBContext.newInstance("elf.xml.sounds"); Unmarshaller unmarshaller = context.createUnmarshaller(); SoundsBaseType root = null; Object tmpobj = unmarshaller.unmarshal(url.openConnection().getInputStream()); if (tmpobj instanceof JAXBElement<?>) { if (((JAXBElement<?>) tmpobj).getValue() instanceof SoundsBaseType) { root = (SoundsBaseType) ((JAXBElement<?>) tmpobj).getValue(); addMusic("MENUSONG", root.getMenumusic().getMusicpath()); List<SoundsMusicType> musiclist = root.getMusic(); Iterator<SoundsMusicType> it = musiclist.iterator(); while (it.hasNext()) { SoundsMusicType smt = it.next(); addMusic(smt.getMusicname(), smt.getMusicpath()); } } } } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { BufferedInputStream is = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[1024]; int count = 0; while ((count = is.read(buf, 0, 1024)) != -1) os.write(buf, 0, count); is.close(); os.close(); } Code Sample 2: public void guardarRecordatorio() { try { if (espaciosLlenos()) { guardarCantidad(); String dat = ""; String filenametxt = String.valueOf("recordatorio" + cantidadArchivos + ".txt"); String filenamezip = String.valueOf("recordatorio" + cantidadArchivos + ".zip"); cantidadArchivos++; dat += identificarDato(datoSeleccionado) + "\n"; dat += String.valueOf(mesTemporal) + "\n"; dat += String.valueOf(anoTemporal) + "\n"; dat += horaT.getText() + "\n"; dat += lugarT.getText() + "\n"; dat += actividadT.getText() + "\n"; File archivo = new File(filenametxt); FileWriter fw = new FileWriter(archivo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter salida = new PrintWriter(bw); salida.print(dat); salida.close(); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filenamezip); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[buffer]; File f = new File(filenametxt); FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, buffer); ZipEntry entry = new ZipEntry(filenametxt); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, buffer)) != -1) out.write(data, 0, count); out.close(); JOptionPane.showMessageDialog(null, "El recordatorio ha sido guardado con exito", "Recordatorio Guardado", JOptionPane.INFORMATION_MESSAGE); marco.hide(); marco.dispose(); establecerMarca(); table.clearSelection(); } else JOptionPane.showMessageDialog(null, "Debe llenar los espacios de Hora, Lugar y Actividad", "Error", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
00
Code Sample 1: public void bubbleSort(int[] arr) { boolean swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < arr.length - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } } Code Sample 2: protected static String encodePassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); return HexString.bufferToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
11
Code Sample 1: public DoSearch(String searchType, String searchString) { String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerDoSearch"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "search.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + key + "&search=" + URLEncoder.encode(searchString, "UTF-8") + "&searchtype=" + URLEncoder.encode(searchType, "UTF-8") + "&filename=" + URLEncoder.encode(username, "UTF-8") + "search.xml"; ; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("entry"); int num = nodelist.getLength(); searchDocs = new String[num][3]; searchDocImageName = new String[num]; searchDocsToolTip = new String[num]; for (int i = 0; i < num; i++) { searchDocs[i][0] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "filename"); searchDocs[i][1] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "project"); searchDocs[i][2] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "documentid"); searchDocImageName[i] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "imagename"); searchDocsToolTip[i] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "description"); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (Exception ex) { System.out.println(ex); } System.out.println(rvalue); if (rvalue.equalsIgnoreCase("yes")) { } } Code Sample 2: public void run() { try { File inf = new File(dest); if (!inf.exists()) { inf.getParentFile().mkdirs(); } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); out.transferFrom(in, 0, in.size()); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); System.err.println("Error copying file \n" + src + "\n" + dest); } }