List of usage examples for java.util Map put
V put(K key, V value);
From source file:com.bright.json.PGS.java
public static void main(String[] args) throws FileNotFoundException { String fileBasename = null;/*from w w w . ja va 2 s . c om*/ JFileChooser chooser = new JFileChooser(); try { FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel Spreadsheets", "xls", "xlsx"); chooser.setFileFilter(filter); chooser.setCurrentDirectory(new java.io.File(System.getProperty("user.home"))); chooser.setDialogTitle("Select the Excel file"); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setAcceptAllFileFilterUsed(false); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory()); System.out.println("getSelectedFile() : " + chooser.getSelectedFile()); // String fileBasename = // chooser.getSelectedFile().toString().substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator)+1,chooser.getSelectedFile().toString().lastIndexOf(".")); fileBasename = chooser.getSelectedFile().toString() .substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator) + 1); System.out.println("Base name: " + fileBasename); } else { System.out.println("No Selection "); } } catch (Exception e) { System.out.println(e.toString()); } String fileName = chooser.getSelectedFile().toString(); InputStream inp = new FileInputStream(fileName); Workbook workbook = null; if (fileName.toLowerCase().endsWith("xlsx")) { try { workbook = new XSSFWorkbook(inp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (fileName.toLowerCase().endsWith("xls")) { try { workbook = new HSSFWorkbook(inp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Sheet nodeSheet = workbook.getSheet("Devices"); Sheet interfaceSheet = workbook.getSheet("Interfaces"); System.out.println("Read nodes sheet."); // Row nodeRow = nodeSheet.getRow(1); // System.out.println(row.getCell(0).toString()); // System.exit(0); JTextField uiHost = new JTextField("demo.brightcomputing.com"); // TextPrompt puiHost = new // TextPrompt("demo.brightcomputing.com",uiHost); JTextField uiUser = new JTextField("root"); // TextPrompt puiUser = new TextPrompt("root", uiUser); JTextField uiPass = new JPasswordField(""); // TextPrompt puiPass = new TextPrompt("x5deix5dei", uiPass); JPanel myPanel = new JPanel(new GridLayout(5, 1)); myPanel.add(new JLabel("Bright HeadNode hostname:")); myPanel.add(uiHost); // myPanel.add(Box.createHorizontalStrut(1)); // a spacer myPanel.add(new JLabel("Username:")); myPanel.add(uiUser); myPanel.add(new JLabel("Password:")); myPanel.add(uiPass); int result = JOptionPane.showConfirmDialog(null, myPanel, "Please fill in all the fields.", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { System.out.println("Input received."); } String rhost = uiHost.getText(); String ruser = uiUser.getText(); String rpass = uiPass.getText(); String cmURL = "https://" + rhost + ":8081/json"; List<Cookie> cookies = doLogin(ruser, rpass, cmURL); chkVersion(cmURL, cookies); Map<String, Long> categories = UniqueKeyMap(cmURL, "cmdevice", "getCategories", cookies); Map<String, Long> networks = UniqueKeyMap(cmURL, "cmnet", "getNetworks", cookies); Map<String, Long> partitions = UniqueKeyMap(cmURL, "cmpart", "getPartitions", cookies); Map<String, Long> racks = UniqueKeyMap(cmURL, "cmpart", "getRacks", cookies); Map<String, Long> switches = UniqueKeyMap(cmURL, "cmdevice", "getEthernetSwitches", cookies); // System.out.println(switches.get("switch01")); // System.out.println("Size of the map: "+ switches.size()); // System.exit(0); cmDevice newnode = new cmDevice(); cmDevice.deviceObject devObj = new cmDevice.deviceObject(); cmDevice.switchObject switchObj = new cmDevice.switchObject(); // cmDevice.netObject netObj = new cmDevice.netObject(); List<String> emptyslist = new ArrayList<String>(); // Row nodeRow = nodeSheet.getRow(1); // Row ifRow = interfaceSheet.getRow(1); // System.out.println(nodeRow.getCell(0).toString()); // nodeRow.getCell(3).getStringCellValue() Map<String, ArrayList<cmDevice.netObject>> ifmap = new HashMap<String, ArrayList<cmDevice.netObject>>(); // Map<String,netObject> helperMap = new HashMap<String,netObject>(); // Iterator<Row> rows = interfaceSheet.rowIterator (); // while (rows. < interfaceSheet.getPhysicalNumberOfRows()) { // List<netObject> netList = new ArrayList<netObject>(); for (int i = 0; i < interfaceSheet.getPhysicalNumberOfRows(); i++) { Row ifRow = interfaceSheet.getRow(i); if (ifRow.getRowNum() == 0) { continue; // just skip the rows if row number is 0 } System.out.println("Row nr: " + ifRow.getRowNum()); cmDevice.netObject netObj = new cmDevice.netObject(); ArrayList<cmDevice.netObject> helperList = new ArrayList<cmDevice.netObject>(); netObj.setBaseType("NetworkInterface"); netObj.setCardType(ifRow.getCell(3).getStringCellValue()); netObj.setChildType(ifRow.getCell(4).getStringCellValue()); netObj.setDhcp((ifRow.getCell(5).getNumericCellValue() > 0.1) ? true : false); netObj.setIp(ifRow.getCell(7).getStringCellValue()); // netObj.setMac(ifRow.getCell(0).toString()); //netObj.setModified(true); netObj.setName(ifRow.getCell(1).getStringCellValue()); netObj.setNetwork(networks.get(ifRow.getCell(6).getStringCellValue())); //netObj.setOldLocalUniqueKey(0L); netObj.setRevision(""); netObj.setSpeed(ifRow.getCell(8, Row.CREATE_NULL_AS_BLANK).getStringCellValue()); netObj.setStartIf("ALWAYS"); netObj.setToBeRemoved(false); netObj.setUniqueKey((long) ifRow.getCell(2).getNumericCellValue()); //netObj.setAdditionalHostnames(new ArrayList<String>(Arrays.asList(ifRow.getCell(9, Row.CREATE_NULL_AS_BLANK).getStringCellValue().split("\\s*,\\s*")))); //netObj.setMac(ifRow.getCell(10, Row.CREATE_NULL_AS_BLANK).getStringCellValue()); netObj.setMode((int) ifRow.getCell(11, Row.CREATE_NULL_AS_BLANK).getNumericCellValue()); netObj.setOptions(ifRow.getCell(12, Row.CREATE_NULL_AS_BLANK).getStringCellValue()); netObj.setMembers(new ArrayList<String>(Arrays .asList(ifRow.getCell(13, Row.CREATE_NULL_AS_BLANK).getStringCellValue().split("\\s*,\\s*")))); // ifmap.put(ifRow.getCell(0).getStringCellValue(), new // HashMap<String, cmDevice.netObject>()); // helperMap.put(ifRow.getCell(1).getStringCellValue(), netObj) ; // ifmap.get(ifRow.getCell(0).getStringCellValue()).putIfAbsent(ifRow.getCell(1).getStringCellValue(), // netObj); // ifmap.put(ifRow.getCell(0).getStringCellValue(), helperMap); if (!ifmap.containsKey(ifRow.getCell(0).getStringCellValue())) { ifmap.put(ifRow.getCell(0).getStringCellValue(), new ArrayList<cmDevice.netObject>()); } helperList = ifmap.get(ifRow.getCell(0).getStringCellValue()); helperList.add(netObj); ifmap.put(ifRow.getCell(0).getStringCellValue(), helperList); continue; } for (int i = 0; i < nodeSheet.getPhysicalNumberOfRows(); i++) { Row nodeRow = nodeSheet.getRow(i); if (nodeRow.getRowNum() == 0) { continue; // just skip the rows if row number is 0 } newnode.setService("cmdevice"); newnode.setCall("addDevice"); Map<String, Long> ifmap2 = new HashMap<String, Long>(); for (cmDevice.netObject j : ifmap.get(nodeRow.getCell(0).getStringCellValue())) ifmap2.put(j.getName(), j.getUniqueKey()); switchObj.setEthernetSwitch(switches.get(nodeRow.getCell(8).getStringCellValue())); System.out.println(nodeRow.getCell(8).getStringCellValue()); System.out.println(switches.get(nodeRow.getCell(8).getStringCellValue())); switchObj.setPrt((int) nodeRow.getCell(9).getNumericCellValue()); switchObj.setBaseType("SwitchPort"); devObj.setBaseType("Device"); // devObj.setCreationTime(0L); devObj.setCustomPingScript(""); devObj.setCustomPingScriptArgument(""); devObj.setCustomPowerScript(""); devObj.setCustomPowerScriptArgument(""); devObj.setCustomRemoteConsoleScript(""); devObj.setCustomRemoteConsoleScriptArgument(""); devObj.setDisksetup(""); devObj.setBmcPowerResetDelay(0L); devObj.setBurning(false); devObj.setEthernetSwitch(switchObj); devObj.setExcludeListFull(""); devObj.setExcludeListGrab(""); devObj.setExcludeListGrabnew(""); devObj.setExcludeListManipulateScript(""); devObj.setExcludeListSync(""); devObj.setExcludeListUpdate(""); devObj.setFinalize(""); devObj.setRack(racks.get(nodeRow.getCell(10).getStringCellValue())); devObj.setRackHeight((long) nodeRow.getCell(11).getNumericCellValue()); devObj.setRackPosition((long) nodeRow.getCell(12).getNumericCellValue()); devObj.setIndexInsideContainer(0L); devObj.setInitialize(""); devObj.setInstallBootRecord(false); devObj.setInstallMode(""); devObj.setIoScheduler(""); devObj.setLastProvisioningNode(0L); devObj.setMac(nodeRow.getCell(6).getStringCellValue()); devObj.setModified(true); devObj.setCategory(categories.get(nodeRow.getCell(1).getStringCellValue())); devObj.setChildType("PhysicalNode"); //devObj.setDatanode((nodeRow.getCell(5).getNumericCellValue() > 0.1) ? true // : false); devObj.setHostname(nodeRow.getCell(0).getStringCellValue()); devObj.setModified(true); devObj.setPartition(partitions.get(nodeRow.getCell(2).getStringCellValue())); devObj.setUseExclusivelyFor("Category"); devObj.setNextBootInstallMode(""); devObj.setNotes(""); devObj.setOldLocalUniqueKey(0L); devObj.setPowerControl(nodeRow.getCell(7).getStringCellValue()); // System.out.println(ifmap.get("excelnode001").size()); // System.out.println(ifmap.get(nodeRow.getCell(0).getStringCellValue()).get(nodeRow.getCell(3).getStringCellValue()).getUniqueKey()); devObj.setManagementNetwork(networks.get(nodeRow.getCell(3).getStringCellValue())); devObj.setProvisioningNetwork(ifmap2.get(nodeRow.getCell(4).getStringCellValue())); devObj.setProvisioningTransport("RSYNCDAEMON"); devObj.setPxelabel(""); // "rack": 90194313218, // "rackHeight": 1, // "rackPosition": 4, devObj.setRaidconf(""); devObj.setRevision(""); devObj.setSoftwareImageProxy(null); devObj.setStartNewBurn(false); devObj.setTag("00000000a000"); devObj.setToBeRemoved(false); // devObj.setUcsInfoConfigured(null); // devObj.setUniqueKey(12345L); devObj.setUserdefined1(""); devObj.setUserdefined2(""); ArrayList<Object> mylist = new ArrayList<Object>(); ArrayList<cmDevice.netObject> mylist2 = new ArrayList<cmDevice.netObject>(); ArrayList<Object> emptylist = new ArrayList<Object>(); devObj.setFsexports(emptylist); devObj.setFsmounts(emptylist); devObj.setGpuSettings(emptylist); devObj.setFspartAssociations(emptylist); devObj.setPowerDistributionUnits(emptyslist); devObj.setRoles(emptylist); devObj.setServices(emptylist); devObj.setStaticRoutes(emptylist); mylist2 = ifmap.get(nodeRow.getCell(0).getStringCellValue()); devObj.setNetworks(mylist2); mylist.add(devObj); mylist.add(1); newnode.setArgs(mylist); GsonBuilder builder = new GsonBuilder(); builder.enableComplexMapKeySerialization(); // Gson g = new Gson(); Gson g = builder.create(); String json2 = g.toJson(newnode); // To be used from a real console and not Eclipse String message = JSonRequestor.doRequest(json2, cmURL, cookies); continue; } JOptionPane optionPaneF = new JOptionPane("The nodes have been added!"); JDialog myDialogF = optionPaneF.createDialog(null, "Complete: "); myDialogF.setModal(false); myDialogF.setVisible(true); doLogout(cmURL, cookies); // System.exit(0); }
From source file:de.citec.sc.matoll.process.Matoll_CreateMax.java
public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException, InstantiationException, IllegalAccessException, ClassNotFoundException, Exception { String directory;/*from w w w.j a v a 2s. c o m*/ String gold_standard_lexicon; String output_lexicon; String configFile; Language language; String output; Stopwords stopwords = new Stopwords(); HashMap<String, Double> maxima; maxima = new HashMap<String, Double>(); if (args.length < 3) { System.out.print("Usage: Matoll --mode=train/test <DIRECTORY> <CONFIG>\n"); return; } // Classifier classifier; directory = args[1]; configFile = args[2]; final Config config = new Config(); config.loadFromFile(configFile); gold_standard_lexicon = config.getGoldStandardLexicon(); String model_file = config.getModel(); output_lexicon = config.getOutputLexicon(); output = config.getOutput(); language = config.getLanguage(); LexiconLoader loader = new LexiconLoader(); Lexicon gold = loader.loadFromFile(gold_standard_lexicon); Set<String> uris = new HashSet<>(); // Map<Integer,String> sentence_list = new HashMap<>(); Map<Integer, Set<Integer>> mapping_words_sentences = new HashMap<>(); //consider only properties for (LexicalEntry entry : gold.getEntries()) { try { for (Sense sense : entry.getSenseBehaviours().keySet()) { String tmp_uri = sense.getReference().getURI().replace("http://dbpedia.org/ontology/", ""); if (!Character.isUpperCase(tmp_uri.charAt(0))) { uris.add(sense.getReference().getURI()); } } } catch (Exception e) { } ; } ModelPreprocessor preprocessor = new ModelPreprocessor(language); preprocessor.setCoreferenceResolution(false); Set<String> dep = new HashSet<>(); dep.add("prep"); dep.add("appos"); dep.add("nn"); dep.add("dobj"); dep.add("pobj"); dep.add("num"); preprocessor.setDEP(dep); List<File> list_files = new ArrayList<>(); if (config.getFiles().isEmpty()) { File folder = new File(directory); File[] files = folder.listFiles(); for (File file : files) { if (file.toString().contains(".ttl")) list_files.add(file); } } else { list_files.addAll(config.getFiles()); } System.out.println(list_files.size()); int sentence_counter = 0; Map<String, Set<Integer>> bag_words_uri = new HashMap<>(); Map<String, Integer> mapping_word_id = new HashMap<>(); for (File file : list_files) { Model model = RDFDataMgr.loadModel(file.toString()); for (Model sentence : getSentences(model)) { String reference = getReference(sentence); reference = reference.replace("http://dbpedia/", "http://dbpedia.org/"); if (uris.contains(reference)) { sentence_counter += 1; Set<Integer> words_ids = getBagOfWords(sentence, stopwords, mapping_word_id); //TODO: add sentence preprocessing String obj = getObject(sentence); String subj = getSubject(sentence); preprocessor.preprocess(sentence, subj, obj, language); //TODO: also return marker if object or subject of property (in SPARQL this has to be optional of course) String parsed_sentence = getParsedSentence(sentence); try (FileWriter fw = new FileWriter("mapping_sentences_to_ids_goldstandard.tsv", true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw)) { out.println(sentence_counter + "\t" + parsed_sentence); } catch (IOException e) { e.printStackTrace(); } for (Integer word_id : words_ids) { if (mapping_words_sentences.containsKey(word_id)) { Set<Integer> tmp_set = mapping_words_sentences.get(word_id); tmp_set.add(sentence_counter); mapping_words_sentences.put(word_id, tmp_set); } else { Set<Integer> tmp_set = new HashSet<>(); tmp_set.add(sentence_counter); mapping_words_sentences.put(word_id, tmp_set); } } if (bag_words_uri.containsKey(reference)) { Set<Integer> tmp = bag_words_uri.get(reference); for (Integer w : words_ids) { tmp.add(w); } bag_words_uri.put(reference, tmp); } else { Set<Integer> tmp = new HashSet<>(); for (Integer w : words_ids) { tmp.add(w); } bag_words_uri.put(reference, tmp); } } } model.close(); } PrintWriter writer = new PrintWriter("bag_of_words_only_goldstandard.tsv"); StringBuilder string_builder = new StringBuilder(); for (String r : bag_words_uri.keySet()) { string_builder.append(r); for (Integer i : bag_words_uri.get(r)) { string_builder.append("\t"); string_builder.append(i); } string_builder.append("\n"); } writer.write(string_builder.toString()); writer.close(); writer = new PrintWriter("mapping_words_to_sentenceids_goldstandard.tsv"); string_builder = new StringBuilder(); for (Integer w : mapping_words_sentences.keySet()) { string_builder.append(w); for (int i : mapping_words_sentences.get(w)) { string_builder.append("\t"); string_builder.append(i); } string_builder.append("\n"); } writer.write(string_builder.toString()); writer.close(); }
From source file:com.oneapm.base.SparkAggregation.java
public static void main(String[] args) throws IOException { String configfile = "alert.cnf"; final FlowConstant flowConstant = new FlowConstant(); Properties config = null;/*from w w w .j a v a2 s . c om*/ try { config = getConfig(configfile); } catch (IOException e) { LOG.error(configfile + " doesnt exist in /etc/analysis/... exit" + e); System.exit(-1); } final int window = Integer.parseInt(config.getProperty("time.window", "60")); final List<String> percent = Arrays.asList("tryConnectPer", "cBitpacketAccount", "abortConntionCount", "unidirectionalTrafficPer"); final List<String> jsonList = new ArrayList<>(); final Map<String, Tuple2<String, Integer>> stats = new HashMap<String, Tuple2<String, Integer>>(); final Map<ClientKey, BaseData> broadClient = new HashMap<ClientKey, BaseData>(); final Map<HostKey, BaseData> broadHost = new HashMap<HostKey, BaseData>(); final Map<ServiceKey, BaseData> broadService = new HashMap<ServiceKey, BaseData>(); final Map<SubnetKey, BaseData> broadSubnet = new HashMap<SubnetKey, BaseData>(); final Map<VlanKey, BaseData> broadVlan = new HashMap<VlanKey, BaseData>(); final String URL = config.getProperty("alert.url"); final String HEART_BEAT = config.getProperty("alert.heartbeat"); final String RECOVER = config.getProperty("alert.recover"); ZookeeperConfigWatcher.startZookeeperWatcherService(getConfig("alert.cnf").getProperty("kafaka.zoo"), "/ni/site", new SiteConvertImpl(flowConstant)); ZookeeperConfigWatcher.startZookeeperWatcherService(getConfig("alert.cnf").getProperty("kafaka.zoo"), "/ni/net", new NetConvertImpl(flowConstant)); ZookeeperConfigWatcher.startZookeeperWatcherService(getConfig("alert.cnf").getProperty("kafaka.zoo"), "/ni/vlan_sflow", new LinkConvertImpl(flowConstant)); ZookeeperConfigWatcher.startZookeeperWatcherService(getConfig("alert.cnf").getProperty("kafaka.zoo"), "/ni/subnet", new SubnetConvertImpl(flowConstant)); zookeeperClient.connectZookeeper(config.getProperty("kafaka.zoo")); esGet.setNodeClient(); startZookeeperService(flowConstant, zookeeperClient); zookeeperClient.setRules("/ni/caution"); JavaPairReceiverInputDStream<String, byte[]> rawStream = setupRawStreamFromKafka(config, config.getProperty("group.id", "oneapm-alert")); LOG.info("alert config:" + config.toString()); final Broadcast<IPDataInfo> ipDataBroadcastInfo = getJsc().sparkContext().broadcast(new IPDataInfo()); final Broadcast<ProtocalTypeInfo> protocalTypeBroadcastInfo = getJsc().sparkContext() .broadcast(new ProtocalTypeInfo()); JavaPairDStream<TimeAgg, BeforeAgg> aggJavaPairDStream = rawStream .mapToPair(new PairFunction<Tuple2<String, byte[]>, TimeAgg, BeforeAgg>() { private static final long serialVersionUID = -2751318332921803477L; @Override public Tuple2<TimeAgg, BeforeAgg> call(Tuple2<String, byte[]> stringTuple2) throws Exception { String[] s = TAB.split(new String(stringTuple2._2)); String clientIP = s[1]; String serverIP = s[2]; TimeAgg timeAgg = new TimeAgg(); BeforeAgg beforeAgg = new BeforeAgg(); timeAgg.setServer_ip(serverIP); if (s.length >= 60) { //setProtocal_type if (!"-".equals(s[11]) && !"".equals(s[11])) { timeAgg.setProtocal_type(s[11]); } else { if ("TCP".equals(s[12])) { ProtocalTypeInfo protocalTypeInfo = protocalTypeBroadcastInfo.value(); String protocalType = protocalTypeInfo.config.getProperty(s[4]); if (protocalType != null) { timeAgg.setProtocal_type(protocalType); } else { timeAgg.setProtocal_type("TCP_" + s[4]); } } else { timeAgg.setProtocal_type(s[12]); } } timeAgg.setType("tcp"); //setVlan_id String vlanLinkAlias = flowConstant.VLAN_LINK.get(s[13]); String portLinkAlias = flowConstant.PROBE_POTR_MAP.get(s[0] + "_" + s[15]); if (flowConstant.PROBE_HOST_ENABLE) { if (portLinkAlias != null) { timeAgg.setVlan_id(portLinkAlias); } else { timeAgg.setVlan_id(s[0] + "-nic" + s[15]); } } else if (flowConstant.VLAN_LINK_ENABLE) { if (vlanLinkAlias != null) { timeAgg.setVlan_id(vlanLinkAlias); } else { timeAgg.setVlan_id(s[13]); } } else { timeAgg.setVlan_id("Vlan" + s[13]); } if (!"-".equals(s[6])) { timeAgg.setTimestamp(format.format((long) Double.parseDouble(s[6]) * 1000)); } else { timeAgg.setTimestamp(s[6]); } if (!"-".equals(s[7])) { timeAgg.setTimeEnd(format.format((long) Double.parseDouble(s[7]) * 1000)); } else { timeAgg.setTimeEnd(s[7]); } beforeAgg.setPacket_size(Double.parseDouble(s[55]) + Double.parseDouble(s[56])); beforeAgg.setC_packet_size(Double.parseDouble(s[55])); beforeAgg.setS_packet_size(Double.parseDouble(s[56])); beforeAgg.setPacket_count(Double.parseDouble(s[59]) + Double.parseDouble(s[60])); beforeAgg.setLosspacket_count(Double.parseDouble(s[33]) + Double.parseDouble(s[39]) + Double.parseDouble(s[35]) + Double.parseDouble(s[41])); double cRto = (Double.valueOf(s[19]) + Double.valueOf(s[21]) + Double.valueOf(s[23])) * 1000; double sRto = (Double.valueOf(s[20]) + Double.valueOf(s[22]) + Double.valueOf(s[24])) * 1000; beforeAgg.setTotal_rto(cRto + sRto); // ?/TCP????/TCP????/TCP?MTU?MTU/TCP? beforeAgg.setInt_ZWIN_COUNT(Double.parseDouble(s[43])); beforeAgg.setInt_OOR_COUNT(Double.parseDouble(s[46])); beforeAgg.setInt_CONGEST_COUNT(Double.parseDouble(s[47])); beforeAgg.setMTU(Double.parseDouble(s[61]) + Double.parseDouble(s[62])); Boolean hasSynFlag = Boolean.valueOf(s[5]); timeAgg.setHasSyn(hasSynFlag); timeAgg.setBool_FIN(Boolean.valueOf(s[25])); timeAgg.setBool_RST(Boolean.valueOf(s[26])); if (hasSynFlag && "-".equals(s[9])) { beforeAgg.setAbort(1); } else { beforeAgg.setAbort(0); } beforeAgg.setTcpTurns(Integer.parseInt(s[30])); //int_TURN_COUNT beforeAgg.setConnrequest_count(Double.parseDouble(s[48])); beforeAgg.setsAbortConnCount(Integer.valueOf(s[50])); Long cPayLoad = Long.valueOf(s[53]); Long sPayLoad = Long.valueOf(s[54]); long payLoad = cPayLoad + sPayLoad; double sessionJlRtt = 0; if (!"-".equals(s[9])) { sessionJlRtt = Double.valueOf(s[9]) * 1000; beforeAgg.setRtt(sessionJlRtt); beforeAgg.setServerJlRttCount(1); beforeAgg.setClientJlRttCount(1); } if (hasSynFlag && !"-".equals(s[9])) { beforeAgg.setCount(1); if ("true".equals(s[26]) && payLoad == 0) { beforeAgg.setCount(0); } } if (!"-".equals(s[10])) { double clientJlRtt = Double.valueOf(s[10]) * 1000; double serverJlRtt = sessionJlRtt - clientJlRtt; if (clientJlRtt < sessionJlRtt) { beforeAgg.setServer_rtt(clientJlRtt); beforeAgg.setClient_rtt(serverJlRtt); } else { beforeAgg.setServer_rtt(sessionJlRtt / 2); beforeAgg.setClient_rtt(sessionJlRtt / 2); } } if (beforeAgg.tcpTurns > 0) { beforeAgg.setSessionCount(1); if (Double.parseDouble(s[18]) > 0) { beforeAgg.setServer_reponsetime( Double.parseDouble(s[18]) / beforeAgg.tcpTurns * 1000); } if (Double.parseDouble(s[16]) > 0) { beforeAgg.setResponseTransmissionTime( Double.parseDouble(s[16]) / beforeAgg.tcpTurns * 1000); } if (Double.parseDouble(s[17]) > 0) { beforeAgg.setRequestTransmissionTime( Double.parseDouble(s[17]) / beforeAgg.tcpTurns * 1000); } if (beforeAgg.total_rto > 0) { beforeAgg.setTotal_rto(beforeAgg.getTotal_rto() / beforeAgg.tcpTurns); } beforeAgg.setUserResponseTime( beforeAgg.getRtt() + beforeAgg.getRequestTransmissionTime() + beforeAgg.getResponseTransmissionTime() + beforeAgg.getServer_reponsetime() + beforeAgg.total_rto); } else { beforeAgg.setServer_reponsetime(0); beforeAgg.setResponseTransmissionTime(0); beforeAgg.setRequestTransmissionTime(0); beforeAgg.setTotal_rto(0); beforeAgg.setUserResponseTime(0); } beforeAgg.setC_bitpacket_account(Double.parseDouble(s[57]) + Double.parseDouble(s[58])); } else if (s.length <= 28) { if (!"-".equals(s[8]) && !"".equals(s[8])) { timeAgg.setProtocal_type(s[8]); } else { if ("UDP".equals(s[9])) { ProtocalTypeInfo protocalTypeInfo = protocalTypeBroadcastInfo.value(); String protocalType = protocalTypeInfo.config.getProperty(s[4]); if (protocalType != null) { timeAgg.setProtocal_type(protocalType); } else { timeAgg.setProtocal_type("UDP"); } } else { timeAgg.setProtocal_type(s[9]); } } beforeAgg.setCount(0); timeAgg.setType("udp"); timeAgg.setHasSyn(false); timeAgg.setBool_FIN(false); timeAgg.setBool_RST(false); //setVlan_id String vlanLinkAlias = flowConstant.VLAN_LINK.get(s[12]); String portLinkAlias = flowConstant.PROBE_POTR_MAP.get(s[0] + "_" + s[10]); if (flowConstant.PROBE_HOST_ENABLE) { if (portLinkAlias != null) { timeAgg.setVlan_id(portLinkAlias); } else { timeAgg.setVlan_id(s[0] + "-nic" + s[10]); } } else if (flowConstant.VLAN_LINK_ENABLE) { if (vlanLinkAlias != null) { timeAgg.setVlan_id(vlanLinkAlias); } else { timeAgg.setVlan_id(s[12]); } } else { timeAgg.setVlan_id("Vlan" + s[12]); } if (!"-".equals(s[5])) { timeAgg.setTimestamp(format.format((long) Double.parseDouble(s[5]) * 1000)); } else { timeAgg.setTimestamp(s[5]); } if (!"-".equals(s[6])) { timeAgg.setTimeEnd(format.format((long) Double.parseDouble(s[6]) * 1000)); } else { timeAgg.setTimeEnd(s[6]); } beforeAgg.setPacket_size(Double.parseDouble(s[20]) + Double.parseDouble(s[21])); beforeAgg.setPacket_count(Double.parseDouble(s[24]) + Double.parseDouble(s[25])); beforeAgg.setC_packet_size(Double.parseDouble(s[20])); beforeAgg.setS_packet_size(Double.parseDouble(s[21])); beforeAgg.setInt_ZWIN_COUNT(0); beforeAgg.setInt_OOR_COUNT(0); beforeAgg.setInt_CONGEST_COUNT(0); beforeAgg.setMTU(0); beforeAgg.setC_bitpacket_account(Double.parseDouble(s[22]) + Double.parseDouble(s[23])); beforeAgg.setAbort(0); beforeAgg.setClient_rtt(0); beforeAgg.setServer_rtt(0); beforeAgg.setRtt(0); beforeAgg.setServerJlRttCount(0); beforeAgg.setClientJlRttCount(0); beforeAgg.setLosspacket_count(0); beforeAgg.setServer_reponsetime(0); beforeAgg.setTcpTurns(0); beforeAgg.setConnrequest_count(0); beforeAgg.setTotal_rto(0); beforeAgg.setUserResponseTime(0); beforeAgg.setResponseTransmissionTime(0); beforeAgg.setRequestTransmissionTime(0); beforeAgg.setServer_reponsetime(0); beforeAgg.setsAbortConnCount(0); beforeAgg.setSessionCount(0); } String sInOutFlag = IPUtils.isInHomeNet(serverIP, flowConstant.HOMENET); String cInOutFlag = IPUtils.isInHomeNet(clientIP, flowConstant.HOMENET); //setSubnet if ("IN".equals(sInOutFlag)) { String sSubNet = IPUtils.getSubNet(serverIP, flowConstant.NETMASK); timeAgg.setSubnet(sSubNet + "/" + flowConstant.MASKBITS); } else { timeAgg.setSubnet("-"); } if ("255.255.255.255".equals(clientIP)) { timeAgg.setClient_site("-"); } else { String clientSiteInfo = IPUtils.getSiteInfo(clientIP, flowConstant.SITEINFO_MAP); IPDataInfo ipDataInfo = ipDataBroadcastInfo.getValue(); if (clientSiteInfo != null) { String[] clientSiteInfos = clientSiteInfo.split("_", 3); timeAgg.setClient_site(clientSiteInfos[2]); } else { if ("IN".equals(cInOutFlag)) { timeAgg.setClient_site(""); } else { if (ipDataInfo != null) { String[] ipinfo = ipDataInfo.find(clientIP); // if (ipinfo.length < 3) { timeAgg.setClient_site(""); } else { if ("".equals(ipinfo[0])) { timeAgg.setClient_site(""); } else { //,areasite if ("".equals(ipinfo[1])) { ipinfo[1] = ipinfo[0]; } if ("".equals(ipinfo[2])) { ipinfo[2] = ipinfo[1]; } timeAgg.setClient_site(ipinfo[2]); } } } else { timeAgg.setClient_site("?"); } } } } return new Tuple2<>(timeAgg, beforeAgg); } }).filter(new Function<Tuple2<TimeAgg, BeforeAgg>, Boolean>() { @Override public Boolean call(Tuple2<TimeAgg, BeforeAgg> v1) throws Exception { return !v1._1.getTimestamp().equals("-") && !v1._1.getTimestamp().equals(""); } }); // aggJavaPairDStream.foreachRDD(new Function<JavaPairRDD<TimeAgg, BeforeAgg>, Void>() { // @Override // public Void call(JavaPairRDD<TimeAgg, BeforeAgg> v1) throws Exception { // if (Boolean.parseBoolean(getConfig("alert.cnf").getProperty("save.es")) && v1 != null) { // JavaRDD<Map<String, ?>> es = v1.map(new Function<Tuple2<TimeAgg, BeforeAgg>, Map<String, // ?>>() { // // @Override // public Map<String, ?> call(Tuple2<TimeAgg, BeforeAgg> v1) throws Exception { // ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder(); // // TimeAgg a = v1._1; // BeforeAgg b = v1._2; // String todayStr = sdf.format(format.parse(a.getTimestamp())); // builder.put("server_ip", a.server_ip); // builder.put("protocal_type", a.protocal_type); // builder.put("client_site", a.client_site); // builder.put("vlan_id", a.vlan_id); // builder.put("subnet", a.subnet); // builder.put("timestamp", format.parse(a.timestamp)); // if (b.packet_size > 0) { // builder.put("packet_size", b.packet_size); // } // if (b.c_packet_size > 0) { // builder.put("c_packet_size", b.c_packet_size); // } // // if (b.packet_count > 0) { // builder.put("packet_count", b.packet_count); // } // // if (b.losspacket_count > 0) { // builder.put("losspacket_count", b.losspacket_count); // } // if (b.total_rto > 0) { // builder.put("total_rto", b.total_rto); // builder.put("rtoCount", b.rtoCount); // } // // // if (b.tcpTurns > 0) { // builder.put("tcpTurns", b.tcpTurns); // } // if (b.connrequest_count > 0) { // builder.put("connrequest_count", b.connrequest_count); // } // if (b.abort > 0) { // builder.put("abort", b.abort); // } // if (b.client_rtt > 0) { // builder.put("client_rtt", b.client_rtt); // builder.put("clientJlRttCount", b.clientJlRttCount); // } // if (b.server_rtt > 0) { // builder.put("server_rtt", b.server_rtt); // builder.put("serverJlRttCount", b.serverJlRttCount); // } // // if (b.server_reponsetime > 0) { // builder.put("server_reponsetime", b.server_reponsetime); // builder.put("server_reponsetime_count", b.server_reponsetime_count); // } // // if (b.responseTransmissionTime > 0) { // builder.put("responseTransmissionTime", b.responseTransmissionTime); // builder.put("responseTransmissionTimeCount", b.responseTransmissionTimeCount); // } // if (b.requestTransmissionTime > 0) { // builder.put("requestTransmissionTime", b.requestTransmissionTime); // builder.put("requestTransmissionTimeCount", b.requestTransmissionTimeCount); // // } // // if (b.sAbortConnCount > 0) { // builder.put("sAbortConnCount", b.sAbortConnCount); // } // // if (b.userResponseTime > 0) { // builder.put("userResponseTime", b.userResponseTime); // builder.put("userResponseTimeCount", b.userResponseTimeCount); // } // if (b.c_bitpacket_account > 0) { // builder.put("c_bitpacket_account", b.c_bitpacket_account); // } // builder.put("index_name", todayStr); // // return builder.build(); // } // }).cache(); // if (es != null) { // JavaEsSpark.saveToEs(es, "ni-alert-session-{index_name}/alert", ImmutableMap.of // (ConfigurationOptions.ES_MAPPING_EXCLUDE, "index_name")); // } // } // return null; // } // }); JavaPairDStream<TimeAgg, BeforeAgg> reduceByWindow = aggJavaPairDStream .reduceByKeyAndWindow(new Function2<BeforeAgg, BeforeAgg, BeforeAgg>() { @Override public BeforeAgg call(BeforeAgg v1, BeforeAgg v2) throws Exception { BeforeAgg sum = new BeforeAgg(); sum.setPacket_size(v1.getPacket_size() + v2.getPacket_size()); sum.setC_packet_size(v1.getC_packet_size() + v2.getC_packet_size()); sum.setS_packet_size(v1.getS_packet_size() + v2.getS_packet_size()); sum.setPacket_count(v1.getPacket_count() + v2.getPacket_count()); sum.setC_packet_count(v1.getC_packet_count() + v2.getC_packet_count()); sum.setS_packet_count(v1.getS_packet_count() + v2.getS_packet_count()); sum.setLosspacket_count(v1.getLosspacket_count() + v2.getLosspacket_count()); sum.setTotal_rto(v1.getTotal_rto() + v2.getTotal_rto()); sum.setAbort(v1.getAbort() + v2.getAbort()); sum.setRequestTransmissionTime( v1.getRequestTransmissionTime() + v2.getRequestTransmissionTime()); sum.setResponseTransmissionTime( v1.getResponseTransmissionTime() + v2.getResponseTransmissionTime()); sum.setTcpTurns(v1.getTcpTurns() + v2.getTcpTurns()); sum.setConnrequest_count(v1.getConnrequest_count() + v2.getConnrequest_count()); sum.setRtt(v1.getRtt() + v2.getRtt()); sum.setClient_rtt(v1.getClient_rtt() + v2.getClient_rtt()); sum.setServer_rtt(v1.getServer_rtt() + v2.getServer_rtt()); sum.setServer_reponsetime(v1.getServer_reponsetime() + v2.getServer_reponsetime()); sum.setC_bitpacket_account(v1.getC_bitpacket_account() + v2.getC_bitpacket_account()); sum.setClientJlRttCount(v1.getClientJlRttCount() + v2.getClientJlRttCount()); sum.setServerJlRttCount(v1.getServerJlRttCount() + v2.getServerJlRttCount()); sum.setUserResponseTime(v1.getUserResponseTime() + v2.getUserResponseTime()); sum.setSessionCount(v1.sessionCount + v2.sessionCount); sum.setsAbortConnCount(v1.sAbortConnCount + v2.sAbortConnCount); sum.setCount(v1.getCount() + v2.getCount()); sum.setInt_CONGEST_COUNT(v1.int_CONGEST_COUNT + v2.int_CONGEST_COUNT); sum.setInt_OOR_COUNT(v1.int_OOR_COUNT + v2.int_OOR_COUNT); sum.setInt_ZWIN_COUNT(v1.int_ZWIN_COUNT + v2.int_ZWIN_COUNT); sum.setMTU(v1.MTU + v2.MTU); return sum; } }, Durations.seconds(300), Durations.seconds(60)).cache(); reduceByWindow.foreachRDD(new Function<JavaPairRDD<TimeAgg, BeforeAgg>, Void>() { private static final long serialVersionUID = -4144342491397135515L; @Override public Void call(JavaPairRDD<TimeAgg, BeforeAgg> v1) throws Exception { if (v1.count() > 0) { /** * getStartTime */ List<Long> timeList = v1.map(new Function<Tuple2<TimeAgg, BeforeAgg>, Long>() { @Override public Long call(Tuple2<TimeAgg, BeforeAgg> v1) throws Exception { return format.parse(v1._1.getTimestamp()).getTime(); } }).distinct().collect(); Collections.sort(timeList, new MyComparator()); long a = timeList.get(3); final String time = format.format(new Date(a)); long b = timeList.get(1); final String endTime = format.format(new Date(b)); if (b > 0) { JavaRDD<Map<String, ?>> active = v1 .filter(new Function<Tuple2<TimeAgg, BeforeAgg>, Boolean>() { @Override public Boolean call(Tuple2<TimeAgg, BeforeAgg> v1) throws Exception { String sInOutFlag = IPUtils.isInHomeNet(v1._1.getServer_ip(), flowConstant.HOMENET); return v1._1.getType().equals("tcp") && "IN".equals(sInOutFlag); } }).mapToPair( new PairFunction<Tuple2<TimeAgg, BeforeAgg>, Tuple2<String, String>, ConnectStatus>() { @Override public Tuple2<Tuple2<String, String>, ConnectStatus> call( Tuple2<TimeAgg, BeforeAgg> timeAggBeforeAggTuple2) throws Exception { ConnectStatus connectStatus = new ConnectStatus(); String serverIp = timeAggBeforeAggTuple2._1.getServer_ip(); String protoType = timeAggBeforeAggTuple2._1.getProtocal_type(); TimeAgg a = timeAggBeforeAggTuple2._1; BeforeAgg b = timeAggBeforeAggTuple2._2; // if (format.parse(a.timestamp).getTime() == format.parse(endTime) .getTime() && a.hasSyn) { connectStatus.setNewCreate(b.getCount()); } else { connectStatus.setNewCreate(0); } //?breakreset?break if (format.parse(a.timeEnd).getTime() == format.parse(endTime) .getTime() && (a.bool_FIN || a.bool_RST)) { connectStatus.setCloseConn(b.getCount()); } else { connectStatus.setCloseConn(0); } if (format.parse(a.timestamp).getTime() <= format.parse(endTime) .getTime() && format.parse(a.timeEnd).getTime() > format.parse(endTime) .getTime() && a.hasSyn) { connectStatus.setActiveConn(b.getCount()); } else if (format.parse(a.timestamp).getTime() == format .parse(endTime).getTime() && format.parse(a.timeEnd).getTime() == format .parse(endTime).getTime() && a.hasSyn) { connectStatus.setActiveConn(b.getCount()); } return new Tuple2<>(new Tuple2<>(serverIp, protoType), connectStatus); } }) .reduceByKey(new Function2<ConnectStatus, ConnectStatus, ConnectStatus>() { @Override public ConnectStatus call(ConnectStatus v1, ConnectStatus v2) throws Exception { ConnectStatus connectStatus = new ConnectStatus(); connectStatus.setNewCreate(v1.newCreate + v2.newCreate); connectStatus.setActiveConn(v1.activeConn + v2.activeConn); connectStatus.setCloseConn(v1.closeConn + v2.closeConn); return connectStatus; } }) .map(new Function<Tuple2<Tuple2<String, String>, ConnectStatus>, Map<String, ?>>() { @Override public Map<String, ?> call(Tuple2<Tuple2<String, String>, ConnectStatus> v1) throws Exception { ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder(); String todayStr = sdf.format(format.parse(endTime)); builder.put("server_ip", v1._1._1); builder.put("protocal_type", v1._1._2); builder.put("newCreateConn", v1._2.getNewCreate()); builder.put("closeConn", v1._2.getCloseConn()); builder.put("activeConn", v1._2.getActiveConn()); builder.put("index_name", todayStr); builder.put("timestamp", format.parse(endTime)); return builder.build(); } }).cache(); if (active != null) { JavaEsSpark.saveToEs(active, "ni-active-conn-{index_name}/active", ImmutableMap.of(ConfigurationOptions.ES_MAPPING_EXCLUDE, "index_name")); } } JavaPairRDD<TimeAgg, BeforeAgg> before = v1 .filter(new Function<Tuple2<TimeAgg, BeforeAgg>, Boolean>() { @Override public Boolean call(Tuple2<TimeAgg, BeforeAgg> v1) throws Exception { return v1._1.getTimestamp().equals(time); } }); if (Boolean.parseBoolean(getConfig("alert.cnf").getProperty("save.es")) && before != null) { JavaRDD<Map<String, ?>> es = before .map(new Function<Tuple2<TimeAgg, BeforeAgg>, Map<String, ?>>() { @Override public Map<String, ?> call(Tuple2<TimeAgg, BeforeAgg> v1) throws Exception { ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder(); TimeAgg a = v1._1; BeforeAgg b = v1._2; String todayStr = sdf.format(format.parse(a.getTimestamp())); builder.put("server_ip", a.server_ip); builder.put("protocal_type", a.protocal_type); builder.put("client_site", a.client_site); builder.put("vlan_id", a.vlan_id); builder.put("subnet", a.subnet); builder.put("timestamp", format.parse(a.timestamp)); if (b.packet_size > 0) { builder.put("packet_size", b.packet_size); } if (b.c_packet_size > 0) { builder.put("c_packet_size", b.c_packet_size); } builder.put("count", b.count); if (b.packet_count > 0) { builder.put("packet_count", b.packet_count); } if (b.losspacket_count > 0) { builder.put("losspacket_count", b.losspacket_count); } if (b.total_rto > 0) { builder.put("total_rto", b.total_rto); } if (b.tcpTurns > 0) { builder.put("tcpTurns", b.tcpTurns); builder.put("sessionCount", b.sessionCount); } if (b.connrequest_count > 0) { builder.put("connrequest_count", b.connrequest_count); } if (b.abort > 0) { builder.put("abort", b.abort); } if (b.client_rtt > 0) { builder.put("client_rtt", b.client_rtt); builder.put("clientJlRttCount", b.clientJlRttCount); } if (b.server_rtt > 0) { builder.put("server_rtt", b.server_rtt); builder.put("serverJlRttCount", b.serverJlRttCount); } if (b.server_reponsetime > 0) { builder.put("server_reponsetime", b.server_reponsetime); } if (b.responseTransmissionTime > 0) { builder.put("responseTransmissionTime", b.responseTransmissionTime); } if (b.requestTransmissionTime > 0) { builder.put("requestTransmissionTime", b.requestTransmissionTime); } if (b.sAbortConnCount > 0) { builder.put("sAbortConnCount", b.sAbortConnCount); } if (b.userResponseTime > 0) { builder.put("userResponseTime", b.userResponseTime); } if (b.c_bitpacket_account > 0) { builder.put("c_bitpacket_account", b.c_bitpacket_account); } builder.put("index_name", todayStr); return builder.build(); } }).cache(); if (es != null) { JavaEsSpark.saveToEs(es, "ni-alert-session-{index_name}/alert", ImmutableMap.of(ConfigurationOptions.ES_MAPPING_EXCLUDE, "index_name")); } } UrlPostMethod.urlPostMethod(HEART_BEAT, "frequency=" + window); rules = zookeeperClient.getRules(); if (rules != null) { ArrayList<String> flagRules = new ArrayList<String>(); //?ruleType for (final RuleRecover ruleRecover : rules) { final Rule rule = ruleRecover.getRule(); if (rule.isEnable() && !flagRules.contains(rule.getType())) { //ruleType? flagRules.add(rule.getType()); //ruleType? JavaPairRDD<String, AggResult> alert = before.mapToPair( new PairFunction<Tuple2<TimeAgg, BeforeAgg>, String, BeforeAgg>() { @Override public Tuple2<String, BeforeAgg> call( Tuple2<TimeAgg, BeforeAgg> timeAggBeforeAggTuple2) throws Exception { Field field1 = timeAggBeforeAggTuple2._1.getClass() .getDeclaredField(rule.getType()); field1.setAccessible(true); String result1 = (String) field1.get(timeAggBeforeAggTuple2._1); if (rule.getType().equals("server_ip")) { String sInOutFlag = IPUtils.isInHomeNet( timeAggBeforeAggTuple2._1.getServer_ip(), flowConstant.HOMENET); if ("IN".equals(sInOutFlag)) { return new Tuple2<>(result1, timeAggBeforeAggTuple2._2); } else { return new Tuple2<>(result1, null); } } else { return new Tuple2<>(result1, timeAggBeforeAggTuple2._2); } } }).filter(new Function<Tuple2<String, BeforeAgg>, Boolean>() { @Override public Boolean call(Tuple2<String, BeforeAgg> v1) throws Exception { return v1._2 != null && !v1._1.equals("") && !v1._1.equals("-"); } }).reduceByKey(new Function2<BeforeAgg, BeforeAgg, BeforeAgg>() { @Override public BeforeAgg call(BeforeAgg v1, BeforeAgg v2) throws Exception { BeforeAgg sum = new BeforeAgg(); sum.setPacket_size(v1.getPacket_size() + v2.getPacket_size()); sum.setC_packet_size(v1.getC_packet_size() + v2.getC_packet_size()); sum.setS_packet_size(v1.getS_packet_size() + v2.getS_packet_size()); sum.setPacket_count(v1.getPacket_count() + v2.getPacket_count()); sum.setC_packet_count( v1.getC_packet_count() + v2.getC_packet_count()); sum.setS_packet_count( v1.getS_packet_count() + v2.getS_packet_count()); sum.setLosspacket_count( v1.getLosspacket_count() + v2.getLosspacket_count()); sum.setTotal_rto(v1.getTotal_rto() + v2.getTotal_rto()); sum.setAbort(v1.getAbort() + v2.getAbort()); sum.setRequestTransmissionTime(v1.getRequestTransmissionTime() + v2.getRequestTransmissionTime()); sum.setResponseTransmissionTime(v1.getResponseTransmissionTime() + v2.getResponseTransmissionTime()); sum.setTcpTurns(v1.getTcpTurns() + v2.getTcpTurns()); sum.setConnrequest_count( v1.getConnrequest_count() + v2.getConnrequest_count()); sum.setRtt(v1.getRtt() + v2.getRtt()); sum.setClient_rtt(v1.getClient_rtt() + v2.getClient_rtt()); sum.setServer_rtt(v1.getServer_rtt() + v2.getServer_rtt()); sum.setServer_reponsetime( v1.getServer_reponsetime() + v2.getServer_reponsetime()); sum.setC_bitpacket_account( v1.getC_bitpacket_account() + v2.getC_bitpacket_account()); sum.setClientJlRttCount( v1.getClientJlRttCount() + v2.getClientJlRttCount()); sum.setServerJlRttCount( v1.getServerJlRttCount() + v2.getServerJlRttCount()); sum.setUserResponseTime( v1.getUserResponseTime() + v2.getUserResponseTime()); sum.setSessionCount(v1.sessionCount + v2.sessionCount); sum.setsAbortConnCount(v1.sAbortConnCount + v2.sAbortConnCount); return sum; } }).mapToPair( new PairFunction<Tuple2<String, BeforeAgg>, String, AggResult>() { @Override public Tuple2<String, AggResult> call( Tuple2<String, BeforeAgg> stringBeforeAggTuple2) throws Exception { BeforeAgg before = stringBeforeAggTuple2._2; AggResult result = new AggResult(); result.setTimestamp(time); result.setThroughput(before.packet_size * 8 / window); result.setS_throughput(before.s_packet_size * 8 / window); result.setC_throughput( before.c_bitpacket_account * 8 / window); result.setPacketThroughput(before.packet_count / window); result.setLossRate(before.losspacket_count / before.packet_count * 100); if (before.sessionCount > 0) { result.setRetransferTime( before.total_rto / before.sessionCount); } else { result.setRetransferTime(0); } if (before.clientJlRttCount > 0) { result.setClientRoundTripTime( before.client_rtt / before.clientJlRttCount); result.setRtt(before.rtt / before.clientJlRttCount); } else { result.setClientRoundTripTime(0); result.setRtt(0); } if (before.serverJlRttCount > 0) { result.setServerRoundTripTime( before.server_rtt / before.serverJlRttCount); } else { result.setServerRoundTripTime(0); } if (before.sessionCount > 0) { result.setUserRespTime(before.getUserResponseTime() / before.sessionCount); result.setTransmissionTime( (before.requestTransmissionTime + before.responseTransmissionTime) / before.sessionCount); } else { result.setUserRespTime(0); result.setTransmissionTime(0); } if (before.sessionCount > 0) { result.setServerRespTime(before.server_reponsetime / before.sessionCount); } else { result.setServerRespTime(0); } result.setConnectFailedRate(before.abort / window); //@Deprecates result.setTryConnectPer(0); result.setCongest_pre(before.getInt_CONGEST_COUNT() / before.getCount() * 100); result.setOutoforder_pre(before.getInt_OOR_COUNT() / before.getCount() * 100); result.setZerowindow_pre(before.getInt_ZWIN_COUNT() / before.getCount() * 100); result.setMTU_pre( before.getMTU() / before.getCount() * 100); if (before.packet_count > 0) { result.setcBitpacketAccount(before.c_bitpacket_account / before.packet_count * 100); } else { result.setcBitpacketAccount(0); } if (before.connrequest_count - before.abort > 0) { result.setAbortConntionCount(before.sAbortConnCount / (before.connrequest_count - before.abort) * 100); } else { result.setAbortConntionCount(0); } return new Tuple2<>(stringBeforeAggTuple2._1, result); } }) .cache(); if (alert.count() > 0) { List<String> alertList = new ArrayList<>(); for (final RuleRecover newRule : rules) { final Rule sameRule = newRule.getRule(); if (Boolean.parseBoolean(getConfig("alert.cnf").getProperty("save.es"))) { System.out.println( "rule:" + sameRule.toString() + "--------------"); } final int recover = newRule.getRecover(); if (sameRule.isEnable() && sameRule.getType().equals(flagRules.get(flagRules.size() - 1))) { if (!sameRule.getThresholdErrType().equals("absolute")) { if (esGet.getClient() == null) { esGet.setNodeClient(); } final Calendar now = Calendar.getInstance(); now.setTime(format.parse(time)); int minute = now.get(Calendar.MINUTE); Key key = null; switch (sameRule.getType()) { case "server_ip": if (minute % 5 != 0) { now.set(Calendar.MINUTE, minute / 5 * 5); if (broadHost.isEmpty()) { Map<HostKey, BaseData> service = esGet .setHost(now.getTime(), "ni-base-hostname"); broadHost.putAll(service); } } else { Map<HostKey, BaseData> service = esGet .setHost(now.getTime(), "ni-base-hostname"); broadHost.clear(); broadHost.putAll(service); } key = new HostKey(); // baseData = broadHost.get(key); break; case "protocal_type": if (minute % 5 != 0) { now.set(Calendar.MINUTE, minute / 5 * 5); if (broadService.isEmpty()) { Map<ServiceKey, BaseData> service = esGet .setService(now.getTime(), "ni-base-service"); broadService.putAll(service); } } else { Map<ServiceKey, BaseData> service = esGet .setService(now.getTime(), "ni-base-service"); broadService.clear(); broadService.putAll(service); } key = new ServiceKey(); // key.setKeyWord(stringAggResultTuple2._1); // key.setStart_timestamp(now.getTime()); // baseData = broadService.get(key); break; case "client_site": if (minute % 5 != 0) { now.set(Calendar.MINUTE, minute / 5 * 5); if (broadClient.isEmpty()) { Map<ClientKey, BaseData> service = esGet .setClient(now.getTime(), "ni-base-clientsite"); broadClient.putAll(service); } } else { Map<ClientKey, BaseData> service = esGet .setClient(now.getTime(), "ni-base-clientsite"); broadClient.clear(); broadClient.putAll(service); } key = new ClientKey(); // key.setKeyWord(stringAggResultTuple2._1); // key.setStart_timestamp(now.getTime()); // baseData = broadClient.get(key); break; case "vlan_id": if (minute % 5 != 0) { now.set(Calendar.MINUTE, minute / 5 * 5); if (broadVlan.isEmpty()) { Map<VlanKey, BaseData> service = esGet .setVlan(now.getTime(), "ni-base-link"); broadVlan.putAll(service); } } else { Map<VlanKey, BaseData> service = esGet .setVlan(now.getTime(), "ni-base-link"); broadVlan.clear(); broadVlan.putAll(service); } key = new VlanKey(); // key.setKeyWord(stringAggResultTuple2._1); // key.setStart_timestamp(now.getTime()); // baseData = broadVlan.get(key); break; case "subnet": if (minute % 5 != 0) { now.set(Calendar.MINUTE, minute / 5 * 5); if (broadSubnet.isEmpty()) { Map<SubnetKey, BaseData> service = esGet .setSubnet(now.getTime(), "ni-base-subnet"); broadSubnet.putAll(service); } } else { Map<SubnetKey, BaseData> service = esGet .setSubnet(now.getTime(), "ni-base-subnet"); broadSubnet.clear(); broadSubnet.putAll(service); } key = new SubnetKey(); // key.setKeyWord(stringAggResultTuple2._1); // key.setStart_timestamp(now.getTime()); // baseData = broadSubnet.get(key); break; } final Key finalKey = key; alertList = alert .filter(new Function<Tuple2<String, AggResult>, Boolean>() { @Override public Boolean call(Tuple2<String, AggResult> v1) throws Exception { Field field2 = v1._2.getClass() .getDeclaredField(sameRule.getValue()); field2.setAccessible(true); double result2 = (double) field2.get(v1._2); if (result2 == 0) { return false; } String contain = sameRule.getContain(); if (contain.equals("") && !v1._1.equals("")) { return true; } if (v1._1 == null || v1._1.equals("")) { return false; } return v1._1.contains(sameRule.getContain()); } }).mapToPair( new PairFunction<Tuple2<String, AggResult>, String, String>() { @Override public Tuple2<String, String> call( Tuple2<String, AggResult> stringAggResultTuple2) throws Exception { Field field2 = stringAggResultTuple2._2 .getClass().getDeclaredField( sameRule.getValue()); field2.setAccessible(true); double alertCursor = (double) field2 .get(stringAggResultTuple2._2); JSONObject json = new JSONObject(); BaseData baseData = new BaseData(); finalKey.setKeyWord( stringAggResultTuple2._1); finalKey.setStart_timestamp(now.getTime()); baseData = broadService.get(finalKey); if (baseData != null) { Field field = baseData.getClass() .getDeclaredField( sameRule.getValue()); field.setAccessible(true); double result = (double) field .get(baseData); AlertLevel alertLevel = new AlertLevel(); if (sameRule.getThresholdErrOp() .equals("ge")) { if (alertCursor - result >= sameRule .getMax_cardinality()) { alertLevel.setWarningLevel( "levelBad"); } else if (alertCursor - result >= sameRule .getMin_cardinality()) { alertLevel.setWarningLevel( "levelWarn"); } else { alertLevel.setWarningLevel( "levelNormal"); } } if (sameRule.getThresholdErrOp() .equals("le")) { if (result - alertCursor <= sameRule .getMax_cardinality()) { alertLevel.setWarningLevel( "levelBad"); } else if (result - alertCursor <= sameRule .getMin_cardinality()) { alertLevel.setWarningLevel( "levelWarn"); } else { alertLevel.setWarningLevel( "levelNormal"); } } alertLevel.setResourceName( stringAggResultTuple2._1); if (sameRule.getType() .equals("server_ip")) { alertLevel.setIpAddress( stringAggResultTuple2._1); } else { alertLevel.setIpAddress(""); } alertLevel.setOccureTime( esFormat.format(format.parse( stringAggResultTuple2._2 .getTimestamp()))); alertLevel.setResourceType( sameRule.getType()); alertLevel.setMetricId( sameRule.getValue()); alertLevel.setResourceInstanceId( stringAggResultTuple2._1); // top2 d?>10%? Map<String, Double> top2 = new HashMap<String, Double>(); top2.put("MTU?", stringAggResultTuple2._2 .getMTU_pre()); top2.put("?", stringAggResultTuple2._2 .getCongest_pre()); top2.put("??", stringAggResultTuple2._2 .getOutoforder_pre()); top2.put("??", stringAggResultTuple2._2 .getZerowindow_pre()); List<Map.Entry<String, Double>> list = SortHashMap .sortHashMap(top2); if ("lossRate" .equals(sameRule.getValue())) { if (list.get(0).getValue() > 10 && list.get(1) .getValue() > 10) { alertLevel.setWarningContent( alertLevel.getMetricId() + "" + df.format( alertCursor) + "%25," + list.get(0) .getKey() + "" + list.get(0) .getValue() + "%25," + list.get(1) .getKey() + "" + list.get(1) .getValue() + "%25." + result + "." + sameRule .getMin_cardinality() + "," + sameRule .getMax_cardinality()); } else { alertLevel.setWarningContent( alertLevel.getMetricId() + "" + df.format( alertCursor) + "%25," + result + "." + sameRule .getMin_cardinality() + "," + sameRule .getMax_cardinality()); } } else { if ("userRespTime".equals( sameRule.getValue())) { if (list.get(0).getValue() > 10 && list.get(1) .getValue() > 10) { alertLevel .setWarningContent( alertLevel .getMetricId() + "" + millToSec( (long) alertCursor) + "," + millToSec( (long) stringAggResultTuple2._2 .getRtt()) + "ms,?" + millToSec( (long) stringAggResultTuple2._2 .getServerRespTime()) + "ms," + millToSec( (long) stringAggResultTuple2._2 .getTransmissionTime()) + "ms,?" + millToSec( (long) stringAggResultTuple2._2 .getRetransferTime()) + "." + list.get( 0) .getKey() + "" + list.get( 0) .getValue() + "%25," + list.get( 1) .getKey() + "" + list.get( 1) .getValue() + "%25." + result + "." + sameRule .getMin_cardinality() + "," + sameRule .getMax_cardinality()); } else { alertLevel .setWarningContent( alertLevel .getMetricId() + "" + millToSec( (long) alertCursor) + "," + millToSec( (long) stringAggResultTuple2._2 .getRtt()) + "ms,?" + millToSec( (long) stringAggResultTuple2._2 .getServerRespTime()) + "ms," + millToSec( (long) stringAggResultTuple2._2 .getTransmissionTime()) + "ms,?" + millToSec( (long) stringAggResultTuple2._2 .getRetransferTime()) + "." + result + "." + sameRule .getMin_cardinality() + "," + sameRule .getMax_cardinality()); } } else if ("rtt".equals( sameRule.getValue())) { alertLevel.setWarningContent( "RTT" + millToSec( (long) alertCursor) + ",RTT" + millToSec( (long) stringAggResultTuple2._2 .getClientRoundTripTime()) + "ms,?RTT" + millToSec( (long) stringAggResultTuple2._2 .getServerRoundTripTime()) + "ms." + result + "." + sameRule .getMin_cardinality() + "," + sameRule .getMax_cardinality()); } else if ("throughput".equals( sameRule.getType())) { alertLevel.setWarningContent( alertLevel.getMetricId() + "" + convertUnit( (long) alertCursor) + ",????" + convertUnit( (long) stringAggResultTuple2._2 .getS_throughput()) + ",????" + convertUnit( (long) stringAggResultTuple2._2 .getC_throughput()) + "." + convertUnit( (long) result) + "." + sameRule .getMin_cardinality() + "," + sameRule .getMax_cardinality()); } else if ("packetThroughput" .equals(sameRule .getValue())) { alertLevel.setWarningContent( alertLevel.getMetricId() + "" + df.format( alertCursor) + ",????" + stringAggResultTuple2._2 .getS_packetThroughput() + ",????" + stringAggResultTuple2._2 .getC_packetThroughput() + "." + result + "." + sameRule .getMin_cardinality() + "," + sameRule .getMax_cardinality()); } else if (percent.contains( sameRule.getValue())) { alertLevel.setWarningContent( alertLevel.getMetricId() + "" + df.format( alertCursor) + "%25," + sameRule .getMin_cardinality() + "." + result + "." + sameRule .getMax_cardinality()); } else { alertLevel.setWarningContent( alertLevel.getMetricId() + "" + df.format( alertCursor) + "." + result + "." + sameRule .getMin_cardinality() + "," + sameRule .getMax_cardinality()); } } alertLevel.setRuleId( sameRule.getRuleName()); alertLevel.setUniqueMark(sameRule .getRuleName() + "-" + stringAggResultTuple2._1 + "-" + sameRule.getValue()); if (stats.containsKey( alertLevel.getUniqueMark())) { String preLevel = stats .get(alertLevel .getUniqueMark())._1; int num = stats.get(alertLevel .getUniqueMark())._2; boolean preWarning = preLevel .equals("levelWarn") || preLevel .equals("levelBad"); boolean newWarning = alertLevel .getWarningLevel() .equals("levelWarn") || alertLevel .getWarningLevel() .equals("levelBad"); if (preWarning && !newWarning) { num = 1 - num; stats.put(alertLevel .getUniqueMark(), new Tuple2<String, Integer>( alertLevel .getWarningLevel(), num)); } else if (!preWarning && newWarning) { stats.put(alertLevel .getUniqueMark(), new Tuple2<String, Integer>( alertLevel .getWarningLevel(), 0 - recover)); } else if (!preWarning && !preWarning) { num = 1 - num; stats.put(alertLevel .getUniqueMark(), new Tuple2<String, Integer>( alertLevel .getWarningLevel(), num)); } else { num = 0 - num; stats.put(alertLevel .getUniqueMark(), new Tuple2<String, Integer>( alertLevel .getWarningLevel(), num)); } } else { if (alertLevel.getWarningLevel() .equals("levelWarn") || alertLevel .getWarningLevel() .equals("levelBad")) { stats.put(alertLevel .getUniqueMark(), new Tuple2<String, Integer>( alertLevel .getWarningLevel(), 0 - recover)); json = (JSONObject) JSON .toJSON(alertLevel); return new Tuple2<>( stringAggResultTuple2._1, json.toString()); } } } return new Tuple2<>( stringAggResultTuple2._1, ""); } }) .filter(new Function<Tuple2<String, String>, Boolean>() { @Override public Boolean call(Tuple2<String, String> v1) throws Exception { return !v1._2.equals("") && v1._2 != null; } }).map(new Function<Tuple2<String, String>, String>() { @Override public String call(Tuple2<String, String> v1) throws Exception { return v1._2; } }).collect(); } else { alertList = alert .filter(new Function<Tuple2<String, AggResult>, Boolean>() { @Override public Boolean call(Tuple2<String, AggResult> v1) throws Exception { Field field2 = v1._2.getClass() .getDeclaredField(sameRule.getValue()); field2.setAccessible(true); double result2 = (double) field2.get(v1._2); if (result2 == 0.0) { return false; } String contain = sameRule.getContain(); if (contain.equals("") && !v1._1.equals("")) { return true; } if (v1._1 == null || v1._1.equals("")) { return false; } return v1._1.contains(sameRule.getContain()); } }).mapToPair( new PairFunction<Tuple2<String, AggResult>, String, String>() { @Override public Tuple2<String, String> call( Tuple2<String, AggResult> stringAggResultTuple2) throws Exception { Field field2 = stringAggResultTuple2._2 .getClass().getDeclaredField( sameRule.getValue()); field2.setAccessible(true); double alertCursor = (double) field2 .get(stringAggResultTuple2._2); JSONObject json = new JSONObject(); AlertLevel alertLevel = new AlertLevel(); if (alertCursor >= sameRule .getMax_cardinality()) { alertLevel.setWarningLevel("levelBad"); } else if (alertCursor >= sameRule .getMin_cardinality()) { alertLevel.setWarningLevel("levelWarn"); } else { alertLevel .setWarningLevel("levelNormal"); } alertLevel.setResourceName( stringAggResultTuple2._1); if (sameRule.getType() .equals("server_ip")) { alertLevel.setIpAddress( stringAggResultTuple2._1); } else { alertLevel.setIpAddress(""); } alertLevel.setResourceType( sameRule.getType()); alertLevel.setOccureTime( esFormat.format(format.parse( stringAggResultTuple2._2 .getTimestamp()))); alertLevel.setMetricId(sameRule.getValue()); alertLevel.setResourceInstanceId( stringAggResultTuple2._1); // top2 d?>10%? Map<String, Double> top2 = new HashMap<String, Double>(); top2.put("MTU?", stringAggResultTuple2._2 .getMTU_pre()); top2.put("?", stringAggResultTuple2._2 .getCongest_pre()); top2.put("??", stringAggResultTuple2._2 .getOutoforder_pre()); top2.put("??", stringAggResultTuple2._2 .getZerowindow_pre()); List<Map.Entry<String, Double>> list = SortHashMap .sortHashMap(top2); if ("lossRate" .equals(sameRule.getValue())) { if (list.get(0).getValue() > 10 && list .get(1).getValue() > 10) { alertLevel.setWarningContent( alertLevel.getMetricId() + "" + df.format( alertCursor) + "%25," + list.get(0) .getKey() + "" + list.get(0) .getValue() + "%25," + list.get(1) .getKey() + "" + list.get(1) .getValue() + "%25." + "" + sameRule .getMin_cardinality() + "," + sameRule .getMax_cardinality()); } else { alertLevel.setWarningContent( alertLevel.getMetricId() + "" + df.format( alertCursor) + "%25," + "," + sameRule .getMin_cardinality() + "," + sameRule .getMax_cardinality()); } } else if ("userRespTime" .equals(sameRule.getValue())) { if (list.get(0).getValue() > 10 && list .get(1).getValue() > 10) { alertLevel.setWarningContent( alertLevel.getMetricId() + "" + millToSec( (long) alertCursor) + "," + millToSec( (long) stringAggResultTuple2._2 .getRtt()) + ",?" + millToSec( (long) stringAggResultTuple2._2 .getServerRespTime()) + "," + millToSec( (long) stringAggResultTuple2._2 .getTransmissionTime()) + "?" + millToSec( (long) stringAggResultTuple2._2 .getRetransferTime()) + "." + list.get(0) .getKey() + "" + list.get(0) .getValue() + "%25," + list.get(1) .getKey() + "" + list.get(1) .getValue() + "%25." + "" + sameRule .getMin_cardinality() + "," + sameRule .getMax_cardinality()); } else { alertLevel.setWarningContent( alertLevel.getMetricId() + "" + millToSec( (long) alertCursor) + "," + millToSec( (long) stringAggResultTuple2._2 .getRtt()) + ",?" + millToSec( (long) stringAggResultTuple2._2 .getServerRespTime()) + "," + millToSec( (long) stringAggResultTuple2._2 .getTransmissionTime()) + "?" + millToSec( (long) stringAggResultTuple2._2 .getRetransferTime()) + "." + sameRule .getMin_cardinality() + "," + sameRule .getMax_cardinality()); } } else if ("rtt" .equals(sameRule.getValue())) { alertLevel.setWarningContent("RTT" + millToSec((long) alertCursor) + ",RTT" + millToSec( (long) stringAggResultTuple2._2 .getClientRoundTripTime()) + ",?RTT" + millToSec( (long) stringAggResultTuple2._2 .getServerRoundTripTime()) + "." + sameRule.getMin_cardinality() + "," + sameRule .getMax_cardinality()); } else if ("throughput" .equals(sameRule.getType())) { alertLevel.setWarningContent(alertLevel .getMetricId() + "" + convertUnit( (long) alertCursor) + ",????" + convertUnit( (long) stringAggResultTuple2._2 .getS_throughput()) + ",????" + convertUnit( (long) stringAggResultTuple2._2 .getC_throughput()) + "." + sameRule.getMin_cardinality() + "," + sameRule .getMax_cardinality()); } else if ("packetThroughput" .equals(sameRule.getValue())) { alertLevel.setWarningContent(alertLevel .getMetricId() + "" + df.format(alertCursor) + ",????" + stringAggResultTuple2._2 .getS_packetThroughput() + ",????" + stringAggResultTuple2._2 .getC_packetThroughput() + "." + sameRule.getMin_cardinality() + "," + sameRule .getMax_cardinality()); } else if (percent .contains(sameRule.getValue())) { alertLevel.setWarningContent(alertLevel .getMetricId() + "" + df.format(alertCursor) + "%25," + sameRule.getMin_cardinality() + "," + sameRule .getMax_cardinality()); } else { alertLevel.setWarningContent(alertLevel .getMetricId() + "" + df.format(alertCursor) + "," + sameRule.getMin_cardinality() + "," + sameRule .getMax_cardinality()); } alertLevel .setRuleId(sameRule.getRuleName()); alertLevel.setUniqueMark( sameRule.getRuleName() + "-" + stringAggResultTuple2._1 + "-" + sameRule.getValue()); if (stats.containsKey( alertLevel.getUniqueMark())) { String preLevel = stats.get( alertLevel.getUniqueMark())._1; int num = stats.get( alertLevel.getUniqueMark())._2; boolean preWarning = preLevel .equals("levelWarn") || preLevel.equals("levelBad"); boolean newWarning = alertLevel .getWarningLevel() .equals("levelWarn") || alertLevel.getWarningLevel() .equals("levelBad"); if (preWarning && !newWarning) { num = 1 - num; stats.put( alertLevel.getUniqueMark(), new Tuple2<String, Integer>( alertLevel .getWarningLevel(), num)); } else if (!preWarning && newWarning) { stats.put( alertLevel.getUniqueMark(), new Tuple2<String, Integer>( alertLevel .getWarningLevel(), 0 - recover)); } else if (!preWarning && !preWarning) { num = 1 - num; stats.put( alertLevel.getUniqueMark(), new Tuple2<String, Integer>( alertLevel .getWarningLevel(), num)); } else { num = 0 - num; stats.put( alertLevel.getUniqueMark(), new Tuple2<String, Integer>( alertLevel .getWarningLevel(), num)); } } else { if (alertLevel.getWarningLevel() .equals("levelWarn") || alertLevel.getWarningLevel() .equals("levelBad")) { stats.put( alertLevel.getUniqueMark(), new Tuple2<String, Integer>( alertLevel .getWarningLevel(), 0 - recover)); json = (JSONObject) JSON .toJSON(alertLevel); return new Tuple2<>( stringAggResultTuple2._1, json.toString()); } } return new Tuple2<>( stringAggResultTuple2._1, ""); } }) .filter(new Function<Tuple2<String, String>, Boolean>() { private static final long serialVersionUID = 662946729452638751L; @Override public Boolean call(Tuple2<String, String> v1) throws Exception { return !v1._2.equals("") && v1._2 != null; } }).map(new Function<Tuple2<String, String>, String>() { @Override public String call(Tuple2<String, String> v1) throws Exception { return v1._2; } }).collect(); } } jsonList.addAll(alertList); alertList.clear(); } } } } flagRules.clear(); } Iterator<Map.Entry<String, Tuple2<String, Integer>>> iterator = stats.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Tuple2<String, Integer>> entry = iterator.next(); int num = entry.getValue()._2; if (num == 0) { UrlPostMethod.urlPostMethod(RECOVER, entry.getValue()._1); iterator.remove(); } else if (num < 0) { num = 0 - num; entry.setValue(new Tuple2<String, Integer>(entry.getValue()._1, num)); } else { num = 1 - num; if (num == 0) { UrlPostMethod.urlPostMethod(RECOVER, entry.getValue()._1); iterator.remove(); } else { entry.setValue(new Tuple2<String, Integer>(entry.getValue()._1, num)); } } } if (stats.size() > 200000) { stats.clear(); } if (jsonList.size() > 0) { if (Boolean.parseBoolean(getConfig("alert.cnf").getProperty("save.es"))) { System.out.println( "-------------------" + jsonList.toString() + "-----------------------"); } for (int i = 0; i <= jsonList.size() / 2000; i++) { UrlPostMethod.urlPostMethod(URL, "warnings=" + Arrays.asList(Arrays.copyOfRange( jsonList.toArray(), i * 2000, (i + 1) * 2000 - 1 > jsonList.size() ? jsonList.size() : (i + 1) * 2000 - 1)) .toString()); } jsonList.clear(); } } return null; } }); rawStream.context().start(); rawStream.context().awaitTermination(); }
From source file:com.moviejukebox.MovieJukebox.java
public static void main(String[] args) throws Throwable { JukeboxStatistics.setTimeStart(System.currentTimeMillis()); // Create the log file name here, so we can change it later (because it's locked System.setProperty("file.name", LOG_FILENAME); PropertyConfigurator.configure("properties/log4j.properties"); LOG.info("Yet Another Movie Jukebox {}", GitRepositoryState.getVersion()); LOG.info("~~~ ~~~~~~~ ~~~~~ ~~~~~~~ {}", StringUtils.repeat("~", GitRepositoryState.getVersion().length())); LOG.info("https://github.com/YAMJ/yamj-v2"); LOG.info("Copyright (c) 2004-2016 YAMJ Members"); LOG.info(""); LOG.info("This software is licensed under the GNU General Public License v3+"); LOG.info("See this page: https://github.com/YAMJ/yamj-v2/wiki/License"); LOG.info(""); LOG.info(" Revision SHA: {} {}", GIT.getCommitId(), GIT.getDirty() ? "(Custom Build)" : ""); LOG.info(" Commit Date: {}", GIT.getCommitTime()); LOG.info(" Build Date: {}", GIT.getBuildTime()); LOG.info(""); LOG.info(" Java Version: {}", GitRepositoryState.getJavaVersion()); LOG.info(""); if (!SystemTools.validateInstallation()) { LOG.info("ABORTING."); return;/*from w w w . j a v a 2 s .c o m*/ } String movieLibraryRoot = null; String jukeboxRoot = null; Map<String, String> cmdLineProps = new LinkedHashMap<>(); try { for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-v".equalsIgnoreCase(arg)) { // We've printed the version, so quit now return; } else if ("-t".equalsIgnoreCase(arg)) { String pin = args[++i]; // load the apikeys.properties file if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) { return; } // authorize to Trakt.TV TraktTV.getInstance().initialize().authorizeWithPin(pin); // We've authorized access to Trakt.TV, so quit now return; } else if ("-o".equalsIgnoreCase(arg)) { jukeboxRoot = args[++i]; PropertiesUtil.setProperty("mjb.jukeboxRoot", jukeboxRoot); } else if ("-c".equalsIgnoreCase(arg)) { jukeboxClean = Boolean.TRUE; PropertiesUtil.setProperty("mjb.jukeboxClean", TRUE); } else if ("-k".equalsIgnoreCase(arg)) { setJukeboxPreserve(Boolean.TRUE); } else if ("-p".equalsIgnoreCase(arg)) { userPropertiesName = args[++i]; } else if ("-i".equalsIgnoreCase(arg)) { skipIndexGeneration = Boolean.TRUE; PropertiesUtil.setProperty("mjb.skipIndexGeneration", TRUE); } else if ("-h".equalsIgnoreCase(arg)) { skipHtmlGeneration = Boolean.TRUE; PropertiesUtil.setProperty("mjb.skipHtmlGeneration", Boolean.TRUE); } else if ("-dump".equalsIgnoreCase(arg)) { dumpLibraryStructure = Boolean.TRUE; } else if ("-memory".equalsIgnoreCase(arg)) { showMemory = Boolean.TRUE; PropertiesUtil.setProperty("mjb.showMemory", Boolean.TRUE); } else if (arg.startsWith("-D")) { String propLine = arg.length() > 2 ? arg.substring(2) : args[++i]; int propDiv = propLine.indexOf('='); if (-1 != propDiv) { cmdLineProps.put(propLine.substring(0, propDiv), propLine.substring(propDiv + 1)); } } else if (arg.startsWith("-")) { help(); return; } else { movieLibraryRoot = args[i]; } } } catch (Exception error) { LOG.error("Wrong arguments specified"); help(); return; } // Save the name of the properties file for use later setProperty("userPropertiesName", userPropertiesName); LOG.info("Processing started at {}", new Date()); LOG.info(""); // Load the moviejukebox-default.properties file if (!setPropertiesStreamName("./properties/moviejukebox-default.properties", Boolean.TRUE)) { return; } // Load the user properties file "moviejukebox.properties" // No need to abort if we don't find this file // Must be read before the skin, because this may contain an override skin setPropertiesStreamName(userPropertiesName, Boolean.FALSE); // Grab the skin from the command-line properties if (cmdLineProps.containsKey(SKIN_DIR)) { setProperty(SKIN_DIR, cmdLineProps.get(SKIN_DIR)); } // Load the skin.properties file if (!setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin.properties", Boolean.TRUE)) { return; } // Load the skin-user.properties file (ignore the error) setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin-user.properties", Boolean.FALSE); // Load the overlay.properties file (ignore the error) String overlayRoot = getProperty("mjb.overlay.dir", Movie.UNKNOWN); overlayRoot = (PropertiesUtil.getBooleanProperty("mjb.overlay.skinroot", Boolean.TRUE) ? (getProperty(SKIN_DIR, SKIN_DEFAULT) + File.separator) : "") + (StringTools.isValidString(overlayRoot) ? (overlayRoot + File.separator) : ""); setPropertiesStreamName(overlayRoot + "overlay.properties", Boolean.FALSE); // Load the apikeys.properties file if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) { return; } // This is needed to update the static reference for the API Keys in the pattern formatter // because the formatter is initialised before the properties files are read FilteringLayout.addApiKeys(); // Load the rest of the command-line properties for (Map.Entry<String, String> propEntry : cmdLineProps.entrySet()) { setProperty(propEntry.getKey(), propEntry.getValue()); } // Read the information about the skin SkinProperties.readSkinVersion(); // Display the information about the skin SkinProperties.printSkinVersion(); StringBuilder properties = new StringBuilder("{"); for (Map.Entry<Object, Object> propEntry : PropertiesUtil.getEntrySet()) { properties.append(propEntry.getKey()); properties.append("="); properties.append(propEntry.getValue()); properties.append(","); } properties.replace(properties.length() - 1, properties.length(), "}"); // Print out the properties to the log file. LOG.debug("Properties: {}", properties.toString()); // Check for mjb.skipIndexGeneration and set as necessary // This duplicates the "-i" functionality, but allows you to have it in the property file skipIndexGeneration = PropertiesUtil.getBooleanProperty("mjb.skipIndexGeneration", Boolean.FALSE); if (PropertiesUtil.getBooleanProperty("mjb.people", Boolean.FALSE)) { peopleScan = Boolean.TRUE; peopleScrape = PropertiesUtil.getBooleanProperty("mjb.people.scrape", Boolean.TRUE); peopleMax = PropertiesUtil.getIntProperty("mjb.people.maxCount", 10); popularity = PropertiesUtil.getIntProperty("mjb.people.popularity", 5); // Issue 1947: Cast enhancement - option to save all related files to a specific folder peopleFolder = PropertiesUtil.getProperty("mjb.people.folder", ""); if (isNotValidString(peopleFolder)) { peopleFolder = ""; } else if (!peopleFolder.endsWith(File.separator)) { peopleFolder += File.separator; } StringTokenizer st = new StringTokenizer( PropertiesUtil.getProperty("photo.scanner.photoExtensions", "jpg,jpeg,gif,bmp,png"), ",;| "); while (st.hasMoreTokens()) { PHOTO_EXTENSIONS.add(st.nextToken()); } } // Check for mjb.skipHtmlGeneration and set as necessary // This duplicates the "-h" functionality, but allows you to have it in the property file skipHtmlGeneration = PropertiesUtil.getBooleanProperty("mjb.skipHtmlGeneration", Boolean.FALSE); // Look for the parameter in the properties file if it's not been set on the command line // This way we don't overwrite the setting if it's not found and defaults to FALSE showMemory = PropertiesUtil.getBooleanProperty("mjb.showMemory", Boolean.FALSE); // This duplicates the "-c" functionality, but allows you to have it in the property file jukeboxClean = PropertiesUtil.getBooleanProperty("mjb.jukeboxClean", Boolean.FALSE); MovieFilenameScanner.setSkipKeywords( tokenizeToArray(getProperty("filename.scanner.skip.keywords", ""), ",;| "), PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive", Boolean.TRUE)); MovieFilenameScanner.setSkipRegexKeywords( tokenizeToArray(getProperty("filename.scanner.skip.keywords.regex", ""), ","), PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive.regex", Boolean.TRUE)); MovieFilenameScanner.setExtrasKeywords( tokenizeToArray(getProperty("filename.extras.keywords", "trailer,extra,bonus"), ",;| ")); MovieFilenameScanner.setMovieVersionKeywords(tokenizeToArray( getProperty("filename.movie.versions.keywords", "remastered,directors cut,extended cut,final cut"), ",;|")); MovieFilenameScanner.setLanguageDetection( PropertiesUtil.getBooleanProperty("filename.scanner.language.detection", Boolean.TRUE)); final KeywordMap languages = PropertiesUtil.getKeywordMap("filename.scanner.language.keywords", null); if (!languages.isEmpty()) { MovieFilenameScanner.clearLanguages(); for (String lang : languages.getKeywords()) { String values = languages.get(lang); if (values != null) { MovieFilenameScanner.addLanguage(lang, values, values); } else { LOG.info("No values found for language code '{}'", lang); } } } final KeywordMap sourceKeywords = PropertiesUtil.getKeywordMap("filename.scanner.source.keywords", "HDTV,PDTV,DVDRip,DVDSCR,DSRip,CAM,R5,LINE,HD2DVD,DVD,DVD5,DVD9,HRHDTV,MVCD,VCD,TS,VHSRip,BluRay,HDDVD,D-THEATER,SDTV"); MovieFilenameScanner.setSourceKeywords(sourceKeywords.getKeywords(), sourceKeywords); String temp = getProperty("sorting.strip.prefixes"); if (temp != null) { StringTokenizer st = new StringTokenizer(temp, ","); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.startsWith("\"") && token.endsWith("\"")) { token = token.substring(1, token.length() - 1); } Movie.addSortIgnorePrefixes(token.toLowerCase()); } } enableWatchScanner = PropertiesUtil.getBooleanProperty("watched.scanner.enable", Boolean.TRUE); enableWatchTraktTv = PropertiesUtil.getBooleanProperty("watched.trakttv.enable", Boolean.FALSE); enableCompleteMovies = PropertiesUtil.getBooleanProperty("complete.movies.enable", Boolean.TRUE); // Check to see if don't have a root, check the property file if (StringTools.isNotValidString(movieLibraryRoot)) { movieLibraryRoot = getProperty("mjb.libraryRoot"); if (StringTools.isValidString(movieLibraryRoot)) { LOG.info("Got libraryRoot from properties file: {}", movieLibraryRoot); } else { LOG.error("No library root found!"); help(); return; } } if (jukeboxRoot == null) { jukeboxRoot = getProperty("mjb.jukeboxRoot"); if (jukeboxRoot == null) { LOG.info("jukeboxRoot is null in properties file. Please fix this as it may cause errors."); } else { LOG.info("Got jukeboxRoot from properties file: {}", jukeboxRoot); } } File f = new File(movieLibraryRoot); if (f.exists() && f.isDirectory() && jukeboxRoot == null) { jukeboxRoot = movieLibraryRoot; } if (movieLibraryRoot == null) { help(); return; } if (jukeboxRoot == null) { LOG.info("Wrong arguments specified: you must define the jukeboxRoot property (-o) !"); help(); return; } if (!f.exists()) { LOG.error("Directory or library configuration file '{}', not found.", movieLibraryRoot); return; } FileTools.initUnsafeChars(); FileTools.initSubtitleExtensions(); // make canonical names jukeboxRoot = FileTools.getCanonicalPath(jukeboxRoot); movieLibraryRoot = FileTools.getCanonicalPath(movieLibraryRoot); MovieJukebox ml = new MovieJukebox(movieLibraryRoot, jukeboxRoot); if (dumpLibraryStructure) { LOG.warn( "WARNING !!! A dump of your library directory structure will be generated for debug purpose. !!! Library won't be built or updated"); ml.makeDumpStructure(); } else { ml.generateLibrary(); } // Now rename the log files renameLogFile(); if (ScanningLimit.isLimitReached()) { LOG.warn("Scanning limit of {} was reached, please re-run to complete processing.", ScanningLimit.getLimit()); System.exit(EXIT_SCAN_LIMIT); } else { System.exit(EXIT_NORMAL); } }
From source file:edu.msu.cme.rdp.alignment.errorcheck.CompareErrorType.java
public static void main(String[] args) throws IOException { Options options = new Options(); options.addOption("s", "stem", true, "Output stem (default <query_nucl.fasta>)"); final SeqReader queryReader; final List<Sequence> refSeqList; final PrintStream alignOutStream; final CompareErrorType errorProcessor; Sequence seq;// w ww.jav a2s. co m Map<String, PAObject> matchMap = new HashMap(); try { CommandLine line = new PosixParser().parse(options, args); String stem; args = line.getArgs(); if (args.length != 2 && args.length != 3) { throw new Exception("Unexpected number of arguments"); } File refFile = new File(args[0]); File queryFile = new File(args[1]); if (line.hasOption("stem")) { stem = line.getOptionValue("stem"); } else { stem = queryFile.getName(); } File alignOutFile = new File(stem + "_alignments.txt"); File mismatchOutFile = new File(stem + "_mismatches.txt"); File indelOutFile = new File(stem + "_indels.txt"); File qualOutFile = null; refSeqList = SequenceReader.readFully(refFile); if (args.length == 3) { queryReader = new QSeqReader(queryFile, new File(args[2])); } else { queryReader = new SequenceReader(queryFile); } seq = queryReader.readNextSequence(); if (seq instanceof QSequence) { qualOutFile = new File(stem + "_qual.txt"); } errorProcessor = new CompareErrorType(mismatchOutFile, indelOutFile, qualOutFile); alignOutStream = new PrintStream(alignOutFile); System.err.println("Starting CompareErrorType"); System.err.println("* Time: " + new Date()); System.err.println("* Reference File: " + refFile); System.err.println("* Query File: " + queryFile); if (args.length == 3) { System.err.println("* Qual File: " + args[2]); } System.err.println("* Query format: " + queryReader.getFormat()); System.err.println("* Alignment Output: " + alignOutFile); System.err.println("* Mismatches Output: " + mismatchOutFile); System.err.println("* Alignment Output: " + indelOutFile); if (qualOutFile != null) { System.err.println("* Quality Output: " + qualOutFile); } } catch (Exception e) { new HelpFormatter().printHelp( "CompareErrorType [options] <ref_nucl> (<query_nucl> | <query_nucl.fasta> <query_nucl.qual>)", options); System.err.println("ERROR: " + e.getMessage()); throw new RuntimeException(e); //System.exit(1); //return; } //ScoringMatrix scoringMatrix = ScoringMatrix.getDefaultNuclMatrix(); // use a simple scoring function, match score 0, mismatch -1, gap opening -1, gap extension -1. ScoringMatrix scoringMatrix = new ScoringMatrix( ScoringMatrix.class.getResourceAsStream("/data/simple_scoringmatrix.txt"), -1, -1); do { try { PairwiseAlignment bestResult = null; Sequence bestSeq = null; boolean bestReversed = false; String querySeqStr = seq.getSeqString().toLowerCase(); String reversedQuery = IUBUtilities.reverseComplement(querySeqStr); PAObject bestMatch = null; //checking if sequence has been seen before if (matchMap.containsKey(seq.getSeqString())) { bestMatch = matchMap.get(seq.getSeqString()); } else { for (Sequence refSeq : refSeqList) { String refSeqStr = refSeq.getSeqString().toLowerCase(); PairwiseAlignment result = PairwiseAligner.align(refSeqStr, querySeqStr, scoringMatrix, AlignmentMode.global); PairwiseAlignment reversedResult = PairwiseAligner.align(refSeqStr, IUBUtilities.reverseComplement(querySeqStr), scoringMatrix, AlignmentMode.global); PairwiseAlignment currBest = (result.getScore() > reversedResult.getScore()) ? result : reversedResult; if (bestResult == null || currBest.getScore() > bestResult.getScore()) { bestResult = currBest; bestSeq = refSeq; if (currBest == reversedResult) { bestReversed = true; } else { bestReversed = false; } } //Since this is a new sequence, make a new PAObject to put into the map to compare against later bestMatch = new PAObject(bestResult, bestReversed, bestSeq); matchMap.put(seq.getSeqString(), bestMatch); } } int refStart = bestMatch.getPA().getStarti(); int refEnd = bestMatch.getPA().getEndi(); bestSeq = bestMatch.getRefSeq(); bestReversed = bestMatch.getReversed(); bestResult = bestMatch.getPA(); //output information alignOutStream.println(">\t" + seq.getSeqName() + "\t" + bestSeq.getSeqName() + "\t" + seq.getSeqString().length() + "\t" + refStart + "\t" + refEnd + "\t" + bestResult.getScore() + "\t" + ((bestReversed) ? "\treversed" : "")); alignOutStream.println(bestResult.getAlignedSeqj() + "\n"); alignOutStream.println(bestResult.getAlignedSeqi() + "\n"); //seqi is reference seq, seqj is the refseq errorProcessor.processSequence(seq, bestResult.getAlignedSeqj(), bestSeq.getSeqName(), bestResult.getAlignedSeqi(), refStart, bestReversed); } catch (Exception e) { throw new RuntimeException("Failed while processing seq " + seq.getSeqName(), e); } } while ((seq = queryReader.readNextSequence()) != null); queryReader.close(); alignOutStream.close(); errorProcessor.close(); }
From source file:com.github.wshackle.java4cpp.J4CppMain.java
public static void main(String[] args) throws IOException, ClassNotFoundException { main_completed = false;/* w w w .j a va 2 s.c om*/ Options options = new Options(); options.addOption(Option.builder("?").desc("Print this message").longOpt("help").build()); options.addOption(Option.builder("n").hasArg().desc("C++ namespace for newly generated classes.") .longOpt("namespace").build()); options.addOption( Option.builder("c").hasArgs().desc("Single Java class to extract.").longOpt("classes").build()); options.addOption( Option.builder("p").hasArgs().desc("Java Package prefix to extract").longOpt("packages").build()); options.addOption(Option.builder("o").hasArg().desc("Output C++ source file.").longOpt("output").build()); options.addOption(Option.builder("j").hasArg().desc("Input jar file").longOpt("jar").build()); options.addOption(Option.builder("h").hasArg().desc("Output C++ header file.").longOpt("header").build()); options.addOption(Option.builder("l").hasArg() .desc("Maximum limit on classes to extract from jars.[default=200]").longOpt("limit").build()); options.addOption(Option.builder("v").desc("enable verbose output").longOpt("verbose").build()); options.addOption(Option.builder().hasArg().desc("Classes per output file.[default=10]") .longOpt(CLASSESPEROUTPUT).build()); options.addOption(Option.builder().hasArgs().desc( "Comma seperated list of nativeclass=javaclass native where nativeclass will be generated as an extension/implementation of the java class.") .longOpt("natives").build()); options.addOption(Option.builder().hasArg() .desc("library name for System.loadLibrary(...) for native extension classes") .longOpt("loadlibname").build()); String output = null; String header = null; String jar = null; Set<String> classnamesToFind = null; Set<String> packageprefixes = null; String loadlibname = null; Map<String, String> nativesNameMap = null; Map<String, Class> nativesClassMap = null; int limit = DEFAULT_LIMIT; int classes_per_file = 10; List<Class> classes = new ArrayList<>(); String limitstring = Integer.toString(limit); try { // parse the command line arguments System.out.println("args = " + Arrays.toString(args)); CommandLine line = new DefaultParser().parse(options, args); loadlibname = line.getOptionValue("loadlibname"); verbose = line.hasOption("verbose"); if (line.hasOption(CLASSESPEROUTPUT)) { String cpoStr = line.getOptionValue(CLASSESPEROUTPUT); try { int cpoI = Integer.valueOf(cpoStr); classes_per_file = cpoI; } catch (Exception e) { System.err.println("Option for " + CLASSESPEROUTPUT + "=\"" + cpoStr + "\""); printHelpAndExit(options, args); } } if (line.hasOption("natives")) { String natives[] = line.getOptionValues("natives"); if (verbose) { System.out.println("natives = " + Arrays.toString(natives)); } nativesNameMap = new HashMap<>(); nativesClassMap = new HashMap<>(); for (int i = 0; i < natives.length; i++) { int eq_index = natives[i].indexOf('='); String nativeClassName = natives[i].substring(0, eq_index).trim(); String javaClassName = natives[i].substring(eq_index + 1).trim(); Class javaClass = null; try { javaClass = Class.forName(javaClassName); } catch (ClassNotFoundException e) { //e.printStackTrace(); System.err.println("Class for " + javaClassName + " not found. (It may be found later in jar if specified.)"); } nativesNameMap.put(javaClassName, nativeClassName); if (javaClass != null) { nativesClassMap.put(nativeClassName, javaClass); if (!classes.contains(javaClass)) { classes.add(javaClass); } } } } // // validate that block-size has been set // if (line.hasOption("block-size")) { // // print the value of block-size // if(verbose) System.out.println(line.getOptionValue("block-size")); // } jar = line.getOptionValue("jar", jar); if (verbose) { System.out.println("jar = " + jar); } if (null != jar) { if (jar.startsWith("~/")) { jar = new File(new File(getHomeDir()), jar.substring(2)).getCanonicalPath(); } if (jar.startsWith("./")) { jar = new File(new File(getCurrentDir()), jar.substring(2)).getCanonicalPath(); } if (jar.startsWith("../")) { jar = new File(new File(getCurrentDir()).getParentFile(), jar.substring(3)).getCanonicalPath(); } } if (line.hasOption("classes")) { classnamesToFind = new HashSet<String>(); String classStrings[] = line.getOptionValues("classes"); if (verbose) { System.out.println("classStrings = " + Arrays.toString(classStrings)); } classnamesToFind.addAll(Arrays.asList(classStrings)); if (verbose) { System.out.println("classnamesToFind = " + classnamesToFind); } } // if (!line.hasOption("namespace")) { // if (classname != null && classname.length() > 0) { // namespace = classname.toLowerCase().replace(".", "_"); // } else if (jar != null && jar.length() > 0) { // int lastSep = jar.lastIndexOf(File.separator); // int start = Math.max(0, lastSep + 1); // int period = jar.indexOf('.', start + 1); // int end = Math.max(start + 1, period); // namespace = jar.substring(start, end).toLowerCase(); // namespace = namespace.replace(" ", "_"); // if (namespace.indexOf("-") > 0) { // namespace = namespace.substring(0, namespace.indexOf("-")); // } // } // } namespace = line.getOptionValue("namespace", namespace); if (verbose) { System.out.println("namespace = " + namespace); } if (null != namespace) { output = namespace + ".cpp"; } output = line.getOptionValue("output", output); if (verbose) { System.out.println("output = " + output); } if (null != output) { if (output.startsWith("~/")) { output = System.getProperty("user.home") + output.substring(1); } header = output.substring(0, output.lastIndexOf('.')) + ".h"; } else { output = "out.cpp"; } header = line.getOptionValue("header", header); if (verbose) { System.out.println("header = " + header); } if (null != header) { if (header.startsWith("~/")) { header = System.getProperty("user.home") + header.substring(1); } } else { header = "out.h"; } if (line.hasOption("packages")) { packageprefixes = new HashSet<String>(); packageprefixes.addAll(Arrays.asList(line.getOptionValues("packages"))); } if (line.hasOption("limit")) { limitstring = line.getOptionValue("limit", Integer.toString(DEFAULT_LIMIT)); limit = Integer.valueOf(limitstring); } if (line.hasOption("help")) { printHelpAndExit(options, args); } } catch (ParseException exp) { if (verbose) { System.out.println("Unexpected exception:" + exp.getMessage()); } printHelpAndExit(options, args); } Set<Class> excludedClasses = new HashSet<>(); Set<String> foundClassNames = new HashSet<>(); excludedClasses.add(Object.class); excludedClasses.add(String.class); excludedClasses.add(void.class); excludedClasses.add(Void.class); excludedClasses.add(Class.class); excludedClasses.add(Enum.class); Set<String> packagesSet = new TreeSet<>(); List<URL> urlsList = new ArrayList<>(); String cp = System.getProperty("java.class.path"); if (verbose) { System.out.println("System.getProperty(\"java.class.path\") = " + cp); } if (null != cp) { for (String cpe : cp.split(File.pathSeparator)) { if (verbose) { System.out.println("class path element = " + cpe); } File f = new File(cpe); if (f.isDirectory()) { urlsList.add(new URL("file:" + f.getCanonicalPath() + File.separator)); } else if (cpe.endsWith(".jar")) { urlsList.add(new URL("jar:file:" + f.getCanonicalPath() + "!/")); } } } cp = System.getenv("CLASSPATH"); if (verbose) { System.out.println("System.getenv(\"CLASSPATH\") = " + cp); } if (null != cp) { for (String cpe : cp.split(File.pathSeparator)) { if (verbose) { System.out.println("class path element = " + cpe); } File f = new File(cpe); if (f.isDirectory()) { urlsList.add(new URL("file:" + f.getCanonicalPath() + File.separator)); } else if (cpe.endsWith(".jar")) { urlsList.add(new URL("jar:file:" + f.getCanonicalPath() + "!/")); } } } if (verbose) { System.out.println("urlsList = " + urlsList); } if (null != jar && jar.length() > 0) { Path jarPath = FileSystems.getDefault().getPath(jar); ZipInputStream zip = new ZipInputStream(Files.newInputStream(jarPath, StandardOpenOption.READ)); URL jarUrl = new URL("jar:file:" + jarPath.toFile().getCanonicalPath() + "!/"); urlsList.add(jarUrl); URL[] urls = urlsList.toArray(new URL[urlsList.size()]); if (verbose) { System.out.println("urls = " + Arrays.toString(urls)); } URLClassLoader cl = URLClassLoader.newInstance(urls); for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { // This ZipEntry represents a class. Now, what class does it represent? String entryName = entry.getName(); if (verbose) { System.out.println("entryName = " + entryName); } if (!entry.isDirectory() && entryName.endsWith(".class")) { if (entryName.indexOf('$') >= 0) { continue; } String classFileName = entry.getName().replace('/', '.'); String className = classFileName.substring(0, classFileName.length() - ".class".length()); if (classnamesToFind != null && classnamesToFind.size() > 0 && !classnamesToFind.contains(className)) { if (verbose) { System.out.println("skipping className=" + className + " because it does not found in=" + classnamesToFind); } continue; } try { Class clss = cl.loadClass(className); if (null != nativesClassMap && null != nativesNameMap && nativesNameMap.containsKey(className)) { nativesClassMap.put(nativesNameMap.get(className), clss); if (!classes.contains(clss)) { classes.add(clss); } } if (packageprefixes != null && packageprefixes.size() > 0) { if (null == clss.getPackage()) { continue; } final String pkgName = clss.getPackage().getName(); boolean matchFound = false; for (String prefix : packageprefixes) { if (pkgName.startsWith(prefix)) { matchFound = true; break; } } if (!matchFound) { continue; } } Package p = clss.getPackage(); if (null != p) { packagesSet.add(clss.getPackage().getName()); } if (!classes.contains(clss) && isAddableClass(clss, excludedClasses)) { if (null != classnamesToFind && classnamesToFind.contains(className) && !foundClassNames.contains(className)) { foundClassNames.add(className); if (verbose) { System.out.println("foundClassNames = " + foundClassNames); } } // if(verbose) System.out.println("clss = " + clss); classes.add(clss); // Class superClass = clss.getSuperclass(); // while (null != superClass // && !classes.contains(superClass) // && isAddableClass(superClass, excludedClasses)) { // classes.add(superClass); // superClass = superClass.getSuperclass(); // } } } catch (ClassNotFoundException | NoClassDefFoundError ex) { System.err.println( "Caught " + ex.getClass().getName() + ":" + ex.getMessage() + " for className=" + className + ", entryName=" + entryName + ", jarPath=" + jarPath); } } } } if (null != classnamesToFind) { if (verbose) { System.out.println("Checking classnames arguments"); } for (String classname : classnamesToFind) { if (verbose) { System.out.println("classname = " + classname); } if (foundClassNames.contains(classname)) { if (verbose) { System.out.println("foundClassNames.contains(" + classname + ")"); } continue; } try { if (classes.contains(Class.forName(classname))) { if (verbose) { System.out.println("Classes list already contains: " + classname); } continue; } } catch (Exception e) { } if (null != classname && classname.length() > 0) { urlsList.add(new URL("file://" + System.getProperty("user.dir") + "/")); URL[] urls = urlsList.toArray(new URL[urlsList.size()]); if (verbose) { System.out.println("urls = " + Arrays.toString(urls)); } URLClassLoader cl = URLClassLoader.newInstance(urls); Class c = null; try { c = cl.loadClass(classname); } catch (ClassNotFoundException e) { System.err.println("Class " + classname + " not found "); } if (verbose) { System.out.println("c = " + c); } if (null == c) { try { c = ClassLoader.getSystemClassLoader().loadClass(classname); } catch (ClassNotFoundException e) { if (verbose) { System.out.println("System ClassLoader failed to find " + classname); } } } if (null != c) { classes.add(c); } else { System.err.println("Class " + classname + " not found"); } } } if (verbose) { System.out.println("Finished checking classnames arguments"); } } if (classes == null || classes.size() < 1) { if (null == nativesClassMap || nativesClassMap.keySet().size() < 1) { System.err.println("No Classes specified or found."); System.exit(1); } } if (verbose) { System.out.println("Classes found = " + classes.size()); } if (classes.size() > limit) { System.err.println("limit=" + limit); System.err.println( "Too many classes please use -c or -p options to limit classes or -l to increase limit."); if (verbose) { System.out.println("packagesSet = " + packagesSet); } System.exit(1); } List<Class> newClasses = new ArrayList<Class>(); for (Class clss : classes) { Class superClass = clss.getSuperclass(); while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass) && isAddableClass(superClass, excludedClasses)) { newClasses.add(superClass); superClass = superClass.getSuperclass(); } try { Field fa[] = clss.getDeclaredFields(); for (Field f : fa) { if (Modifier.isPublic(f.getModifiers())) { Class fClass = f.getType(); if (!classes.contains(fClass) && !newClasses.contains(fClass) && isAddableClass(fClass, excludedClasses)) { newClasses.add(fClass); } } } } catch (NoClassDefFoundError e) { e.printStackTrace(); } for (Method m : clss.getDeclaredMethods()) { if (m.isSynthetic()) { continue; } if (!Modifier.isPublic(m.getModifiers()) || Modifier.isAbstract(m.getModifiers())) { continue; } Class retType = m.getReturnType(); if (verbose) { System.out.println("Checking dependancies for Method = " + m); } if (!classes.contains(retType) && !newClasses.contains(retType) && isAddableClass(retType, excludedClasses)) { newClasses.add(retType); superClass = retType.getSuperclass(); while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass) && isAddableClass(superClass, excludedClasses)) { newClasses.add(superClass); superClass = superClass.getSuperclass(); } } for (Class paramType : m.getParameterTypes()) { if (!classes.contains(paramType) && !newClasses.contains(paramType) && isAddableClass(paramType, excludedClasses)) { newClasses.add(paramType); superClass = paramType.getSuperclass(); while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass) && !excludedClasses.contains(superClass)) { newClasses.add(superClass); superClass = superClass.getSuperclass(); } } } } } if (null != nativesClassMap) { for (Class clss : nativesClassMap.values()) { if (null != clss) { Class superClass = clss.getSuperclass(); while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass) && !excludedClasses.contains(superClass)) { newClasses.add(superClass); superClass = superClass.getSuperclass(); } } } } if (verbose) { System.out.println("Dependency classes needed = " + newClasses.size()); } classes.addAll(newClasses); List<Class> newOrderClasses = new ArrayList<>(); for (Class clss : classes) { if (newOrderClasses.contains(clss)) { continue; } Class superClass = clss.getSuperclass(); Stack<Class> stack = new Stack<>(); while (null != superClass && !newOrderClasses.contains(superClass) && !superClass.equals(java.lang.Object.class)) { stack.push(superClass); superClass = superClass.getSuperclass(); } while (!stack.empty()) { newOrderClasses.add(stack.pop()); } newOrderClasses.add(clss); } classes = newOrderClasses; if (verbose) { System.out.println("Total number of classes = " + classes.size()); System.out.println("classes = " + classes); } String forward_header = header.substring(0, header.lastIndexOf('.')) + "_fwd.h"; Map<String, String> map = new HashMap<>(); map.put(JAR, jar != null ? jar : ""); map.put("%CLASSPATH_PREFIX%", getCurrentDir() + ((jar != null) ? (File.pathSeparator + ((new File(jar).getCanonicalPath()).replace("\\", "\\\\"))) : "")); map.put("%FORWARD_HEADER%", forward_header); map.put("%HEADER%", header); map.put("%PATH_SEPERATOR%", File.pathSeparator); String tabs = ""; String headerDefine = forward_header.substring(Math.max(0, forward_header.indexOf(File.separator))) .replace(".", "_"); map.put(HEADER_DEFINE, headerDefine); map.put(NAMESPACE, namespace); if (null != nativesClassMap) { for (Entry<String, Class> e : nativesClassMap.entrySet()) { final Class javaClass = e.getValue(); final String nativeClassName = e.getKey(); try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassName + ".java"))) { if (javaClass.isInterface()) { pw.println("public class " + nativeClassName + " implements " + javaClass.getCanonicalName() + ", AutoCloseable{"); } else { pw.println("public class " + nativeClassName + " extends " + javaClass.getCanonicalName() + " implements AutoCloseable{"); } if (null != loadlibname && loadlibname.length() > 0) { pw.println(TAB_STRING + "static {"); pw.println(TAB_STRING + TAB_STRING + "System.loadLibrary(\"" + loadlibname + "\");"); pw.println(TAB_STRING + "}"); pw.println(); } pw.println(TAB_STRING + "public " + nativeClassName + "() {"); pw.println(TAB_STRING + "}"); pw.println(); pw.println(TAB_STRING + "private long nativeAddress=0;"); pw.println(TAB_STRING + "private boolean nativeDeleteOnClose=false;"); pw.println(); pw.println(TAB_STRING + "protected " + nativeClassName + "(final long nativeAddress) {"); pw.println(TAB_STRING + TAB_STRING + "this.nativeAddress = nativeAddress;"); pw.println(TAB_STRING + "}"); pw.println(TAB_STRING + "private native void nativeDelete();"); pw.println(); pw.println(TAB_STRING + "@Override"); pw.println(TAB_STRING + "public synchronized void close() {"); // pw.println(TAB_STRING + TAB_STRING + "if(nativeAddress != 0 && nativeDeleteOnClose) {"); pw.println(TAB_STRING + TAB_STRING + "nativeDelete();"); // pw.println(TAB_STRING + TAB_STRING + "}"); // pw.println(TAB_STRING + TAB_STRING + "nativeAddress=0;"); // pw.println(TAB_STRING + TAB_STRING + "nativeDeleteOnClose=false;"); pw.println(TAB_STRING + "}"); pw.println(); pw.println(TAB_STRING + "protected void finalizer() {"); pw.println(TAB_STRING + TAB_STRING + "close();"); pw.println(TAB_STRING + "}"); pw.println(); Method ma[] = javaClass.getDeclaredMethods(); for (Method m : ma) { int modifiers = m.getModifiers(); if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) // && !m.isDefault() && !m.isSynthetic()) { pw.println(); pw.println(TAB_STRING + "@Override"); String params = ""; for (int i = 0; i < m.getParameterTypes().length; i++) { params += m.getParameterTypes()[i].getCanonicalName() + " param" + i; if (i < m.getParameterTypes().length - 1) { params += ","; } } pw.println(TAB_STRING + "native public " + m.getReturnType().getCanonicalName() + " " + m.getName() + "(" + params + ");"); // + IntStream.range(0, m.getParameterTypes().length) // .mapToObj(i -> m.getParameterTypes()[i].getCanonicalName() + " param" + i) // .collect(Collectors.joining(",")) + ");"); } } pw.println("}"); } } } try (PrintWriter pw = new PrintWriter(new FileWriter(forward_header))) { tabs = ""; processTemplate(pw, map, "header_fwd_template_start.h", tabs); Class lastClass = null; for (int class_index = 0; class_index < classes.size(); class_index++) { Class clss = classes.get(class_index); String clssOnlyName = getCppClassName(clss); tabs = openClassNamespace(clss, pw, tabs, lastClass); tabs += TAB_STRING; pw.println(tabs + "class " + clssOnlyName + ";"); tabs = tabs.substring(0, tabs.length() - 1); Class nextClass = (class_index < (classes.size() - 1)) ? classes.get(class_index + 1) : null; tabs = closeClassNamespace(clss, pw, tabs, nextClass); lastClass = clss; } processTemplate(pw, map, "header_fwd_template_end.h", tabs); } headerDefine = header.substring(Math.max(0, header.indexOf(File.separator))).replace(".", "_"); map.put(HEADER_DEFINE, headerDefine); map.put(NAMESPACE, namespace); if (classes_per_file < 1) { classes_per_file = classes.size(); } final int num_class_segments = (classes.size() > 1) ? ((classes.size() + classes_per_file - 1) / classes_per_file) : 1; String fmt = "%d"; if (num_class_segments > 10) { fmt = "%02d"; } if (num_class_segments > 100) { fmt = "%03d"; } String header_file_base = header; if (header_file_base.endsWith(".h")) { header_file_base = header_file_base.substring(0, header_file_base.length() - 2); } else if (header_file_base.endsWith(".hh")) { header_file_base = header_file_base.substring(0, header_file_base.length() - 3); } else if (header_file_base.endsWith(".hpp")) { header_file_base = header_file_base.substring(0, header_file_base.length() - 4); } try (PrintWriter pw = new PrintWriter(new FileWriter(header))) { tabs = ""; processTemplate(pw, map, HEADER_TEMPLATE_STARTH, tabs); for (int segment_index = 0; segment_index < num_class_segments; segment_index++) { String header_segment_file = header_file_base + String.format(fmt, segment_index) + ".h"; pw.println("#include \"" + header_segment_file + "\""); } if (null != nativesClassMap) { tabs = TAB_STRING; for (Entry<String, Class> e : nativesClassMap.entrySet()) { final Class javaClass = e.getValue(); final String nativeClassName = e.getKey(); pw.println(); pw.println(tabs + "class " + nativeClassName + "Context;"); pw.println(); map.put(CLASS_NAME, nativeClassName); map.put("%BASE_CLASS_FULL_NAME%", "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::")); map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object"); processTemplate(pw, map, HEADER_CLASS_STARTH, tabs); tabs += TAB_STRING; pw.println(tabs + nativeClassName + "Context *context;"); pw.println(tabs + nativeClassName + "();"); pw.println(tabs + "~" + nativeClassName + "();"); Method methods[] = javaClass.getDeclaredMethods(); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { continue; } if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) // && !method.isDefault() && !method.isSynthetic()) { pw.println(tabs + getNativeMethodCppDeclaration(method, javaClass)); } } pw.println(tabs + "void initContext(" + nativeClassName + "Context *ctx,bool isref);"); pw.println(tabs + "void deleteContext();"); tabs = tabs.substring(TAB_STRING.length()); pw.println(tabs + "}; // end class " + nativeClassName); } } tabs = ""; processTemplate(pw, map, HEADER_TEMPLATE_ENDH, tabs); } for (int segment_index = 0; segment_index < num_class_segments; segment_index++) { String header_segment_file = header_file_base + String.format(fmt, segment_index) + ".h"; try (PrintWriter pw = new PrintWriter(new FileWriter(header_segment_file))) { tabs = ""; //processTemplate(pw, map, HEADER_TEMPLATE_STARTH, tabs); pw.println("// Never include this file (" + header_segment_file + ") directly. include " + header + " instead."); pw.println(); Class lastClass = null; final int start_segment_index = segment_index * classes_per_file; final int end_segment_index = Math.min(segment_index * classes_per_file + classes_per_file, classes.size()); List<Class> classesSegList = classes.subList(start_segment_index, end_segment_index); pw.println(); pw.println(tabs + "// start_segment_index = " + start_segment_index); pw.println(tabs + "// start_segment_index = " + end_segment_index); pw.println(tabs + "// segment_index = " + segment_index); pw.println(tabs + "// classesSegList=" + classesSegList); pw.println(); for (int class_index = 0; class_index < classesSegList.size(); class_index++) { Class clss = classesSegList.get(class_index); pw.println(); pw.println(tabs + "// class_index = " + class_index + " clss=" + clss); pw.println(); String clssName = clss.getCanonicalName(); tabs = openClassNamespace(clss, pw, tabs, lastClass); String clssOnlyName = getCppClassName(clss); map.put(CLASS_NAME, clssOnlyName); map.put("%BASE_CLASS_FULL_NAME%", classToCppBase(clss)); map.put(OBJECT_CLASS_FULL_NAME, getCppRelativeName(Object.class, clss)); tabs += TAB_STRING; processTemplate(pw, map, HEADER_CLASS_STARTH, tabs); tabs += TAB_STRING; Constructor constructors[] = clss.getDeclaredConstructors(); if (!hasNoArgConstructor(constructors)) { if (Modifier.isAbstract(clss.getModifiers()) || clss.isInterface()) { pw.println(tabs + "protected:"); pw.println(tabs + clssOnlyName + "() {};"); pw.println(tabs + "public:"); } else { if (constructors.length > 0) { pw.println(tabs + "protected:"); } pw.println(tabs + clssOnlyName + "();"); if (constructors.length > 0) { pw.println(tabs + "public:"); } } } for (Constructor c : constructors) { if (c.getParameterTypes().length == 0 && Modifier.isProtected(c.getModifiers())) { pw.println(tabs + "protected:"); pw.println(tabs + clssOnlyName + "();"); pw.println(tabs + "public:"); } if (checkConstructor(c, clss, classes)) { continue; } if (c.getParameterTypes().length == 1 && clss.isAssignableFrom(c.getParameterTypes()[0])) { continue; } if (!Modifier.isPublic(c.getModifiers())) { continue; } if (c.getParameterTypes().length == 1) { if (c.getParameterTypes()[0].getName().equals(clss.getName())) { // if(verbose) System.out.println("skipping constructor."); continue; } } if (!checkParameters(c.getParameterTypes(), classes)) { continue; } pw.println( tabs + clssOnlyName + getCppParamDeclarations(c.getParameterTypes(), clss) + ";"); if (isConstructorToMakeEasy(c, clss)) { pw.println(tabs + clssOnlyName + getEasyCallCppParamDeclarations(c.getParameterTypes(), clss) + ";"); } } pw.println(tabs + "~" + clssOnlyName + "();"); Field fa[] = clss.getDeclaredFields(); for (int findex = 0; findex < fa.length; findex++) { Field field = fa[findex]; if (addGetterMethod(field, clss, classes)) { pw.println(tabs + getCppFieldGetterDeclaration(field, clss)); } if (addSetterMethod(field, clss, classes)) { pw.println(tabs + getCppFieldSetterDeclaration(field, clss)); } } Method methods[] = clss.getDeclaredMethods(); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; if (!checkMethod(method, classes)) { continue; } if ((method.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC) { pw.println(tabs + getCppDeclaration(method, clss)); } if (isArrayStringMethod(method)) { pw.println(tabs + getCppModifiers(method.getModifiers()) + getCppType(method.getReturnType(), clss) + " " + fixMethodName(method) + "(int argc,const char **argv);"); } if (isMethodToMakeEasy(method)) { pw.println(tabs + getEasyCallCppDeclaration(method, clss)); } } tabs = tabs.substring(TAB_STRING.length()); pw.println(tabs + "}; // end class " + clssOnlyName); tabs = tabs.substring(0, tabs.length() - 1); Class nextClass = (class_index < (classesSegList.size() - 1)) ? classesSegList.get(class_index + 1) : null; tabs = closeClassNamespace(clss, pw, tabs, nextClass); pw.println(); lastClass = clss; } //processTemplate(pw, map, HEADER_TEMPLATE_ENDH, tabs); } } for (int segment_index = 0; segment_index < num_class_segments; segment_index++) { String output_segment_file = output; if (output_segment_file.endsWith(".cpp")) { output_segment_file = output_segment_file.substring(0, output_segment_file.length() - 4); } else if (output_segment_file.endsWith(".cc")) { output_segment_file = output_segment_file.substring(0, output_segment_file.length() - 3); } output_segment_file += "" + String.format(fmt, segment_index) + ".cpp"; try (PrintWriter pw = new PrintWriter(new FileWriter(output_segment_file))) { tabs = ""; if (segment_index < 1) { processTemplate(pw, map, "cpp_template_start_first.cpp", tabs); } else { processTemplate(pw, map, CPP_TEMPLATE_STARTCPP, tabs); } final int start_segment_index = segment_index * classes_per_file; final int end_segment_index = Math.min(segment_index * classes_per_file + classes_per_file, classes.size()); List<Class> classesSegList = classes.subList(start_segment_index, end_segment_index); pw.println(); pw.println(tabs + "// start_segment_index = " + start_segment_index); pw.println(tabs + "// start_segment_index = " + end_segment_index); pw.println(tabs + "// segment_index = " + segment_index); pw.println(tabs + "// classesSegList=" + classesSegList); pw.println(); Class lastClass = null; for (int class_index = 0; class_index < classesSegList.size(); class_index++) { Class clss = classesSegList.get(class_index); pw.println(); pw.println(tabs + "// class_index = " + class_index + " clss=" + clss); pw.println(); String clssName = clss.getCanonicalName(); tabs = openClassNamespace(clss, pw, tabs, lastClass); String clssOnlyName = getCppClassName(clss); map.put(CLASS_NAME, clssOnlyName); map.put("%BASE_CLASS_FULL_NAME%", classToCppBase(clss)); map.put(FULL_CLASS_NAME, clssName); String fcjs = classToJNISignature(clss); fcjs = fcjs.substring(1, fcjs.length() - 1); map.put(FULL_CLASS_JNI_SIGNATURE, fcjs); if (verbose) { System.out.println("fcjs = " + fcjs); } map.put(OBJECT_CLASS_FULL_NAME, getCppRelativeName(Object.class, clss)); map.put("%INITIALIZE_CONTEXT%", ""); map.put("%INITIALIZE_CONTEXT_REF%", ""); processTemplate(pw, map, CPP_START_CLASSCPP, tabs); Constructor constructors[] = clss.getDeclaredConstructors(); if (!hasNoArgConstructor(constructors)) { if (!Modifier.isAbstract(clss.getModifiers()) && !clss.isInterface()) { pw.println(tabs + clssOnlyName + "::" + clssOnlyName + "() : " + classToCppBase(clss) + "((jobject)NULL,false) {"); map.put(JNI_SIGNATURE, "()V"); map.put(CONSTRUCTOR_ARGS, ""); processTemplate(pw, map, CPP_NEWCPP, tabs); pw.println(tabs + "}"); pw.println(); } } for (Constructor c : constructors) { if (checkConstructor(c, clss, classes)) { continue; } Class[] paramClasses = c.getParameterTypes(); pw.println(tabs + clssOnlyName + "::" + clssOnlyName + getCppParamDeclarations(paramClasses, clss) + " : " + classToCppBase(clss) + "((jobject)NULL,false) {"); tabs = tabs + TAB_STRING; map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(paramClasses) + ")V"); map.put(CONSTRUCTOR_ARGS, (paramClasses.length > 0 ? "," : "") + getCppParamNames(paramClasses)); processTemplate(pw, map, CPP_NEWCPP, tabs); tabs = tabs.substring(0, tabs.length() - 1); pw.println(tabs + "}"); pw.println(); if (isConstructorToMakeEasy(c, clss)) { pw.println(tabs + clssOnlyName + "::" + clssOnlyName + getEasyCallCppParamDeclarations(c.getParameterTypes(), clss) + " : " + classToCppBase(clss) + "((jobject)NULL,false) {"); processTemplate(pw, map, "cpp_start_easy_constructor.cpp", tabs); for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) { Class paramClasse = paramClasses[paramIndex]; String parmName = getParamNameIn(paramClasse, paramIndex); if (isString(paramClasse)) { pw.println(tabs + "jstring " + parmName + " = env->NewStringUTF(easyArg_" + paramIndex + ");"); } else if (isPrimitiveArray(paramClasse)) { String callString = getMethodCallString(paramClasse.getComponentType()); pw.println(tabs + getCppArrayType(paramClasse.getComponentType()) + " " + classToParamNameDecl(paramClasse, paramIndex) + "= env->New" + callString + "Array(easyArg_" + paramIndex + "_length);"); pw.println(tabs + "env->Set" + callString + "ArrayRegion(" + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_" + paramIndex + "_length,easyArg_" + paramIndex + ");"); } else { pw.println(tabs + getCppType(paramClasse, clss) + " " + classToParamNameDecl(paramClasse, paramIndex) + "= easyArg_" + paramIndex + ";"); } } processTemplate(pw, map, "cpp_new_easy_internals.cpp", tabs); for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) { Class paramClasse = paramClasses[paramIndex]; String parmName = getParamNameIn(paramClasse, paramIndex); if (isString(paramClasse)) { pw.println(tabs + "jobjectRefType ref_" + paramIndex + " = env->GetObjectRefType(" + parmName + ");"); pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {"); pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");"); pw.println(tabs + "}"); } else if (isPrimitiveArray(paramClasse)) { String callString = getMethodCallString(paramClasse.getComponentType()); pw.println(tabs + "env->Get" + callString + "ArrayRegion(" + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_" + paramIndex + "_length,easyArg_" + paramIndex + ");"); pw.println(tabs + "jobjectRefType ref_" + paramIndex + " = env->GetObjectRefType(" + parmName + ");"); pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {"); pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");"); pw.println(tabs + "}"); } else { } } processTemplate(pw, map, "cpp_end_easy_constructor.cpp", tabs); pw.println(tabs + "}"); } } pw.println(); pw.println(tabs + "// Destructor for " + clssName); pw.println(tabs + clssOnlyName + "::~" + clssOnlyName + "() {"); pw.println(tabs + "\t// Place-holder for later extensibility."); pw.println(tabs + "}"); pw.println(); Field fa[] = clss.getDeclaredFields(); for (int findex = 0; findex < fa.length; findex++) { Field field = fa[findex]; if (addGetterMethod(field, clss, classes)) { pw.println(); pw.println(tabs + "// Field getter for " + field.getName()); pw.println(getCppFieldGetterDefinitionStart(tabs, clssOnlyName, field, clss)); map.put("%FIELD_NAME%", field.getName()); map.put(JNI_SIGNATURE, classToJNISignature(field.getType())); Class returnClass = field.getType(); map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss)); map.put(METHOD_ARGS, ""); map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return"); map.put("%METHOD_CALL_TYPE%", getMethodCallString(returnClass)); map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss)); map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass)); String retStore = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnVarType(returnClass) + ") "; map.put("%METHOD_RETURN_STORE%", retStore); map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss)); if (Modifier.isStatic(field.getModifiers())) { processTemplate(pw, map, "cpp_static_getfield.cpp", tabs); } else { processTemplate(pw, map, "cpp_getfield.cpp", tabs); } pw.println(tabs + "}"); } if (addSetterMethod(field, clss, classes)) { pw.println(); pw.println(tabs + "// Field setter for " + field.getName()); pw.println(getCppFieldSetterDefinitionStart(tabs, clssOnlyName, field, clss)); map.put("%FIELD_NAME%", field.getName()); map.put(JNI_SIGNATURE, classToJNISignature(field.getType())); Class returnClass = void.class; map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss)); Class[] paramClasses = new Class[] { field.getType() }; String methodArgs = getCppParamNames(paramClasses); map.put(METHOD_ARGS, (paramClasses.length > 0 ? "," : "") + methodArgs); map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return"); map.put("%METHOD_CALL_TYPE%", getMethodCallString(field.getType())); map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss)); map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass)); String retStore = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnVarType(returnClass) + ") "; map.put("%METHOD_RETURN_STORE%", retStore); map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss)); if (Modifier.isStatic(field.getModifiers())) { processTemplate(pw, map, "cpp_static_setfield.cpp", tabs); } else { processTemplate(pw, map, "cpp_setfield.cpp", tabs); } pw.println(tabs + "}"); } } Method methods[] = clss.getDeclaredMethods(); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; if (checkMethod(method, classes)) { pw.println(); pw.println(getCppMethodDefinitionStart(tabs, clssOnlyName, method, clss)); map.put(METHOD_NAME, method.getName()); if (fixMethodName(method).contains("equals2")) { if (verbose) { System.out.println("debug me"); } } map.put("%JAVA_METHOD_NAME%", method.getName()); Class[] paramClasses = method.getParameterTypes(); String methodArgs = getCppParamNames(paramClasses); map.put(METHOD_ARGS, (paramClasses.length > 0 ? "," : "") + methodArgs); Class returnClass = method.getReturnType(); map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(paramClasses) + ")" + classToJNISignature(returnClass)); map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss)); map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return"); map.put("%METHOD_CALL_TYPE%", getMethodCallString(returnClass)); map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss)); map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass)); String retStore = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnVarType(returnClass) + ") "; map.put("%METHOD_RETURN_STORE%", retStore); map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss)); tabs += TAB_STRING; if (!Modifier.isStatic(method.getModifiers())) { processTemplate(pw, map, CPP_METHODCPP, tabs); } else { processTemplate(pw, map, CPP_STATIC_METHODCPP, tabs); } tabs = tabs.substring(0, tabs.length() - TAB_STRING.length()); pw.println(tabs + "}"); if (isArrayStringMethod(method)) { map.put(METHOD_RETURN_STORE, isVoid(returnClass) ? "" : getCppType(returnClass, clss) + " returnVal="); map.put(METHOD_RETURN_GET, isVoid(returnClass) ? "return ;" : "return returnVal;"); processTemplate(pw, map, CPP_EASY_STRING_ARRAY_METHODCPP, tabs); } else if (isMethodToMakeEasy(method)) { pw.println(); pw.println(tabs + "// Easy call alternative for " + method.getName()); pw.println(getEasyCallCppMethodDefinitionStart(tabs, clssOnlyName, method, clss)); tabs += TAB_STRING; map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclareOut(returnClass, clss)); processTemplate(pw, map, "cpp_start_easy_method.cpp", tabs); for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) { Class paramClasse = paramClasses[paramIndex]; String parmName = getParamNameIn(paramClasse, paramIndex); if (isString(paramClasse)) { pw.println(tabs + "jstring " + parmName + " = env->NewStringUTF(easyArg_" + paramIndex + ");"); } else if (isPrimitiveArray(paramClasse)) { String callString = getMethodCallString(paramClasse.getComponentType()); pw.println(tabs + getCppArrayType(paramClasse.getComponentType()) + " " + classToParamNameDecl(paramClasse, paramIndex) + "= env->New" + callString + "Array(easyArg_" + paramIndex + "_length);"); pw.println(tabs + "env->Set" + callString + "ArrayRegion(" + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_" + paramIndex + "_length,easyArg_" + paramIndex + ");"); } else { pw.println(tabs + getCppType(paramClasse, clss) + " " + classToParamNameDecl(paramClasse, paramIndex) + "= easyArg_" + paramIndex + ";"); } } String methodArgsIn = getCppParamNamesIn(paramClasses); String retStoreOut = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnOutVarType(returnClass, clss) + ") "; pw.println(tabs + retStoreOut + fixMethodName(method) + "(" + methodArgsIn + ");"); for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) { Class paramClasse = paramClasses[paramIndex]; String parmName = getParamNameIn(paramClasse, paramIndex); if (isString(paramClasse)) { pw.println(tabs + "jobjectRefType ref_" + paramIndex + " = env->GetObjectRefType(" + parmName + ");"); pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {"); pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");"); pw.println(tabs + "}"); } else if (isPrimitiveArray(paramClasse)) { String callString = getMethodCallString(paramClasse.getComponentType()); pw.println(tabs + "env->Get" + callString + "ArrayRegion(" + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_" + paramIndex + "_length,easyArg_" + paramIndex + ");"); pw.println(tabs + "jobjectRefType ref_" + paramIndex + " = env->GetObjectRefType(" + parmName + ");"); pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {"); pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");"); pw.println(tabs + "}"); } else { } } processTemplate(pw, map, "cpp_end_easy_method.cpp", tabs); if (!isVoid(returnClass)) { pw.println(tabs + "return retVal;"); } tabs = tabs.substring(TAB_STRING.length()); pw.println(tabs + "}"); pw.println(); } } } processTemplate(pw, map, CPP_END_CLASSCPP, tabs); tabs = tabs.substring(0, tabs.length() - 1); Class nextClass = (class_index < (classesSegList.size() - 1)) ? classesSegList.get(class_index + 1) : null; tabs = closeClassNamespace(clss, pw, tabs, nextClass); lastClass = clss; } if (segment_index < 1) { if (null != nativesClassMap) { for (Entry<String, Class> e : nativesClassMap.entrySet()) { final Class javaClass = e.getValue(); final String nativeClassName = e.getKey(); map.put(CLASS_NAME, nativeClassName); map.put(FULL_CLASS_NAME, nativeClassName); map.put(FULL_CLASS_JNI_SIGNATURE, nativeClassName); map.put("%BASE_CLASS_FULL_NAME%", "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::")); map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object"); map.put("%INITIALIZE_CONTEXT%", "context=NULL; initContext(NULL,false);"); map.put("%INITIALIZE_CONTEXT_REF%", "context=NULL; initContext(objref.context,true);"); tabs += TAB_STRING; processTemplate(pw, map, CPP_START_CLASSCPP, tabs); pw.println(); pw.println(tabs + nativeClassName + "::" + nativeClassName + "() : " + getModifiedClassName(javaClass).replace(".", "::") + "((jobject)NULL,false) {"); tabs += TAB_STRING; pw.println(tabs + "context=NULL;"); pw.println(tabs + "initContext(NULL,false);"); map.put(JNI_SIGNATURE, "()V"); map.put(CONSTRUCTOR_ARGS, ""); processTemplate(pw, map, "cpp_new_native.cpp", tabs); tabs = tabs.substring(TAB_STRING.length()); pw.println(tabs + "}"); pw.println(); pw.println(tabs + "// Destructor for " + nativeClassName); pw.println(tabs + nativeClassName + "::~" + nativeClassName + "() {"); pw.println(tabs + TAB_STRING + "if(NULL != context) {"); pw.println(tabs + TAB_STRING + TAB_STRING + "deleteContext();"); pw.println(tabs + TAB_STRING + "}"); pw.println(tabs + TAB_STRING + "context=NULL;"); pw.println(tabs + "}"); pw.println(); // pw.println(tabs + "public:"); // pw.println(tabs + nativeClassName + "();"); // pw.println(tabs + "~" + nativeClassName + "();"); tabs = tabs.substring(TAB_STRING.length()); // Method methods[] = javaClass.getDeclaredMethods(); // for (int j = 0; j < methods.length; j++) { // Method method = methods[j]; // int modifiers = method.getModifiers(); // if (!Modifier.isPublic(modifiers)) { // continue; // } // pw.println(tabs + getCppDeclaration(method, javaClass)); // } // pw.println(tabs + "}; // end class " + nativeClassName); processTemplate(pw, map, CPP_END_CLASSCPP, tabs); } } processTemplate(pw, map, "cpp_template_end_first.cpp", tabs); tabs = ""; if (null != nativesClassMap) { pw.println("using namespace " + namespace + ";"); pw.println("#ifdef __cplusplus"); pw.println("extern \"C\" {"); pw.println("#endif"); int max_method_count = 0; tabs = ""; for (Entry<String, Class> e : nativesClassMap.entrySet()) { final Class javaClass = e.getValue(); final String nativeClassName = e.getKey(); map.put(CLASS_NAME, nativeClassName); map.put(FULL_CLASS_NAME, nativeClassName); map.put("%BASE_CLASS_FULL_NAME%", "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::")); map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object"); map.put(FULL_CLASS_JNI_SIGNATURE, nativeClassName); map.put(METHOD_ONFAIL, "return;"); Method methods[] = javaClass.getDeclaredMethods(); if (max_method_count < methods.length) { max_method_count = methods.length; } for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { continue; } if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) // && !method.isDefault() && !method.isSynthetic()) { Class[] paramClasses = method.getParameterTypes(); String methodArgs = getCppParamNames(paramClasses); map.put(METHOD_ARGS, methodArgs); map.put(METHOD_NAME, method.getName()); Class returnClass = method.getReturnType(); String retStore = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnVarType(returnClass) + ") "; map.put(METHOD_ONFAIL, getOnFailString(returnClass, javaClass)); map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass)); map.put("%METHOD_RETURN_STORE%", retStore); map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, javaClass)); pw.println(); String paramDecls = getCppParamDeclarations(paramClasses, javaClass); String argsToAdd = method.getParameterTypes().length > 0 ? "," + paramDecls.substring(1, paramDecls.length() - 1) : ""; pw.println("JNIEXPORT " + getCppType(returnClass, javaClass) + " JNICALL Java_" + nativeClassName + "_" + method.getName() + "(JNIEnv *env, jobject jthis" + argsToAdd + ") {"); tabs = TAB_STRING; processTemplate(pw, map, "cpp_native_wrap.cpp", tabs); tabs = tabs.substring(TAB_STRING.length()); pw.println("}"); pw.println(); } } pw.println("JNIEXPORT void JNICALL Java_" + nativeClassName + "_nativeDelete(JNIEnv *env, jobject jthis) {"); tabs += TAB_STRING; map.put(METHOD_ONFAIL, getOnFailString(void.class, javaClass)); processTemplate(pw, map, "cpp_native_delete.cpp", tabs); tabs = tabs.substring(TAB_STRING.length()); pw.println(tabs + "}"); pw.println(); } pw.println("#ifdef __cplusplus"); pw.println("} // end extern \"C\""); pw.println("#endif"); map.put("%MAX_METHOD_COUNT%", Integer.toString(max_method_count + 1)); processTemplate(pw, map, "cpp_start_register_native.cpp", tabs); for (Entry<String, Class> e : nativesClassMap.entrySet()) { final Class javaClass = e.getValue(); final String nativeClassName = e.getKey(); map.put(CLASS_NAME, nativeClassName); map.put(FULL_CLASS_NAME, nativeClassName); map.put("%BASE_CLASS_FULL_NAME%", "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::")); map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object"); processTemplate(pw, map, "cpp_start_register_native_class.cpp", tabs); tabs += TAB_STRING; Method methods[] = javaClass.getDeclaredMethods(); int method_number = 0; for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { continue; } if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) // && !method.isDefault() && !method.isSynthetic()) { map.put("%METHOD_NUMBER%", Integer.toString(method_number)); map.put(METHOD_NAME, method.getName()); map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(method.getParameterTypes()) + ")" + classToJNISignature(method.getReturnType())); processTemplate(pw, map, "cpp_register_native_item.cpp", tabs); method_number++; } } map.put("%METHOD_NUMBER%", Integer.toString(method_number)); map.put(METHOD_NAME, "nativeDelete"); map.put(JNI_SIGNATURE, "()V"); processTemplate(pw, map, "cpp_register_native_item.cpp", tabs); map.put("%NUM_NATIVE_METHODS%", Integer.toString(method_number)); processTemplate(pw, map, "cpp_end_register_native_class.cpp", tabs); tabs = tabs.substring(TAB_STRING.length()); } processTemplate(pw, map, "cpp_end_register_native.cpp", tabs); } else { pw.println("// No Native classes : registerNativMethods not needed."); pw.println("static void registerNativeMethods(JNIEnv *env) {}"); } } else { processTemplate(pw, map, CPP_TEMPLATE_ENDCPP, tabs); } } if (null != nativesClassMap) { tabs = ""; for (Entry<String, Class> e : nativesClassMap.entrySet()) { String nativeClassName = e.getKey(); File nativeClassHeaderFile = new File( namespace.toLowerCase() + "_" + nativeClassName.toLowerCase() + ".h"); map.put("%NATIVE_CLASS_HEADER%", nativeClassHeaderFile.getName()); map.put(CLASS_NAME, nativeClassName); if (nativeClassHeaderFile.exists()) { if (verbose) { System.out.println("skipping " + nativeClassHeaderFile.getCanonicalPath() + " since it already exists."); } } else { try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassHeaderFile))) { processTemplate(pw, map, "header_native_imp.h", tabs); } } File nativeClassCppFile = new File( namespace.toLowerCase() + "_" + nativeClassName.toLowerCase() + ".cpp"); if (nativeClassCppFile.exists()) { if (verbose) { System.out.println("skipping " + nativeClassCppFile.getCanonicalPath() + " since it already exists."); } } else { try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassCppFile))) { processTemplate(pw, map, "cpp_native_imp_start.cpp", tabs); Class javaClass = e.getValue(); Method methods[] = javaClass.getDeclaredMethods(); int method_number = 0; for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { continue; } if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) // && !method.isDefault() && !method.isSynthetic()) { Class[] paramClasses = method.getParameterTypes(); // String methodArgs = getCppParamNames(paramClasses); String paramDecls = getCppParamDeclarations(paramClasses, javaClass); String methodArgs = method.getParameterTypes().length > 0 ? paramDecls.substring(1, paramDecls.length() - 1) : ""; map.put(METHOD_ARGS, methodArgs); map.put(METHOD_NAME, method.getName()); Class returnClass = method.getReturnType(); String retStore = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnVarType(returnClass) + ") "; map.put(METHOD_ONFAIL, getOnFailString(returnClass, javaClass)); map.put("%RETURN_TYPE%", getCppType(returnClass, javaClass)); map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass)); map.put("%METHOD_RETURN_STORE%", retStore); map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, javaClass)); processTemplate(pw, map, "cpp_native_imp_stub.cpp", tabs); } } processTemplate(pw, map, "cpp_native_imp_end.cpp", tabs); } } } } } main_completed = true; }
From source file:FaceRatios.java
@SuppressWarnings("serial") public static void main(String[] args) { int r = FSDK.ActivateLibrary(FACE_SDK_LICENSE); if (r == FSDK.FSDKE_OK) { FSDK.Initialize();//from w w w. j a v a 2s .c om FSDK.SetFaceDetectionParameters(true, true, 384); Map<String, Map<String, ArrayList<Double>>> faceProperties = new HashMap<>(); for (String directory : new File(FACE_DIRECTORY).list()) { if (new File(FACE_DIRECTORY + directory).isDirectory()) { Map<String, ArrayList<Double>> properties = new HashMap<String, ArrayList<Double>>() { { for (String property : propertyNames) put(property, new ArrayList<Double>()); } }; File[] files = new File(FACE_DIRECTORY + directory).listFiles(); System.out.println("Analyzing " + directory + " with " + files.length + " files\n"); for (File file : files) { if (file.isFile()) { HImage imageHandle = new HImage(); FSDK.LoadImageFromFileW(imageHandle, file.getAbsolutePath()); FSDK.TFacePosition.ByReference facePosition = new FSDK.TFacePosition.ByReference(); if (FSDK.DetectFace(imageHandle, facePosition) == FSDK.FSDKE_OK) { FSDK_Features.ByReference facialFeatures = new FSDK_Features.ByReference(); FSDK.DetectFacialFeaturesInRegion(imageHandle, (FSDK.TFacePosition) facePosition, facialFeatures); Point[] featurePoints = new Point[FSDK.FSDK_FACIAL_FEATURE_COUNT]; for (int i = 0; i < FSDK.FSDK_FACIAL_FEATURE_COUNT; i++) { featurePoints[i] = new Point(0, 0); featurePoints[i].x = facialFeatures.features[i].x; featurePoints[i].y = facialFeatures.features[i].y; } double eyeDistance = featureDistance(featurePoints, FeatureID.LEFT_EYE, FeatureID.RIGHT_EYE); double rightEyeSize = featureDistance(featurePoints, FeatureID.RIGHT_EYE_INNER_CORNER, FeatureID.RIGHT_EYE_OUTER_CORNER); double leftEyeSize = featureDistance(featurePoints, FeatureID.LEFT_EYE_INNER_CORNER, FeatureID.LEFT_EYE_OUTER_CORNER); double averageEyeSize = (rightEyeSize + leftEyeSize) / 2; double mouthLength = featureDistance(featurePoints, FeatureID.MOUTH_RIGHT_CORNER, FeatureID.MOUTH_LEFT_CORNER); double mouthHeight = featureDistance(featurePoints, FeatureID.MOUTH_BOTTOM, FeatureID.MOUTH_TOP); double noseHeight = featureDistance(featurePoints, FeatureID.NOSE_BOTTOM, FeatureID.NOSE_BRIDGE); double chinHeight = featureDistance(featurePoints, FeatureID.CHIN_BOTTOM, FeatureID.MOUTH_BOTTOM); double chinToBridgeHeight = featureDistance(featurePoints, FeatureID.CHIN_BOTTOM, FeatureID.NOSE_BRIDGE); double faceContourLeft = (featurePoints[FeatureID.CHIN_BOTTOM.getIndex()].getY() - featurePoints[FeatureID.FACE_CONTOUR2.getIndex()].getY()) / (featurePoints[FeatureID.CHIN_BOTTOM.getIndex()].getX() - featurePoints[FeatureID.FACE_CONTOUR2.getIndex()].getX()); double faceContourRight = (featurePoints[FeatureID.CHIN_BOTTOM.getIndex()].getY() - featurePoints[FeatureID.FACE_CONTOUR12.getIndex()].getY()) / (featurePoints[FeatureID.CHIN_BOTTOM.getIndex()].getX() - featurePoints[FeatureID.FACE_CONTOUR12.getIndex()].getX()); double bridgeLeftEyeDistance = featureDistance(featurePoints, FeatureID.LEFT_EYE_INNER_CORNER, FeatureID.NOSE_BRIDGE); double bridgeRightEyeDistance = featureDistance(featurePoints, FeatureID.RIGHT_EYE_INNER_CORNER, FeatureID.NOSE_BRIDGE); properties.get("eyeSize/eyeDistance").add(averageEyeSize / eyeDistance); properties.get("eyeSizeDisparity") .add(Math.abs(leftEyeSize - rightEyeSize) / averageEyeSize); properties.get("bridgeToEyeDisparity") .add(Math.abs(bridgeLeftEyeDistance - bridgeRightEyeDistance) / ((bridgeLeftEyeDistance + bridgeRightEyeDistance) / 2)); properties.get("eyeDistance/mouthLength").add(eyeDistance / mouthLength); properties.get("eyeDistance/noseHeight").add(eyeDistance / noseHeight); properties.get("eyeSize/mouthLength").add(eyeDistance / mouthLength); properties.get("eyeSize/noseHeight").add(eyeDistance / noseHeight); properties.get("mouthLength/mouthHeight").add(mouthLength / mouthHeight); properties.get("chinHeight/noseHeight").add(chinHeight / noseHeight); properties.get("chinHeight/chinToBridgeHeight") .add(chinHeight / chinToBridgeHeight); properties.get("noseHeight/chinToBridgeHeight") .add(noseHeight / chinToBridgeHeight); properties.get("mouthHeight/chinToBridgeHeight") .add(mouthHeight / chinToBridgeHeight); properties.get("faceCountourAngle") .add(Math.toDegrees(Math.atan((faceContourLeft - faceContourRight) / (1 + faceContourLeft * faceContourRight)))); } FSDK.FreeImage(imageHandle); } } System.out.format("%32s\t%8s\t%8s\t%3s%n", "Property", "", "", "c"); System.out.println(new String(new char[76]).replace("\0", "-")); ArrayList<Entry<String, ArrayList<Double>>> propertyList = new ArrayList<>( properties.entrySet()); Collections.sort(propertyList, new Comparator<Entry<String, ArrayList<Double>>>() { @Override public int compare(Entry<String, ArrayList<Double>> arg0, Entry<String, ArrayList<Double>> arg1) { DescriptiveStatistics dStats0 = new DescriptiveStatistics(listToArray(arg0.getValue())); DescriptiveStatistics dStats1 = new DescriptiveStatistics(listToArray(arg1.getValue())); return new Double(dStats0.getStandardDeviation() / dStats0.getMean()) .compareTo(dStats1.getStandardDeviation() / dStats1.getMean()); } }); for (Entry<String, ArrayList<Double>> property : propertyList) { DescriptiveStatistics dStats = new DescriptiveStatistics(listToArray(property.getValue())); System.out.format("%32s\t%4f\t%4f\t%3s%n", property.getKey(), dStats.getMean(), dStats.getStandardDeviation(), Math.round(dStats.getStandardDeviation() / dStats.getMean() * 100) + "%"); } System.out.println("\n"); faceProperties.put(directory, properties); } } for (String propertyName : propertyNames) { DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset(); for (Entry<String, Map<String, ArrayList<Double>>> face : faceProperties.entrySet()) { dataset.add(face.getValue().get(propertyName), "Default Series", face.getKey()); } PropertyBoxWhisker plot = new PropertyBoxWhisker(propertyName, dataset); plot.pack(); plot.setVisible(true); } } }
From source file:Main.java
public static final Map<String, String> getMap() { Map<String, String> map = new HashMap<String, String>(); map.put("x", "y"); return Collections.unmodifiableMap(map); }
From source file:Main.java
public static void evalIdEqMap(Map<String, Object> map, Long id) { map.put("id", id); }
From source file:Main.java
public static <A, B> Map<A, B> singletonMap(A a, B b) { Map<A, B> map = new HashMap<A, B>(); map.put(a, b); return map;/* www.j av a 2 s. co m*/ }