List of usage examples for java.util.logging Logger getAnonymousLogger
public static Logger getAnonymousLogger()
From source file:Classes.Database.java
/** * reusable database function//from w w w . j a v a2 s . c om * * @param sql * @param returnfunction * @return * @throws SQLException */ private <T> ArrayList<T> getDatabase(String sql, DatabaseReturn<T> returnfunction, Object... arguments) throws SQLException { ArrayList<T> objList = new ArrayList<>(); Connection conn = null; PreparedStatement psta = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, username, password); psta = conn.prepareStatement(sql); EscapeSQL(psta, arguments); rs = psta.executeQuery(); while (rs.next()) { objList.add(returnfunction.ReturnType(rs)); } } catch (SQLException e) { Logger.getAnonymousLogger().log(Level.WARNING, "SQL Error: " + e.getMessage(), e); } catch (ClassNotFoundException e) { Logger.getAnonymousLogger().log(Level.WARNING, "Class Error: " + e.getMessage(), e); } finally { if (conn != null) { conn.close(); } if (rs != null) { rs.close(); } } return objList; }
From source file:com.vmware.photon.controller.api.client.resource.ApiBase.java
public final <T> void getObjectByPathAsync(final String path, final int expectedStatus, final FutureCallback<T> responseCallback, final TypeReference<T> tr) throws IOException { this.restClient.performAsync(RestClient.Method.GET, path, null, new org.apache.http.concurrent.FutureCallback<HttpResponse>() { @Override//from w ww . ja va 2 s. co m public void completed(HttpResponse result) { T response = null; try { restClient.checkResponse(result, expectedStatus); response = restClient.parseHttpResponse(result, tr); } catch (Throwable e) { responseCallback.onFailure(e); } if (response != null) { Logger.getAnonymousLogger().log(Level.INFO, String .format("getObjectByPathAsync returned task [%s] %s", this.toString(), path)); responseCallback.onSuccess(response); } else { Logger.getAnonymousLogger().log(Level.INFO, String.format("getObjectByPathAsync failed [%s] %s", this.toString(), path)); } } @Override public void failed(Exception ex) { Logger.getAnonymousLogger().log(Level.INFO, "{}", ex); responseCallback.onFailure(ex); } @Override public void cancelled() { responseCallback.onFailure( new RuntimeException(String.format("getObjectByPathAsync %s was cancelled", path))); } }); }
From source file:jp.go.nict.langrid.servicecontainer.handler.jsonrpc.servlet.JsonRpcServlet.java
@Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ByteArrayOutputStream dupIn = null; if (dumpRequests) { String qs = req.getQueryString(); Logger.getAnonymousLogger().info(String.format("method: %s, requestUrl: %s", req.getMethod(), req.getRequestURL().append(qs != null ? "?" + URLDecoder.decode(qs, "UTF-8") : "").toString() ));/*w w w . j av a 2 s . c om*/ dupIn = new ByteArrayOutputStream(); req = new AlternateInputHttpServletRequestWrapper(req, new InputStreamServletInputStream(new DuplicatingInputStream(req.getInputStream(), dupIn))); } long s = System.currentTimeMillis(); try { super.service(req, res); } finally { long d = System.currentTimeMillis() - s; if (displayProcessTime) { Logger.getAnonymousLogger().info("processTime: " + d + "ms."); } if (dupIn != null && dupIn.size() > 0) { Logger.getAnonymousLogger() .info(String.format("requestInput: %s", new String(dupIn.toByteArray(), "UTF-8"))); } } }
From source file:Classes.Database.java
private boolean DatabaseConnection(String connection) throws SQLException { Connection conn = null;/*from w ww . j a va2 s . com*/ Statement sta = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(connection, username, password); sta = conn.createStatement(); if (conn == null) { return false; } return !conn.isClosed(); } catch (SQLException e) { Logger.getAnonymousLogger().log(Level.WARNING, "SQL Error: " + e.getMessage(), e); return false; } catch (ClassNotFoundException e) { Logger.getAnonymousLogger().log(Level.WARNING, "Class Error: " + e.getMessage(), e); return false; } finally { if (conn != null) { conn.close(); } if (sta != null) { sta.close(); } } }
From source file:org.silverpeas.core.util.DBUtilIT.java
@Test public void nextUniqueIdUpdateForAnExistingTableShouldWorkAndConcurrency() throws SQLException, InterruptedException { int nextIdBeforeTesting = actualMaxIdInUniqueIdFor("User"); assertThat(nextIdBeforeTesting, is(1)); int nbThreads = 2 + (int) (Math.random() * 10); Logger.getAnonymousLogger() .info("Start at " + System.currentTimeMillis() + " with " + nbThreads + " threads"); final Thread[] threads = new Thread[nbThreads]; for (int i = 0; i < nbThreads; i++) { threads[i] = new Thread(() -> { try { int nextId = DBUtil.getNextId("User", "id"); Logger.getAnonymousLogger().info("Next id is " + nextId + " at " + System.currentTimeMillis()); Thread.sleep(10); } catch (InterruptedException e) { throw new RuntimeException(e); }/* w w w . ja v a2 s . c o m*/ }); } try { for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { thread.join(); } int expectedNextId = nextIdBeforeTesting + nbThreads; Logger.getAnonymousLogger() .info("Verifying nextId is " + expectedNextId + " at " + System.currentTimeMillis()); assertThat(actualMaxIdInUniqueIdFor("User"), is(expectedNextId)); } finally { for (Thread thread : threads) { if (thread.isAlive()) { thread.interrupt(); } } } }
From source file:org.silverpeas.core.util.DBUtilIntegrationTest.java
@Test public void nextUniqueIdUpdateForAnExistingTableShouldWorkAndConcurrency() throws SQLException, InterruptedException { int nextIdBeforeTesting = actualMaxIdInUniqueIdFor("User"); assertThat(nextIdBeforeTesting, is(1)); int nbThreads = 2 + (int) (Math.random() * 10); Logger.getAnonymousLogger() .info("Start at " + System.currentTimeMillis() + " with " + nbThreads + " threads"); final Thread[] threads = new Thread[nbThreads]; for (int i = 0; i < nbThreads; i++) { threads[i] = new Thread(() -> { try { int nextId = DBUtil.getNextId("User", "id"); Logger.getAnonymousLogger().info("Next id is " + nextId + " at " + System.currentTimeMillis()); Thread.sleep(10); } catch (InterruptedException | SQLException e) { throw new RuntimeException(e); }/*w w w .j a v a2 s . c o m*/ }); } try { for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { thread.join(); } int expectedNextId = nextIdBeforeTesting + nbThreads; Logger.getAnonymousLogger() .info("Verifying nextId is " + expectedNextId + " at " + System.currentTimeMillis()); assertThat(actualMaxIdInUniqueIdFor("User"), is(expectedNextId)); } finally { for (Thread thread : threads) { if (thread.isAlive()) { thread.interrupt(); } } } }
From source file:org.fiware.cybercaptor.server.rest.RestJsonAPI.java
/** * Generates the attack graph and initializes the main objects for other API calls * (database, attack graph, attack paths,...). * Load the objects from the POST XML file describing the whole network topology * * @param request the HTTP request//from w w w. java2 s . com * @return the HTTP response * @throws Exception */ @POST @Path("/initialize") @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_JSON) public Response initializeFromXMLText(@Context HttpServletRequest request, String xmlString) throws Exception { String costParametersFolderPath = ProjectProperties.getProperty("cost-parameters-path"); String databasePath = ProjectProperties.getProperty("database-path"); if (xmlString == null || xmlString.isEmpty()) return RestApplication.returnErrorMessage(request, "The input text string is empty."); Logger.getAnonymousLogger().log(Level.INFO, "Load the vulnerability and remediation database"); Database database = new Database(databasePath); String topologyFilePath = ProjectProperties.getProperty("topology-path"); Logger.getAnonymousLogger().log(Level.INFO, "Storing topology in " + topologyFilePath); PrintWriter out = new PrintWriter(topologyFilePath); out.print(xmlString); out.close(); Logger.getAnonymousLogger().log(Level.INFO, "Loading topology " + topologyFilePath); InformationSystem informationSystem = InformationSystemManagement.loadTopologyXMLFile(topologyFilePath, database); AttackGraph attackGraph = InformationSystemManagement.prepareInputsAndExecuteMulVal(informationSystem); if (attackGraph == null) return RestApplication.returnErrorMessage(request, "the attack graph is empty"); Logger.getAnonymousLogger().log(Level.INFO, "Launch scoring function"); attackGraph.loadMetricsFromTopology(informationSystem); List<AttackPath> attackPaths = AttackPathManagement.scoreAttackPaths(attackGraph, attackGraph.getNumberOfVertices()); //Delete attack paths that have less than 3 hosts (attacker that pown its own host). List<AttackPath> attackPathToKeep = new ArrayList<AttackPath>(); for (AttackPath attackPath : attackPaths) { if (attackPath.vertices.size() > 3) { attackPathToKeep.add(attackPath); } } attackPaths = attackPathToKeep; Logger.getAnonymousLogger().log(Level.INFO, attackPaths.size() + " attack paths scored"); Monitoring monitoring = new Monitoring(costParametersFolderPath); monitoring.setAttackPathList(attackPaths); monitoring.setInformationSystem(informationSystem); monitoring.setAttackGraph((MulvalAttackGraph) attackGraph); request.getSession(true).setAttribute("database", database); request.getSession(true).setAttribute("monitoring", monitoring); return RestApplication.returnJsonObject(request, new JSONObject().put("status", "Loaded")); }
From source file:org.fiware.cybercaptor.server.api.InformationSystemManagement.java
/** * @param informationSystem The initial topology * @param remediation the remediation deployment that must be simulated * @param db the vulnerability database * @return a clone of the topology, in which the remediation is applied */// w w w. j a v a2 s . c om public static InformationSystem simulateRemediationOnNewInforationSystem(InformationSystem informationSystem, DeployableRemediation remediation, Database db) { InformationSystem simulatedTopology = null; try { simulatedTopology = informationSystem.clone(); for (int i = 0; i < remediation.getActions().size(); i++) { DeployableRemediationAction action = remediation.getActions().get(i); Logger.getAnonymousLogger().log(Level.INFO, "Simulate the remediation " + action.getRemediationAction().getActionType() + " on machine " + action.getHost()); switch (action.getRemediationAction().getActionType()) { case APPLY_PATCH: for (int j = 0; j < action.getRemediationAction().getRemediationParameters().size(); j++) { Patch patch = (Patch) action.getRemediationAction().getRemediationParameters().get(j); List<Vulnerability> correctedVulnerabilities = patch .getCorectedVulnerabilities(db.getConn()); simulatedTopology.existingMachineByNameOrIPAddress(action.getHost().getName()) .correctVulnerabilities(correctedVulnerabilities); } break; case DEPLOY_FIREWALL_RULE: FirewallRule rule = (FirewallRule) action.getRemediationAction().getRemediationParameters() .get(0); if (rule.getTable() == FirewallRule.Table.INPUT) { simulatedTopology.existingMachineByNameOrIPAddress(action.getHost().getName()) .getInputFirewallRulesTable().getRuleList().add(0, rule); } else if (rule.getTable() == FirewallRule.Table.OUTPUT) { simulatedTopology.existingMachineByNameOrIPAddress(action.getHost().getName()) .getOutputFirewallRulesTable().getRuleList().add(0, rule); } break; case DEPLOY_SNORT_RULE: for (int j = 0; j < action.getRemediationAction().getRemediationParameters().size(); j++) { Rule snortRule = (Rule) action.getRemediationAction().getRemediationParameters().get(j); List<Vulnerability> correctedVulnerabilities = snortRule .getCorectedVulnerabilities(db.getConn()); //TODO: In fact, the vulnerability is not really corrected but rather suppressed on the path... simulatedTopology .existingMachineByNameOrIPAddress( action.getRemediationAction().getRelatedVertex().concernedMachine.getName()) .correctVulnerabilities(correctedVulnerabilities); } break; default: break; } } } catch (Exception e) { e.printStackTrace(); } return simulatedTopology; }
From source file:org.kalypso.model.hydrology.internal.test.OptimizeTest.java
private Logger createLogger(final File logFile) throws SecurityException, IOException { final Logger logger = Logger.getAnonymousLogger(); final Handler[] handlers = logger.getHandlers(); for (final Handler handler : handlers) logger.removeHandler(handler);//from w w w .j a v a 2 s . co m final FileHandler fileHandler = new FileHandler(logFile.getAbsolutePath()); logger.addHandler(fileHandler); return logger; }
From source file:Classes.Database.java
/** * Login check in database.//w w w . java 2 s . co m * * @param query The querry used * @param arguments Login Data */ public ArrayList<User> LogIn(String query, Object... arguments) { try { return getDatabase(query, userReturn, arguments); } catch (SQLException e) { Logger.getAnonymousLogger().log(Level.WARNING, e.getMessage(), e); } return new ArrayList<>(); }