public BookCatalogImpl() { try { final String filePath = path + "catalog.json"; // read the json file ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream inputStream = classLoader.getResourceAsStream(filePath); BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); bookStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) bookStrBuilder.append(inputStr); final ObjectMapper mapper = new ObjectMapper(); catalog = mapper.readValue(bookStrBuilder.toString(), new TypeReference<List<Book>>() {}); hBookDetails = new Hashtable(); for (Book book : catalog) { hBookDetails.put(book.getId(), book); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (NullPointerException ex) { ex.printStackTrace(); } }
private static String convertLocalURLTag(final String name, final String arg) { if (name.equals("sprite")) { try { Pony tmp = PonyCreator.create(arg); return "" + tmp.getFrontSprite(); } catch (ReflectiveOperationException e) { printDebug("[Meta.toLocalURL] Error creating pony " + arg + ": " + e); e.printStackTrace(); } } else if (name.equals("type")) { try { return "" + pokepon.enums.Type.forName(arg).getToken(); } catch (NullPointerException e) { printDebug("[Meta.toLocalURL] Error creating type " + arg); e.printStackTrace(); } } else if (name.equals("movetype")) { try { return "" + Move.MoveType.forName(arg).getToken(); } catch (NullPointerException e) { printDebug("[Meta.toLocalURL] Error creating movetype " + arg); e.printStackTrace(); } } return ""; }
/** * Parse a single part * * @param ts * @throws java.io.IOException * @throws org.apache.cocoon.servlet.multipart.MultipartException */ private void parsePart(DSpaceTokenStream ts) throws IOException, MultipartException { Hashtable headers = new Hashtable(); headers = readHeaders(ts); try { if (headers.containsKey("filename")) { if (!"".equals(headers.get("filename"))) { parseFilePart(ts, headers); } else { // IE6 sends an empty part with filename="" for // empty upload fields. Just parse away the part byte[] buf = new byte[32]; while (ts.getState() == DSpaceTokenStream.STATE_READING) ts.read(buf); } } else if (((String) headers.get("content-disposition")).toLowerCase().equals("form-data")) { parseInlinePart(ts, headers); } // FIXME: multipart/mixed parts are untested. else if (((String) headers.get("content-disposition")).toLowerCase().indexOf("multipart") > -1) { parseMultiPart( new DSpaceTokenStream(ts, MAX_BOUNDARY_SIZE), "--" + (String) headers.get("boundary")); ts.read(); // read past boundary } else { throw new MultipartException("Unknown part type"); } } catch (IOException e) { throw new MultipartException("Malformed stream: " + e.getMessage()); } catch (NullPointerException e) { e.printStackTrace(); throw new MultipartException("Malformed header"); } }
public boolean intersects(int x, int y, Rectangle rectangle) { try { Rectangle up = new Rectangle(rectangle.getX(), rectangle.getY() - 2, rectangle.getWidth(), 1); Rectangle right = new Rectangle( rectangle.getX() + rectangle.getWidth() + 1, rectangle.getY(), 1, rectangle.getHeight()); Rectangle down = new Rectangle( rectangle.getX(), rectangle.getY() + rectangle.getHeight() + 1, rectangle.getWidth(), 1); Rectangle left = new Rectangle(rectangle.getX() - 2, rectangle.getY(), 1, rectangle.getHeight()); Rectangle rect = blocks[x][y].getRect(); return (rect.intersects(up) || rect.intersects(right) || rect.intersects(down) || rect.intersects(left)); } catch (NullPointerException e) { logger.log("NullPointerException in World.intersects(int, int, Rectangle)", Level.DEBUG); logger.log("Stack:", Level.DEBUG); logger.log(e.getMessage(), Level.DEBUG); } return false; }
public trafficReceiver() { try { OISforTG = new ObjectInputStream(socketForTG.getInputStream()); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException npe) { npe.printStackTrace(); } }
public void actionPerformed(ActionEvent e) { JTextField fieldEdited = (JTextField) e.getSource(); try { editingClassName = fieldEdited.getText(); } catch (NullPointerException npex) { System.out.println("Null pointer exception in getting java class name"); npex.printStackTrace(); } String updatedStatusText = prepareStatusText(); statusAreaTop.setText(updatedStatusText); }
private void doSolve() { try { gg.solve(); sinchronizeGrids(); setGridToFinished(); sGrid.repaint(); } catch (NullPointerException e) { e.printStackTrace(); JOptionPane.showMessageDialog( this, "Sudoku seems to be solved.", "Solved", JOptionPane.INFORMATION_MESSAGE); } }
static void writeToFile(RandomAccessFile rf, FileSendingFormat ff) { synchronized (rf) { try { System.out.println(">>>>>" + ff.length + " >>>" + ff.ary.length); rf.seek(ff.from); rf.write(ff.ary, 0, ff.length); // System.out.append(" "+) } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException n) { n.printStackTrace(); } // System.out.println("rf "+rf.getFilePointer()+) } }
public InstanceBlock[] intersects(Rectangle rectangle) { InstanceBlock[] ret = new InstanceBlock[4]; try { for (int x = 0; x < BWIDTH; x++) { for (int y = 0; y < BHEIGHT; y++) { Block block = blocks[x][y].getBlock(); Rectangle rect = blocks[x][y].getRect(); if (block.isCollidable()) { Rectangle up = new Rectangle(rectangle.getX(), rectangle.getY() - 2, rectangle.getWidth(), 1); Rectangle right = new Rectangle( rectangle.getX() + rectangle.getWidth() + 1, rectangle.getY(), 1, rectangle.getHeight()); Rectangle down = new Rectangle( rectangle.getX(), rectangle.getY() + rectangle.getHeight() + 1, rectangle.getWidth(), 1); Rectangle left = new Rectangle(rectangle.getX() - 2, rectangle.getY(), 1, rectangle.getHeight()); if (rect.intersects(up)) { ret[Player.UP] = blocks[x][y]; } if (rect.intersects(right)) { ret[Player.RIGHT] = blocks[x][y]; } if (rect.intersects(down)) { ret[Player.DOWN] = blocks[x][y]; } if (rect.intersects(left)) { ret[Player.LEFT] = blocks[x][y]; } } } } } catch (NullPointerException e) { logger.log("NullPointerException in World.intersects(Rectangle)", Level.DEBUG); logger.log("Stack:", Level.DEBUG); logger.log(e.getMessage(), Level.DEBUG); } return ret; }
/** * Verifies the given ECDSA signature against the message bytes using the public key bytes. * * <p>When using native ECDSA verification, data must be 32 bytes, and no element may be larger * than 520 bytes. * * @param data Hash of the data to verify. * @param signature ASN.1 encoded signature. * @param pub The public key bytes to use. */ public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub) { ECDSASigner signer = new ECDSASigner(); ECPublicKeyParameters params = new ECPublicKeyParameters(CURVE.getCurve().decodePoint(pub), CURVE); signer.init(false, params); try { return signer.verifySignature(data, signature.r, signature.s); } catch (NullPointerException e) { // Bouncy Castle contains a bug that can cause NPEs given specially crafted signatures. Those // signatures // are inherently invalid/attack sigs so we just fail them here rather than crash the thread. log.error("Caught NPE inside bouncy castle"); e.printStackTrace(); return false; } }
/** * Function that creates a "ARCHIVE" folder that is going to contain all the archives that will be * created by this program. * * @return folder that is going to contain all the archives that will be created by this program */ private File createArchive() { archiveDirectory = null; try { String homePath = System.getProperty("user.home"); archiveDirectory = new File(homePath + File.separatorChar + "Archive"); if (!archiveDirectory.exists()) archiveDirectory.mkdir(); } catch (SecurityException ex) { ex.printStackTrace(); } catch (NullPointerException ex) { ex.printStackTrace(); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } return archiveDirectory; }
public void print_cd() { String file = "."; File file1 = new File(file); if (file1 != null) { try { File[] files = file1.listFiles(); for (File f : files) { System.out.println(f); } } catch (SecurityException s) { System.out.println("throws a SecurityException"); } catch (NullPointerException x) { x.printStackTrace(); } } }
public void draw() { try { for (int x = 0; x < BWIDTH; x++) for (int y = 0; y < BHEIGHT; y++) { if (!(blocks[x][y].getBlock() == Block.air)) blocks[x][y].draw(); } if (player != null) { player.draw(); } } catch (NullPointerException e) { logger.log("NullPointerException in World.intersects(Rectangle)", Level.DEBUG); logger.log("Stack:", Level.DEBUG); logger.log(e.getMessage(), Level.DEBUG); } }
TaskListInitialize(Queue taskQueue) { try { FileReader reader = new FileReader("D:/1.txt"); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(reader); JSONArray jsonArray = (JSONArray) jsonObject.get("URLlist"); for (int i = 0; i < jsonArray.size(); i++) { Task task = new Task(jsonArray.get(i).toString()); if (task != null) taskQueue.add(task); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (ParseException ex) { ex.printStackTrace(); } catch (NullPointerException ex) { ex.printStackTrace(); } }
@Override public void actionPerformed(ActionEvent action) { // Get the file the user wants to use and store it. if (action.getSource() == chooseFile) { // *sigh* I spent like 10 minutes trying to figure out why my if statement was not working // and then I found a semicolon on the end...noob mistake... // I had written a paragraph about it to send you too. if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { try { System.out.println( "File: " + fileChooser.getSelectedFile() + "\nInt: " + fileChooser.showOpenDialog(this)); file = fileChooser.getSelectedFile(); inputFile = new Scanner(file); if (JOptionPane.showConfirmDialog( this, "Overwrite orginal file?", "Overwrite Confimration", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { outputFile = new PrintWriter(file); } else { fileChooser.showOpenDialog(this); outputFile = new PrintWriter(fileChooser.getSelectedFile()); } // Enable the buttons now that a file has been chosen. sort.setEnabled(true); next.setEnabled(true); } catch (FileNotFoundException exception) { JOptionPane.showMessageDialog(this, "Error: Could not find or open file."); exception.printStackTrace(); } // Just in case something weird happens and all those files don't get linked correctly, // this will get called and prevent the buttons from being enabled. Essentially, the user // won't see anything. catch (NullPointerException exception) { sort.setEnabled(false); next.setEnabled(false); exception.printStackTrace(); } } } else if (action.getSource() == sort) { // Call the quicksort method to sort, and handle the file writing. while (inputFile.hasNextLine()) { arrayList.add(inputFile.nextLine()); } inputFile.close(); temp = new String[arrayList.size()]; array = arrayList.toArray(temp); sorter.quicksort(array, 0, array.length - 1); for (int i = 0; i < array.length; i++) { outputFile.println(array[i]); } outputFile.close(); JOptionPane.showMessageDialog(this, "List successfully sorted."); } else if (action.getSource() == next) { // Go to the search options. buttonPanel.remove(chooseFile); buttonPanel.remove(sort); buttonPanel.add(search); repaint(); setVisible(true); } else if (action.getSource() == exit) { // Exit, obviously. dispose(); } else if (action.getSource() == search) { // Call the binarySearch method and display the result. String searchValue = JOptionPane.showInputDialog("Enter the value to search for:"); boolean ignoreCase; int result; if (JOptionPane.showConfirmDialog( this, "Case-sensitive search?", "Case-sensitive", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) { ignoreCase = false; } else { ignoreCase = true; } result = searcher.binarySearch(array, searchValue, ignoreCase) + 1; if (result == 0) { text.setText("The value, " + searchValue + ", was not found."); } else { text.setText("The value, " + searchValue + ", was found on line: " + result + "."); } } }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter out = response.getWriter(); String id = request.getParameter("hashID"); JSONObject result = new JSONObject(); if (id != null && id.trim().isEmpty()) { response.setContentType("text/plain"); response.setStatus(400); out.println("Empty hash ID"); return; } Connection conn = null; Statement st = null; ResultSet rs = null; String password; try { // Read the SQL password from a file BufferedReader reader = null; try { InputStream inputStream = getClass().getClassLoader().getResourceAsStream("SQLpw.txt"); reader = new BufferedReader(new InputStreamReader(inputStream)); password = reader.readLine(); } catch (NullPointerException e) { e.getStackTrace(); password = ""; } // create a mysql database connection String myDriver = "com.mysql.jdbc.Driver"; String myUrl = "jdbc:mysql://localhost/lodstories"; Class.forName(myDriver); conn = DriverManager.getConnection(myUrl, "root", password); st = conn.createStatement(); rs = st.executeQuery("SELECT hash,title,author FROM hash_objects where id='" + id + "'"); if (!rs.next()) { response.setContentType("text/plain"); response.setStatus(400); out.println("Error retrieving hash object"); return; } result.put("hash", rs.getString("hash")); result.put("title", rs.getString("title")); result.put("author", rs.getString("author")); // result.put("path", rs.getString("path")); // result.put("rating", rs.getInt("rating")); // Update the lastAccessed field st.executeUpdate( "UPDATE hash_objects SET lastAccessed=CURRENT_TIMESTAMP() WHERE id='" + id + "'"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); out.println(result); } catch (ClassNotFoundException e) { System.err.println("Could not connect to driver!"); System.err.println(e.getMessage()); } catch (SQLException ex) { System.err.println( "SQLException: " + ex.getMessage() + ", SQLState: " + ex.getSQLState() + "VendorError: " + ex.getErrorCode()); } catch (JSONException ex) { ex.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } if (st != null) { try { st.close(); } catch (SQLException ex) { ex.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } }
public void bad() throws Throwable { if (private_t) { java.util.logging.Logger log2 = java.util.logging.Logger.getLogger("local-logger"); /* This code could be a part of a user questionnaire */ String address = null; BufferedReader bufread2 = null; InputStreamReader inread2 = null; try { IO.writeLine("Do you know your forwarding address (y/n)? "); inread2 = new InputStreamReader(System.in); bufread2 = new BufferedReader(inread2); if (bufread2.readLine().equalsIgnoreCase("y")) { IO.writeLine("Enter your forwarding address: "); inread2 = new InputStreamReader(System.in); bufread2 = new BufferedReader(inread2); address = bufread2.readLine(); } IO.writeLine( "bad() - address length = " + address.length()); /* INCIDENTAL: CWE476 Null Pointer Dereference */ } catch ( NullPointerException npe) /* FLAW: Use of catch block to detect null dereferences */ { IO.writeLine(npe.getMessage()); } catch (Exception e) { log2.warning("Error!"); } finally { try { if (bufread2 != null) { bufread2.close(); } } catch (IOException e) { log2.warning("Error closing bufread2"); } finally { try { if (inread2 != null) { inread2.close(); } } catch (IOException e) { log2.warning("Error closing inread2"); } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ java.util.logging.Logger log2 = java.util.logging.Logger.getLogger("local-logger"); /* This code could be a part of a user questionnaire */ String address = null; BufferedReader bufread2 = null; InputStreamReader inread2 = null; try { IO.writeLine("Do you know your forwarding address (y/n)? "); inread2 = new InputStreamReader(System.in); bufread2 = new BufferedReader(inread2); if (bufread2.readLine().equalsIgnoreCase("y")) { IO.writeLine("Enter your forwarding address: "); inread2 = new InputStreamReader(System.in); bufread2 = new BufferedReader(inread2); address = bufread2.readLine(); } } catch (Exception e) { log2.warning("Error!"); } finally { try { if (bufread2 != null) { bufread2.close(); } } catch (IOException e) { log2.warning("Error closing bufread2"); } finally { try { if (inread2 != null) { inread2.close(); } } catch (IOException e) { log2.warning("Error closing inread2"); } } } if (address != null) /* FIX: Check for null value before calling a method */ { IO.writeLine("good() - address length = " + address.length()); } } }
public void start() { Connection connection = null; // manages connection Connection connection2 = null; Statement statement = null; // query statement Statement statement2 = null; wm = new double[20][Data.windows_size]; String QueryKinasesName = "%" + Data.kinease + "%"; // data.code = data.codenames[3]; String QueryCodeName = Data.code; int windows_size = Data.windows_size; // int windows_size = 9; int shift = windows_size / 2; try { Class.forName(JDBC_DRIVER); // load database driver class for (windows_size = Data.windows_size; windows_size <= Data.windows_size; windows_size += 2) { shift = windows_size / 2; // establish connection to database connection = DriverManager.getConnection(DATABASE_URL, "", ""); connection2 = DriverManager.getConnection(DATABASE_URL, "", ""); // create Statement for querying database statement = connection.createStatement(); statement2 = connection2.createStatement(); String ACC = null; String SEQUENCE = null; String KINASES = null; String LIKE = "LIKE"; // int POSITION = 0; // int index = 0; String temp = null; // int numtemp = 0; // int LENGTH = (int) 0; // int count = 0; double[] totalAAcount = new double[windows_size]; double weightmatrix[][] = new double[windows_size][128]; // windowssize;aa; String statementquery1 = "SELECT Mid(sequence,(position-" + shift + ")," + windows_size + ") AS TARGET, index,code,length,position,sequence FROM Dataset_041106 WHERE ((position-" + shift + ")>1) AND ((position +" + shift + ")<length) AND kinases " + LIKE + " '" + QueryKinasesName + "' AND (code LIKE '" + QueryCodeName + "')"; System.out.println("#" + statementquery1); /// fout.println("#"+statementquery1); ResultSet resultSet1 = statement.executeQuery(statementquery1); int seqsize = 0; while ((resultSet1.next())) { String posseq = resultSet1.getString("TARGET"); seqsize = posseq.length(); if (posseq.charAt(0) != 'X' && posseq.charAt(seqsize - 1) != 'X') { // �h����t for (int i = 0; i < seqsize; i++) { weightmatrix[i][posseq.charAt(i)]++; } // possequence.addElement(posseq); } } // end while char[] aaMap = { 'A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V', 'X' }; double[] expmatrix = { 0.0701313443873091, 0.0582393695201718, 0.0359362961736045, 0.0520743144385134, 0.0172010453343506, 0.0498574962335004, 0.0796465136978452, 0.0624720283551962, 0.0241405228512130, 0.0416989778376737, 0.0934441156861220, 0.0632334844952389, 0.0213293464067050, 0.0324554733241482, 0.0651181982370858, 0.0881672518230193, 0.0524630941595624, 0.0101093184162382, 0.0244701177088640, 0.0578116909136386 }; // double[] aaMapfreq = new double[windows_size]; double freq = 0; for (int j = 0; j < weightmatrix.length; j++) { for (int i = 0; i < aaMap.length - 1; i++) { totalAAcount[j] += weightmatrix[j][aaMap[i]]; } } for (int i = 0; i < aaMap.length - 1; i++) { // profilefout.print(aaMap[i]); for (int j = 0; j < windows_size; j++) { freq = ((weightmatrix[j][aaMap[i]]) / (totalAAcount[j])) + 1; wm[i][j] = Math.log10((freq / expmatrix[i])) / Math.log10(2.0); // profilefout.print(","+aaMapfreq[i]); } // profilefout.println(); } // fout.close(); // profilefout.close(); resultSet1.close(); connection.close(); } } // end try catch (ClassNotFoundException classNotFound) { classNotFound.printStackTrace(); System.exit(1); } catch (NullPointerException nullpointerException) { nullpointerException.printStackTrace(); System.exit(1); } catch (SQLException ex) { /** @todo Handle this exception */ /* } catch (IOException ex) { */ /** @todo Handle this exception */ } catch (NoClassDefFoundError ex) { } finally { // ensure statement and connection are closed properly try { statement.close(); statement2.close(); connection.close(); connection2.close(); } catch (Exception exception) { // end try exception.printStackTrace(); System.exit(1); } // end catch } // end finally } // end main
public void start2() { wm = new double[20][Data.windows_size]; String QueryKinasesName = "%" + Data.kinease + "%"; // data.code = data.codenames[3]; String QueryCodeName = Data.code; int windows_size = Data.windows_size; // int windows_size = 9; int shift = windows_size / 2; try { { shift = windows_size / 2; // establish connection to database String ACC = null; String SEQUENCE = null; String KINASES = null; String LIKE = "LIKE"; // int POSITION = 0; // int index = 0; String temp = null; // int numtemp = 0; // int LENGTH = (int) 0; // int count = 0; double[] totalAAcount = new double[windows_size]; double weightmatrix[][] = new double[windows_size][128]; // windowssize;aa; /// fout.println("#"+statementquery1); int seqsize = 0; for (int i = 0; i < pwmseq.size(); i++) { String posseq = pwmseq.elementAt(i).toString(); seqsize = posseq.length(); { for (int j = 0; j < seqsize; j++) { weightmatrix[j][posseq.charAt(j)]++; } // possequence.addElement(posseq); } } // end while char[] aaMap = { 'A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V', 'X' }; double[] expmatrix = { 0.0701313443873091, 0.0582393695201718, 0.0359362961736045, 0.0520743144385134, 0.0172010453343506, 0.0498574962335004, 0.0796465136978452, 0.0624720283551962, 0.0241405228512130, 0.0416989778376737, 0.0934441156861220, 0.0632334844952389, 0.0213293464067050, 0.0324554733241482, 0.0651181982370858, 0.0881672518230193, 0.0524630941595624, 0.0101093184162382, 0.0244701177088640, 0.0578116909136386 }; // double[] aaMapfreq = new double[windows_size]; double freq = 0; for (int j = 0; j < weightmatrix.length; j++) { for (int i = 0; i < aaMap.length - 1; i++) { totalAAcount[j] += weightmatrix[j][aaMap[i]]; } } for (int i = 0; i < aaMap.length - 1; i++) { // profilefout.print(aaMap[i]); for (int j = 0; j < windows_size; j++) { freq = ((weightmatrix[j][aaMap[i]] + 0.05) / (totalAAcount[j] + 1)); wm[i][j] = Math.log10((freq / expmatrix[i])) / Math.log10(2.0); // profilefout.print(","+aaMapfreq[i]); } // profilefout.println(); } // fout.close(); // profilefout.close(); } } // end try catch (NullPointerException nullpointerException) { nullpointerException.printStackTrace(); System.exit(1); } catch (NoClassDefFoundError ex) { } finally { // ensure statement and connection are closed properly try { } catch (Exception exception) { // end try exception.printStackTrace(); System.exit(1); } // end catch } // end finally } // end main
// Process the request private String processRequest(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); String userIDs = (String) session.getAttribute("user.id"); userIDs = (userIDs != null && userIDs.compareTo(" ") > 0) ? userIDs : "0"; long userID = Long.parseLong(userIDs); String command = request.getParameter("command"); String template = request.getParameter("template"); String pageHash = request.getParameter("pagehash"); String pageTitle = request.getParameter("pagetitle"); String pageDescription = request.getParameter("pagedescription"); String outLine = ""; String nextScript = request.getParameter("nextscript"); OutputStream toClient; boolean success = false; // System.out.println("userid=" + userID + ", id=" + id + ", command=" + command); command = (command != null && command.compareTo(" ") > 0) ? command : "form"; nextScript = (nextScript != null && nextScript.compareTo(" ") > 0) ? nextScript : "simple1.jsp"; // inputstring = (inputstring != null && inputstring.compareTo(" ") > 0) ? inputstring : ""; DbConn myConn = null; try { Context initCtx = new InitialContext(); // String csiSchema = (String) initCtx.lookup("java:comp/env/csi-schema-path"); // String acronym = (String) initCtx.lookup("java:comp/env/SystemAcronym"); myConn = new DbConn(); String csiSchema = myConn.getSchemaPath(); if (userID != 0) { if (command.equals("add")) { outLine = ""; } else if (command.equals("update")) { outLine = ""; } else if (command.equals("updatepage")) { UHash uPage = new UHash(pageHash, myConn); // System.out.println("Got Here 1"); if (template.equals("simple1")) { TextItem title = new TextItem(uPage.get("title"), myConn); title.setText(pageTitle); title.save(myConn); TextItem description = new TextItem(uPage.get("description"), myConn); description.setText(pageDescription); description.save(myConn); } else if (template.equals("simple2")) { } } else if (command.equals("test")) { outLine = "test"; } success = true; } } catch (IllegalArgumentException e) { outLine = outLine + "IllegalArgumentException caught: " + e.getMessage(); ALog.logActivity(userID, "csi", 0, pageHash + " error: '" + outLine + "'"); // log(outLine); } catch (NullPointerException e) { outLine = outLine + "NullPointerException caught: " + e.getMessage(); ALog.logActivity(userID, "csi", 0, pageHash + " error: '" + outLine + "'"); // log(outLine); } // catch (IOException e) { // outLine = outLine + "IOException caught: " + e.getMessage(); // ALog.logActivity(userID, "csi", 0, pageHash + " error: '" + outLine + "'"); // //log(outLine); // } catch (Exception e) { outLine = outLine + "Exception caught: " + e.getMessage(); ALog.logActivity(userID, "csi", 0, pageHash + " error: '" + outLine + "'"); // log(outLine); } finally { try { generateResponse(outLine, command, nextScript, success, response); } catch (Exception i) { } myConn.release(); // log("Test log message\n"); } return outLine; }
public void ast_prser(String file_name) { try { rawContent = hadoop_Training3_CATCH.readFileToString(file_name); } catch (Exception e) { System.out.println(); } ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(rawContent.toCharArray()); parser.setKind(ASTParser.K_COMPILATION_UNIT); final CompilationUnit cu = (CompilationUnit) parser.createAST(null); try { cu.accept( new ASTVisitor() { public boolean visit(ImportDeclaration id) { Name imp = id.getName(); // System.out.println("import =" + id.getName().getFullyQualifiedName()); return false; } public boolean visit(VariableDeclarationFragment node) { SimpleName name = node.getName(); // System.out.println("var.declaration =" + (name.getFullyQualifiedName() + ":" + // cu.getLineNumber(name.getStartPosition()))); return false; // do not continue } public boolean visit(TypeDeclaration node) { String name = node.getName().toString(); // System.out.println(" calss declaration =" + name); class_name = name; return true; // do not continue } public boolean visit(MethodDeclaration method) { // id=0; method_name = method.getName().getFullyQualifiedName(); method_parameter = method.parameters(); try { Block methodBlock = method.getBody(); String myblock = methodBlock.toString(); method_content = methodBlock.toString(); // method_content = method_content.replaceAll("\"", " "); // method_content = method_content.replaceAll("\'", " "); method_content = method_content.replaceAll( "<\\?>", " "); // @@@ Note adding two spaces for reason because it was giving error // // // in some cases if use single space here " tr } } " // method_content = method_content.trim(); // myblock = myblock.replaceAll("\\?","a"); // System.out.println("Myblock="+myblock); methodVisitor(myblock); // visitMethodDeclarion(myblock); } catch (java.lang.NullPointerException jnull) { System.out.println("Method Body is NULL"); jnull.printStackTrace(); reset_parameters(); // write_in_db(0, ,"",""); } catch (Exception e) { e.printStackTrace(); reset_parameters(); // insert("12", "",""); } /*reset_parameters(); insert("13", "",""); System.out.println("Hello");*/ return false; } }); } catch (NullPointerException e) { e.printStackTrace(); } }
public void run() { int i, j, storedValues, sleepTime = 3000, timeoutCtr = 0, lastFlags = -1, trackCnt = 0, lastLocMethod = -5; String bssid; WMapEntry currEntry; DataOutputStream out; FileInputStream in; while (running) { try { if (scanData.getNoGPSExitInterval() > 0) { if (System.currentTimeMillis() > lastGPSTime + scanData.getNoGPSExitInterval()) { break; } } if (ScanService.scanData.getThreadMode() == OWMapAtAndroid.THREAD_MODE_UPLOAD) { if ((m_uploadThread != null) && (m_uploadThread.isUploading())) OWMapAtAndroid.sendMessage( ScannerHandler.MSG_SIMPLE_ALERT, 0, 0, getResources().getText(R.string.upload_in_progress)); else m_uploadThread = new UploadThread(scanData, this, SP, false, notification, null); ScanService.scanData.setThreadMode(OWMapAtAndroid.THREAD_MODE_SCAN); } else { if ((posState == 0) && (scanData != null) && (scanData.isScanningEnabled())) { posState = 1; timeoutCtr = 0; if (scanData.getFlags() != lastFlags) { if ((scanData.getFlags() & OWMapAtAndroid.FLAG_NO_NET_ACCESS) == 0) scanData.getWifiManager().createWifiLock(WifiManager.WIFI_MODE_FULL, "OpenWLANMap"); else scanData .getWifiManager() .createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, "OpenWLANMap"); lastFlags = scanData.getFlags(); } if ((scanData.getFlags() & OWMapAtAndroid.FLAG_NO_NET_ACCESS) == 0) myWLocate.wloc_request_position(WLocate.FLAG_NO_IP_LOCATION); else { myWLocate.wloc_request_position( WLocate.FLAG_NO_NET_ACCESS | WLocate.FLAG_NO_IP_LOCATION); // stopGoogleLocation(); } } else if (!scanData.isScanningEnabled()) { try { trackCnt += 1500; Thread.sleep(1500); } catch (InterruptedException ie) { } } if (posState == 1) { // sleep while waiting for result try { trackCnt += 2500; java.lang.Thread.sleep(2500); // is interrupted from result handler timeoutCtr++; if (timeoutCtr > 3) { timeoutCtr = 0; posState = 0; } } catch (InterruptedException ie) { } } if ((posState == 2) || (posState == 100)) { loc_info locationInfo; NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); locationInfo = myWLocate.last_location_info(); if (lastLocMethod != locationInfo.lastLocMethod) { scanData.getmView().setMode(locationInfo.lastLocMethod); scanData.getmView().postInvalidate(); lastLocMethod = locationInfo.lastLocMethod; } if (posState == 100) locationInfo.lastLocMethod = -1; OWMapAtAndroid.sendMessage( OWMapAtAndroid.ScannerHandler.MSG_UPD_LOC_STATE, (int) (lastRadius * 1000), locationInfo.lastLocMethod, locationInfo); if (SP.getBoolean("autoConnect", false)) { if (!mWifi.isConnected()) { for (i = 0; i < locationInfo.wifiScanResult.size(); i++) { ScanResult result; result = locationInfo.wifiScanResult.get(i); result.capabilities = result.capabilities.toUpperCase(Locale.US); if ((isFreeHotspot(result) & WMapEntry.FLAG_IS_FREIFUNK) != 0) { // auto-connect to this open network WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.BSSID = result.BSSID; wifiConfig.priority = 1; wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE); wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wifiConfig.status = WifiConfiguration.Status.ENABLED; int netId = scanData.getWifiManager().addNetwork(wifiConfig); scanData.getWifiManager().enableNetwork(netId, true); } } } } if ((posValid) && (locationInfo.wifiScanResult != null) && (locationInfo.wifiScanResult.size() > 0)) { boolean foundExisting; for (i = 0; i < locationInfo.wifiScanResult.size(); i++) { ScanResult result; result = locationInfo.wifiScanResult.get(i); bssid = result.BSSID.replace(":", "").replace(".", "").toUpperCase(Locale.US); if (bssid.equalsIgnoreCase("000000000000")) break; foundExisting = false; scanData.getLock().lock(); for (j = 0; j < scanData.getWmapList().size(); j++) { currEntry = scanData.getWmapList().elementAt(j); if (currEntry.getBSSID().equalsIgnoreCase(bssid)) { currEntry.setPos(lastLat, lastLon); foundExisting = true; break; } } if (!foundExisting) { String lowerSSID; storedValues = scanData.incStoredValues(); scanData.getmView().setValue(storedValues); scanData.getmView().postInvalidate(); currEntry = new WMapEntry(bssid, result.SSID, lastLat, lastLon, storedValues); lowerSSID = result.SSID.toLowerCase(Locale.US); if ((lowerSSID.endsWith("_nomap")) || // Google unsubscibe option (lowerSSID.contains("iphone")) || // mobile AP (lowerSSID.contains("android")) || // mobile AP (lowerSSID.contains("motorola")) || // mobile AP (lowerSSID.contains("deinbus.de")) || // WLAN network on board of German bus (lowerSSID.contains("fernbus")) || // WLAN network on board of German bus (lowerSSID.contains("flixbus")) || // WLAN network on board of German bus (lowerSSID.contains("ecolines")) || // WLAN network on board of German bus (lowerSSID.contains("eurolines_wifi")) || // WLAN network on board of German bus (lowerSSID.contains("contiki-wifi")) || // WLAN network on board of bus (lowerSSID.contains("guest@ms ")) || // WLAN network on Hurtigruten ships (lowerSSID.contains("admin@ms ")) || // WLAN network on Hurtigruten ships (lowerSSID.contains("nsb_interakti")) || // WLAN network in NSB trains (lowerSSID.equals("southwestwifi"))) // WLAN network on Southwest flights currEntry.setFlags(currEntry.getFlags() | WMapEntry.FLAG_IS_NOMAP); else currEntry.setFlags(currEntry.getFlags() | isFreeHotspot(result)); if (isFreeHotspot(currEntry.getFlags())) scanData.incFreeHotspotWLANs(); scanData.getWmapList().add(currEntry); if ((scanData.getUploadThres() > 0) && (storedValues > scanData.getUploadThres())) { if ((m_uploadThread == null) || (!m_uploadThread.isUploading())) { if (mWifi.isConnected()) { m_uploadThread = new UploadThread(scanData, this, SP, true, notification, mWifi); } } } } result.capabilities = result.capabilities.toUpperCase(Locale.US); scanData.getLock().unlock(); } } scanData.getLock().lock(); for (j = 0; j < scanData.getWmapList().size(); j++) { currEntry = scanData.getWmapList().elementAt(j); if ((currEntry.getLastUpdate() + OWMapAtAndroid.RECV_TIMEOUT < System.currentTimeMillis()) && ((currEntry.getFlags() & WMapEntry.FLAG_IS_VISIBLE) == 0)) { scanData.getWmapList().remove(j); if (currEntry.posIsValid()) { int padBytes = 0, k; try { in = scanData.getCtx().openFileInput(OWMapAtAndroid.WSCAN_FILE); padBytes = in.available() % 28; in.close(); if (padBytes > 0) padBytes = 28 - padBytes; } catch (IOException ioe) { ioe.printStackTrace(); } try { out = new DataOutputStream( scanData .getCtx() .openFileOutput( OWMapAtAndroid.WSCAN_FILE, Context.MODE_PRIVATE | Context.MODE_APPEND)); if (padBytes > 0) for (k = 0; k < padBytes; k++) out.writeByte(0); out.write(currEntry.getBSSID().getBytes(), 0, 12); if ((currEntry.getFlags() & WMapEntry.FLAG_IS_NOMAP) != 0) { out.writeDouble(0.0); out.writeDouble(0.0); } else { out.writeDouble(currEntry.getLat()); out.writeDouble(currEntry.getLon()); } out.close(); } catch (IOException ioe) { ioe.printStackTrace(); } if ((currEntry.getFlags() & (WMapEntry.FLAG_IS_FREIFUNK | WMapEntry.FLAG_IS_NOMAP)) == WMapEntry.FLAG_IS_FREIFUNK) { padBytes = 0; try { in = scanData.getCtx().openFileInput(OWMapAtAndroid.WFREI_FILE); padBytes = in.available() % 12; in.close(); if (padBytes > 0) padBytes = 12 - padBytes; } catch (IOException ioe) { ioe.printStackTrace(); } try { out = new DataOutputStream( scanData .getCtx() .openFileOutput( OWMapAtAndroid.WFREI_FILE, Context.MODE_PRIVATE | Context.MODE_APPEND)); if (padBytes > 0) for (k = 0; k < padBytes; k++) out.writeByte(0); out.write(currEntry.getBSSID().getBytes(), 0, 12); out.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } } // flushData(false); } scanData.getLock().unlock(); m_lastSpeed = locationInfo.lastSpeed; if (!SP.getBoolean("adaptiveScanning", true)) sleepTime = 500; else if (locationInfo.lastSpeed > 90) sleepTime = 350; else if (locationInfo.lastSpeed < 0) sleepTime = 1300; // no speed information, may be because of WLAN localisation else if (locationInfo.lastSpeed < 6) sleepTime = 2500; // user seems to walk else { double f; f = 1.0 - (locationInfo.lastSpeed / 90.0); sleepTime = (int) ((1000.0 * f) + 350); } try { trackCnt += sleepTime; java.lang.Thread.sleep(sleepTime); // sleep between scans } catch (InterruptedException ie) { } posState = 0; } } } catch (NullPointerException npe) // in case the parent activity dies too fast { npe.printStackTrace(); } if ((trackCnt > 500000) && (lastLat != 0) && (lastLon != 0)) { if (SP.getBoolean("track", false)) new UploadPositionTask().execute(null, null, null); trackCnt = 0; } } onDestroy(); // remove all resources (in case the thread was stopped due to some other reason }
@Override protected void download() { File destination = new File(request.getDestination()); final boolean fileExists = destination.exists(); if (request.isDeleteOnFailure() && fileExists) { Log.w(TAG, "File already exists"); if (request.getFeedfileType() != FeedImage.FEEDFILETYPE_FEEDIMAGE) { onFail(DownloadError.ERROR_FILE_EXISTS, null); return; } else { onSuccess(); return; } } HttpClient httpClient = AntennapodHttpClient.getHttpClient(); RandomAccessFile out = null; InputStream connection = null; try { HttpGet httpGet = new HttpGet(URIUtil.getURIFromRequestUrl(request.getSource())); // add authentication information String userInfo = httpGet.getURI().getUserInfo(); if (userInfo != null) { String[] parts = userInfo.split(":"); if (parts.length == 2) { httpGet.addHeader( BasicScheme.authenticate( new UsernamePasswordCredentials(parts[0], parts[1]), "UTF-8", false)); } } else if (!StringUtils.isEmpty(request.getUsername()) && request.getPassword() != null) { httpGet.addHeader( BasicScheme.authenticate( new UsernamePasswordCredentials(request.getUsername(), request.getPassword()), "UTF-8", false)); } // add range header if necessary if (fileExists) { request.setSoFar(destination.length()); httpGet.addHeader(new BasicHeader("Range", "bytes=" + request.getSoFar() + "-")); if (BuildConfig.DEBUG) Log.d(TAG, "Adding range header: " + request.getSoFar()); } HttpResponse response = httpClient.execute(httpGet); HttpEntity httpEntity = response.getEntity(); int responseCode = response.getStatusLine().getStatusCode(); Header contentEncodingHeader = response.getFirstHeader("Content-Encoding"); final boolean isGzip = contentEncodingHeader != null && contentEncodingHeader.getValue().equalsIgnoreCase("gzip"); if (BuildConfig.DEBUG) Log.d(TAG, "Response code is " + responseCode); if (responseCode / 100 != 2 || httpEntity == null) { final DownloadError error; final String details; if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { error = DownloadError.ERROR_UNAUTHORIZED; details = String.valueOf(responseCode); } else { error = DownloadError.ERROR_HTTP_DATA_ERROR; details = String.valueOf(responseCode); } onFail(error, details); return; } if (!StorageUtils.storageAvailable(PodcastApp.getInstance())) { onFail(DownloadError.ERROR_DEVICE_NOT_FOUND, null); return; } connection = new BufferedInputStream(AndroidHttpClient.getUngzippedContent(httpEntity)); Header[] contentRangeHeaders = (fileExists) ? response.getHeaders("Content-Range") : null; if (fileExists && responseCode == HttpStatus.SC_PARTIAL_CONTENT && contentRangeHeaders != null && contentRangeHeaders.length > 0) { String start = contentRangeHeaders[0] .getValue() .substring("bytes ".length(), contentRangeHeaders[0].getValue().indexOf("-")); request.setSoFar(Long.valueOf(start)); Log.d(TAG, "Starting download at position " + request.getSoFar()); out = new RandomAccessFile(destination, "rw"); out.seek(request.getSoFar()); } else { destination.delete(); destination.createNewFile(); out = new RandomAccessFile(destination, "rw"); } byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; request.setStatusMsg(R.string.download_running); if (BuildConfig.DEBUG) Log.d(TAG, "Getting size of download"); request.setSize(httpEntity.getContentLength() + request.getSoFar()); if (BuildConfig.DEBUG) Log.d(TAG, "Size is " + request.getSize()); if (request.getSize() < 0) { request.setSize(DownloadStatus.SIZE_UNKNOWN); } long freeSpace = StorageUtils.getFreeSpaceAvailable(); if (BuildConfig.DEBUG) Log.d(TAG, "Free space is " + freeSpace); if (request.getSize() != DownloadStatus.SIZE_UNKNOWN && request.getSize() > freeSpace) { onFail(DownloadError.ERROR_NOT_ENOUGH_SPACE, null); return; } if (BuildConfig.DEBUG) Log.d(TAG, "Starting download"); while (!cancelled && (count = connection.read(buffer)) != -1) { out.write(buffer, 0, count); request.setSoFar(request.getSoFar() + count); request.setProgressPercent( (int) (((double) request.getSoFar() / (double) request.getSize()) * 100)); } if (cancelled) { onCancelled(); } else { // check if size specified in the response header is the same as the size of the // written file. This check cannot be made if compression was used if (!isGzip && request.getSize() != DownloadStatus.SIZE_UNKNOWN && request.getSoFar() != request.getSize()) { onFail( DownloadError.ERROR_IO_ERROR, "Download completed but size: " + request.getSoFar() + " does not equal expected size " + request.getSize()); return; } onSuccess(); } } catch (IllegalArgumentException e) { e.printStackTrace(); onFail(DownloadError.ERROR_MALFORMED_URL, e.getMessage()); } catch (SocketTimeoutException e) { e.printStackTrace(); onFail(DownloadError.ERROR_CONNECTION_ERROR, e.getMessage()); } catch (UnknownHostException e) { e.printStackTrace(); onFail(DownloadError.ERROR_UNKNOWN_HOST, e.getMessage()); } catch (IOException e) { e.printStackTrace(); onFail(DownloadError.ERROR_IO_ERROR, e.getMessage()); } catch (NullPointerException e) { // might be thrown by connection.getInputStream() e.printStackTrace(); onFail(DownloadError.ERROR_CONNECTION_ERROR, request.getSource()); } finally { IOUtils.closeQuietly(out); AntennapodHttpClient.cleanup(); } }
// ----This function getting search terms and inserts/updates counter with time slots handling---- // ---------the function making shore the data is always up to date----------- // ---------------------------------------------------------------------------------------- @SuppressWarnings("deprecation") public void update_search_terms( String text, double num_of_slots, double max_time_frame_hours, String query) throws MongoException { // long starttime = System.currentTimeMillis(); log4j.info( "starting function update_search_terms, num_of_slots = " + num_of_slots + ", max_time_frame_hours = " + max_time_frame_hours + ", query = " + query); String[] textarray = text.split(" "); // split tweet text into a words array log4j.info("split tweet text into a word array"); BasicDBObject objterm = new BasicDBObject(); DBObject objtoupd = new BasicDBObject(); DBObject update = new BasicDBObject(); DBObject curr_slot = new BasicDBObject(); log4j.info("starting function update_search_terms"); curr_slot = this.collslot.findOne(); // get current time slot information this.current_slot_start_time = (long) (Double.parseDouble((curr_slot.get("slot_start_time").toString()))); Date resultdate = new Date(this.current_slot_start_time); log4j.info("current_slot_start_time is : " + resultdate.toLocaleString()); this.current_slot_index = Integer.parseInt(curr_slot.get("current_slot").toString()); log4j.info("current time slot is : " + this.current_slot_index); long difference = System.currentTimeMillis() - this.current_slot_start_time; if (difference > this.slot_time_millis) { // starting a new time slot // update current slot information this.current_slot_start_time += (long) this.slot_time_millis; this.current_slot_index = (int) ((this.current_slot_index + 1) % num_of_slots); log4j.info("new slot time has come, new slot is slot number " + this.current_slot_index); curr_slot.put("current_slot", this.current_slot_index); curr_slot.put("slot_start_time", this.current_slot_start_time); curr_slot.put( "slot_start_time_string", new Date(this.current_slot_start_time).toLocaleString()); log4j.info("updating new current slot time and number in db"); this.collslot.save(curr_slot); DBCursor terms = this.collsearch.find(); // get all search_terms documents to update new slot to zero while (terms.hasNext()) { try { // update new slot to zero and reducing from over_all the old data in all documents DBObject term = terms.next(); if (term.get("search_term") != null) { objtoupd.put("search_term", term.get("search_term")); term.put("slot" + this.current_slot_index, 0); term.put("current_slot", this.current_slot_index); term.put( "over_all", Integer.parseInt(term.get("over_all").toString()) - Integer.parseInt(term.get("slot" + this.current_slot_index).toString())); this.collsearch.save(term); } } catch (NullPointerException e) { e.printStackTrace(); log4j.info(e); } } } // start looking for new search terms in text log4j.info("going over the tweet text"); query = query.replaceAll("%40", "@"); // utf-8 code of @ query = query.replaceAll("%23", "#"); // utf-8 code of # DBObject nodes = new BasicDBObject(); nodes.put("parent", query); nodes = colltree.findOne(nodes); // check if there is a document for parent in tree_nodes collection if (nodes == null) // there is no document in tree_nodes { nodes = new BasicDBObject(); nodes.put("son", "no"); nodes.put("parent", query); } else // there is document in tree_nodes { nodes.put("in_process", 1); // mark as busy this.colltree.save(nodes); // nodes.put("son", nodes.get("son").toString() + ""); } for (int i = 0; i < textarray.length; i++) { // loop over the words of the tweet if (textarray[i].trim().startsWith("@") || textarray[i].trim().startsWith("#")) { String thisterm = textarray[i].trim(); // cut white spaces String[] no_ddot = thisterm.split("[:,., ,;,\n]"); thisterm = no_ddot[0]; thisterm = thisterm.replaceAll("%40", "@"); thisterm = thisterm.replaceAll("%23", "#"); if (thisterm.length() > 1) { log4j.info("search word: " + thisterm); objterm.put("search_term", thisterm); // object to find the search word in collection log4j.info("inserting tree nodes to mongodb"); if (String.valueOf(query) != String.valueOf(thisterm)) { // query and search term not equal if (nodes.get("son").toString() == "no") // no document in collection yet { nodes.put("son", thisterm); } else // there is document in collection { nodes.put("son", nodes.get("son").toString() + "," + thisterm); } // nodes.put("son", thisterm); // neo4j.addNode(query, thisterm, log4j); } // objtoupd = collsearch.findOne(objterm); // find the search word in collection try { DBObject term = this.collsearch.findOne(objterm); // get document os search_term if exists // update current slot and over_all for existing document term.put("over_all", Integer.parseInt(term.get("over_all").toString()) + 1); term.put( "slot" + current_slot_index, Integer.parseInt(term.get("slot" + this.current_slot_index).toString()) + 1); // term.put("current_slot_start_time_millis", current_slot_start_time); log4j.info("updating counter in current slot for word: " + thisterm); this.collsearch.update(objterm, term); } catch (NullPointerException e) { // there is no document for search term in collection // creating a new document log4j.info(thisterm + " is not yet in collection , inserting it"); DBObject newline = new BasicDBObject(); newline.put("search_term", thisterm); newline.put("over_all", 1); newline.put("max_id", 0); newline.put("current_slot", current_slot_index); newline.put("current_slot_start_time_millis", current_slot_start_time); // creating all slots for document for (int j = 0; j < num_of_slots; j++) { if (j == current_slot_index) { newline.put("slot" + current_slot_index, 1); // current slot = 1 } else { newline.put("slot" + j, 0); // non current slot = 0 } } this.collsearch.insert(newline); } } nodes.put("in_process", 0); // update tree_nodes document as not busy this.colltree.save(nodes); } } log4j.info("end update_search_terms"); }
/** * Create a multicast socket and join the multicast group. This method creates a multicast socket * that is used to broadcast The <CODE>DiscoveryResponder</CODE> will then join the multicast * group and send a join message. This method has no effect if the <CODE>DiscoveryResponder</CODE> * is <CODE>ONLINE</CODE> or <CODE>STOPPING</CODE> or <CODE>STARTING</CODE>. * * @exception IOException The creation of the Multicast socket failed. */ public void start() throws IOException { if (state == OFFLINE) { changeState(STARTING); if (cmf == null) { if (logger.finerOn()) { logger.finer("start ", "Can't start discoveryResponder: JDMK MBeanServer is not set"); } return; } // ---------------- // Create a new obj to receive multicast msg ; // ---------------- try { if (logger.finerOn()) { logger.finer("start ", "Create a new responder"); } responder = new ActualResponder(multicastGroup, multicastPort, getTimeToLive(), cmf, spy, this); if (local != null) { responder.setLocalHost(local); } // NPCTE fix for bugId 4499338, esc 0, 04 Sept 2001 if (usrInet != null) { responder.setInterface(usrInet); if (logger.finerOn()) { logger.finer("start ", "set interface to " + usrInet); } } // end of NPCTE fix for bugId 4499338 if (noEvent != null) responder.noEvent(); if (logger.finerOn()) { logger.finer("start ", "call responder connect"); } responder.connectToGroup(); // ---------------- // Create a new thread to receive multicast msg ; // ---------------- // responderThread = cmf.getThreadAllocatorSrvIf().obtainThread(responderObjectName, // responder); responderThread = new Thread(responder); responderThread.setName("Multicast responder"); // ---------------- // Start thread // ---------------- responderThread.start(); // ---------------- // Update state // ---------------- // changeState(ONLINE) ; } catch (SocketException e) { if (logger.finestOn()) { logger.finest("start", e); } throw new IOException(e.getMessage()); } catch (IOException e) { // ------------------------ // Keep exception for us // ------------------------ if (logger.finestOn()) { logger.finest("start ", e); } throw e; } catch (NullPointerException e) { // ------------------------ // the set group did not worked // ------------------------ if (logger.finestOn()) { logger.finest("start ", e); } throw new IOException(e.getMessage()); } } else { if (logger.finerOn()) { logger.finer("start ", "Responder is not OFFLINE"); } } }
public static void main(String[] args) throws EOFException { queue = new ArrayList<Traffic>(); ObjectInputStream OISforTG = null; ObjectOutputStream OOSforLot = null; System.out.print("login?"); sc = new Scanner(System.in); String input = sc.nextLine(); if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")) { // System.out.println(ConnectionData.ipTG+" "+ConnectionData.portForTG); try { // socketForManager = new Socket(ConnectionData.ipMani, ConnectionData.portForManager); socketForTG = new Socket(ConnectionData.ipTG, ConnectionData.portForTG); socketForTime = new Socket(ConnectionData.ipTG, ConnectionData.portForTime); socketForParkingLot = new Socket(ConnectionData.ipLot, ConnectionData.portForLot); System.out.println("Connected"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } receiverForManager RFM = new receiverForManager(); Thread ThreadRFM = new Thread(RFM); ThreadRFM.start(); trafficReceiver trafficRec = new trafficReceiver(); Thread ThreadTraffic = new Thread(trafficRec); ThreadTraffic.start(); try { OOSforLot = new ObjectOutputStream(socketForParkingLot.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException npe) { npe.printStackTrace(); } timeReader TR = new timeReader(); Thread thread = new Thread(TR); thread.start(); carReturned CR = new carReturned(); Thread thread1 = new Thread(CR); thread1.start(); // System.out.println("reach1"); while (true) { try { if (Token > 0 && queue.size() > 0) { Token--; System.out.println(Token); OOSforLot.writeObject(queue.get(0)); } else if (Token == 0 && queue.size() > 0) { String carOrig = queue.get(0).getGeneratedTime(); Integer carOrigInt[] = utils.timeConverter(carOrig); int Orig = (carOrigInt[0] * 3600) + (carOrigInt[1] * 60); int Curren = (currentTime[0] * 3600) + (currentTime[1] * 60); if ((Curren - Orig) > 600) { // need to something... // // // // } else { System.out.println("Token: " + Token + " queue Size: " + queue.size()); continue; } } } catch (IOException e) { e.printStackTrace(); } } } }
public void run() { // Here's where everything happens. The select method will // return when any operations registered above have occurred, the // thread has been interrupted, etc. try { while (!stop) { try { if (selector.select() > 0) { if (stop) { break; } // Someone is ready for I/O, get the ready keys Set readyKeys = selector.selectedKeys(); Iterator it = readyKeys.iterator(); // Walk through the ready keys collection and process date requests. while (it.hasNext()) { SelectionKey sk = (SelectionKey) it.next(); it.remove(); SocketChannel readChannel = null; TcpAddress incomingAddress = null; if (sk.isAcceptable()) { // The key indexes into the selector so you // can retrieve the socket that's ready for I/O ServerSocketChannel nextReady = (ServerSocketChannel) sk.channel(); // Accept the date request and send back the date string Socket s = nextReady.accept().socket(); readChannel = s.getChannel(); readChannel.configureBlocking(false); readChannel.register(selector, SelectionKey.OP_READ); incomingAddress = new TcpAddress(s.getInetAddress(), s.getPort()); SocketEntry entry = new SocketEntry(incomingAddress, s); sockets.put(incomingAddress, entry); timeoutSocket(entry); TransportStateEvent e = new TransportStateEvent( DefaultTcpTransportMapping.this, incomingAddress, TransportStateEvent.STATE_CONNECTED, null); fireConnectionStateChanged(e); } else if (sk.isReadable()) { readChannel = (SocketChannel) sk.channel(); incomingAddress = new TcpAddress( readChannel.socket().getInetAddress(), readChannel.socket().getPort()); } else if (sk.isWritable()) { try { SocketEntry entry = (SocketEntry) sk.attachment(); SocketChannel sc = (SocketChannel) sk.channel(); if (entry != null) { writeMessage(entry, sc); } } catch (IOException iox) { if (logger.isDebugEnabled()) { iox.printStackTrace(); } logger.warn(iox); TransportStateEvent e = new TransportStateEvent( DefaultTcpTransportMapping.this, incomingAddress, TransportStateEvent.STATE_DISCONNECTED_REMOTELY, iox); fireConnectionStateChanged(e); sk.cancel(); } } else if (sk.isConnectable()) { try { SocketEntry entry = (SocketEntry) sk.attachment(); SocketChannel sc = (SocketChannel) sk.channel(); if ((!sc.isConnected()) && (sc.finishConnect())) { sc.configureBlocking(false); logger.debug("Connected to " + entry.getPeerAddress()); // make sure conncetion is closed if not used for timeout // micro seconds timeoutSocket(entry); sc.register(selector, SelectionKey.OP_WRITE, entry); } TransportStateEvent e = new TransportStateEvent( DefaultTcpTransportMapping.this, incomingAddress, TransportStateEvent.STATE_CONNECTED, null); fireConnectionStateChanged(e); } catch (IOException iox) { if (logger.isDebugEnabled()) { iox.printStackTrace(); } logger.warn(iox); sk.cancel(); } } if (readChannel != null) { try { readMessage(sk, readChannel, incomingAddress); } catch (IOException iox) { // IO exception -> channel closed remotely if (logger.isDebugEnabled()) { iox.printStackTrace(); } logger.warn(iox); sk.cancel(); readChannel.close(); TransportStateEvent e = new TransportStateEvent( DefaultTcpTransportMapping.this, incomingAddress, TransportStateEvent.STATE_DISCONNECTED_REMOTELY, iox); fireConnectionStateChanged(e); } } } } } catch (NullPointerException npex) { // There seems to happen a NullPointerException within the select() npex.printStackTrace(); logger.warn("NullPointerException within select()?"); } processPending(); } if (ssc != null) { ssc.close(); } } catch (IOException iox) { logger.error(iox); lastError = iox; } if (!stop) { stop = true; synchronized (DefaultTcpTransportMapping.this) { server = null; } } }
// Process the request private String processRequest(HttpServletRequest request, HttpServletResponse response) { String command = request.getParameter("command"); String id = request.getParameter("id"); String description = request.getParameter("description"); String status = request.getParameter("rstatus"); status = (status != null && status.compareTo(" ") > 0) ? status : null; String outLine = ""; // String nextScript = "home.jsp"; String nextScript = request.getParameter("nextscript"); OutputStream toClient; HttpSession session = request.getSession(); boolean success = false; String userIDs = (String) session.getAttribute("user.id"); long userID = Long.parseLong(userIDs); command = (command != null && command.compareTo(" ") > 0) ? command : "form"; nextScript = (nextScript != null && nextScript.compareTo(" ") > 0) ? nextScript : "roles.jsp"; // inputstring = (inputstring != null && inputstring.compareTo(" ") > 0) ? inputstring : ""; DbConn myConn = null; try { Context initCtx = new InitialContext(); // String csiSchema = (String) initCtx.lookup("java:comp/env/csi-schema-path"); String acronym = (String) initCtx.lookup("java:comp/env/SystemAcronym"); myConn = new DbConn(); String csiSchema = myConn.getSchemaPath(); if (command.equals("add")) { Role item = new Role(); item.setDescription(description); item.setStatus(status); getPermissions(request, item); getPositions(request, item); item.add(myConn, userID); GlobalMembership.refresh(myConn); success = true; outLine = ""; } else if (command.equals("update")) { Role item = new Role(myConn, Long.parseLong(id)); item.setDescription(description); item.setStatus(status); getPermissions(request, item); getPositions(request, item); item.save(myConn, userID); GlobalMembership.refresh(myConn); success = true; outLine = ""; } else if (command.equals("drop")) { Role item = new Role(myConn, Long.parseLong(id)); item.drop(myConn, userID); success = true; outLine = "Role " + item.getDescription() + " Removed"; } else if (command.equals("test")) { outLine = "test"; } } catch (IllegalArgumentException e) { outLine = outLine + "IllegalArgumentException caught: " + e.getMessage(); ALog.logActivity(userID, "csi", 0, "Role error: '" + outLine + "'"); // log(outLine); } catch (NullPointerException e) { outLine = outLine + "NullPointerException caught: " + e.getMessage(); ALog.logActivity(userID, "csi", 0, "Role error: '" + outLine + "'"); // log(outLine); } // catch (IOException e) { // outLine = outLine + "IOException caught: " + e.getMessage(); // ALog.logActivity(userID, "csi", 0, "Role error: '" + outLine + "'"); // //log(outLine); // } catch (Exception e) { outLine = outLine + "Exception caught: " + e.getMessage(); ALog.logActivity(userID, "csi", 0, "Role error: '" + outLine + "'"); // log(outLine); } finally { try { generateResponse(outLine, command, nextScript, success, response); } catch (Exception i) { } myConn.release(); // log("Test log message\n"); } return outLine; }
public void collect(Player player, List<ItemStack> itemDrops, EntityDeathEvent event) { if (itemDrops.isEmpty() && !levelAllow(player) && !expAllow(player)) { return; } if (plugin.config.dropOnPVPDeath() && player.getKiller() instanceof Player) { plugin.message(player, plugin.config.msgPVPDeath()); return; } if (plugin.config.residence()) { ClaimedResidence res = Residence.getResidenceManager().getByLoc(player.getLocation()); if (res != null) { ResidencePermissions perms = res.getPermissions(); if (perms.playerHas(player.getName(), plugin.config.resFlag(), true)) { plugin.logDebug( "Player '" + player.getName() + "' is not allowed to use Scavenger in this residence. Items will be dropped."); plugin.message(player, plugin.config.msgInsideRes()); return; } else { plugin.logDebug( "Player '" + player.getName() + "' is allowed to use Scavenger in this residence."); } } } if (plugin.config.factionEnemyDrops() && plugin.factionHook != null) { if (plugin.factionHook.isPlayerInEnemyFaction(player)) { return; } } if (plugin.config.dungeonMazeDrops() && plugin.dmHook != null) { plugin.logDebug("Checking if '" + player.getName() + "' is in DungeonMaze."); if (plugin.dmHook.isPlayerInDungeon(player)) { plugin.logDebug("Player '" + player.getName() + "' is in DungeonMaze."); plugin.message(player, plugin.config.msgInsideDungeonMaze()); return; } } if (plugin.getWorldGuard() != null) { plugin.logDebug("Checking region support for '" + player.getWorld().getName() + "'"); if (plugin.getWorldGuard().getRegionManager(player.getWorld()) != null) { try { RegionManager regionManager = plugin.getWorldGuard().getRegionManager(player.getWorld()); ApplicableRegionSet set = regionManager.getApplicableRegions(player.getLocation()); if (set.allows(DefaultFlag.PVP) && plugin.config.wgPVPIgnore()) { plugin.logDebug( "This is a WorldGuard PVP zone and WorldGuardPVPIgnore is " + plugin.config.wgPVPIgnore()); if (!plugin.config.msgInsideWGPVP().isEmpty()) { plugin.message(player, plugin.config.msgInsideWGPVP()); } return; } if (!set.allows(DefaultFlag.PVP) && plugin.config.wgGuardPVPOnly()) { plugin.logDebug( "This is NOT a WorldGuard PVP zone and WorldGuardPVPOnly is " + plugin.config.wgGuardPVPOnly()); if (!plugin.config.msgInsideWGPVP().isEmpty()) { plugin.message(player, plugin.config.msgInsideWGPVPOnly()); } return; } } catch (NullPointerException ex) { plugin.logDebug(ex.getMessage()); } } else { plugin.logDebug("Region support disabled for '" + player.getWorld().getName() + "'"); } } if (plugin.getUltimateArena() != null) { if (UltimateArenaAPI.hookIntoUA(plugin).isInArena(player)) { if (!plugin.config.msgInsideUA().isEmpty()) { plugin.message(player, plugin.config.msgInsideUA()); } return; } } if (plugin.maHandler != null && plugin.maHandler.isPlayerInArena(player)) { if (!plugin.config.msgInsideMA().isEmpty()) { plugin.message(player, plugin.config.msgInsideMA()); } return; } if (plugin.pvpHandler != null && !PVPArenaAPI.getArenaName(player).equals("")) { String x = plugin.config.msgInsidePA(); if (!x.isEmpty()) { x = x.replace("%ARENA%", PVPArenaAPI.getArenaName(player)); plugin.message(player, x); } return; } if (plugin.battleArena) { mc.alk.arena.objects.ArenaPlayer ap = mc.alk.arena.BattleArena.toArenaPlayer(player); if (ap != null) { Match match = BattleArena.getBAController().getMatch(ap); if (match != null) { if (match.isInMatch(ap)) { String x = plugin.config.msgInsideBA(); if (!x.isEmpty()) { plugin.message(player, x); } return; } } } } if (plugin.minigames != null) { if (plugin.minigames.playerInMinigame(player)) { plugin.logDebug( "Player '" + player.getName() + "' is in a Minigame. Not recovering items."); return; } } if (hasRestoration(player)) { plugin.error(player, "Restoration already exists, ignoring."); return; } if (plugin.getEconomy() != null && !(player.hasPermission(PERM_FREE) || (player.isOp() && plugin.config.opsAllPerms())) && plugin.config.economyEnabled()) { NumberFormat formatter = NumberFormat.getInstance(new Locale(plugin.config.countryCode())); formatter.setMaximumFractionDigits(plugin.config.decimalPlaces()); double restoreCost = plugin.config.restoreCost(); double withdrawAmount; double playerBalance = plugin.getEconomy().getBalance(player); double percentCost = plugin.config.percentCost(); double minCost = plugin.config.minCost(); double maxCost = plugin.config.maxCost(); EconomyResponse er; String currency; if (plugin.config.percent()) { if (playerBalance < 0) { withdrawAmount = 0; } else { withdrawAmount = playerBalance * (percentCost / 100.0); } plugin.logDebug("withdrawAmount: " + withdrawAmount); plugin.logDebug("playeBalance: " + playerBalance); plugin.logDebug("percentCost: " + percentCost + "(" + (percentCost / 100.0) + ")"); if (plugin.config.addMin()) { withdrawAmount = withdrawAmount + minCost; plugin.logDebug("withdrawAmount (addMin): " + withdrawAmount); } else if (withdrawAmount < minCost) { withdrawAmount = minCost; } if (withdrawAmount > maxCost && maxCost > 0) { withdrawAmount = maxCost; } } else { withdrawAmount = restoreCost; } er = plugin.getEconomy().withdrawPlayer(player, withdrawAmount); if (er.transactionSuccess()) { plugin.logDebug("Withdraw success!"); if (withdrawAmount == 1) { currency = plugin.getEconomy().currencyNameSingular(); } else { currency = plugin.getEconomy().currencyNamePlural(); } String x = plugin.config.msgSaveForFee(); if (!x.isEmpty()) { x = x.replace("%COST%", formatter.format(withdrawAmount)); x = x.replace("%CURRENCY%", currency); plugin.message(player, x); } if (!plugin.config.depositDestination().isEmpty()) { plugin.logDebug("DepositDesination: " + plugin.config.depositDestination()); if (plugin.config.depositType().equalsIgnoreCase("bank")) { plugin.logDebug("DepositType: BANK"); if (plugin.getEconomy().hasBankSupport()) { plugin.logDebug("Bank support is enabled"); plugin.getEconomy().bankDeposit(plugin.config.depositDestination(), withdrawAmount); } else { plugin.logDebug("Bank support is NOT enabled"); } } else if (plugin.config.depositType().equalsIgnoreCase("player")) { plugin.logDebug("DepositType: PLAYER"); plugin.logDebug("DepositDestination: " + plugin.config.depositDestination()); if (plugin.getEconomy().hasAccount(plugin.config.depositDestination())) { plugin.logDebug("DepositDestination: VALID"); plugin.getEconomy().depositPlayer(plugin.config.depositDestination(), withdrawAmount); } else { plugin.logDebug("DepositDestination: INVALID"); } } else { plugin.logDebug("DepositType: INVALID"); } } else { plugin.logDebug("No deposit destination!"); } } else { plugin.logDebug("Withdraw fail! " + er.errorMessage); if (playerBalance == 1) { currency = plugin.getEconomy().currencyNameSingular(); } else { currency = plugin.getEconomy().currencyNamePlural(); } String x = plugin.config.msgNotEnoughMoney(); if (!x.isEmpty()) { x = x.replace("%BALANCE%", formatter.format(playerBalance)); x = x.replace("%COST%", formatter.format(withdrawAmount)); x = x.replace("%CURRENCY%", currency); x = x.replace("%ERRORMESSAGE%", er.errorMessage); plugin.message(player, x); } return; } } else { plugin.message(player, plugin.config.msgSaving()); } Restoration restoration = new Restoration(); restoration.enabled = false; // temporary fix for 1.9 restoration.inventory = Arrays.copyOfRange(player.getInventory().getContents(), 0, 36); restoration.armour = player.getInventory().getArmorContents(); if (plugin.isMc19or110()) { restoration.offHand = player.getInventory().getItemInOffHand(); } restoration.playerName = player.getDisplayName(); itemDrops.clear(); if (levelAllow(player)) { plugin.logDebug("Collecting level " + player.getLevel() + " for " + player.getName()); restoration.level = player.getLevel(); } if (expAllow(player)) { plugin.logDebug("Collecting exp " + player.getExp() + " for " + player.getName()); restoration.exp = player.getExp(); event.setDroppedExp(0); } String deathCause = "NULL"; if (player.getLastDamageCause() != null) { if (player.getLastDamageCause().getCause() != null) { deathCause = player.getLastDamageCause().getCause().toString(); } } String deathCausePermission = PERM_SCAVENGE_PREFIX + deathCause; plugin.logDebug( "[p:" + player.getName() + "] [" + PERM_SCAVENGE + ":" + player.hasPermission(PERM_SCAVENGE) + "]" + " [" + deathCausePermission + ":" + player.hasPermission(deathCausePermission) + "]"); if (player.hasPermission(PERM_SCAVENGE) || player.hasPermission(deathCausePermission)) { plugin.logDebug("Permissions are okay. Time to scavenge..."); if (plugin.config.chanceToDrop() > 0 && !player.hasPermission(PERM_NO_CHANCE)) { checkChanceToDropItems(restoration.armour, itemDrops); checkChanceToDropItems(restoration.inventory, itemDrops); if (plugin.isMc19or110()) { checkChanceToDropItems(restoration.offHand, itemDrops); } } if (plugin.config.singleItemDrops()) { checkSingleItemDrops(player, restoration.armour, itemDrops); checkSingleItemDrops(player, restoration.inventory, itemDrops); checkSingleItemDrops(player, restoration.offHand, itemDrops); } else if (plugin.config.singleItemKeeps()) { checkSingleItemKeeps(player, "armour", restoration.armour, itemDrops); checkSingleItemKeeps(player, "inv", restoration.inventory, itemDrops); if (plugin.isMc19or110()) { checkSingleItemKeeps(player, "offhand", restoration.offHand, itemDrops, 1); } } else if (plugin.config.slotBasedRecovery()) { checkSlots(player, "armour", restoration.armour, itemDrops); checkSlots(player, "inv", restoration.inventory, itemDrops); if (plugin.isMc19or110()) { checkSlots(player, "offhand", restoration.offHand, itemDrops, 1); } } } else { plugin.logDebug("Permissions are NOT okay. Dropping items..."); dropItems(restoration.armour, itemDrops); dropItems(restoration.inventory, itemDrops); dropItem(restoration.offHand, itemDrops); } addRestoration(player, restoration); }