List of usage examples for java.util.logging Logger getAnonymousLogger
public static Logger getAnonymousLogger()
From source file:com.basp.trabajo_al_minuto.model.business.BusinessUtils.java
public static void writeLog(String file, List<LogRecord> records) throws BusinessException { try {// www . j av a 2 s .co m Logger logger = Logger.getAnonymousLogger(); SimpleFormatter formatter = new SimpleFormatter(); FileHandler fh = new FileHandler(file, Boolean.TRUE); fh.setFormatter(formatter); logger.addHandler(fh); logger.setUseParentHandlers(false); records.stream().forEach((logRecord) -> { logger.log(logRecord); }); } catch (IOException | SecurityException ex) { Logger.getLogger(BusinessUtils.class.getName()).log(Level.SEVERE, "BusinessUtils.writeLog Exception", ex); throw new BusinessException(ex); } }
From source file:com.tckb.geo.stubgen.Generator.java
/** * Create a file with 'fileName' with 'rawData' contents * * @param rawData/* ww w. j a v a2 s . co m*/ * @param fileName * @return * @throws java.io.IOException */ public static String createJSONFile(String rawData, String fileName) throws IOException { File file = File.createTempFile(fileName, ".json"); try (FileWriter fr = new FileWriter(file)) { fr.write(rawData); } catch (IOException ex) { Logger.getAnonymousLogger().log(Level.SEVERE, "Error while creating file: ", ex); return ""; } return file.getAbsolutePath(); }
From source file:com.dclab.preparation.ReadTest.java
public String scan(Reader r) { try {//ww w . j a va 2 s . c o m CharBuffer cb = CharBuffer.allocate(MAX_CAPACITY); int i = r.read(cb); Logger.getAnonymousLogger().log(Level.INFO, "read {0} bytes", i); String content = cb.toString(); return extract(content); } catch (IOException ex) { Logger.getLogger(ReadTest.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:jgnash.ui.report.compiled.SecurityHighLowChart.java
private void updateChart() { try {/* w w w.j ava 2 s .c o m*/ SecurityNode sNode = combo.getSelectedSecurityNode(); if (sNode != null) { final AbstractXYDataset dataSet = createHighLowDataSet(sNode); JFreeChart chart = createHighLowChart(sNode.getDescription(), rb.getString("Column.Date"), rb.getString("Column.Price"), dataSet, false); chart.setBackgroundPaint(null); chartPanel.setChart(chart); chartPanel.validate(); } } catch (Exception ex) { Logger.getAnonymousLogger().severe(ex.toString()); } }
From source file:org.objectpocket.storage.FileStore.java
@Override public Map<String, Map<String, String>> readJsonObjects(String typeName) throws IOException { if (typeName == null) { return null; }//w w w . j a va 2 s. c om Set<String> filenames = index.getTypeToFilenamesMapping().get(typeName); Map<String, Map<String, String>> objects = new HashMap<String, Map<String, String>>(); if (filenames != null) { for (String filename : filenames) { Map<String, String> objectAndIdMap = new HashMap<String, String>(); // maximum fast file reading StringBuilder stringBuilder = new StringBuilder(); try (BufferedReader br = getBufferedReader(filename)) { String line = null; while ((line = br.readLine()) != null) { stringBuilder.append(line); } } String s = null; // remove first occurrence of "[", as this is the start of the // container array // all other object splitting will work with that! int index = stringBuilder.indexOf("["); if (index > -1) { s = stringBuilder.substring(index + 1, stringBuilder.length()); } else { throw new IOException("The file " + directory + "/" + filename + " does not contain valid JSON. " + getReadErrorMessage()); } List<String> jsonStrings = JsonHelper.splitToTopLevelJsonObjects(s); for (int i = 0; i < jsonStrings.size(); i++) { String[] typeAndIdFromJson = JsonHelper.getTypeAndIdFromJson(jsonStrings.get(i)); if (typeAndIdFromJson[0].equals(typeName)) { objectAndIdMap.put(jsonStrings.get(i), typeAndIdFromJson[1]); } } objects.put(filename, objectAndIdMap); } } else { Logger.getAnonymousLogger().log(Level.WARNING, "File for requested type: " + typeName + " does not exist in data store."); } return objects; }
From source file:org.kalypso.model.hydrology.internal.test.NaPreprocessingTest.java
private NAModelPreprocessor initPreprocessor(final String baseResourceLocation, final File asciiDir) throws Exception { final NaAsciiDirs outputDirs = new NaAsciiDirs(asciiDir); final Logger logger = Logger.getAnonymousLogger(); final URL gmlInputZipLocation = getClass().getResource(baseResourceLocation + "/gmlInput.zip"); //$NON-NLS-1$ final URL baseURL = new URL(String.format("jar:%s!/", gmlInputZipLocation.toExternalForm())); //$NON-NLS-1$ final INaSimulationData simulationData = createDemoModelsimulationData(baseURL); return new NAModelPreprocessor(outputDirs, simulationData, logger); }
From source file:org.kalypso.model.hydrology.internal.test.NAPostprocessingTest.java
private File doPostprocessing(final String baseResourceLocation, final File outputDir, final File asciiBaseDir) throws Exception { final File resultsDir = new File(outputDir, "results"); //$NON-NLS-1$ final URL gmlInputZipLocation = getClass().getResource(baseResourceLocation + "/gmlInput.zip"); //$NON-NLS-1$ final URL baseURL = new URL(String.format("jar:%s!/", gmlInputZipLocation.toExternalForm())); //$NON-NLS-1$ final Logger logger = Logger.getAnonymousLogger(); logger.setUseParentHandlers(false);// www.j ava 2 s .com final Handler[] handlers = logger.getHandlers(); for (final Handler handler : handlers) logger.removeHandler(handler); final URL modelResource = new URL(baseURL, "modell.gml"); //$NON-NLS-1$ final GMLWorkspace modelWorkspace = GmlSerializer.createGMLWorkspace(modelResource, null); final URL parameterResource = new URL(baseURL, "parameter.gml"); //$NON-NLS-1$ final GMLWorkspace parameterWorkspace = GmlSerializer.createGMLWorkspace(parameterResource, null); final Parameter parameter = (Parameter) parameterWorkspace.getRootFeature(); final URL controlResource = new URL(baseURL, "expertControl.gml"); //$NON-NLS-1$ final GMLWorkspace controlWorkspace = GmlSerializer.createGMLWorkspace(controlResource, null); final NAModellControl naControl = (NAModellControl) controlWorkspace.getRootFeature(); final NaAsciiDirs naAsciiDirs = new NaAsciiDirs(asciiBaseDir); final NaSimulationDirs naSimulationDirs = new NaSimulationDirs(resultsDir); final URL hydrotopResource = new URL(baseURL, "hydrotop.gml"); //$NON-NLS-1$ final GMLWorkspace hydrotopWorkspace = GmlSerializer.createGMLWorkspace(hydrotopResource, null); final HydrotopeCollection naHydrotop = (HydrotopeCollection) hydrotopWorkspace.getRootFeature(); final NaModell model = (NaModell) modelWorkspace.getRootFeature(); final IFeatureBindingCollection<Catchment> catchmentList = model.getCatchments(); final Catchment[] catchments = catchmentList.toArray(new Catchment[catchmentList.size()]); final ParameterHash landuseHash = new ParameterHash(parameter, logger); final IDManager idManager = new IDManager(); final HydroHash hydroHash = new HydroHash(landuseHash, catchments, idManager, false); hydroHash.initHydrotopes(naHydrotop); final NaPostProcessor postProcessor = new NaPostProcessor(idManager, logger, modelWorkspace, naControl, hydroHash); postProcessor.process(naAsciiDirs, naSimulationDirs); return resultsDir; }
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,...) * * @param request the HTTP request//from ww w . j av a 2s. c o m * @return the HTTP response * @throws Exception */ @GET @Path("initialize") @Produces(MediaType.APPLICATION_JSON) public Response initialise(@Context HttpServletRequest request) throws Exception { String costParametersFolderPath = ProjectProperties.getProperty("cost-parameters-path"); String databasePath = ProjectProperties.getProperty("database-path"); //Load the vulnerability and remediation database Database database = new Database(databasePath); String topologyFilePath = ProjectProperties.getProperty("topology-path"); Logger.getAnonymousLogger().log(Level.INFO, "Generating topology and mulval inputs " + topologyFilePath); InformationSystemManagement.prepareMulVALInputs(); Logger.getAnonymousLogger().log(Level.INFO, "Loading topology " + topologyFilePath); InformationSystem informationSystem = InformationSystemManagement.loadTopologyXMLFile(topologyFilePath, database); AttackGraph attackGraph = InformationSystemManagement .generateAttackGraphWithMulValUsingAlreadyGeneratedMulVALInputFile(); 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:com.devnexus.ting.web.controller.CalendarController.java
@RequestMapping(value = "/{eventKey}/usercalendar/{id}", method = { RequestMethod.POST, RequestMethod.PUT }) @ResponseBody/*from w ww . ja v a 2s. com*/ public ResponseEntity<UserCalendar> updateCalendar(@PathVariable("eventKey") String eventKey, @PathVariable("id") String id, HttpServletRequest request) { HttpHeaders headers = new HttpHeaders(); if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof String) { headers.add("WWW-Authenticate", "Google realm=\"http://www.devnexus.org\""); return new ResponseEntity<>(new UserCalendar(), headers, HttpStatus.UNAUTHORIZED); } User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); UserCalendar calendar = null; try { calendar = GSON.fromJson(request.getReader(), UserCalendar.class); calendar = calendarService.updateEntry(calendar.getId(), user, calendar); UnifiedMessage unifiedMessage = new UnifiedMessage.Builder().pushApplicationId(PUSH_APP_ID) .masterSecret(PUSH_APP_SECRET).aliases(Arrays.asList(user.getEmail())) .attribute("org.devnexus.sync.UserCalendar", "true").build(); javaSender.send(unifiedMessage); return new ResponseEntity<>(calendar, headers, HttpStatus.OK); } catch (IOException e) { Logger.getAnonymousLogger().log(Level.SEVERE, e.getMessage(), e); throw new RuntimeException(e); } }
From source file:org.fiware.cybercaptor.server.api.IDMEFManagement.java
/** * Get the JSON object of the alerts stored on the disk that have not been already sent * * @param informationSystem the information system * @return the JSON object of the alerts */// ww w.j a v a 2s . c om public static JSONObject getAlerts(InformationSystem informationSystem) throws IOException, ClassNotFoundException { String alertsTemporaryPath = ProjectProperties.getProperty("alerts-temporary-path"); if (alertsTemporaryPath == null || alertsTemporaryPath.isEmpty()) { alertsTemporaryPath = ProjectProperties.getProperty("output-path") + "/alerts.bin"; } if (alertsTemporaryPath == null || alertsTemporaryPath.isEmpty()) { throw new IllegalStateException("The path where the alerts should be saved is invalid."); } //Load the alerts history File alertsFile = new File(alertsTemporaryPath); List<Alert> alerts; if (alertsFile.exists()) { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(alertsTemporaryPath)); alerts = (List<Alert>) ois.readObject(); } else { alerts = new ArrayList<Alert>(); } Logger.getAnonymousLogger().log(Level.INFO, alerts.size() + " alerts loaded."); //Build the json list of alerts JSONObject json = new JSONObject(); JSONArray alerts_array = new JSONArray(); for (Alert alert : alerts) { if (!alert.isSent()) { JSONObject alert_object = new JSONObject(); alert_object.put("name", alert.getName()); alert_object.put("timestamp", alert.getTimestamp().getTime()); alert_object.put("date", alert.getTimestamp().toString()); //sources JSONArray sources_array = new JSONArray(); for (String source : alert.getSources()) { sources_array.put(source); } alert_object.put("sources", sources_array); //targets JSONArray targets_array = new JSONArray(); for (String target : alert.getTargets()) { targets_array.put(target); } alert_object.put("targets", targets_array); //CVE JSONArray CVE_array = new JSONArray(); for (String cve : alert.getCveLinks().keySet()) { JSONObject cveElement = new JSONObject(); cveElement.put("CVE", cve); cveElement.put("link", alert.getCveLinks().get(cve)); CVE_array.put(cveElement); } alert_object.put("CVEs", CVE_array); //Remediations JSONArray remediations_array = new JSONArray(); try { for (List<DynamicRemediation> dynamicRemediationActions : alert .computeRemediations(informationSystem)) { JSONArray remediations_actions_array = new JSONArray(); for (DynamicRemediation dynamicRemediation : dynamicRemediationActions) { JSONObject dynamicRemediationActionObject = dynamicRemediation.toJsonObject(); remediations_actions_array.put(dynamicRemediationActionObject); } remediations_array.put(remediations_actions_array); } } catch (Exception e) { e.printStackTrace(); } alert_object.put("dynamic_remediations", remediations_array); alerts_array.put(alert_object); } alert.setSent(true); } //Save to the modified alerts in the temporary file ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(alertsFile)); oos.writeObject(alerts); Logger.getAnonymousLogger().log(Level.INFO, alerts.size() + " alerts are now stored in temporary file."); json.put("alerts", alerts_array); return json; }