answer
stringlengths
17
10.2M
package edu.wustl.xipHost.application; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.UUID; import javax.xml.ws.Endpoint; import org.apache.log4j.Logger; import org.jdom.Document; import org.nema.dicom.wg23.ArrayOfString; import org.nema.dicom.wg23.ArrayOfUUID; import org.nema.dicom.wg23.AvailableData; import org.nema.dicom.wg23.Host; import org.nema.dicom.wg23.ModelSetDescriptor; import org.nema.dicom.wg23.ObjectLocator; import org.nema.dicom.wg23.QueryResult; import org.nema.dicom.wg23.Rectangle; import org.nema.dicom.wg23.State; import org.nema.dicom.wg23.Uuid; import edu.wustl.xipHost.avt2ext.ADRetrieveTarget; import edu.wustl.xipHost.avt2ext.AVTRetrieve2; import edu.wustl.xipHost.avt2ext.AVTRetrieve2Event; import edu.wustl.xipHost.avt2ext.AVTRetrieve2Listener; import edu.wustl.xipHost.avt2ext.AVTUtil; import edu.wustl.xipHost.avt2ext.Query; import edu.wustl.xipHost.avt2ext.iterator.IterationTarget; import edu.wustl.xipHost.avt2ext.iterator.IteratorElementEvent; import edu.wustl.xipHost.avt2ext.iterator.IteratorEvent; import edu.wustl.xipHost.avt2ext.iterator.NotificationRunner; import edu.wustl.xipHost.avt2ext.iterator.TargetElement; import edu.wustl.xipHost.avt2ext.iterator.TargetIteratorRunner; import edu.wustl.xipHost.avt2ext.iterator.TargetIteratorListener; import edu.wustl.xipHost.dataModel.SearchResult; import edu.wustl.xipHost.dicom.DicomUtil; import edu.wustl.xipHost.gui.HostMainWindow; import edu.wustl.xipHost.hostControl.Util; import edu.wustl.xipHost.hostControl.XindiceManager; import edu.wustl.xipHost.hostControl.XindiceManagerFactory; import edu.wustl.xipHost.wg23.ClientToApplication; import edu.wustl.xipHost.wg23.HostImpl; import edu.wustl.xipHost.wg23.NativeModelListener; import edu.wustl.xipHost.wg23.NativeModelRunner; import edu.wustl.xipHost.wg23.WG23DataModel; public class Application implements NativeModelListener, TargetIteratorListener, AVTRetrieve2Listener { final static Logger logger = Logger.getLogger(Application.class); UUID id; String name; File exePath; String vendor; String version; File iconFile; String type; boolean requiresGUI; String wg23DataModelType; int concurrentInstances; IterationTarget iterationTarget; /* Application is a WG23 compatibile application*/ public Application(String name, File exePath, String vendor, String version, File iconFile, String type, boolean requiresGUI, String wg23DataModelType, int concurrentInstances, IterationTarget iterationTarget){ if(name == null || exePath == null || vendor == null || version == null || type == null || wg23DataModelType == null || iterationTarget == null){ throw new IllegalArgumentException("Application parameters are invalid: " + name + " , " + exePath + " , " + vendor + " , " + version + type + " , " + requiresGUI + " , " + wg23DataModelType + " , " + iterationTarget); } else if(name.isEmpty() || name.trim().length() == 0 || exePath.exists() == false){ try { throw new IllegalArgumentException("Application parameters are invalid: " + name + " , " + exePath.getCanonicalPath() + " , " + vendor + " , " + version); } catch (IOException e) { throw new IllegalArgumentException("Application exePath is invalid. Application name: " + name); } } else{ id = UUID.randomUUID(); this.name = name; this.exePath = exePath; this.vendor = vendor; this.version = version; if(iconFile != null && iconFile.exists()){ this.iconFile = iconFile; }else{ this.iconFile = null; } this.type = type; this.requiresGUI = requiresGUI; this.wg23DataModelType = wg23DataModelType; this.concurrentInstances = concurrentInstances; this.iterationTarget = iterationTarget; } } //verify this pattern /*public boolean verifyFileName(String fileName){ String str = "/ \\ : * ? \" < > | , "; Pattern filePattern = Pattern.compile(str); boolean matches = filePattern.matcher(fileName).matches(); return matches; } public static void main (String args[]){ Application app = new Application("ApplicationTest", new File("test.txt"), "", ""); System.out.println(app.getExePath().getName()); System.out.println(app.verifyFileName(app.getExePath().getName())); }*/ public UUID getID(){ return id; } public String getName(){ return name; } public void setName(String name){ if(name == null || name.isEmpty() || name.trim().length() == 0){ throw new IllegalArgumentException("Invalid application name: " + name); }else{ this.name = name; } } public File getExePath(){ return exePath; } public void setExePath(File path){ if(path == null){ throw new IllegalArgumentException("Invalid exePath name: " + path); }else{ exePath = path; } } public String getVendor(){ return vendor; } public void setVendor(String vendor){ if(vendor == null){ throw new IllegalArgumentException("Invalid vendor: " + vendor); }else{ this.vendor = vendor; } } public String getVersion(){ return version; } public void setVersion(String version){ if(version == null){ throw new IllegalArgumentException("Invalid version: " + version); }else{ this.version = version; } } public File getIconFile(){ return iconFile; } public void setIconFile(File iconFile){ if(iconFile == null){ throw new IllegalArgumentException("Invalid exePath name: " + iconFile); }else{ this.iconFile = iconFile; } } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean requiresGUI() { return requiresGUI; } public void setRequiresGUI(boolean requiresGUI) { this.requiresGUI = requiresGUI; } public String getWG23DataModelType() { return wg23DataModelType; } public void setWG23DataModelType(String wg23DataModelType) { this.wg23DataModelType = wg23DataModelType; } public int getConcurrentInstances() { return concurrentInstances; } public void setConcurrentInstances(int concurrentInstances) { this.concurrentInstances = concurrentInstances; } public IterationTarget getIterationTarget() { return iterationTarget; } public void setIterationTarget(IterationTarget iterationTarget) { this.iterationTarget = iterationTarget; } //Each application has: //1. Out directories assigned //2. clientToApplication //3. Host scheleton (reciever) //4. Data assigned for processing //5. Data produced //when launching diploy service and set URLs ClientToApplication clientToApplication; public void startClientToApplication(){ clientToApplication = new ClientToApplication(getApplicationServiceURL()); } public ClientToApplication getClientToApplication(){ return clientToApplication; } //Implementation HostImpl is used to be able to add WG23Listener //It is eventually casted to Host type Host host = new HostImpl(this); //All loaded application by default will be saved again. //New instances of an application will be saved only when the save checkbox is selected Boolean doSave = true; public void setDoSave(boolean doSave){ this.doSave = doSave; } public boolean getDoSave(){ return doSave; } Endpoint hostEndpoint; URL hostServiceURL; URL appServiceURL; public void launch(URL hostServiceURL, URL appServiceURL){ this.hostServiceURL = hostServiceURL; this.appServiceURL = appServiceURL; setApplicationOutputDir(ApplicationManagerFactory.getInstance().getOutputDir()); setApplicationTmpDir(ApplicationManagerFactory.getInstance().getTmpDir()); setApplicationPreferredSize(HostMainWindow.getApplicationPreferredSize()); //prepare native models //createNativeModels(getWG23DataModel()); //diploy host service hostEndpoint = Endpoint.publish(hostServiceURL.toString(), host); // Ways of launching XIP application: exe, bat, class or jar //if(((String)getExePath().getName()).endsWith(".exe") || ((String)getExePath().getName()).endsWith(".bat")){ try { if(getExePath().toURI().toURL().toExternalForm().endsWith(".exe") || getExePath().toURI().toURL().toExternalForm().endsWith(".bat")){ //TODO unvoid try { Runtime.getRuntime().exec("cmd /c start /min " + getExePath().toURI().toURL().toExternalForm() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); /*List< String > command = new LinkedList<String>(); command.add("cmd"); command.add("/c"); command.add("start"); command.add("/min"); command.add(getExePath().getCanonicalPath()); command.add("--hostURL"); command.add(hostServiceURL.toURI().toURL().toExternalForm()); command.add( "--applicationURL" ); command.add(appServiceURL.toURI().toURL().toExternalForm()); ProcessBuilder builder = new ProcessBuilder(command); String str =""; for(int i = 0; i < command.size(); i++){ str = str + command.get(i) + " "; } System.out.println(str); File dir = getExePath().getParentFile(); builder.directory(dir); builder.start();*/ } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (getExePath().toURI().toURL().toExternalForm().endsWith(".sh")){ try { //Runtime.getRuntime().exec("/bin/sh " + getExePath().getCanonicalPath() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); System.out.println(getExePath().toURI().toURL().toExternalForm() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); Runtime.getRuntime().exec("open " + getExePath().toURI().toURL().toExternalForm() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); /*List<String> command = new ArrayList<String>(); command.add("/bin/sh"); command.add(getExePath().getCanonicalPath()); command.add("--hostURL"); command.add(hostServiceURL.toURI().toURL().toExternalForm()); command.add("--applicationURL"); command.add(appServiceURL.toURI().toURL().toExternalForm()); ProcessBuilder builder = new ProcessBuilder(command); //Map<String, String> environ = builder.environment(); //builder.directory(new File(System.getenv("temp"))); //System.out.println("Directory : " + System.getenv("temp") ); final Process process = builder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } System.out.println("Program terminated!"); */ } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { Runtime.getRuntime().exec(getExePath().toURI().toURL().toExternalForm() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO Auto-generated catch block } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //startIterator //Query query = new AVTQueryStub(null, null, null, null, null); //SearchResultSetupAvailableData resultForSubqueries = new SearchResultSetupAvailableData(); //SearchResult selectedDataSearchResult = resultForSubqueries.getSearchResult(); TargetIteratorRunner targetIter = new TargetIteratorRunner(selectedDataSearchResult, getIterationTarget(), query, getApplicationTmpDir(), this); try { Thread t = new Thread(targetIter); t.start(); } catch(Exception e) { logger.error(e, e); } } public Endpoint getHostEndpoint(){ return hostEndpoint; } File appOutputDir; public void setApplicationOutputDir(File outDir){ try { appOutputDir = Util.create("xipOUT_" + getName() + "_", "", outDir); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public File getApplicationOutputDir() { return appOutputDir; } File appTmpDir; public void setApplicationTmpDir(File tmpDir){ appTmpDir = tmpDir; } public File getApplicationTmpDir() { return appTmpDir; } java.awt.Rectangle preferredSize; public void setApplicationPreferredSize(java.awt.Rectangle preferredSize){ this.preferredSize = preferredSize; } State priorState = null; State state = null; boolean firstPass = true; public void setState(State state){ priorState = this.state; this.state = state; logger.debug("State changed to: " + this.state); if(state.equals(State.INPROGRESS)){ notifyDataAvailable2(); //notifyDataAvailable3(); } else if (state.equals(State.IDLE)){ if(firstPass){ firstPass = false; } else { synchronized (wg23DataModelItems){ if(i < wg23DataModelItems.size()){ getClientToApplication().setState(State.INPROGRESS); }else { getClientToApplication().setState(State.EXIT); } } } } else if (state.equals(State.EXIT)){ firstPass = true; i = 0; j = 0; wg23DataModelItems.clear(); retrievedTargetElements.clear(); targetElements.clear(); iter = null; } } public State getState(){ return state; } public State getPriorState(){ return priorState; } WG23DataModel wg23dm = null; public void setData(WG23DataModel wg23DataModel){ this.wg23dm = wg23DataModel; } public WG23DataModel getWG23DataModel(){ return wg23dm; } SearchResult selectedDataSearchResult; public void setSelectedDataSearchResult(SearchResult selectedDataSearchResult){ this.selectedDataSearchResult = selectedDataSearchResult; } Query query; public void setDataSource(Query query){ this.query = query; } public Rectangle getApplicationPreferredSize() { double x = preferredSize.getX(); double y = preferredSize.getY(); double width = preferredSize.getWidth(); double height = preferredSize.getHeight(); Rectangle rect = new Rectangle(); rect.setRefPointX(new Double(x).intValue()); rect.setRefPointY(new Double(y).intValue()); rect.setWidth(new Double(width).intValue()); rect.setHeight(new Double(height).intValue()); return rect; } public URL getApplicationServiceURL(){ return appServiceURL; } public void notifyAddSideTab(){ HostMainWindow.addTab(getName(), getID()); } public void bringToFront(){ clientToApplication.bringToFront(); } public boolean shutDown(){ if(getState().equals(State.IDLE)){ if(getClientToApplication().setState(State.EXIT)){ return true; } }else{ if(cancelProcessing()){ return shutDown(); } } return false; } public void runShutDownSequence(){ HostMainWindow.removeTab(getID()); getHostEndpoint().stop(); /* voided to make compatibile with the iterator //Delete documents from Xindice created for this application XindiceManagerFactory.getInstance().deleteAllDocuments(getID().toString()); //Delete collection created for this application XindiceManagerFactory.getInstance().deleteCollection(getID().toString()); */ } public boolean cancelProcessing(){ if(getState().equals(State.INPROGRESS) || getState().equals(State.SUSPENDED)){ return getClientToApplication().setState(State.CANCELED); }else{ return false; } } public boolean suspendProcessing(){ if(getState().equals(State.INPROGRESS)){ return getClientToApplication().setState(State.SUSPENDED); }else{ return false; } } /** * Method is used to create XML native models for all object locators * found in WG23DataModel. * It uses threads and add NativeModelListener to the NativeModelRunner * @param wg23dm */ void createNativeModels(WG23DataModel wg23dm){ if(XindiceManagerFactory.getInstance().createCollection(getID().toString())){ ObjectLocator[] objLocs = wg23dm.getObjectLocators(); for (int i = 0; i < objLocs.length; i++){ boolean isDICOM = false; try { isDICOM = DicomUtil.isDICOM(new File(new URI(objLocs[i].getUri()))); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(isDICOM){ NativeModelRunner nmRunner; nmRunner = new NativeModelRunner(objLocs[i]); nmRunner.addNativeModelListener(this); Thread t = new Thread(nmRunner); t.start(); } } }else{ //TODO //Action when system cannot create collection } } /** * Adds JDOM Document to Xindice collection. * Only valid documents (e.g. not null, with root element) will be added * (non-Javadoc) * @see edu.wustl.xipHost.wg23.NativeModelListener#nativeModelAvailable(org.jdom.Document, org.nema.dicom.wg23.Uuid) */ public void nativeModelAvailable(Document doc, Uuid objUUID) { XindiceManagerFactory.getInstance().addDocument(doc, getID().toString(), objUUID); } public void nativeModelAvailable(String xmlNativeModel) { // Ignore in XIP Host. // Used by AVT AD } /** * Method returns ModelSetDescriptor containing UUID of native models * as well as UUID of object locators for which native models could * not be created * @param objUUIDs * @return */ public ModelSetDescriptor getModelSetDescriptor(List<Uuid> objUUIDs){ String[] models = XindiceManagerFactory.getInstance().getModelUUIDs(getID().toString()); List<String> listModels = Arrays.asList(models); ModelSetDescriptor msd = new ModelSetDescriptor(); ArrayOfUUID uuidsModels = new ArrayOfUUID(); List<Uuid> listUUIDs = uuidsModels.getUuid(); ArrayOfUUID uuidsFailed = new ArrayOfUUID(); List<Uuid> listUUIDsFailed = uuidsFailed.getUuid(); for(int i = 0; i < objUUIDs.size(); i++){ Uuid uuid = new Uuid(); if(objUUIDs.get(i) == null || objUUIDs.get(i).getUuid() == null){ //do not add anything to model set descriptor }else if(objUUIDs.get(i).getUuid().toString().trim().isEmpty()){ //do not add anything to model set descriptor }else if(listModels.contains("wg23NM-"+ objUUIDs.get(i).getUuid())){ int index = listModels.indexOf("wg23NM-"+ objUUIDs.get(i).getUuid()); uuid.setUuid(listModels.get(index)); listUUIDs.add(uuid); }else{ uuid.setUuid(objUUIDs.get(i).getUuid()); listUUIDsFailed.add(uuid); } } msd.setModels(uuidsModels); msd.setFailedSourceObjects(uuidsFailed); return msd; } /** * queryResults list hold teh values from queryResultAvailable */ List<QueryResult> queryResults; public List<QueryResult> queryModel(List<Uuid> modelUUIDs, List<String> listXPaths){ queryResults = new ArrayList<QueryResult>(); if(modelUUIDs == null || listXPaths == null){ return queryResults; } String collectionName = getID().toString(); XindiceManager xm = XindiceManagerFactory.getInstance(); for(int i = 0; i < listXPaths.size(); i++){ for(int j = 0; j < modelUUIDs.size(); j++){ //String[] results = xm.query(service, collectionName, modelUUIDs.get(j), listXPaths.get(i)); String[] results = xm.query(collectionName, modelUUIDs.get(j), listXPaths.get(i)); QueryResult queryResult = new QueryResult(); queryResult.setModel(modelUUIDs.get(j)); queryResult.setXpath(listXPaths.get(i)); ArrayOfString arrayOfString = new ArrayOfString(); List<String> listString = arrayOfString.getString(); for(int k = 0; k < results.length; k++){ listString.add(results[k]); } queryResult.setResults(arrayOfString); queryResults.add(queryResult); } } return queryResults; } Iterator<TargetElement> iter = null; @SuppressWarnings("unchecked") @Override public synchronized void fullIteratorAvailable(IteratorEvent e) { iter = (Iterator<TargetElement>)e.getSource(); logger.debug("Full TargetIterator available"); logger.debug("Number of elements: " + wg23DataModelItems.size()); } List<WG23DataModel> wg23DataModelItems = new ArrayList<WG23DataModel>(); List<TargetElement> targetElements = new ArrayList<TargetElement>(); AVTUtil util = new AVTUtil(); int j; @Override public void targetElementAvailable(IteratorElementEvent e) { logger.debug("TargetElement available " + (j++)); TargetElement element = (TargetElement) e.getSource(); targetElements.add(element); WG23DataModel wg23data = util.getWG23DataModel(element); synchronized(wg23DataModelItems){ wg23DataModelItems.add(wg23data); wg23DataModelItems.notify(); } } //This method performs multiple notifyDataAvailable calls until all iterator's elements are used. void notifyDataAvailable(){ // for loop need to be replaced. When state changes to INPROGRESS and // availableDataItems is empty (size = 0) notification is going to fail. int i = 0; boolean notificationComplete = false; if(iter != null){ logger.debug("Iterator complete at the start of the notification."); int totalSize = wg23DataModelItems.size(); if(totalSize == 1){ AvailableData availableData = wg23DataModelItems.get(i).getAvailableData(); getClientToApplication().notifyDataAvailable(availableData, true); notificationComplete = true; logger.debug("Notification complete? " + notificationComplete); } else { while(i < (totalSize - 1)){ AvailableData availableData = wg23DataModelItems.get(i).getAvailableData(); getClientToApplication().notifyDataAvailable(availableData, false); i++; } AvailableData availableData = wg23DataModelItems.get(i).getAvailableData(); getClientToApplication().notifyDataAvailable(availableData, true); notificationComplete = true; logger.debug("Notification complete? " + notificationComplete); } } while(iter == null){ logger.debug("Iterator not complete at the start of the notification"); if(wg23DataModelItems.size() > (i + 1)){ AvailableData availableData = wg23DataModelItems.get(i).getAvailableData(); getClientToApplication().notifyDataAvailable(availableData, false); i++; } } while(notificationComplete != true){ int totalSize = wg23DataModelItems.size(); while(i < (totalSize - 1)){ AvailableData availableData = wg23DataModelItems.get(i).getAvailableData(); getClientToApplication().notifyDataAvailable(availableData, false); i++; } AvailableData availableData = wg23DataModelItems.get(i).getAvailableData(); getClientToApplication().notifyDataAvailable(availableData, true); notificationComplete = true; logger.debug("Notification complete? " + notificationComplete); } } //notification contains only one TargetElement int i; void notifyDataAvailable2(){ boolean notificationComplete = false; if(iter != null){ logger.debug("Iterator complete at the start of the notification."); int totalSize = wg23DataModelItems.size(); if(totalSize == 1 && i == 0){ logger.debug("Value of i: " + i); AvailableData availableData = wg23DataModelItems.get(i).getAvailableData(); NotificationRunner runner = new NotificationRunner(getClientToApplication(), availableData, true); Thread t = new Thread(runner); i++; t.start(); notificationComplete = true; logger.debug("Notification complete? " + notificationComplete); } else { logger.debug("Value of i: " + i); AvailableData availableData = wg23DataModelItems.get(i).getAvailableData(); NotificationRunner runner = new NotificationRunner(getClientToApplication(), availableData, true); Thread t = new Thread(runner); i++; t.start(); notificationComplete = true; logger.debug("Notification complete? " + notificationComplete); } } if(iter == null){ logger.debug("Iterator not complete at the start of the notification"); int size = wg23DataModelItems.size(); System.out.println("notify2: " + size); if(wg23DataModelItems.size() == 0){ synchronized (wg23DataModelItems){ while(wg23DataModelItems.isEmpty()){ try { wg23DataModelItems.wait(); } catch (InterruptedException e) { logger.error(e, e); } } } } if(wg23DataModelItems.size() > 0){ logger.debug("Value of i: " + i); AvailableData availableData = wg23DataModelItems.get(i).getAvailableData(); NotificationRunner runner = new NotificationRunner(getClientToApplication(), availableData, true); Thread t = new Thread(runner); i++; t.start(); notificationComplete = true; logger.debug("Notification complete? " + notificationComplete); } } } void notifyDataAvailable3(){ boolean notificationComplete = false; int size = wg23DataModelItems.size(); System.out.println("notify3: " + size); synchronized (wg23DataModelItems){ while(wg23DataModelItems.isEmpty()){ try { wg23DataModelItems.wait(); AvailableData availableData = wg23DataModelItems.remove(0).getAvailableData(); NotificationRunner runner = new NotificationRunner(getClientToApplication(), availableData, true); Thread t = new Thread(runner); t.start(); notificationComplete = true; logger.debug("Notification complete? " + notificationComplete); } catch (InterruptedException e) { logger.error(e, e); } } while(!wg23DataModelItems.isEmpty()){ AvailableData availableData = wg23DataModelItems.remove(0).getAvailableData(); NotificationRunner runner = new NotificationRunner(getClientToApplication(), availableData, true); Thread t = new Thread(runner); t.start(); notificationComplete = true; logger.debug("Notification complete? " + notificationComplete); } } } public WG23DataModel getW23DataModelForCurrentTargetElement(){ WG23DataModel wg23DataModelItem = wg23DataModelItems.get(i - 1); //Start data retrieval related to the element ADRetrieveTarget retrieveTarget = ADRetrieveTarget.DICOM_AND_AIM; AVTRetrieve2 avtRetrieve = null; try { TargetElement element = targetElements.get(i - 1); avtRetrieve = new AVTRetrieve2(element, retrieveTarget); avtRetrieve.addAVTListener(this); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //avtRetrieve.addAVTListener(this); Thread t = new Thread(avtRetrieve); t.start(); //Wait for actual data being retrieved before sending file pointers String currentElementID = targetElements.get(i - 1).getId(); synchronized(retrievedTargetElements){ while(!retrievedTargetElements.contains(currentElementID)){ try { retrievedTargetElements.wait(); } catch (InterruptedException e) { logger.error(e, e); } } } return wg23DataModelItem; } List<String> retrievedTargetElements = new ArrayList<String>(); @Override public void retriveCompleted(AVTRetrieve2Event e) { String elementID = (String)e.getSource(); synchronized(retrievedTargetElements){ retrievedTargetElements.add(elementID); retrievedTargetElements.notify(); logger.debug("Data retrived for TargetElement: " + elementID); } } }
package com.ardverk.dht; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.math.BigInteger; import java.security.MessageDigest; import java.util.Arrays; import java.util.Random; import org.apache.commons.lang.NullArgumentException; import org.ardverk.coding.CodingUtils; import org.ardverk.collection.ByteArrayKeyAnalyzer; import org.ardverk.collection.Key; import org.ardverk.io.Writable; import com.ardverk.dht.security.SecurityUtils; import com.ardverk.lang.Negation; import com.ardverk.lang.Xor; /** * Kademlia Unique Identifier ({@link KUID}) */ public class KUID implements Identifier, Key<KUID>, Xor<KUID>, Negation<KUID>, Writable, Serializable, Comparable<KUID>, Cloneable { private static final long serialVersionUID = -4611363711131603626L; private static final Random GENERATOR = SecurityUtils.createSecureRandom(); public static KUID createRandom(int length) { byte[] key = new byte[length]; GENERATOR.nextBytes(key); return new KUID(key); } public static KUID createRandom(KUID otherId) { return createRandom(otherId.length()); } public static KUID create(byte[] key) { return new KUID(key); } public static KUID create(byte[] key, int offset, int length) { byte[] copy = new byte[length]; System.arraycopy(key, 0, copy, 0, copy.length); return new KUID(copy); } public static KUID create(BigInteger key) { return create(key.toByteArray()); } public static KUID create(String key, int radix) { return create(new BigInteger(key, radix)); } public static KUID createWithPrefix(KUID prefix, int bits) { // 1) Create a random KUID of the same length byte[] dst = new byte[prefix.length()]; GENERATOR.nextBytes(dst); // 2) Overwrite the prefix bytes ++bits; int length = bits/8; System.arraycopy(prefix.key, 0, dst, 0, length); // 3) Overwrite the remaining bits int bitsToCopy = bits % 8; if (bitsToCopy != 0) { // Mask has the low-order (8-bits) bits set int mask = (1 << (8-bitsToCopy)) - 1; int prefixByte = prefix.key[length]; int randByte = dst[length]; dst[length] = (byte) ((prefixByte & ~mask) | (randByte & mask)); } return create(dst); } private final byte[] key; private final int hashCode; private KUID(byte[] key) { if (key.length == 0) { throw new IllegalArgumentException( "key.length=" + key.length); } this.key = key; this.hashCode = Arrays.hashCode(key); } @Override public KUID getId() { return this; } /** * Returns {@code true} if the given {@link KUID} is compatible with * this {@link KUID}. */ public boolean isCompatible(KUID otherId) { return otherId != null && length() == otherId.length(); } /** * Returns the {@link KUID}'s bytes. */ public byte[] getBytes() { return key.clone(); } /** * Copies the {@link KUID}'s bytes into the given byte array. */ public byte[] getBytes(byte[] dst, int destPos) { System.arraycopy(key, 0, dst, destPos, key.length); return dst; } /** * Calls {@link MessageDigest#update(byte[])} with the {@link KUID}'s bytes. */ public void update(MessageDigest md) { md.update(key); } /** * Returns the length of the {@link KUID} in bytes. */ public int length() { return key.length; } @Override public int lengthInBits() { return ByteArrayKeyAnalyzer.INSTANCE.lengthInBits(key); } @Override public boolean isBitSet(int bitIndex) { return ByteArrayKeyAnalyzer.INSTANCE.isBitSet(key, bitIndex); } @Override public int bitIndex(KUID otherKey) { return ByteArrayKeyAnalyzer.INSTANCE.bitIndex(key, otherKey.key); } @Override public boolean isPrefixedBy(KUID prefix) { return ByteArrayKeyAnalyzer.INSTANCE.isPrefix(key, prefix.key); } @Override public KUID xor(KUID otherId) { if (!isCompatible(otherId)) { throw new IllegalArgumentException("otherId=" + otherId); } byte[] data = new byte[length()]; for (int i = 0; i < key.length; i++) { data[i] = (byte) (key[i] ^ otherId.key[i]); } return new KUID(data); } @Override public KUID negate() { byte[] data = new byte[length()]; for (int i = 0; i < key.length; i++) { data[i] = (byte)(~key[i]); } return new KUID(data); } /** * Returns the minimum {@link KUID}. */ public KUID min() { byte[] minKey = new byte[length()]; return new KUID(minKey); } /** * Returns the maximum {@link KUID}. */ public KUID max() { byte[] maxKey = new byte[length()]; Arrays.fill(maxKey, (byte)0xFF); return new KUID(maxKey); } /** * Sets the bit at the given bitIndex position to true (one, 1) * and returns the {@link KUID}. */ public KUID set(int bitIndex) { return set(bitIndex, true); } /** * Sets the bit at the given bitIndex position to false (zero, 0) * and returns the {@link KUID}. */ public KUID unset(int bitIndex) { return set(bitIndex, false); } /** * Flips the bit at the given bitIndex position and returns the * {@link KUID}. */ public KUID flip(int bitIndex) { return set(bitIndex, !isBitSet(bitIndex)); } private KUID set(int bitIndex, boolean on) { int lengthInBits = lengthInBits(); if (bitIndex < 0 || lengthInBits < bitIndex) { throw new IllegalArgumentException("bitIndex=" + bitIndex); } int index = (int)(bitIndex / Byte.SIZE); int bit = (int)(bitIndex % Byte.SIZE); int mask = (int)(0x80 >>> bit); int value = (int)(key[index] & 0xFF); if (on != ((value & mask) != 0x00)) { byte[] copy = getBytes(); if (on) { copy[index] = (byte)(value | mask); } else { copy[index] = (byte)(value & ~mask); } return new KUID(copy); } return this; } public int commonPrefix(KUID otherId) { return commonPrefix(otherId, 0, lengthInBits()); } public int commonPrefix(KUID otherId, int offsetInBits, int length) { if (otherId == null) { throw new NullArgumentException("otherId"); } int lengthInBits = lengthInBits(); if (offsetInBits < 0 || length < 0 || lengthInBits < (offsetInBits+length)) { throw new IllegalArgumentException( "offsetInBits=" + offsetInBits + ", length=" + length); } if (lengthInBits != otherId.lengthInBits()) { throw new IllegalArgumentException("otherId=" + otherId); } if (otherId != this) { int index = (int)(offsetInBits / Byte.SIZE); int bit = offsetInBits % Byte.SIZE; int bitIndex = 0; for (int i = index; i < key.length && bitIndex < length; i++) { int value = (int)(key[i] ^ otherId.key[i]); // A short cut we can take... if (value == 0 && (bit == 0 || i != index) && i < (key.length-1)) { bitIndex += Byte.SIZE; continue; } for (int j = (i == index ? bit : 0); j < Byte.SIZE && bitIndex < length; j++) { if ((value & (0x80 >>> j)) != 0) { return offsetInBits + bitIndex; } ++bitIndex; } } } return offsetInBits + length; } /** * Returns true if all bits of the {@link KUID} are zero */ public boolean isMin() { int lengthInBits = lengthInBits(); return compare(0x00, 0, lengthInBits) == lengthInBits; } /** * Returns true if all bits of the {@link KUID} are one */ public boolean isMax() { int lengthInBits = lengthInBits(); return compare(0xFF, 0, lengthInBits) == lengthInBits; } private int compare(int expected, int offsetInBits, int length) { int lengthInBits = lengthInBits(); if (offsetInBits < 0 || length < 0 || lengthInBits < (offsetInBits + length)) { throw new IllegalArgumentException( "offsetInBits=" + offsetInBits + ", length=" + length); } int index = (int)(offsetInBits / Byte.SIZE); int bit = offsetInBits % Byte.SIZE; int bitIndex = 0; for (int i = 0; i < key.length && bitIndex < length; i++) { int value = (key[i] & 0xFF) ^ expected; // A shortcut we can take... if (value == 0 && (bit == 0 || i != index)) { bitIndex += Byte.SIZE; continue; } for (int j = (i == index ? bit : 0); j < Byte.SIZE && bitIndex < length; j++) { if ((value & (0x80 >>> j)) != 0) { return offsetInBits + bitIndex; } ++bitIndex; } } return offsetInBits + length; } /** * Returns true if this {@link KUID} is closer in terms of XOR distance * to the given key than the other {@link KUID} is to the key. */ public boolean isCloserTo(KUID key, KUID otherId) { return xor(key).compareTo(key.xor(otherId)) < 0; } @Override public int compareTo(KUID otherId) { return compareTo(otherId, 0, lengthInBits()); } public int compareTo(KUID otherId, int offsetInBits, int length) { if (otherId == null) { throw new NullArgumentException("otherId"); } int lengthInBits = lengthInBits(); if (offsetInBits < 0 || length < 0 || lengthInBits < (offsetInBits + length)) { throw new IllegalArgumentException( "offsetInBits=" + offsetInBits + ", length=" + length); } if (otherId.lengthInBits() != lengthInBits) { throw new IllegalArgumentException(); } if (otherId != this) { int index = (int)(offsetInBits / Byte.SIZE); int bit = offsetInBits % Byte.SIZE; int bitIndex = 0; int mask, diff; byte value1, value2; for (int i = index; i < key.length && bitIndex < length; i++) { value1 = key[i]; value2 = otherId.key[i]; // A shot cut we can take... if (value1 == value2 && (bit == 0 || i != index)) { bitIndex += Byte.SIZE; continue; } for (int j = (i == index ? bit : 0); j < Byte.SIZE && bitIndex < length; j++) { mask = 0x80 >>> j; diff = (value1 & mask) - (value2 & mask); if (diff != 0) { return diff; } ++bitIndex; } } } return 0; } @Override public int hashCode() { return hashCode; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (!(obj instanceof KUID)) { return false; } KUID otherId = (KUID) obj; return Arrays.equals(key, otherId.key); } @Override public KUID clone() { return this; } @Override public int write(OutputStream out) throws IOException { if (out == null) { throw new NullArgumentException("out"); } out.write(key); return length(); } /** * Returns the {@link KUID}'s value as an {@link BigInteger} */ public BigInteger toBigInteger() { return new BigInteger(1 /* unsigned */, key); } /** * Returns the {@link KUID}'s value as a Base 16 (hex) encoded String. */ public String toHexString() { return CodingUtils.encodeBase16(key); } /** * Returns the {@link KUID}'s value as a Base 2 (bin) encoded String. */ public String toBinString() { return CodingUtils.encodeBase2(key); } @Override public String toString() { return toHexString(); //return toBinString(); } }
package dr.app.tracer.analysis; import dr.inference.trace.TraceDistribution; import dr.inference.trace.TraceList; import dr.stats.Variate; import jebl.evolution.coalescent.IntervalList; import jebl.evolution.coalescent.Intervals; import jebl.evolution.io.ImportException; import jebl.evolution.io.NewickImporter; import jebl.evolution.io.NexusImporter; import jebl.evolution.io.TreeImporter; import jebl.evolution.trees.RootedTree; import org.virion.jam.components.RealNumberField; import org.virion.jam.components.WholeNumberField; import org.virion.jam.framework.DocumentFrame; import org.virion.jam.panels.OptionsPanel; import org.virion.jam.util.LongTask; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.HashSet; import java.util.Set; public class BayesianSkylineDialog { private JFrame frame; private String[][] argumentGuesses = { {"populationsize", "population", "popsize"}, {"groupsize", "groups"}}; private String[] argumentNames = new String[]{ "Population Size", "Group Size" }; private final JButton button = new JButton("Choose File..."); private ActionListener buttonListener; private final JTextField fileNameText = new JTextField("not selected", 16); private File treeFile = null; private WholeNumberField binCountField; private String[] argumentTraces = new String[argumentNames.length]; private JComboBox[] argumentCombos = new JComboBox[argumentNames.length]; private JComboBox maxHeightCombo = new JComboBox(new String[]{ "Lower 95% HPD", "Median", "Mean", "Upper 95% HPD"}); private JComboBox rootHeightCombo; private JCheckBox manualRangeCheckBox; private RealNumberField minTimeField; private RealNumberField maxTimeField; private JComboBox changeTypeCombo = new JComboBox(new String[]{"Stepwise (Constant)", "Linear Change", "Exponential Change"}); private JCheckBox ratePlotCheck; private String rootHeightTrace = "None selected"; private RealNumberField ageOfYoungestField = new RealNumberField(); private OptionsPanel optionPanel; public BayesianSkylineDialog(JFrame frame) { this.frame = frame; for (int i = 0; i < argumentNames.length; i++) { argumentCombos[i] = new JComboBox(); argumentTraces[i] = "None selected"; } rootHeightCombo = new JComboBox(); binCountField = new WholeNumberField(2, 2000); binCountField.setValue(100); binCountField.setColumns(4); ratePlotCheck = new JCheckBox("Plot growth rate"); manualRangeCheckBox = new JCheckBox("Use manual range for bins:"); maxTimeField = new RealNumberField(0.0, Double.MAX_VALUE); maxTimeField.setColumns(12); minTimeField = new RealNumberField(0.0, Double.MAX_VALUE); minTimeField.setColumns(12); ageOfYoungestField.setValue(0.0); ageOfYoungestField.setColumns(12); optionPanel = new OptionsPanel(12, 12); } private int findArgument(JComboBox comboBox, String argument) { for (int i = 0; i < comboBox.getItemCount(); i++) { String item = ((String) comboBox.getItemAt(i)).toLowerCase(); if (item.indexOf(argument) != -1) return i; } return -1; } private String getNumericalSuffix(String argument) { int i = argument.length() - 1; if (i < 0) return ""; char ch = argument.charAt(i); if (!Character.isDigit(ch)) return ""; while (i > 0 && Character.isDigit(ch)) { i -= 1; ch = argument.charAt(i); } return argument.substring(i + 1, argument.length()); } private int getTraceRange(TraceList traceList, int first) { int i = 1; int k = first; String name = traceList.getTraceName(first); String root = name.substring(0, name.length() - 1); while (k < traceList.getTraceCount() && traceList.getTraceName(k).equals(root + i)) { i++; k++; } return i - 1; } public int showDialog(TraceList traceList, TemporalAnalysisFrame temporalAnalysisFrame) { Set<String> roots = new HashSet<String>(); for (int j = 0; j < traceList.getTraceCount(); j++) { String statistic = traceList.getTraceName(j); String suffix = getNumericalSuffix(statistic); if (suffix.equals("1")) { roots.add(statistic.substring(0, statistic.length() - 1)); } } if (roots.size() == 0) { JOptionPane.showMessageDialog(frame, "No traces found with a range of numerical suffixes (1-n).", "Probably not a Bayesian Skyline analysis", JOptionPane.ERROR_MESSAGE); return JOptionPane.CANCEL_OPTION; } for (int i = 0; i < argumentCombos.length; i++) { argumentCombos[i].removeAllItems(); for (String root : roots) { argumentCombos[i].addItem(root); } int index = findArgument(argumentCombos[i], argumentTraces[i]); for (int j = 0; j < argumentGuesses[i].length; j++) { if (index != -1) break; index = findArgument(argumentCombos[i], argumentGuesses[i][j]); } if (index == -1) index = 0; argumentCombos[i].setSelectedIndex(index); } setArguments(temporalAnalysisFrame); for (int j = 0; j < traceList.getTraceCount(); j++) { String statistic = traceList.getTraceName(j); rootHeightCombo.addItem(statistic); } int index = findArgument(rootHeightCombo, rootHeightTrace); if (index == -1) index = findArgument(rootHeightCombo, "root"); if (index == -1) index = findArgument(rootHeightCombo, "height"); if (index == -1) index = 0; rootHeightCombo.setSelectedIndex(index); final JOptionPane optionPane = new JOptionPane(optionPanel, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, null, null); optionPane.setBorder(new EmptyBorder(12, 12, 12, 12)); button.removeActionListener(buttonListener); buttonListener = new ActionListener() { public void actionPerformed(ActionEvent ae) { FileDialog dialog = new FileDialog(frame, "Open Trees Log File...", FileDialog.LOAD); dialog.setVisible(true); if (dialog.getFile() == null) { // the dialog was cancelled... return; } treeFile = new File(dialog.getDirectory(), dialog.getFile()); fileNameText.setText(treeFile.getName()); } }; button.addActionListener(buttonListener); final JDialog dialog = optionPane.createDialog(frame, "Bayesian Skyline Analysis"); dialog.pack(); int result = JOptionPane.CANCEL_OPTION; boolean done; do { done = true; dialog.setVisible(true); Integer value = (Integer) optionPane.getValue(); if (value != null && value != -1) { result = value; } if (result == JOptionPane.OK_OPTION) { if (treeFile == null) { JOptionPane.showMessageDialog(frame, "A tree file was not selected", "Error parsing file", JOptionPane.ERROR_MESSAGE); done = false; } else { for (int i = 0; i < argumentCombos.length; i++) { argumentTraces[i] = argumentCombos[i].getSelectedItem() + "1"; } rootHeightTrace = (String) rootHeightCombo.getSelectedItem(); } } } while (!done); return result; } private void setArguments(TemporalAnalysisFrame temporalAnalysisFrame) { optionPanel.removeAll(); JLabel label = new JLabel( "<html>Warning! This analysis should only be run on traces where<br>" + "the Bayesian Skyline plot was specified as the demographic in BEAST.<br>" + "<em>Any other model will produce meaningless results.</em></html>"); label.setFont(label.getFont().deriveFont(((float) label.getFont().getSize() - 2))); optionPanel.addSpanningComponent(label); optionPanel.addSeparator(); if (treeFile != null) { fileNameText.setText(treeFile.getName()); } fileNameText.setEditable(false); JPanel panel = new JPanel(new BorderLayout(0, 0)); panel.add(fileNameText, BorderLayout.CENTER); panel.add(button, BorderLayout.EAST); optionPanel.addComponentWithLabel("Trees Log File: ", panel); optionPanel.addSeparator(); optionPanel.addComponentWithLabel("Bayesian skyline variant: ", changeTypeCombo); optionPanel.addComponent(ratePlotCheck); ratePlotCheck.setEnabled(false); changeTypeCombo.addItemListener(new ItemListener() { public void itemStateChanged(final ItemEvent itemEvent) { if (changeTypeCombo.getSelectedIndex() > 0) { // not piecewise constant ratePlotCheck.setEnabled(true); } else { ratePlotCheck.setEnabled(false); } } }); optionPanel.addSeparator(); optionPanel.addLabel("Select the traces to use for the arguments:"); for (int i = 0; i < argumentNames.length; i++) { optionPanel.addComponentWithLabel(argumentNames[i] + ":", argumentCombos[i]); } optionPanel.addSeparator(); optionPanel.addComponentWithLabel("Maximum time is the root height's:", maxHeightCombo); optionPanel.addComponentWithLabel("Select the trace of the root height:", rootHeightCombo); if (temporalAnalysisFrame == null) { optionPanel.addSeparator(); optionPanel.addComponentWithLabel("Number of bins:", binCountField); optionPanel.addSpanningComponent(manualRangeCheckBox); final JLabel label1 = optionPanel.addComponentWithLabel("Minimum time:", minTimeField); final JLabel label2 = optionPanel.addComponentWithLabel("Maximum time:", maxTimeField); if (manualRangeCheckBox.isSelected()) { label1.setEnabled(true); minTimeField.setEnabled(true); label2.setEnabled(true); maxTimeField.setEnabled(true); } else { label1.setEnabled(false); minTimeField.setEnabled(false); label2.setEnabled(false); maxTimeField.setEnabled(false); } manualRangeCheckBox.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent changeEvent) { if (manualRangeCheckBox.isSelected()) { label1.setEnabled(true); minTimeField.setEnabled(true); label2.setEnabled(true); maxTimeField.setEnabled(true); } else { label1.setEnabled(false); minTimeField.setEnabled(false); label2.setEnabled(false); maxTimeField.setEnabled(false); } } }); } optionPanel.addSeparator(); optionPanel.addComponentWithLabel("Age of youngest tip:", ageOfYoungestField); JLabel label3 = new JLabel( "<html>You can set the age of sampling of the most recent tip in<br>" + "the tree. If this is set to zero then the plot is shown going<br>" + "backwards in time, otherwise forwards in time.</html>"); label3.setFont(label3.getFont().deriveFont(((float) label3.getFont().getSize() - 2))); optionPanel.addSpanningComponent(label3); } javax.swing.Timer timer = null; public void createBayesianSkylineFrame(TraceList traceList, DocumentFrame parent) { TemporalAnalysisFrame frame; int binCount = binCountField.getValue(); double minTime; double maxTime; boolean manualRange = manualRangeCheckBox.isSelected(); if (manualRange) { minTime = minTimeField.getValue(); maxTime = maxTimeField.getValue(); if (minTime >= maxTime) { JOptionPane.showMessageDialog(parent, "The minimum time value should be less than the maximum.", "Error creating Bayesian skyline", JOptionPane.ERROR_MESSAGE); return; } frame = new TemporalAnalysisFrame(parent, "", binCount, minTime, maxTime); } else { frame = new TemporalAnalysisFrame(parent, "", binCount); } frame.initialize(); addToTemporalAnalysis(traceList, frame); } public void addToTemporalAnalysis(TraceList traceList, TemporalAnalysisFrame frame) { int firstPopSize = traceList.getTraceIndex(argumentTraces[0]); int popSizeCount = getTraceRange(traceList, firstPopSize); int firstGroupSize = traceList.getTraceIndex(argumentTraces[1]); int groupSizeCount = getTraceRange(traceList, firstGroupSize); boolean isLinearOrExponential = changeTypeCombo.getSelectedIndex() > 0; if (isLinearOrExponential) { if (groupSizeCount != popSizeCount - 1) { JOptionPane.showMessageDialog(frame, "For the linear or exponential change Bayesian skyline model there should\n" + "one fewer group size than population size parameters. Either\n" + "this is a stepwise (constant) model or the wrong parameters\n" + "were specified. Please try again and check.", "Error creating Bayesian skyline", JOptionPane.ERROR_MESSAGE); return; } } else { if (groupSizeCount != popSizeCount) { JOptionPane.showMessageDialog(frame, "For the stepwise (constant) Bayesian skyline model there should\n" + "be the same number of group size as population size parameters. \n" + "Either this is a linear change model or the wrong parameters\n" + "were specified. Please try again and check.", "Error creating Bayesian skyline", JOptionPane.ERROR_MESSAGE); return; } } final AnalyseBayesianSkylineTask analyseTask = new AnalyseBayesianSkylineTask(traceList, treeFile, firstPopSize, popSizeCount, firstGroupSize, groupSizeCount, frame); final ProgressMonitor progressMonitor = new ProgressMonitor(frame, "Analysing Bayesian Skyline", "", 0, analyseTask.getLengthOfTask()); progressMonitor.setMillisToPopup(0); progressMonitor.setMillisToDecideToPopup(0); timer = new javax.swing.Timer(1000, new ActionListener() { public void actionPerformed(ActionEvent evt) { progressMonitor.setProgress(analyseTask.getCurrent()); if (progressMonitor.isCanceled() || analyseTask.done()) { progressMonitor.close(); analyseTask.stop(); timer.stop(); } } }); analyseTask.go(); timer.start(); } class AnalyseBayesianSkylineTask extends LongTask { TraceList traceList; TemporalAnalysisFrame frame; File treeFile; int firstPopSize; int firstGroupSize; int popSizeCount; int groupSizeCount; int binCount; boolean rangeSet; double minTime; double maxTime; double ageOfYoungest; int stateCount; double[][] popSizes; double[][] groupSizes; private int lengthOfTask = 0; private int current = 0; private boolean isLinearOrExponential; private boolean isExponential; private boolean isRatePlot; public AnalyseBayesianSkylineTask(TraceList traceList, File treeFile, int firstPopSize, int popSizeCount, int firstGroupSize, int groupSizeCount, TemporalAnalysisFrame frame) { this.traceList = traceList; this.frame = frame; this.treeFile = treeFile; this.firstPopSize = firstPopSize; this.firstGroupSize = firstGroupSize; this.popSizeCount = popSizeCount; this.groupSizeCount = groupSizeCount; this.binCount = frame.getBinCount(); this.rangeSet = frame.isRangeSet(); isLinearOrExponential = changeTypeCombo.getSelectedIndex() > 0; isExponential = changeTypeCombo.getSelectedIndex() > 1; isRatePlot = ratePlotCheck.isSelected(); ageOfYoungest = ageOfYoungestField.getValue(); lengthOfTask = traceList.getStateCount() + binCount; stateCount = traceList.getStateCount(); popSizes = new double[popSizeCount][stateCount]; for (int i = 0; i < popSizeCount; i++) { traceList.getValues(firstPopSize + i, popSizes[i]); } groupSizes = new double[groupSizeCount][stateCount]; for (int i = 0; i < groupSizeCount; i++) { traceList.getValues(firstGroupSize + i, groupSizes[i]); } } public int getCurrent() { return current; } public int getLengthOfTask() { return lengthOfTask; } public String getDescription() { return "Calculating Bayesian skyline..."; } public String getMessage() { return null; } public Object doWork() { double[] heights = new double[stateCount]; traceList.getValues(traceList.getTraceIndex(rootHeightTrace), heights); TraceDistribution distribution = new TraceDistribution(heights, traceList.getStepSize()); double timeMean = distribution.getMean(); double timeMedian = distribution.getMedian(); double timeUpper = distribution.getUpperHPD(); double timeLower = distribution.getLowerHPD(); double maxHeight = 0.0; switch (maxHeightCombo.getSelectedIndex()) { // setting a timeXXXX to -1 means that it won't be displayed... case 0: maxHeight = timeLower; break; case 1: maxHeight = timeMedian; break; case 2: maxHeight = timeMean; break; case 3: maxHeight = timeUpper; break; } if (rangeSet) { minTime = frame.getMinTime(); maxTime = frame.getMaxTime(); } else { if (ageOfYoungest > 0.0) { minTime = ageOfYoungest - maxHeight; maxTime = ageOfYoungest; } else { minTime = 0.0; maxTime = maxHeight - ageOfYoungest; } frame.setRange(minTime, maxTime); } if (ageOfYoungest > 0.0) { // reverse them if ageOfYoungest is set positive timeMean = ageOfYoungest - timeMean; timeMedian = ageOfYoungest - timeMedian; timeUpper = ageOfYoungest - timeUpper; timeLower = ageOfYoungest - timeLower; // setting a timeXXXX to -1 means that it won't be displayed... if (minTime >= timeLower) timeLower = -1; if (minTime >= timeMean) timeMean = -1; if (minTime >= timeMedian) timeMedian = -1; if (minTime >= timeUpper) timeUpper = -1; } else { // otherwise use use ageOfYoungest as an offset timeMean = timeMean - ageOfYoungest; timeMedian = timeMedian - ageOfYoungest; timeUpper = timeUpper - ageOfYoungest; timeLower = timeLower - ageOfYoungest; // setting a timeXXXX to -1 means that it won't be displayed... if (maxTime <= timeLower) timeLower = -1; if (maxTime <= timeMean) timeMean = -1; if (maxTime <= timeMedian) timeMedian = -1; if (maxTime <= timeUpper) timeUpper = -1; } double delta = (maxTime - minTime) / (binCount - 1); try { BufferedReader reader = new BufferedReader(new FileReader(treeFile)); String line = reader.readLine(); TreeImporter importer; if (line.toUpperCase().startsWith("#NEXUS")) { importer = new NexusImporter(reader); } else { importer = new NewickImporter(reader, false); } int burnin = traceList.getBurnIn(); int skip = burnin / traceList.getStepSize(); int state = 0; while (importer.hasTree() && state < skip) { importer.importNextTree(); state += 1; } int treeStateCount = state; if ((treeStateCount % stateCount != 0) && (stateCount % treeStateCount != 0)) { JOptionPane.showMessageDialog(frame, "The number of log state and tree state not match !", "Number Format Error", JOptionPane.ERROR_MESSAGE); } double[][] groupTimes; if (treeStateCount > stateCount) { // the age of the end of this group groupTimes = new double[treeStateCount][]; } else { // the age of the end of this group groupTimes = new double[stateCount][]; } //int treeState = 0; //int logState = 0; // increment treeState by 1 // increment logState by totalLogStates / totalTreeState //int tips = 0; state = 0; current = 0; try { while (importer.hasTree()) { RootedTree tree = (RootedTree) importer.importNextTree(); IntervalList intervals = new Intervals(tree); int intervalCount = intervals.getIntervalCount(); //tips = tree.getExternalNodes().size(); // get the coalescent intervales only groupTimes[state] = new double[groupSizeCount]; double totalTime = 0.0; int groupSize = 1; int groupIndex = 0; int subIndex = 0; if (firstGroupSize > 0) { double g = groupSizes[groupIndex][state]; if (g != Math.round(g)) { throw new RuntimeException("Group size " + groupIndex + " should be integer but found:" + g); } else groupSize = (int) Math.round(g); } for (int j = 0; j < intervalCount; j++) { totalTime += intervals.getInterval(j); if (intervals.getIntervalType(j) == IntervalList.IntervalType.COALESCENT) { subIndex += 1; if (subIndex == groupSize) { groupTimes[state][groupIndex] = totalTime; subIndex = 0; groupIndex += 1; if (groupIndex < groupSizeCount) { double g = groupSizes[groupIndex][state]; if (g != Math.round(g)) { throw new RuntimeException("Group size " + groupIndex + " should be integer but found:" + g); } else groupSize = (int) Math.round(g); } } } // insert zero-length coalescent intervals int diff = intervals.getCoalescentEvents(j) - 1; if (diff > 0) throw new RuntimeException("Don't handle multifurcations!"); } state += 1; current += 1; } } catch (ImportException ie) { JOptionPane.showMessageDialog(frame, "Error parsing file: " + ie.getMessage(), "Error parsing file", JOptionPane.ERROR_MESSAGE); } catch (Exception ex) { JOptionPane.showMessageDialog(frame, "Fatal exception during initializing group size:" + ex.getMessage(), "Fatal exception", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(System.out); } Variate[] bins = new Variate[binCount]; double height; if (ageOfYoungest > 0.0) { height = ageOfYoungest - maxTime; } else { height = ageOfYoungest; } for (int k = 0; k < binCount; k++) { bins[k] = new Variate.Double(); if (height >= 0.0 && height <= maxHeight) { for (state = 0; state < groupTimes.length;) { if (isLinearOrExponential) { double lastGroupTime = 0.0; int index = 0; while (index < groupTimes[state].length && groupTimes[state][index] < height) { lastGroupTime = groupTimes[state][index]; index += 1; } if (index < groupTimes[state].length - 1) { double t = (height - lastGroupTime) / (groupTimes[state][index] - lastGroupTime); if (isExponential) { // double p1 = Math.log(getPopSize(index, state)); // double p2 = Math.log(getPopSize(index + 1, state)); // if (isRatePlot) { // double rate = (p2 - p1) / (groupTimes[state][index] - lastGroupTime); // bins[k].add(Math.exp(rate)); // } else { // double popsize = p1 + ((p2 - p1) * t); // bins[k].add(Math.exp(popsize)); } else { double p1 = getPopSize(index, state); double p2 = getPopSize(index + 1, state); if (isRatePlot) { double rate = (Math.log(p1) - Math.log(p2)) / (groupTimes[state][index] - lastGroupTime); bins[k].add(rate); } else { double popsize = p1 + ((p2 - p1) * t); bins[k].add(popsize); } } } } else { int index = 0; while (index < groupTimes[state].length && groupTimes[state][index] < height) { index += 1; } if (index < groupTimes[state].length) { double popSize = getPopSize(index, state); if (popSize == 0.0) { throw new RuntimeException("Zero pop size"); } bins[k].add(popSize); } else { // Do we really want to do this? // bins[k].add(getPopSize(popSizeCount - 1,state)); } } if (treeStateCount > stateCount) { state += treeStateCount / stateCount; } else { state += stateCount / treeStateCount; } } } height += delta; current += 1; } Variate xData = new Variate.Double(); Variate yDataMean = new Variate.Double(); Variate yDataMedian = new Variate.Double(); Variate yDataUpper = new Variate.Double(); Variate yDataLower = new Variate.Double(); double t; if (ageOfYoungest > 0.0) { t = maxTime; } else { t = minTime; } for (Variate bin : bins) { xData.add(t); if (bin.getCount() > 0) { yDataMean.add(bin.getMean()); yDataMedian.add(bin.getQuantile(0.5)); yDataLower.add(bin.getQuantile(0.025)); yDataUpper.add(bin.getQuantile(0.975)); } else { yDataMean.add(Double.NaN); yDataMedian.add(Double.NaN); yDataLower.add(Double.NaN); yDataUpper.add(Double.NaN); } if (ageOfYoungest > 0.0) { t -= delta; } else { t += delta; } } frame.addDemographic("Bayesian Skyline: " + traceList.getName(), xData, yDataMean, yDataMedian, yDataUpper, yDataLower, timeMean, timeMedian, timeUpper, timeLower); } catch (java.io.IOException ioe) { JOptionPane.showMessageDialog(frame, "Error reading file: " + ioe.getMessage(), "Error reading file", JOptionPane.ERROR_MESSAGE); } catch (Exception ex) { JOptionPane.showMessageDialog(frame, "Fatal exception during plot:" + ex.getMessage(), "Fatal exception", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(System.out); } return null; } private double getPopSize(int index, int state) { return popSizes[index][state]; } } }
package org.openrdf.script.base; import junit.framework.TestCase; import org.openrdf.model.Value; import org.openrdf.repository.object.ObjectConnection; import org.openrdf.repository.object.ObjectRepository; import org.openrdf.repository.object.config.ObjectRepositoryFactory; import org.openrdf.repository.sail.SailRepository; import org.openrdf.sail.memory.MemoryStore; import org.openrdf.script.ScriptEngine; import org.openrdf.script.ScriptParser; import org.openrdf.script.ast.ParseException; import org.openrdf.script.ast.SyntaxTreeBuilder; import org.openrdf.script.ast.TokenMgrError; import org.openrdf.script.model.Body; import org.openrdf.store.StoreException; public abstract class ScriptTestCase extends TestCase { private ObjectConnection con; private ObjectRepository repository; @Override public void setUp() throws Exception { super.setUp(); ObjectRepositoryFactory factory = new ObjectRepositoryFactory(); SailRepository delegate = new SailRepository(new MemoryStore()); delegate.initialize(); repository = factory.createRepository(delegate); con = repository.getConnection(); } @Override public void tearDown() throws Exception { con.close(); repository.shutDown(); super.tearDown(); } public Object evaluateSingleObject(String code) throws TokenMgrError, ParseException, StoreException { return con.getObject(evaluateSingleValue(code)); } public Value evaluateSingleValue(String code) throws TokenMgrError, ParseException, StoreException { return new ScriptEngine(repository).evalSingleValue(code); } public void evaluate(String code) throws TokenMgrError, ParseException, StoreException { SyntaxTreeBuilder.parse(code).dump(""); Body body = new ScriptParser().parse(code); System.out.println(body.toString()); } }
package dr.app.tracer.analysis; import org.virion.jam.framework.AuxilaryFrame; import org.virion.jam.framework.DocumentFrame; import dr.util.Variate; import dr.app.tracer.application.TracerFileMenuHandler; import javax.swing.*; import java.awt.*; import java.awt.geom.Rectangle2D; import java.awt.event.ActionEvent; import java.io.*; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.pdf.*; public class TemporalAnalysisFrame extends AuxilaryFrame implements TracerFileMenuHandler { private int binCount; private double minTime; private double maxTime; private boolean rangeSet; TemporalAnalysisPlotPanel temporalAnalysisPlotPanel = null; public TemporalAnalysisFrame(DocumentFrame frame, String title, int binCount) { this(frame, title, binCount, 0.0, 0.0); rangeSet = false; } public TemporalAnalysisFrame(DocumentFrame frame, String title, int binCount, double minTime, double maxTime) { super(frame); setTitle(title); this.binCount = binCount; this.minTime = minTime; this.maxTime = maxTime; rangeSet = true; temporalAnalysisPlotPanel = new TemporalAnalysisPlotPanel(this); setContentsPanel(temporalAnalysisPlotPanel); getSaveAction().setEnabled(false); getSaveAsAction().setEnabled(false); getCutAction().setEnabled(false); getCopyAction().setEnabled(true); getPasteAction().setEnabled(false); getDeleteAction().setEnabled(false); getSelectAllAction().setEnabled(false); getFindAction().setEnabled(false); getZoomWindowAction().setEnabled(false); } public void initializeComponents() { setSize(new java.awt.Dimension(640, 480)); } public void addDemographic(String title, Variate xData, Variate yDataMean, Variate yDataMedian, Variate yDataUpper, Variate yDataLower, double timeMean, double timeMedian, double timeUpper, double timeLower) { if (!rangeSet) { throw new RuntimeException("Range not set"); } if (getTitle().length() == 0) { setTitle(title); } temporalAnalysisPlotPanel.addDemographicPlot(title, xData, yDataMean, yDataMedian, yDataUpper, yDataLower, timeMean, timeMedian, timeUpper, timeLower); setVisible(true); } public void addDensity(String title, Variate xData, Variate yData) { if (!rangeSet) { throw new RuntimeException("Range not set"); } temporalAnalysisPlotPanel.addDensityPlot(title, xData, yData); setVisible(true); } public boolean useExportAction() { return true; } public JComponent getExportableComponent() { return temporalAnalysisPlotPanel.getExportableComponent(); } public void doCopy() { java.awt.datatransfer.Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); java.awt.datatransfer.StringSelection selection = new java.awt.datatransfer.StringSelection(this.toString()); clipboard.setContents(selection, selection); } public int getBinCount() { return binCount; } public double getMinTime() { if (!rangeSet) { throw new RuntimeException("Range not set"); } return minTime; } public double getMaxTime() { if (!rangeSet) { throw new RuntimeException("Range not set"); } return maxTime; } public void setRange(double minTime, double maxTime) { if (rangeSet) { throw new RuntimeException("Range already set"); } this.minTime = minTime; this.maxTime = maxTime; rangeSet = true; } public boolean isRangeSet() { return rangeSet; } public final void doExportData() { FileDialog dialog = new FileDialog(this, "Export Data...", FileDialog.SAVE); dialog.setVisible(true); if (dialog.getFile() != null) { File file = new File(dialog.getDirectory(), dialog.getFile()); try { FileWriter writer = new FileWriter(file); writer.write(toString()); writer.close(); } catch (IOException ioe) { JOptionPane.showMessageDialog(this, "Unable to write file: " + ioe, "Unable to write file", JOptionPane.ERROR_MESSAGE); } } } public final void doExportPDF() { FileDialog dialog = new FileDialog(this, "Export PDF Image...", FileDialog.SAVE); dialog.setVisible(true); if (dialog.getFile() != null) { File file = new File(dialog.getDirectory(), dialog.getFile()); Rectangle2D bounds = temporalAnalysisPlotPanel.getExportableComponent().getBounds(); Document document = new Document(new com.lowagie.text.Rectangle((float)bounds.getWidth(), (float)bounds.getHeight())); try { // step 2 PdfWriter writer; writer = PdfWriter.getInstance(document, new FileOutputStream(file)); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate((float)bounds.getWidth(), (float)bounds.getHeight()); Graphics2D g2d = tp.createGraphics((float)bounds.getWidth(), (float)bounds.getHeight(), new DefaultFontMapper()); temporalAnalysisPlotPanel.getExportableComponent().print(g2d); g2d.dispose(); cb.addTemplate(tp, 0, 0); } catch(DocumentException de) { JOptionPane.showMessageDialog(this, "Error writing PDF file: " + de, "Export PDF Error", JOptionPane.ERROR_MESSAGE); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(this, "Error writing PDF file: " + e, "Export PDF Error", JOptionPane.ERROR_MESSAGE); } document.close(); } } public String toString() { StringBuffer buffer = new StringBuffer(); java.util.List<TemporalAnalysisPlotPanel.AnalysisData> analyses = temporalAnalysisPlotPanel.getAnalysisData(); buffer.append("Time"); for (TemporalAnalysisPlotPanel.AnalysisData analysis : analyses) { if (analysis.isDemographic) { buffer.append("\t").append(analysis.title).append("\tMedian\tUpper\tLower"); } else { buffer.append("\t").append(analysis.title); } } buffer.append("\n"); Variate timeScale = temporalAnalysisPlotPanel.getTimeScale(); for (int i = 0; i < timeScale.getCount(); i++) { buffer.append(String.valueOf(timeScale.get(i))); for (TemporalAnalysisPlotPanel.AnalysisData analysis : analyses) { if (analysis.isDemographic) { buffer.append("\t"); buffer.append(String.valueOf(analysis.yDataMean.get(i))); buffer.append("\t"); buffer.append(String.valueOf(analysis.yDataMedian.get(i))); buffer.append("\t"); buffer.append(String.valueOf(analysis.yDataUpper.get(i))); buffer.append("\t"); buffer.append(String.valueOf(analysis.yDataLower.get(i))); } else { buffer.append("\t"); buffer.append(String.valueOf(analysis.yDataMean.get(i))); } } buffer.append("\n"); } return buffer.toString(); } public Action getExportDataAction() { return exportDataAction; } public Action getExportPDFAction() { return exportPDFAction; } private AbstractAction exportDataAction = new AbstractAction("Export Data...") { public void actionPerformed(ActionEvent ae) { doExportData(); } }; private AbstractAction exportPDFAction = new AbstractAction("Export PDF...") { public void actionPerformed(ActionEvent ae) { doExportPDF(); } }; }
package dr.evomodel.coalescent; import dr.evolution.coalescent.IntervalType; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evomodel.tree.TreeModel; import dr.evomodelxml.coalescent.GMRFSkyrideLikelihoodParser; import dr.inference.model.MatrixParameter; import dr.inference.model.Parameter; import dr.inference.model.Variable; import dr.math.MathUtils; import dr.util.Author; import dr.util.Citable; import dr.util.Citation; import no.uib.cipr.matrix.DenseVector; import no.uib.cipr.matrix.NotConvergedException; import no.uib.cipr.matrix.SymmTridiagEVD; import no.uib.cipr.matrix.SymmTridiagMatrix; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * A likelihood function for a Gaussian Markov random field on a log population size trajectory. * * @author Jen Tom * @author Erik Bloomquist * @author Vladimir Minin * @author Marc Suchard * @version $Id: GMRFSkylineLikelihood.java,v 1.3 2007/03/20 22:40:04 msuchard Exp $ */ public class GMRFSkyrideLikelihood extends OldAbstractCoalescentLikelihood implements CoalescentIntervalProvider, Citable { // PUBLIC STUFF public static final double LOG_TWO_TIMES_PI = 1.837877; public static final boolean TIME_AWARE_IS_ON_BY_DEFAULT = true; // PRIVATE STUFF protected Parameter popSizeParameter; protected Parameter groupSizeParameter; protected Parameter precisionParameter; protected Parameter lambdaParameter; protected Parameter betaParameter; // protected double[] gmrfWeights; protected int fieldLength; // protected double[] coalescentIntervals; // protected double[] storedCoalescentIntervals; // protected double[] sufficientStatistics; // protected double[] storedSufficientStatistics; protected Parameter coalescentIntervals; protected Parameter storedCoalescentIntervals; protected Parameter sufficientStatistics; protected Parameter storedSufficientStatistics; //changed from private to protected protected double logFieldLikelihood; protected double storedLogFieldLikelihood; protected SymmTridiagMatrix weightMatrix; protected SymmTridiagMatrix storedWeightMatrix; protected MatrixParameter dMatrix; protected boolean timeAwareSmoothing = TIME_AWARE_IS_ON_BY_DEFAULT; protected boolean rescaleByRootHeight; public GMRFSkyrideLikelihood() { super(GMRFSkyrideLikelihoodParser.SKYLINE_LIKELIHOOD); } public GMRFSkyrideLikelihood(String name) { super(name); } public GMRFSkyrideLikelihood(Tree tree, Parameter popParameter, Parameter groupParameter, Parameter precParameter, Parameter lambda, Parameter beta, MatrixParameter dMatrix, boolean timeAwareSmoothing, boolean rescaleByRootHeight) { this(wrapTree(tree), popParameter, groupParameter, precParameter, lambda, beta, dMatrix, timeAwareSmoothing, rescaleByRootHeight); } private static List<Tree> wrapTree(Tree tree) { List<Tree> treeList = new ArrayList<Tree>(); treeList.add(tree); return treeList; } public GMRFSkyrideLikelihood(List<Tree> treeList, Parameter popParameter, Parameter groupParameter, Parameter precParameter, Parameter lambda, Parameter beta, MatrixParameter dMatrix, boolean timeAwareSmoothing, boolean rescaleByRootHeight) { super(GMRFSkyrideLikelihoodParser.SKYLINE_LIKELIHOOD); // adding the key word to the the model means the keyword will be logged in the // header of the logfile. this.addKeyword("skyride"); this.popSizeParameter = popParameter; this.groupSizeParameter = groupParameter; this.precisionParameter = precParameter; this.lambdaParameter = lambda; this.betaParameter = beta; this.dMatrix = dMatrix; this.timeAwareSmoothing = timeAwareSmoothing; this.rescaleByRootHeight = rescaleByRootHeight; addVariable(popSizeParameter); addVariable(precisionParameter); addVariable(lambdaParameter); if (betaParameter != null) { addVariable(betaParameter); } setTree(treeList); int correctFieldLength = getCorrectFieldLength(); if (popSizeParameter.getDimension() <= 1) { // popSize dimension hasn't been set yet, set it here: popSizeParameter.setDimension(correctFieldLength); } fieldLength = popSizeParameter.getDimension(); if (correctFieldLength != fieldLength) { throw new IllegalArgumentException("Population size parameter should have length " + correctFieldLength); } // Field length must be set by this point wrapSetupIntervals(); // coalescentIntervals = new double[fieldLength]; // storedCoalescentIntervals = new double[fieldLength]; // sufficientStatistics = new double[fieldLength]; // storedSufficientStatistics = new double[fieldLength]; coalescentIntervals = new Parameter.Default(fieldLength); storedCoalescentIntervals = new Parameter.Default(fieldLength); sufficientStatistics = new Parameter.Default(fieldLength); storedSufficientStatistics = new Parameter.Default(fieldLength); setupGMRFWeights(); addStatistic(new DeltaStatistic()); initializationReport(); /* Force all entries in groupSizeParameter = 1 for compatibility with Tracer */ if (groupSizeParameter != null) { for (int i = 0; i < groupSizeParameter.getDimension(); i++) groupSizeParameter.setParameterValue(i, 1.0); } } protected int getCorrectFieldLength() { return tree.getExternalNodeCount() - 1; } protected void wrapSetupIntervals() { setupIntervals(); } protected void setTree(List<Tree> treeList) { if (treeList.size() != 1) { throw new RuntimeException("GMRFSkyrideLikelihood only implemented for one tree"); } this.tree = treeList.get(0); this.treesSet = null; if (tree instanceof TreeModel) { addModel((TreeModel) tree); } } // public double[] getCopyOfCoalescentIntervals() { // return coalescentIntervals.clone(); // public double[] getCoalescentIntervals() { // return coalescentIntervals; public void initializationReport() { System.out.println("Creating a GMRF smoothed skyride model:"); System.out.println("\tPopulation sizes: " + popSizeParameter.getDimension()); System.out.println("\tIf you publish results using this model, please reference: Minin, Bloomquist and Suchard (2008) Molecular Biology and Evolution, 25, 1459-1471."); } public static void checkTree(TreeModel treeModel) { // todo Should only be run if there exists a zero-length interval // TreeModel treeModel = (TreeModel) tree; for (int i = 0; i < treeModel.getInternalNodeCount(); i++) { NodeRef node = treeModel.getInternalNode(i); if (node != treeModel.getRoot()) { double parentHeight = treeModel.getNodeHeight(treeModel.getParent(node)); double childHeight0 = treeModel.getNodeHeight(treeModel.getChild(node, 0)); double childHeight1 = treeModel.getNodeHeight(treeModel.getChild(node, 1)); double maxChild = childHeight0; if (childHeight1 > maxChild) maxChild = childHeight1; double newHeight = maxChild + MathUtils.nextDouble() * (parentHeight - maxChild); treeModel.setNodeHeight(node, newHeight); } } treeModel.pushTreeChangedEvent(); } // Likelihood IMPLEMENTATION public double getLogLikelihood() { if (!likelihoodKnown) { logLikelihood = calculateLogCoalescentLikelihood(); logFieldLikelihood = calculateLogFieldLikelihood(); likelihoodKnown = true; } return logLikelihood + logFieldLikelihood; } protected double peakLogCoalescentLikelihood() { return logLikelihood; } protected double peakLogFieldLikelihood() { return logFieldLikelihood; } public double[] getSufficientStatistics() { return sufficientStatistics.getParameterValues(); } public String toString() { return getId() + "(" + Double.toString(getLogLikelihood()) + ")"; } protected void setupSufficientStatistics() { int index = 0; double length = 0; double weight = 0; for (int i = 0; i < getIntervalCount(); i++) { length += getInterval(i); weight += getInterval(i) * getLineageCount(i) * (getLineageCount(i) - 1); if (getIntervalType(i) == CoalescentEventType.COALESCENT) { coalescentIntervals.setParameterValue(index, length); sufficientStatistics.setParameterValue(index, weight / 2.0); index++; length = 0; weight = 0; } } } protected double getFieldScalar() { final double rootHeight; if (rescaleByRootHeight) { rootHeight = tree.getNodeHeight(tree.getRoot()); } else { rootHeight = 1.0; } return rootHeight; } protected void setupGMRFWeights() { setupSufficientStatistics(); //Set up the weight Matrix double[] offdiag = new double[fieldLength - 1]; double[] diag = new double[fieldLength]; //First set up the offdiagonal entries; if (!timeAwareSmoothing) { for (int i = 0; i < fieldLength - 1; i++) { offdiag[i] = -1.0; } } else { for (int i = 0; i < fieldLength - 1; i++) { offdiag[i] = -2.0 / (coalescentIntervals.getParameterValue(i) + coalescentIntervals.getParameterValue(i + 1)) * getFieldScalar(); } } //Then set up the diagonal entries; for (int i = 1; i < fieldLength - 1; i++) diag[i] = -(offdiag[i] + offdiag[i - 1]); //Take care of the endpoints diag[0] = -offdiag[0]; diag[fieldLength - 1] = -offdiag[fieldLength - 2]; weightMatrix = new SymmTridiagMatrix(diag, offdiag); } public SymmTridiagMatrix getScaledWeightMatrix(double precision) { SymmTridiagMatrix a = weightMatrix.copy(); for (int i = 0; i < a.numRows() - 1; i++) { a.set(i, i, a.get(i, i) * precision); a.set(i + 1, i, a.get(i + 1, i) * precision); } a.set(fieldLength - 1, fieldLength - 1, a.get(fieldLength - 1, fieldLength - 1) * precision); return a; } public SymmTridiagMatrix getStoredScaledWeightMatrix(double precision) { SymmTridiagMatrix a = storedWeightMatrix.copy(); for (int i = 0; i < a.numRows() - 1; i++) { a.set(i, i, a.get(i, i) * precision); a.set(i + 1, i, a.get(i + 1, i) * precision); } a.set(fieldLength - 1, fieldLength - 1, a.get(fieldLength - 1, fieldLength - 1) * precision); return a; } public SymmTridiagMatrix getScaledWeightMatrix(double precision, double lambda) { if (lambda == 1) return getScaledWeightMatrix(precision); SymmTridiagMatrix a = weightMatrix.copy(); for (int i = 0; i < a.numRows() - 1; i++) { a.set(i, i, precision * (1 - lambda + lambda * a.get(i, i))); a.set(i + 1, i, a.get(i + 1, i) * precision * lambda); } a.set(fieldLength - 1, fieldLength - 1, precision * (1 - lambda + lambda * a.get(fieldLength - 1, fieldLength - 1))); return a; } private void makeIntervalsKnown() { if (!intervalsKnown) { wrapSetupIntervals(); setupGMRFWeights(); intervalsKnown = true; } } public int getCoalescentIntervalDimension() { makeIntervalsKnown(); return coalescentIntervals.getDimension(); } public double getCoalescentInterval(int i) { makeIntervalsKnown(); return coalescentIntervals.getParameterValue(i); } /*public int getCoalescentIntervalLineageCount(int i) { throw new RuntimeException("Not yet implemented"); } public IntervalType getCoalescentIntervalType(int i) { throw new RuntimeException("getCoalescentIntervalType(int i) in GMRFSkyrideLikelihood not yet implemented"); }*/ public int getNumberOfCoalescentEvents() { return tree.getExternalNodeCount() - 1; } public double getCoalescentEventsStatisticValue(int i) { return sufficientStatistics.getParameterValue(i); } @Override public void setupCoalescentIntervals() { setupIntervals(); setupSufficientStatistics(); } public double[] getCoalescentIntervalHeights() { makeIntervalsKnown(); double[] a = new double[coalescentIntervals.getDimension()]; a[0] = coalescentIntervals.getParameterValue(0); for (int i = 1; i < a.length; i++) { a[i] = a[i - 1] + coalescentIntervals.getParameterValue(i); } return a; } public SymmTridiagMatrix getCopyWeightMatrix() { return weightMatrix.copy(); } public SymmTridiagMatrix getStoredScaledWeightMatrix(double precision, double lambda) { if (lambda == 1) return getStoredScaledWeightMatrix(precision); SymmTridiagMatrix a = storedWeightMatrix.copy(); for (int i = 0; i < a.numRows() - 1; i++) { a.set(i, i, precision * (1 - lambda + lambda * a.get(i, i))); a.set(i + 1, i, a.get(i + 1, i) * precision * lambda); } a.set(fieldLength - 1, fieldLength - 1, precision * (1 - lambda + lambda * a.get(fieldLength - 1, fieldLength - 1))); return a; } protected void storeState() { super.storeState(); // System.arraycopy(coalescentIntervals, 0, storedCoalescentIntervals, 0, coalescentIntervals.length); // System.arraycopy(sufficientStatistics, 0, storedSufficientStatistics, 0, sufficientStatistics.length); for (int i = 0; i < coalescentIntervals.getDimension(); i++) { storedCoalescentIntervals.setParameterValueQuietly(i, coalescentIntervals.getParameterValue(i)); storedSufficientStatistics.setParameterValueQuietly(i, sufficientStatistics.getParameterValue(i)); } storedCoalescentIntervals.fireParameterChangedEvent(-1, Parameter.ChangeType.ALL_VALUES_CHANGED); storedSufficientStatistics.fireParameterChangedEvent(-1, Parameter.ChangeType.ALL_VALUES_CHANGED); storedWeightMatrix = weightMatrix.copy(); storedLogFieldLikelihood = logFieldLikelihood; } protected void restoreState() { super.restoreState(); // TODO Just swap pointers XJ: there you go // System.arraycopy(storedCoalescentIntervals, 0, coalescentIntervals, 0, storedCoalescentIntervals.length); // System.arraycopy(storedSufficientStatistics, 0, sufficientStatistics, 0, storedSufficientStatistics.length); Parameter tmp = coalescentIntervals; coalescentIntervals = storedCoalescentIntervals; storedCoalescentIntervals = tmp; tmp = sufficientStatistics; sufficientStatistics = storedSufficientStatistics; storedSufficientStatistics = tmp; weightMatrix = storedWeightMatrix; logFieldLikelihood = storedLogFieldLikelihood; } protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { likelihoodKnown = false; // Parameters (precision and popsizes do not change intervals or GMRF Q matrix } /** * Calculates the log likelihood of this set of coalescent intervals, * given a demographic model. * * @return coalescent part of density */ protected double calculateLogCoalescentLikelihood() { makeIntervalsKnown(); // Matrix operations taken from block update sampler to calculate data likelihood and field prior double currentLike = 0; double[] currentGamma = popSizeParameter.getParameterValues(); for (int i = 0; i < fieldLength; i++) { currentLike += -currentGamma[i] - sufficientStatistics.getParameterValue(i) * Math.exp(-currentGamma[i]); } return currentLike;// + LogNormalDistribution.logPdf(Math.exp(popSizeParameter.getParameterValue(coalescentIntervals.length - 1)), mu, sigma); } protected double calculateLogFieldLikelihood() { makeIntervalsKnown(); double currentLike = 0; DenseVector diagonal1 = new DenseVector(fieldLength); DenseVector currentGamma = new DenseVector(popSizeParameter.getParameterValues()); SymmTridiagMatrix currentQ = getScaledWeightMatrix(precisionParameter.getParameterValue(0), lambdaParameter.getParameterValue(0)); currentQ.mult(currentGamma, diagonal1); // currentLike += 0.5 * logGeneralizedDeterminant(currentQ) - 0.5 * currentGamma.dot(diagonal1); currentLike += 0.5 * (fieldLength - 1) * Math.log(precisionParameter.getParameterValue(0)) - 0.5 * currentGamma.dot(diagonal1); if (lambdaParameter.getParameterValue(0) == 1) { currentLike -= (fieldLength - 1) / 2.0 * LOG_TWO_TIMES_PI; } else { currentLike -= fieldLength / 2.0 * LOG_TWO_TIMES_PI; } return currentLike; } // public static double logGeneralizedDeterminant(SymmTridiagMatrix X) { // //Set up the eigenvalue solver // SymmTridiagEVD eigen = new SymmTridiagEVD(X.numRows(), false); // //Solve for the eigenvalues // try { // eigen.factor(X); // } catch (NotConvergedException e) { // throw new RuntimeException("Not converged error in generalized determinate calculation.\n" + e.getMessage()); // //Get the eigenvalues // double[] x = eigen.getEigenvalues(); // double a = 0; // for (double d : x) { // if (d > 0.00001) // a += Math.log(d); // return a; public Parameter getPrecisionParameter() { return precisionParameter; } public Parameter getPopSizeParameter() { return popSizeParameter; } public Parameter getLambdaParameter() { return lambdaParameter; } public SymmTridiagMatrix getWeightMatrix() { return weightMatrix.copy(); } public Parameter getBetaParameter() { return betaParameter; } public Parameter getCoalescentIntervals() { return coalescentIntervals; } public MatrixParameter getDesignMatrix() { return dMatrix; } public double calculateWeightedSSE() { double weightedSSE = 0; double currentPopSize = popSizeParameter.getParameterValue(0); double currentInterval = coalescentIntervals.getParameterValue(0); for (int j = 1; j < fieldLength; j++) { double nextPopSize = popSizeParameter.getParameterValue(j); double nextInterval = coalescentIntervals.getParameterValue(j); double delta = nextPopSize - currentPopSize; double weight = (currentInterval + nextInterval) / 2.0; weightedSSE += delta * delta / weight; currentPopSize = nextPopSize; currentInterval = nextInterval; } return weightedSSE; } @Override public Citation.Category getCategory() { return Citation.Category.TREE_PRIORS; } @Override public String getDescription() { return "Skyride coalescent"; } @Override public List<Citation> getCitations() { return Collections.singletonList(CITATION); } public static Citation CITATION = new Citation( new Author[]{ new Author("VN", "Minin"), new Author("EW", "Bloomquist"), new Author("MA", "Suchard") }, "Smooth skyride through a rough skyline: Bayesian coalescent-based inference of population dynamics", 2008, "Mol Biol Evol", 25, 1459, 1471, "10.1093/molbev/msn090" ); } /* WinBUGS code to fixed tree: (A:4.0,(B:2.0,(C:0.5,D:1.0):1.0):2.0) model { stat1 ~ dexp(rate[1]) stat2 ~ dexp(rate[2]) stat3 ~ dexp(rate[3]) rate[1] <- 1 / exp(theta[1]) rate[2] <- 1 / exp(theta[2]) rate[3] <- 1 / exp(theta[3]) theta[1] ~ dnorm(0, 0.001) theta[2] ~ dnorm(theta[1], weight[1]) theta[3] ~ dnorm(theta[2], weight[2]) weight[1] <- tau / 1.0 weight[2] <- tau / 1.5 tau ~ dgamma(1,0.3333) stat1 <- 9 / 2 stat2 <- 6 / 2 stat3 <- 4 / 2 } */
package edu.wheaton.simulator.gui.screen; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ScrollPaneConstants; import com.google.common.collect.ImmutableMap; import edu.wheaton.simulator.gui.BoxLayoutAxis; import edu.wheaton.simulator.gui.Gui; import edu.wheaton.simulator.gui.MaxSize; import edu.wheaton.simulator.gui.MinSize; import edu.wheaton.simulator.gui.PrefSize; import edu.wheaton.simulator.gui.SimulatorFacade; //TODO add elements for step delay public class SetupScreen extends Screen { private JTextField nameField; private JTextField timeField; private JTextField widthField; private JTextField heightField; private JTextField delayField; private String[] agentNames; private JComboBox updateBox; private ArrayList<JComboBox> agentTypes; private ArrayList<JTextField> values; private ArrayList<JButton> deleteButtons; private ArrayList<JPanel> subPanels; private JScrollPane scrollPane; private JPanel conListPanel; private JButton addConditionButton; private static final long serialVersionUID = -8347080877399964861L; public SetupScreen(final SimulatorFacade gm) { super(gm); agentNames = new String[0]; agentTypes = new ArrayList<JComboBox>(); deleteButtons = new ArrayList<JButton>(); subPanels = new ArrayList<JPanel>(); agentTypes = new ArrayList<JComboBox>(); values = new ArrayList<JTextField>(); JPanel upperPanel = makeUpperPanel(); upperPanel.setMinimumSize(new MinSize(300,140)); JPanel lowerPanel = makeLowerPanel(); lowerPanel.setMinimumSize(new MinSize(398,300)); addConditionButton = Gui.makeButton("Add Field", null, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { addCondition(); } }); JPanel bottomButtons = Gui.makePanel( Gui.makeButton("Revert", null, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { load(); } }), makeConfirmButton(),addConditionButton); JPanel mainPanel = Gui.makePanel(new GridBagLayout(), MaxSize.NULL, null, (Component[])null); GridBagConstraints c = new GridBagConstraints(); c.gridy = 0; mainPanel.add(upperPanel,c); c = new GridBagConstraints(); c.gridy = 1; c.insets = new Insets(0,50,0,15); mainPanel.add(lowerPanel,c); c = new GridBagConstraints(); c.gridy = 2; mainPanel.add(Gui.makePanel(bottomButtons),c); this.add(mainPanel); validate(); } private JButton makeConfirmButton() { return Gui.makeButton("Confirm", null, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { SimulatorFacade gm = getGuiManager(); int newWidth = Integer.parseInt(widthField.getText()); int newHeight = Integer.parseInt(widthField.getText()); int newTime = Integer.parseInt(timeField.getText()); int newDelay = Integer.parseInt(delayField.getText()); if (newWidth <= 0 || newHeight <= 0 || newTime <= 0 || newDelay < 0) throw new NumberFormatException(); if (newWidth < gm.getGridWidth() || newHeight < gm.getGridHeight()) { int selection = JOptionPane .showConfirmDialog( null, "The new grid size you provided" + "\nis smaller than its current value." + "\nThis may result in the deletion of objects placed in the grid that" + "\ncannot fit within these new dimensions." + "\nFurthermore, agent data that depended on specific coordinates may" + "\nneed to be checked for bugs after resizing." + "\n\nIf you are sure you want to apply these changes, click 'Ok', otherwise click 'No' or 'Cancel'"); if (selection == JOptionPane.YES_OPTION) gm.resizeGrid(newWidth, newHeight); else return; } if (nameField.getText().equals("")) throw new Exception("All fields must have input"); gm.setName(nameField.getText()); for (int i = 0; i < values.size(); i++) if (values.get(i).getText().equals("")) throw new Exception("All fields must have input."); gm.resizeGrid(newWidth, newHeight); gm.setStepLimit(newTime); gm.setSleepPeriod(newDelay); String str = (String) updateBox.getSelectedItem(); if (str.equals("Linear")) gm.setLinearUpdate(); else if (str.equals("Atomic")) gm.setAtomicUpdate(); else gm.setPriorityUpdate(0, 50); for (int i = 0; i < values.size(); i++) { gm.setPopLimit( (String) (agentTypes.get(i).getSelectedItem()), Integer.parseInt(values.get(i).getText())); } load(); } catch (NumberFormatException excep) { JOptionPane .showMessageDialog(null, "Width and Height fields must be integers greater than 0. Time delay must not be less than 0."); } catch (Exception excep) { JOptionPane.showMessageDialog(null, excep.getMessage()); } } }); } @Override public void load() { reset(); nameField.setText(getGuiManager().getSimName()); updateBox.setSelectedItem(getGuiManager().getCurrentUpdater()); widthField.setText(gm.getGridWidth().toString()); heightField.setText(gm.getGridHeight().toString()); delayField.setText(gm.getSleepPeriod().toString()); SimulatorFacade gm = getGuiManager(); int stepLimit = gm.getStepLimit(); agentNames = gm.getPrototypeNames().toArray(agentNames); timeField.setText(stepLimit + ""); // to prevent accidental starting simulation with time limit of 0 if (stepLimit <= 0) timeField.setText(10 + ""); ImmutableMap<String, Integer> popLimits = gm.getPopLimits(); if (popLimits.size() == 0) { addConditionButton.setEnabled(true); } else { int i = 0; for (String p : popLimits.keySet()) { addCondition(); agentTypes.get(i).setSelectedItem(p); values.get(i).setText(popLimits.get(p) + ""); i++; } } validate(); } private JPanel makeUpperPanel() { JPanel upperPanel = Gui.makePanel(new GridBagLayout(), MaxSize.NULL, PrefSize.NULL, (Component[]) null); JLabel nameLabel = Gui.makeLabel("Name:", new MinSize(50,30)); nameField = Gui.makeTextField(gm.getSimName(), 25, null, new MinSize(150,30)); JLabel widthLabel = Gui.makeLabel("Width:", new MinSize(50,30)); widthField = Gui.makeTextField("10", 5, MaxSize.NULL, new MinSize(50,30)); JLabel yLabel = Gui.makeLabel("Height:", new MinSize(70,30)); heightField = Gui.makeTextField("10", 5, MaxSize.NULL, new MinSize(50,30)); JLabel updateLabel = Gui.makeLabel("Update type:", MaxSize.NULL, null); updateBox = Gui.makeComboBox(new String[] { "Linear", "Atomic", "Priority" }, MaxSize.NULL); updateBox.setMinimumSize(new MinSize(150,30)); //TODO working on adding step delay components JLabel delayLabel = Gui.makeLabel("Step delay (ms):", MaxSize.NULL, null); delayField = Gui.makeTextField("1.0", 5, MaxSize.NULL, new MinSize(150,30)); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(nameLabel, c); c = new GridBagConstraints(); c.gridx = 1; c.gridy = 0; c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(nameField, c); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 1; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(widthLabel, c); c = new GridBagConstraints(); c.gridx = 1; c.gridy = 1; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(widthField, c); c = new GridBagConstraints(); c.gridx = 2; c.gridy = 1; c.insets = new Insets(3, 13, 3, 3); upperPanel.add(yLabel, c); c = new GridBagConstraints(); c.gridx = 3; c.gridy = 1; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(heightField, c); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 2; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(delayLabel, c); c = new GridBagConstraints(); c.gridx = 1; c.gridy = 2; c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(delayField, c); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 3; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(updateLabel, c); c = new GridBagConstraints(); c.gridx = 1; c.gridy = 3; c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(updateBox, c); validate(); return upperPanel; } private JPanel makeLowerPanel() { JPanel lowerPanel = Gui.makePanel(new GridBagLayout(), MaxSize.NULL, PrefSize.NULL, (Component[]) null); JLabel conHeader = Gui.makeLabel("Ending Conditions", MaxSize.NULL, null); JLabel timeLabel = Gui.makeLabel("Max steps:", MaxSize.NULL, null); timeField = Gui.makeTextField(null, 15, MaxSize.NULL, MinSize.NULL); JLabel agentTypeLabel = Gui.makeLabel("Agent Type", MaxSize.NULL, null); JLabel valueLabel = Gui.makeLabel("Population Limit", MaxSize.NULL, null); conListPanel = makeConditionListPanel(); scrollPane = new JScrollPane(conListPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setPreferredSize(new PrefSize(550,300)); JPanel scrollPaneWrapper = Gui.makePanel((BoxLayoutAxis)null,MaxSize.NULL,null,(Component[])null); scrollPaneWrapper.add(scrollPane); GridBagConstraints c = new GridBagConstraints(); c.gridx = 1; c.gridy = 0; c.gridwidth = 3; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(3, 3, 3, 3); lowerPanel.add(conHeader, c); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 1; c.insets = new Insets(3, 3, 3, 3); c.anchor = GridBagConstraints.CENTER; lowerPanel.add(timeLabel, c); c = new GridBagConstraints(); c.gridx = 1; c.gridy = 1; c.gridwidth = 2; c.insets = new Insets(3, 3, 3, 3); c.anchor = GridBagConstraints.CENTER; lowerPanel.add(timeField, c); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 2; c.insets = new Insets(15, 40, 3, 3); c.anchor = GridBagConstraints.CENTER; lowerPanel.add(agentTypeLabel, c); c = new GridBagConstraints(); c.gridx = 1; c.gridy = 2; c.insets = new Insets(15, 50, 3, 3); c.anchor = GridBagConstraints.CENTER; lowerPanel.add(valueLabel, c); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 3; c.gridwidth = 4; c.insets = new Insets(8, 3, 3, 3); c.anchor = GridBagConstraints.LINE_START; c.fill = GridBagConstraints.NONE; lowerPanel.add(scrollPaneWrapper,c); validate(); return lowerPanel; } private static JPanel makeConditionListPanel() { JPanel conListPanel = Gui.makePanel(BoxLayoutAxis.PAGE_AXIS, null, null); return conListPanel; } private void addCondition() { JComboBox newBox = Gui.makeComboBox(agentNames, MaxSize.NULL); agentTypes.add(newBox); JTextField newValue = Gui.makeTextField(null, 25, MaxSize.NULL, MinSize.NULL); values.add(newValue); JButton newButton = Gui.makeButton("Delete", null, new DeleteListener()); deleteButtons.add(newButton); newButton.setActionCommand(deleteButtons.indexOf(newButton) + ""); JPanel newPanel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(3, 0, 3, 0); newPanel.add(newBox, c); c = new GridBagConstraints(); c.gridx = 1; c.gridy = 0; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(3, 0, 3, 0); newPanel.add(newValue, c); c = new GridBagConstraints(); c.gridx = 2; c.gridy = 0; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(3, 0, 3, 0); newPanel.add(newButton, c); subPanels.add(newPanel); conListPanel.add(newPanel); validate(); } private void reset() { nameField.setText(""); conListPanel.removeAll(); agentTypes.clear(); values.clear(); deleteButtons.clear(); subPanels.clear(); } private class DeleteListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { int n = Integer.parseInt(e.getActionCommand()); String str = (String) agentTypes.get(n).getSelectedItem(); if (str != null) getGuiManager().removePopLimit(str); conListPanel.remove(subPanels.get(n)); agentTypes.remove(n); values.remove(n); deleteButtons.remove(n); for (int i = n; i < deleteButtons.size(); i++) deleteButtons.get(i).setActionCommand( (Integer.parseInt(deleteButtons.get(i) .getActionCommand()) - 1) + ""); subPanels.remove(n); validate(); repaint(); } } }
package nl.tud.dcs.fddg.server; import nl.tud.dcs.fddg.client.ClientInterface; import nl.tud.dcs.fddg.game.Field; import nl.tud.dcs.fddg.game.actions.*; import nl.tud.dcs.fddg.game.entities.Player; import nl.tud.dcs.fddg.gui.VisualizerGUI; import nl.tud.dcs.fddg.server.requests.ActionRequest; import java.io.FileNotFoundException; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; public class ServerProcess extends UnicastRemoteObject implements ClientServerInterface, Runnable, ServerInterface { // internal administration private final int ID; private Field field; private Logger logger; private VisualizerGUI visualizerGUI = null; private boolean gameStarted; // client administration private volatile Map<Integer, ClientInterface> connectedPlayers; private int IDCounter; // server administration private Map<Integer, ServerInterface> otherServers; //(id, RMI object) private int requestCounter; private Map<Integer, ActionRequest> pendingRequests; //(requestID,request) private Map<Integer, Integer> pendingAcknowledgements; //(requestID, nr of acks still to receive) /** * The constructor of the ServerProcess class. * It requires an ID and a flag indicating whether a GUI should be started or not.. * * @param id The (unique) ID of the server * @param useGUI The flag that tells whether this server should run a GUI or not * @throws RemoteException */ public ServerProcess(int id, boolean useGUI, String fieldFile) throws RemoteException, FileNotFoundException { super(); this.ID = id; this.field = new Field(fieldFile); this.logger = Logger.getLogger(ServerProcess.class.getName()); logger.setLevel(Level.ALL); logger.setUseParentHandlers(false); Handler consoleHandler = new ConsoleHandler(); consoleHandler.setLevel(Level.ALL); logger.addHandler(consoleHandler); this.gameStarted = false; this.connectedPlayers = new ConcurrentHashMap<>(); this.IDCounter = 0; this.requestCounter = 0; this.otherServers = new HashMap<>(); this.pendingRequests = new HashMap<>(); this.pendingAcknowledgements = new HashMap<>(); // start GUI if necessary if (useGUI) this.visualizerGUI = new VisualizerGUI(field); logger.log(Level.INFO, "Starting server with id " + id); } /** * Main loop of the process. * It first waits 5 seconds the start the game, then lets the dragons attack every second. */ @Override public void run() { try { do { Thread.sleep(1000); } while (!gameStarted); while (!field.gameHasFinished()) { //only attack the servers own players (not the others!!!!). Then, no acks are required Set<Action> actionSet = field.dragonRage(connectedPlayers.keySet()); for (Action a : actionSet) { broadcastActionToClients(a); broadcastActionToServers(a); } Thread.sleep(1000); } logger.log(Level.INFO, "Server " + ID + " finished the game."); } catch (InterruptedException | RemoteException e) { e.printStackTrace(); } } /** * Broadcast an action to all connected clients * * @param action The action to be broadcasted. */ public void broadcastActionToClients(Action action) throws RemoteException { for (ClientInterface client : connectedPlayers.values()) client.performAction(action); } /** * Only updates the GUI if there actually is one */ private void checkAndUpdateGUI() { if (visualizerGUI != null) visualizerGUI.updateGUI(); } /** * A client calls this function if it wants to perform one of the following actions: * MoveAction, HealAction, AttackAction. * * @param action The action the client wants to be performed. * @throws RemoteException */ @Override public void requestAction(Action action) throws RemoteException { logger.fine("Received action request from client " + action.getSenderId()); if (isValidAction(action)) { if (!otherServers.isEmpty()) sendRequestsForAction(action); else performAction(action); } } /** * Checks whether the action is valid for this server. * This is done by checking the validity of the action in the field of this server * and by checking whether is does not conflict with this server's pending requests. * * @param action The action of which the validity needs to be checked * @return true iff the action can safely be performed on this server */ private synchronized boolean isValidAction(Action action) { return action.isValid(field) && checkPendingRequestsForAction(action); } /** * Checks whether there are conflicts between the current request and the pending requests. * * @param action The action a client wants to perform * @return true iff there are no conflicts with the pending actions */ private boolean checkPendingRequestsForAction(Action action) { if (action instanceof MoveAction) { //check if one of the pending requests also wants to go to the same destination tile MoveAction move = (MoveAction) action; for (ActionRequest request : pendingRequests.values()) if (request.getAction() instanceof MoveAction) if (((MoveAction) request.getAction()).hasSameDestinationAs(move)) return false; } else if (action instanceof AttackAction) { //check if there is another attack request for the same dragon AttackAction attack = (AttackAction) action; for (ActionRequest request : pendingRequests.values()) if (request.getAction() instanceof AttackAction) if (((AttackAction) request.getAction()).getDragonId() == attack.getDragonId()) return false; } else if (action instanceof HealAction) { //check if there is another heal request for the same target player HealAction heal = (HealAction) action; for (ActionRequest request : pendingRequests.values()) if (request.getAction() instanceof HealAction) if (((HealAction) request.getAction()).getTargetPlayer() == heal.getTargetPlayer()) return false; } return true; } /** * Creates an ActionRequest for the action and broadcasts this to the other servers * * @param action The action that is requested */ private synchronized void sendRequestsForAction(Action action) throws RemoteException { //create request ActionRequest request = new ActionRequest(requestCounter++, this.ID, action); //initialize acknowledgement counter for the request pendingRequests.put(request.getRequestID(), request); pendingAcknowledgements.put(request.getRequestID(), otherServers.size()); //TODO: remove request from these data structures when not all acks are received after a certain time logger.fine("Sending request " + request.getRequestID() + " to all servers..."); //broadcast the request to the other servers for (ServerInterface server : otherServers.values()) server.requestAction(request); } /** * This function gets called by a client to connect to a server. * * @throws RemoteException */ @Override public int register() throws RemoteException { return IDCounter++; } /** * This function allows a client to connect with a (unique) ID. * * @param clientId The ID of the player that wishes to connect. * @throws RemoteException */ @Override public void connect(int clientId) throws RemoteException { logger.log(Level.INFO, "Client with id " + clientId + " connected"); try { ClientInterface ci = (ClientInterface) Naming.lookup("FDDGClient/" + clientId); field.addPlayer(clientId); ci.initializeField(field); AddPlayerAction apa = new AddPlayerAction(clientId, field.getPlayer(clientId).getxPos(), field.getPlayer(clientId).getyPos()); broadcastActionToClients(apa); broadcastActionToServers(apa); //inform other servers // Now the broadcast is done, add the player to the player map (so he doesn't add himself again on the field). connectedPlayers.put(clientId, ci); } catch (NotBoundException | MalformedURLException e) { e.printStackTrace(); } if (!gameStarted) { logger.log(Level.INFO, "Game started on server " + ID); gameStarted = true; } checkAndUpdateGUI(); } /** * This function sends a heartbeat to a remote machine, identified by its (unique) ID. * * @param remoteId The ID of the remote machine. * @throws RemoteException */ @Override public void heartBeat(int remoteId) throws RemoteException { } /** * This function send back a reply whenever a "ping" comes in. * * @throws RemoteException */ @Override public void pong() throws RemoteException { } /** * Binds this server to the registry and connects to all other servers. * * @param serverURLs The URLs of all servers * @throws MalformedURLException * @throws RemoteException */ public void registerAndConnectToAll(String[] serverURLs) throws MalformedURLException, RemoteException { Naming.rebind(serverURLs[ID], this); for (int i = 0; i < serverURLs.length; i++) if (i != ID) connectToServer(serverURLs[i]); } /** * Blocking method that waits until the server (identified by the serverURL) is online. * * @param serverURL The URL of the server we are waiting for * @throws RemoteException * @throws MalformedURLException */ private void connectToServer(String serverURL) throws RemoteException, MalformedURLException { int id = Integer.parseInt(serverURL.substring(serverURL.lastIndexOf("/") + 1)); while (true) { try { otherServers.put(id, (ServerInterface) Naming.lookup(serverURL)); logger.info("Connected to server: " + serverURL); break; } catch (NotBoundException ignoredException) { } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * Method that one server calls on all other servers to request a certain action. * * @param request A request containing the id and the action the server wants to perform * @throws java.rmi.RemoteException */ @Override public void requestAction(ActionRequest request) throws RemoteException { if (isValidAction(request.getAction())) { int senderID = request.getSenderID(); int requestID = request.getRequestID(); logger.fine("Acknowledging request " + requestID + " to server " + senderID); otherServers.get(senderID).acknowledgeRequest(requestID); } } /** * Method that is used to acknowledge a request send by another server * * @param requestID The id of the request * @throws java.rmi.RemoteException */ @Override public void acknowledgeRequest(int requestID) throws RemoteException { logger.finer("Received acknowledgement for request " + requestID); //decrement pending acknowledgement counter int newCount = pendingAcknowledgements.get(requestID) - 1; if(pendingAcknowledgements.containsKey(requestID)) { pendingAcknowledgements.put(requestID, newCount); } //if all acknowledgements are received, remove the request and perform the action if (newCount == 0) { logger.fine("All acknowledgements for request " + requestID + " received"); Action action = pendingRequests.get(requestID).getAction(); //perform action on local field + connected clients performAction(action); broadcastActionToServers(action); //cleanup removeRequest(requestID); } } /** * Broadcast an action to all other servers * * @param action The action to be broadcasted. */ private void broadcastActionToServers(Action action) throws RemoteException { for (ServerInterface server : otherServers.values()) server.performAction(action); } /** * Removes the request with requestID from the pending requests (and acknowledgement counter) * * @param requestID The id of the request to be removed */ private void removeRequest(int requestID) { pendingAcknowledgements.remove(requestID); pendingRequests.remove(requestID); } /** * Method that indicates that the server should perform a certain action. * This method is only invoked when all other servers have acknowledged the request for the action. * * @param action The action that should be executed * @throws java.rmi.RemoteException */ @Override public void performAction(Action action) throws RemoteException { logger.fine("Performing action from " + action.getSenderId()); //perform the action on the local field action.perform(field); //if a dragon is killed, the action is changed to a DeleteUnitAction if (action instanceof AttackAction) { AttackAction aa = (AttackAction) action; int dragonID = aa.getDragonId(); if (field.getDragon(dragonID).getCurHitPoints() <= 0) { field.removeDragon(dragonID); action = new DeleteUnitAction(dragonID); } } checkAndUpdateGUI(); broadcastActionToClients(action); } }
package io.spine.server.stand; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import io.spine.string.StringifierRegistry; import io.spine.type.TypeUrl; import javax.annotation.CheckReturnValue; import static com.google.common.base.Preconditions.checkNotNull; /** * An identifier for the state of a certain {@link io.spine.server.aggregate.Aggregate Aggregate}. * * <p>{@code Aggregate} state is defined by {@link TypeUrl TypeUrl}. * * <p>The {@code AggregateStateId} is used to store and access the latest {@code Aggregate} * states in a {@link Stand}. * * @param <I> the type for IDs of the source aggregate * @author Alex Tymchenko */ public final class AggregateStateId<I> { static { StringifierRegistry.getInstance() .register(new AggregateStateIdStringifier(), AggregateStateId.class); } private final I aggregateId; private final TypeUrl stateType; private AggregateStateId(I aggregateId, TypeUrl stateType) { this.aggregateId = checkNotNull(aggregateId); this.stateType = checkNotNull(stateType); } @CheckReturnValue public static <I> AggregateStateId of(I aggregateId, TypeUrl stateType) { return new AggregateStateId<>(aggregateId, stateType); } public I getAggregateId() { return aggregateId; } public TypeUrl getStateType() { return stateType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof AggregateStateId)) { return false; } AggregateStateId<?> that = (AggregateStateId<?>) o; return Objects.equal(aggregateId, that.aggregateId) && Objects.equal(stateType, that.stateType); } @Override public int hashCode() { return Objects.hashCode(aggregateId, stateType); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("aggregateId", aggregateId) .add("stateType", stateType) .toString(); } }
package com.netflix.servo.jmx; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.netflix.servo.monitor.CompositeMonitor; import com.netflix.servo.monitor.Monitor; import com.netflix.servo.monitor.NumericMonitor; import com.netflix.servo.tag.Tag; import com.netflix.servo.tag.TagList; import java.util.List; import java.util.regex.Pattern; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.DynamicMBean; import javax.management.InvalidAttributeValueException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.ObjectName; import javax.management.ReflectionException; /** * Exposes a {@link com.netflix.servo.monitor.Monitor} as an MBean that can be registered with JMX. */ class MonitorMBean implements DynamicMBean { /** * Create a set of MBeans for a {@link com.netflix.servo.monitor.Monitor}. This method will * recursively select all of the sub-monitors if a composite type is used. * * @param domain passed in to the object name created to identify the beans * @param monitor monitor to expose to jmx * @return flattened list of simple monitor mbeans */ public static List<MonitorMBean> createMBeans(String domain, Monitor<?> monitor) { List<MonitorMBean> mbeans = Lists.newArrayList(); createMBeans(mbeans, domain, monitor); return mbeans; } private static void createMBeans(List<MonitorMBean> mbeans, String domain, Monitor<?> monitor) { if (monitor instanceof CompositeMonitor<?>) { for (Monitor<?> m : ((CompositeMonitor<?>) monitor).getMonitors()) { createMBeans(mbeans, domain, m); } } else { mbeans.add(new MonitorMBean(domain, monitor)); } } private static final Pattern INVALID_CHARS = Pattern.compile("[^a-zA-Z0-9_\\-\\.]"); private final Monitor<?> monitor; private final ObjectName objectName; private final MBeanInfo beanInfo; /** * Create an MBean for a {@link com.netflix.servo.monitor.Monitor}. * * @param domain passed in to the object name created to identify the beans * @param monitor monitor to expose to jmx */ MonitorMBean(String domain, Monitor<?> monitor) { this.monitor = monitor; this.objectName = createObjectName(domain); this.beanInfo = createBeanInfo(); } /** * Returns the object name built from the {@link com.netflix.servo.monitor.MonitorConfig}. */ public ObjectName getObjectName() { return objectName; } /** {@inheritDoc} */ @Override public Object getAttribute(String name) throws AttributeNotFoundException { return monitor.getValue(); } /** {@inheritDoc} */ @Override public void setAttribute(Attribute attribute) throws InvalidAttributeValueException, MBeanException, AttributeNotFoundException { throw new UnsupportedOperationException("setAttribute is not implemented"); } /** {@inheritDoc} */ @Override public AttributeList getAttributes(String[] names) { AttributeList list = new AttributeList(); for (String name : names) { list.add(new Attribute(name, monitor.getValue())); } return list; } /** {@inheritDoc} */ @Override public AttributeList setAttributes(AttributeList list) { throw new UnsupportedOperationException("setAttributes is not implemented"); } /** {@inheritDoc} */ @Override public Object invoke(String name, Object[] args, String[] sig) throws MBeanException, ReflectionException { throw new UnsupportedOperationException("invoke is not implemented"); } /** {@inheritDoc} */ @Override public MBeanInfo getMBeanInfo() { return beanInfo; } private ObjectName createObjectName(String domain) { try { StringBuilder builder = new StringBuilder(); builder.append(domain).append(':'); builder.append("name=").append(monitor.getConfig().getName()); TagList tags = monitor.getConfig().getTags(); for (Tag tag : tags) { final String sanitizedKey = INVALID_CHARS.matcher(tag.getKey()).replaceAll("_"); final String sanitizedValue = INVALID_CHARS.matcher(tag.getValue()).replaceAll("_"); builder.append(',').append(sanitizedKey).append('=').append(sanitizedValue); } return new ObjectName(builder.toString()); } catch (Exception e) { e.printStackTrace(); throw Throwables.propagate(e); } } private MBeanInfo createBeanInfo() { MBeanAttributeInfo[] attrs = new MBeanAttributeInfo[1]; attrs[0] = createAttributeInfo(monitor); return new MBeanInfo( this.getClass().getName(), "MonitorMBean", attrs, null, // constructors null, // operators null); // notifications } private MBeanAttributeInfo createAttributeInfo(Monitor<?> m) { final String type = (m instanceof NumericMonitor<?>) ? Number.class.getName() : String.class.getName(); return new MBeanAttributeInfo( "value", type, m.getConfig().toString(), true, // isReadable false, // isWritable false); // isIs } }
package fitnesse.testsystems.slim.tables; import java.util.ArrayList; import java.util.Collections; import java.util.List; import fitnesse.slim.converters.BooleanConverter; import fitnesse.slim.converters.VoidConverter; import fitnesse.slim.instructions.Instruction; import fitnesse.testsystems.TestExecutionException; import fitnesse.testsystems.TestResult; import fitnesse.testsystems.slim.SlimTestContext; import fitnesse.testsystems.slim.Table; import fitnesse.testsystems.slim.results.SlimTestResult; public class ScriptTable extends SlimTable { private static final String SEQUENTIAL_ARGUMENT_PROCESSING_SUFFIX = ";"; public ScriptTable(Table table, String tableId, SlimTestContext context) { super(table, tableId, context); } /** * Template method to provide the keyword that identifies the table type. * * @return table type */ @Override protected String getTableType() { return "scriptTable"; } /** * Template method to provide the keyword that identifies the table type. * * @return keyword for script table */ protected String getTableKeyword() { return "script"; } /** * Template method to provide the keyword for the {@code start} action. * * @return keyword for {@code start} action */ protected String getStartKeyword() { return "start"; } /** * Template method to provide the keyword for the {@code check} action. * * @return keyword for {@code check} action */ protected String getCheckKeyword() { return "check"; } /** * Template method to provide the keyword for the {@code checkNot} action. * * @return keyword for {@code checkNot} action */ protected String getCheckNotKeyword() { return "check not"; } /** * Template method to provide the keyword for the {@code reject} action. * * @return keyword for {@code reject} action */ protected String getRejectKeyword() { return "reject"; } /** * Template method to provide the keyword for the {@code ensure} action. * * @return keyword for {@code ensure} action */ protected String getEnsureKeyword() { return "ensure"; } /** * Template method to provide the keyword for the {@code show} action. * * @return keyword for {@code show} action */ protected String getShowKeyword() { return "show"; } /** * Template method to provide the keyword for the {@code note} action. * * @return keyword for {@code note} action */ protected String getNoteKeyword() { return "note"; } @Override public List<SlimAssertion> getAssertions() throws TestExecutionException { List<SlimAssertion> assertions = new ArrayList<>(); ScenarioTable.setDefaultChildClass(getClass()); if (table.getCellContents(0, 0).toLowerCase().startsWith(getTableKeyword())) { List<SlimAssertion> createAssertions = startActor(); if (createAssertions != null) { assertions.addAll(createAssertions); } } for (int row = 1; row < table.getRowCount(); row++) assertions.addAll(instructionsForRow(row)); return assertions; } // returns a list of statements protected List<SlimAssertion> instructionsForRow(int row) throws TestExecutionException { String firstCell = table.getCellContents(0, row).trim(); List<SlimAssertion> assertions; String match; if (firstCell.equalsIgnoreCase(getStartKeyword())) assertions = startActor(row); else if (firstCell.equalsIgnoreCase(getCheckKeyword())) assertions = checkAction(row); else if (firstCell.equalsIgnoreCase(getCheckNotKeyword())) assertions = checkNotAction(row); else if (firstCell.equalsIgnoreCase(getRejectKeyword())) assertions = reject(row); else if (firstCell.equalsIgnoreCase(getEnsureKeyword())) assertions = ensure(row); else if (firstCell.equalsIgnoreCase(getShowKeyword())) assertions = show(row); else if (firstCell.equalsIgnoreCase(getNoteKeyword())) assertions = note(row); else if ((match = ifSymbolAssignment(0, row)) != null) assertions = actionAndAssign(match, row); else if (firstCell.isEmpty()) assertions = note(row); else if (firstCell.trim().startsWith("#") || firstCell.trim().startsWith("*")) assertions = note(row); else { // action() is for now the only function that returns a list of statements assertions = action(row); } return assertions; } protected List<SlimAssertion> actionAndAssign(String symbolName, int row) { List<SlimAssertion> assertions = new ArrayList<>(); int lastCol = table.getColumnCountInRow(row) - 1; String actionName = getActionNameStartingAt(1, lastCol, row); if (!actionName.equals("")) { String[] args = getArgumentsStartingAt(1 + 1, lastCol, row, assertions); assertions.add(makeAssertion(callAndAssign(symbolName, getTableType() + "Actor", actionName, (Object[]) args), new SymbolAssignmentExpectation(symbolName, 0, row))); } return assertions; } protected List<SlimAssertion> action(int row) throws TestExecutionException { List<SlimAssertion> assertions = assertionsFromScenario(row); if (assertions.isEmpty()) { // Invoke fixture: int lastCol = table.getColumnCountInRow(row) - 1; return invokeAction(0, lastCol, row, new ScriptActionExpectation(0, row)); } return assertions; } protected List<SlimAssertion> assertionsFromScenario(int row) throws TestExecutionException { int lastCol = table.getColumnCountInRow(row) - 1; String scenarioName = getScenarioNameFromAlternatingCells(lastCol, row); ScenarioTable scenario = getTestContext().getScenario(scenarioName); String[] args = null; List<SlimAssertion> assertions = new ArrayList<>(); if (scenario != null) { args = getArgumentsStartingAt(1, lastCol, row, assertions); } else if (lastCol == 0) { String cellContents = table.getCellContents(0, row); scenario = getTestContext().getScenarioByPattern(cellContents); if (scenario != null) { args = scenario.matchParameters(cellContents); } } if (scenario != null) { scenario.setCustomComparatorRegistry(customComparatorRegistry); assertions.addAll(scenario.call(args, this, row)); } return assertions; } protected String getScenarioNameFromAlternatingCells(int endingCol, int row) { String actionName = getActionNameStartingAt(0, endingCol, row); String simpleName = actionName.replace(SEQUENTIAL_ARGUMENT_PROCESSING_SUFFIX, ""); return Disgracer.disgraceClassName(simpleName); } protected List<SlimAssertion> note(int row) { return Collections.emptyList(); } protected List<SlimAssertion> show(int row) { int lastCol = table.getColumnCountInRow(row) - 1; return invokeAction(1, lastCol, row, new ShowActionExpectation(0, row)); } protected List<SlimAssertion> ensure(int row) { int lastCol = table.getColumnCountInRow(row) - 1; return invokeAction(1, lastCol, row, new EnsureActionExpectation(0, row)); } protected List<SlimAssertion> reject(int row) { int lastCol = table.getColumnCountInRow(row) - 1; return invokeAction(1, lastCol, row, new RejectActionExpectation(0, row)); } protected List<SlimAssertion> checkAction(int row) { int lastColInAction = table.getColumnCountInRow(row) - 1; table.getCellContents(lastColInAction, row); return invokeAction(1, lastColInAction - 1, row, new ReturnedValueExpectation(lastColInAction, row)); } protected List<SlimAssertion> checkNotAction(int row) { int lastColInAction = table.getColumnCountInRow(row) - 1; table.getCellContents(lastColInAction, row); return invokeAction(1, lastColInAction - 1, row, new RejectedValueExpectation(lastColInAction, row)); } protected List<SlimAssertion> invokeAction(int startingCol, int endingCol, int row, SlimExpectation expectation) { String actionName = getActionNameStartingAt(startingCol, endingCol, row); List<SlimAssertion> assertions = new ArrayList<>(); String[] args = getArgumentsStartingAt(startingCol + 1, endingCol, row, assertions); assertions.add(makeAssertion(callFunction(getTableType() + "Actor", actionName, (Object[]) args), expectation)); return assertions; } protected String getActionNameStartingAt(int startingCol, int endingCol, int row) { StringBuilder actionName = new StringBuilder(); actionName.append(table.getCellContents(startingCol, row)); int actionNameCol = startingCol + 2; while (actionNameCol <= endingCol && !invokesSequentialArgumentProcessing(actionName.toString())) { actionName.append(" ").append(table.getCellContents(actionNameCol, row)); actionNameCol += 2; } return actionName.toString().trim(); } // Adds extra assertions to the "assertions" list! protected String[] getArgumentsStartingAt(int startingCol, int endingCol, int row, List<SlimAssertion> assertions) { ArgumentExtractor extractor = new ArgumentExtractor(startingCol, endingCol, row); while (extractor.hasMoreToExtract()) { assertions.add(makeAssertion(Instruction.NOOP_INSTRUCTION, new ArgumentExpectation(extractor.argumentColumn, row))); extractor.extractNextArgument(); } return extractor.getArguments(); } protected boolean invokesSequentialArgumentProcessing(String cellContents) { return cellContents.endsWith(SEQUENTIAL_ARGUMENT_PROCESSING_SUFFIX); } protected List<SlimAssertion> startActor() { String firstCellContents = table.getCellContents(0, 0); String keyworkd = getTableKeyword() + ":"; int pos = firstCellContents.toLowerCase().indexOf(keyworkd); if (pos == 0) { return startActor(0, firstCellContents.substring(keyworkd.length() ), 0); } else if (table.getColumnCountInRow(0) > 1) { return startActor(0); } return null; } protected List<SlimAssertion> startActor(int row) { int classNameColumn = 1; String cellContents = table.getCellContents(classNameColumn, row); return startActor(row, cellContents, classNameColumn); } protected List<SlimAssertion> startActor(int row, String cellContents, int classNameColumn) { List<SlimAssertion> assertions = new ArrayList<>(); String className = Disgracer.disgraceClassName(cellContents); assertions.add(constructInstance(getTableType() + "Actor", className, classNameColumn, row)); getArgumentsStartingAt(classNameColumn + 1, table.getColumnCountInRow(row) - 1, row, assertions); return assertions; } class ArgumentExtractor { private int argumentColumn; private int endingCol; private int row; private List<String> arguments = new ArrayList<>(); private int increment = 2; private boolean sequentialArguments = false; ArgumentExtractor(int startingCol, int endingCol, int row) { this.argumentColumn = startingCol; this.endingCol = endingCol; this.row = row; } public boolean hasMoreToExtract() { return argumentColumn <= endingCol; } public void extractNextArgument() { arguments.add(table.getCellContents(argumentColumn, row)); String argumentKeyword = table.getCellContents(argumentColumn - 1, row); boolean argumentIsSequential = invokesSequentialArgumentProcessing(argumentKeyword); sequentialArguments = (sequentialArguments || argumentIsSequential); increment = sequentialArguments ? 1 : 2; argumentColumn += increment; } public String[] getArguments() { return arguments.toArray(new String[arguments.size()]); } } private class ScriptActionExpectation extends RowExpectation { private ScriptActionExpectation(int col, int row) { super(col, row); } @Override protected SlimTestResult createEvaluationMessage(String actual, String expected) { if (actual == null) return SlimTestResult.fail("null", expected); else if (actual.equals(VoidConverter.VOID_TAG) || actual.equals("null")) return SlimTestResult.plain(); else if (actual.equals(BooleanConverter.FALSE)) return SlimTestResult.fail(); else if (actual.equals(BooleanConverter.TRUE)) return SlimTestResult.pass(); else return SlimTestResult.plain(); } } private class EnsureActionExpectation extends RowExpectation { public EnsureActionExpectation(int col, int row) { super(col, row); } @Override protected SlimTestResult createEvaluationMessage(String actual, String expected) { return (actual != null && actual.equals(BooleanConverter.TRUE)) ? SlimTestResult.pass() : SlimTestResult.fail(); } } private class RejectActionExpectation extends RowExpectation { public RejectActionExpectation(int col, int row) { super(col, row); } @Override protected SlimTestResult createEvaluationMessage(String actual, String expected) { if (actual == null) return SlimTestResult.pass(); else return actual.equals(BooleanConverter.FALSE) ? SlimTestResult.pass() : SlimTestResult.fail(); } } private class ShowActionExpectation extends RowExpectation { public ShowActionExpectation(int col, int row) { super(col, row); } @Override protected SlimTestResult createEvaluationMessage(String actual, String expected) { try { table.addColumnToRow(getRow(), actual); } catch (Exception e) { return SlimTestResult.fail(actual, e.getMessage()); } return SlimTestResult.plain(); } } private class ArgumentExpectation extends RowExpectation { private ArgumentExpectation(int col, int row) { super(col, row); } @Override public TestResult evaluateExpectation(Object returnValue) { table.substitute(getCol(), getRow(), replaceSymbolsWithFullExpansion(getExpected())); return null; } @Override protected SlimTestResult createEvaluationMessage(String actual, String expected) { return null; } } }
package org.slc.sli.api.security; import java.io.Serializable; import java.lang.reflect.Field; import java.security.Principal; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Component; import org.slc.sli.domain.Entity; /** * Attribute holder for SLI Principal * * @author dkornishev * @author shalka */ @Component public class SLIPrincipal implements Principal, Serializable { private static final long serialVersionUID = 1L; private String id; private String name; private String realm; private String externalId; private String adminRealm; private String edOrg; private String tenantId; private List<String> roles; private List<String> sliRoles; private Entity entity; public SLIPrincipal() { } public SLIPrincipal(String id) { this.id = id; } @Override public String getName() { return this.name; } public String getId() { return id; } /** * Gets the fully-qualified LDAP string generated by OpenAM. * * @return String containing Realm information. */ public String getRealm() { return realm; } public String getExternalId() { return externalId; } public void setId(String id) { this.id = id; } public void setName(String name) { this.name = name; } public void setRealm(String realm) { this.realm = realm; } public void setExternalId(String externalId) { this.externalId = externalId; } public void setEntity(Entity entity) { this.entity = entity; } public Entity getEntity() { return entity; } public List<String> getRoles() { return roles; } public List<String> getSliRoles() { return sliRoles; } public void setRoles(List<String> roles) { this.roles = roles; } public String getAdminRealm() { return adminRealm; } public void setAdminRealm(String adminRealm) { this.adminRealm = adminRealm; } /** * LDAP Attribute "edorg" is set to "X-DistrictY" which is the "stateOrganizationId" * for the District in the edorg hierarchy for the data that will be ingested * * @return */ public String getEdOrg() { return edOrg; } public void setEdOrg(String edOrg) { this.edOrg = edOrg; } public void setSliRoles(List<String> sliRoles) { this.sliRoles = sliRoles; } @Override public String toString() { return this.externalId + "@" + this.realm; } /** * Sets the tenant id of the sli principal. * @param newTenantId new tenant id. */ public void setTenantId(String newTenantId) { this.tenantId = newTenantId; } /** * Gets the tenant id of the sli principal. * @return tenant id. */ public String getTenantId() { return tenantId; } public Map<String, Object> toMap() throws Exception { Field[] fields = this.getClass().getFields(); Map<String, Object> map = new HashMap<String, Object>(); for (Field f : fields) { map.put(f.getName(), f.get(this)); } return map; } }
package gov.nih.nci.cananolab.ui.sample; /** * This class sets up the submit a new sample page and submits a new sample * * @author pansu */ /* CVS $Id: SubmitNanoparticleAction.java,v 1.37 2008-09-18 21:35:25 cais Exp $ */ import gov.nih.nci.cananolab.dto.common.PointOfContactBean; import gov.nih.nci.cananolab.dto.common.UserBean; import gov.nih.nci.cananolab.dto.particle.SampleBean; import gov.nih.nci.cananolab.service.sample.SampleService; import gov.nih.nci.cananolab.service.sample.impl.SampleServiceLocalImpl; import gov.nih.nci.cananolab.ui.core.BaseAnnotationAction; import gov.nih.nci.cananolab.ui.security.InitSecuritySetup; import gov.nih.nci.cananolab.util.Constants; import gov.nih.nci.cananolab.util.StringUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.DynaValidatorForm; public class SampleAction extends BaseAnnotationAction { // logger private static Logger logger = Logger.getLogger(SampleAction.class); /** * Save or update POC data. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; SampleBean sampleBean = (SampleBean) theForm.get("sampleBean"); this.saveSample(request, sampleBean); request.getSession().setAttribute("updateSample", "true"); sampleBean.setLocation(Constants.LOCAL_SITE); request.setAttribute("theSample", sampleBean); return mapping.findForward("summaryEdit"); } private void saveSample(HttpServletRequest request, SampleBean sampleBean) throws Exception { UserBean user = (UserBean) (request.getSession().getAttribute("user")); sampleBean.setupDomain(user.getLoginName()); // persist in the database SampleService service = new SampleServiceLocalImpl(); service.saveSample(sampleBean, user); ActionMessages messages = new ActionMessages(); ActionMessage msg = null; String updateSample = (String) request.getSession().getAttribute( "updateSample"); if (!StringUtils.isEmpty(updateSample)) { msg = new ActionMessage("message.updateSample"); messages.add(ActionMessages.GLOBAL_MESSAGE, msg); saveMessages(request, messages); } } /** * Handle view sample request on sample search result page (read-only view). * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward summaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String location = (String) getValueFromRequest(request, Constants.LOCATION); // "setupSample()" will retrieve and return the SampleBean. SampleBean sampleBean = setupSample(theForm, request, location); theForm.set("sampleBean", sampleBean); return mapping.findForward("summaryView"); } public ActionForward setupView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String location = (String) getValueFromRequest(request, Constants.LOCATION); // "setupSample()" will retrieve and return the SampleBean. SampleBean sampleBean = setupSample(theForm, request, location); theForm.set("sampleBean", sampleBean); return mapping.findForward("bareSummaryView"); } /** * Handle edit sample request on sample search result page (curator view). * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward summaryEdit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String location = theForm.getString(Constants.LOCATION); if (StringUtils.isEmpty(location)) { location = Constants.LOCAL_SITE; } // "setupSample()" will retrieve and return the SampleBean. SampleBean sampleBean = setupSample(theForm, request, location); theForm.set("sampleBean", sampleBean); request.getSession().setAttribute("updateSample", "true"); setupLookups(request, sampleBean.getPrimaryPOCBean().getDomain() .getOrganization().getName()); return mapping.findForward("summaryEdit"); } /** * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setupNew(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { request.getSession().removeAttribute("sampleForm"); request.getSession().removeAttribute("updateSample"); setupLookups(request, null); return mapping.getInputForward(); } /** * Retrieve all POCs and Groups for POC drop-down on sample edit page. * * @param request * @param sampleOrg * @throws Exception */ private void setupLookups(HttpServletRequest request, String sampleOrg) throws Exception { InitSecuritySetup.getInstance().getAllVisibilityGroupsWithoutOrg( request, sampleOrg); InitSecuritySetup.getInstance().getAllVisibilityGroups(request); InitSampleSetup.getInstance().setPOCDropdowns(request); } public ActionForward savePointOfContact(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; UserBean user = (UserBean) (request.getSession().getAttribute("user")); SampleBean sample = (SampleBean) theForm.get("sampleBean"); PointOfContactBean thePOC = sample.getThePOC(); thePOC.setupDomain(user.getLoginName()); SampleService service = new SampleServiceLocalImpl(); //have to save POC separately because the same organizations can not be save in the same session service.savePointOfContact(thePOC, user); sample.addPointOfContact(thePOC); // save sample saveSample(request, sample); ActionForward forward = null; String updateSample = (String) request.getSession().getAttribute( "updateSample"); if (updateSample == null) { forward = mapping.getInputForward(); setupLookups(request, sample.getPrimaryPOCBean().getDomain() .getOrganization().getName()); } else { request.setAttribute("sampleId", sample.getDomain().getId() .toString()); forward = summaryEdit(mapping, form, request, response); } InitSampleSetup.getInstance().persistPOCDropdowns(request, sample.getDomain()); return forward; } public ActionForward removePointOfContact(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; SampleBean sample = (SampleBean) theForm.get("sampleBean"); PointOfContactBean thePOC = sample.getThePOC(); ActionMessages msgs = new ActionMessages(); if (thePOC.getPrimaryStatus()) { ActionMessage msg = new ActionMessage("message.deletePrimaryPOC"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveMessages(request, msgs); } sample.removePointOfContact(thePOC); // save sample saveSample(request, sample); ActionForward forward = null; String updateSample = (String) request.getSession().getAttribute( "updateSample"); if (updateSample == null) { forward = mapping.getInputForward(); setupLookups(request, sample.getPrimaryPOCBean().getDomain() .getOrganization().getName()); } else { request.setAttribute("sampleId", sample.getDomain().getId() .toString()); forward = summaryEdit(mapping, form, request, response); } return forward; } }
package gr.scify.icsee.camera; import android.app.ProgressDialog; import android.content.Context; import android.media.MediaPlayer; import android.telephony.TelephonyManager; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import org.opencv.android.BaseLoaderCallback; import org.opencv.android.LoaderCallbackInterface; import java.util.Locale; import gr.scify.icsee.AsyncProgressCheck; import gr.scify.icsee.ICSeeStartActivity; import gr.scify.icsee.ICSeeTutorial; import gr.scify.icsee.R; public class ModifiedLoaderCallback extends BaseLoaderCallback { public int processStatus=Integer.MIN_VALUE; // Not yet initialized protected String TAG = ModifiedLoaderCallback.class.getCanonicalName(); ProgressBar mPrograssBar; Context mContext; public boolean hasManagerConnected = false; public MediaPlayer mplayer; public ProgressDialog mDialog; public ModifiedLoaderCallback mThis; public ICSeeStartActivity startActivity; String lang; String countryCode; public ModifiedLoaderCallback(Context AppContext, ProgressBar progressBar, MediaPlayer mp, ProgressDialog dialog, ICSeeStartActivity start) { super(AppContext); mPrograssBar = progressBar; mContext = AppContext; mplayer = mp; mDialog = dialog; mThis = this; startActivity = start; } @Override public void onManagerConnected(int status){ processStatus = status; super.onManagerConnected(status); if(processStatus == LoaderCallbackInterface.SUCCESS) { mPrograssBar.setVisibility(View.INVISIBLE); hasManagerConnected = true; lang = Locale.getDefault().getLanguage(); TelephonyManager tm = (TelephonyManager)startActivity.getSystemService(Context.TELEPHONY_SERVICE); countryCode = tm.getSimCountryIso(); ICSeeTutorial.setLanguage(lang, countryCode); //ICSeeTutorial.setLanguage("en", "EN"); Log.i(TAG, "lang: " + lang); Log.i(TAG, "country: " + countryCode); if(ICSeeTutorial.getTutorialState(mContext) == 0) { new AsyncProgressCheck(mDialog, ICSeeStartActivity.mOpenCVCallBack, startActivity).execute(); } else { playTutorial(mContext); } } } private void playTutorial(Context context) { int tutorialId = 0; if(mplayer != null) { if(mplayer.isPlaying()){ mplayer.stop(); } else { if(lang.equals("el") || countryCode.equals("gr")) { tutorialId = R.raw.gr_welcome; } else { tutorialId = R.raw.en_welcome; } } } else { if(lang.equals("el") || countryCode.equals("gr")) { tutorialId = R.raw.gr_welcome; } else { tutorialId = R.raw.en_welcome; } } mplayer = MediaPlayer.create(context, tutorialId); mplayer.start(); /*mplayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mPrograssBar.setVisibility(View.VISIBLE); new AsyncProgressCheck(mDialog, ICSeeStartActivity.mOpenCVCallBack, startActivity).execute(); } });*/ } public void stopTutorial(){ mplayer.stop(); } }
package org.bbop.apollo.gwt.client; import com.google.gwt.cell.client.NumberCell; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.DoubleClickEvent; import com.google.gwt.event.dom.client.DoubleClickHandler; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.Response; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.cellview.client.ColumnSortEvent; import com.google.gwt.user.cellview.client.DataGrid; import com.google.gwt.user.cellview.client.TextColumn; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.view.client.ListDataProvider; import com.google.gwt.view.client.SelectionChangeEvent; import com.google.gwt.view.client.SingleSelectionModel; import org.bbop.apollo.gwt.client.dto.OrganismInfo; import org.bbop.apollo.gwt.client.dto.OrganismInfoConverter; import org.bbop.apollo.gwt.client.event.OrganismChangeEvent; import org.bbop.apollo.gwt.client.event.OrganismChangeEventHandler; import org.bbop.apollo.gwt.client.resources.TableResources; import org.bbop.apollo.gwt.client.rest.OrganismRestService; import org.gwtbootstrap3.client.ui.Button; import org.gwtbootstrap3.client.ui.InputGroupAddon; import org.gwtbootstrap3.client.ui.TextBox; import org.gwtbootstrap3.client.ui.constants.IconType; import java.util.Comparator; import java.util.List; public class OrganismPanel extends Composite { interface OrganismBrowserPanelUiBinder extends UiBinder<Widget, OrganismPanel> { } private static OrganismBrowserPanelUiBinder ourUiBinder = GWT.create(OrganismBrowserPanelUiBinder.class); @UiField TextBox organismName; @UiField TextBox blatdb; @UiField TextBox genus; @UiField TextBox species; @UiField InputGroupAddon annotationCount; @UiField TextBox sequenceFile; DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class); @UiField(provided = true) DataGrid<OrganismInfo> dataGrid = new DataGrid<OrganismInfo>(10, tablecss); @UiField Button newButton; @UiField Button createButton; @UiField Button cancelButton; @UiField Button deleteButton; @UiField InputGroupAddon validDirectory; @UiField Button reloadButton; private ListDataProvider<OrganismInfo> dataProvider = new ListDataProvider<>(); private List<OrganismInfo> organismInfoList = dataProvider.getList(); private final SingleSelectionModel<OrganismInfo> singleSelectionModel = new SingleSelectionModel<>(); public OrganismPanel() { initWidget(ourUiBinder.createAndBindUi(this)); TextColumn<OrganismInfo> organismNameColumn = new TextColumn<OrganismInfo>() { @Override public String getValue(OrganismInfo employee) { return employee.getName(); } }; Column<OrganismInfo, Number> annotationsNameColumn = new Column<OrganismInfo, Number>(new NumberCell()) { @Override public Integer getValue(OrganismInfo object) { return object.getNumFeatures(); } }; Column<OrganismInfo, Number> sequenceColumn = new Column<OrganismInfo, Number>(new NumberCell()) { @Override public Integer getValue(OrganismInfo object) { return object.getNumSequences(); } }; sequenceColumn.setSortable(true); organismNameColumn.setSortable(true); annotationsNameColumn.setSortable(true); Annotator.eventBus.addHandler(OrganismChangeEvent.TYPE, new OrganismChangeEventHandler() { @Override public void onOrganismChanged(OrganismChangeEvent organismChangeEvent) { organismInfoList.clear(); organismInfoList.addAll(MainPanel.getInstance().getOrganismInfoList()); // dataProvider.setList(organismChangeEvent.organismInfoList); } }); dataGrid.setLoadingIndicator(new HTML("Calculating Annotations ... ")); dataGrid.addColumn(organismNameColumn, "Name"); dataGrid.addColumn(annotationsNameColumn, "Annotations"); dataGrid.addColumn(sequenceColumn, "Ref Sequences"); singleSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() { @Override public void onSelectionChange(SelectionChangeEvent event) { if (singleSelectionModel.getSelectedObject() != null) { setSelectedInfo(singleSelectionModel.getSelectedObject()); setDefaultButtonState(singleSelectionModel.getSelectedObject() != null); } } }); dataGrid.setSelectionModel(singleSelectionModel); dataProvider.addDataDisplay(dataGrid); dataGrid.addDomHandler(new DoubleClickHandler() { @Override public void onDoubleClick(DoubleClickEvent event) { if (singleSelectionModel.getSelectedObject() != null) { String orgId = singleSelectionModel.getSelectedObject().getId(); if (!MainPanel.getInstance().getCurrentOrganism().getId().equals(orgId)) { // TODO: set the organism here OrganismRestService.switchOrganismById(orgId); } } } }, DoubleClickEvent.getType()); List<OrganismInfo> trackInfoList = dataProvider.getList(); ColumnSortEvent.ListHandler<OrganismInfo> sortHandler = new ColumnSortEvent.ListHandler<OrganismInfo>(trackInfoList); dataGrid.addColumnSortHandler(sortHandler); sortHandler.setComparator(organismNameColumn, new Comparator<OrganismInfo>() { @Override public int compare(OrganismInfo o1, OrganismInfo o2) { return o1.getName().compareTo(o2.getName()); } }); sortHandler.setComparator(annotationsNameColumn, new Comparator<OrganismInfo>() { @Override public int compare(OrganismInfo o1, OrganismInfo o2) { return o1.getNumFeatures() - o2.getNumFeatures(); } }); sortHandler.setComparator(sequenceColumn, new Comparator<OrganismInfo>() { @Override public int compare(OrganismInfo o1, OrganismInfo o2) { return o1.getNumSequences() - o2.getNumSequences(); } }); } public void setSelectedInfo(OrganismInfo organismInfo){ if(organismInfo==null) { setNoSelection(); return; } organismName.setText(organismInfo.getName()); organismName.setEnabled(true); blatdb.setText(organismInfo.getBlatDb()); blatdb.setEnabled(true); genus.setText(organismInfo.getGenus()); genus.setEnabled(true); species.setText(organismInfo.getSpecies()); species.setEnabled(true); sequenceFile.setText(organismInfo.getDirectory()); sequenceFile.setEnabled(true); annotationCount.setText(organismInfo.getNumFeatures().toString()); deleteButton.setVisible(true); deleteButton.setEnabled(true); if(organismInfo.getValid()==null){ validDirectory.setIcon(IconType.QUESTION); validDirectory.setColor("Red"); } else if(organismInfo.getValid()){ validDirectory.setIcon(IconType.CHECK); validDirectory.setColor("Green"); } else{ validDirectory.setIcon(IconType.XING); validDirectory.setColor("Red"); } validDirectory.setVisible(true); } private class UpdateInfoListCallback implements RequestCallback{ private boolean clearSelections = false ; public UpdateInfoListCallback(){ this(false); } public UpdateInfoListCallback(boolean clearSelections){ this.clearSelections = clearSelections ; } @Override public void onResponseReceived(Request request, Response response) { List<OrganismInfo> organismInfoList = OrganismInfoConverter.convertJSONStringToOrganismInfoList(response.getText()); dataGrid.setSelectionModel(singleSelectionModel); if(clearSelections){ clearSelections(); } MainPanel.getInstance().getOrganismInfoList().clear(); MainPanel.getInstance().setOrganismInfoList(organismInfoList); setDefaultButtonState(singleSelectionModel.getSelectedObject() != null); OrganismChangeEvent organismChangeEvent = new OrganismChangeEvent(organismInfoList); organismChangeEvent.setAction(OrganismChangeEvent.Action.LOADED_ORGANISMS); Annotator.eventBus.fireEvent(organismChangeEvent); } @Override public void onError(Request request, Throwable exception) { Window.alert("problem handling organism: "+exception); } } public void clearSelections(){ singleSelectionModel.clear(); organismName.setText(""); genus.setText(""); species.setText(""); sequenceFile.setText(""); blatdb.setText(""); validDirectory.setVisible(false); newButton.setEnabled(false); } @UiHandler("newButton") public void handleAddNewOrganism(ClickEvent clickEvent) { singleSelectionModel.clear(); setNewOrganismButtonState(); } @UiHandler("createButton") public void handleSaveNewOrganism(ClickEvent clickEvent) { setDefaultButtonState(singleSelectionModel.getSelectedObject() != null); OrganismInfo organismInfo = new OrganismInfo(); organismInfo.setName(organismName.getText()); organismInfo.setDirectory(sequenceFile.getText()); organismInfo.setGenus(genus.getText()); organismInfo.setSpecies(species.getText()); organismInfo.setBlatDb(blatdb.getText()); createButton.setEnabled(false); createButton.setText("Processing"); OrganismRestService.createOrganism(new UpdateInfoListCallback(true), organismInfo); } @UiHandler("cancelButton") public void handleCancelNewOrganism(ClickEvent clickEvent) { organismName.setText(""); sequenceFile.setText(""); species.setText(""); genus.setText(""); blatdb.setText(""); dataGrid.setSelectionModel(singleSelectionModel); newButton.setEnabled(true); setSelectedInfo(singleSelectionModel.getSelectedObject()); setDefaultButtonState(singleSelectionModel.getSelectedObject() != null); } @UiHandler("deleteButton") public void handleDeleteOrganism(ClickEvent clickEvent) { if(Window.confirm("Delete organism: "+singleSelectionModel.getSelectedObject().getName())){ deleteButton.setEnabled(false); OrganismRestService.deleteOrganism(new UpdateInfoListCallback(true), singleSelectionModel.getSelectedObject()); setNoSelection(); } } @UiHandler("organismName") public void handleOrganismNameChange(ChangeEvent changeEvent) { if(singleSelectionModel.getSelectedObject()!=null) { singleSelectionModel.getSelectedObject().setName(organismName.getText()); updateOrganismInfo(); } } @UiHandler("blatdb") public void handleBlatDbChange(ChangeEvent changeEvent) { if(singleSelectionModel.getSelectedObject()!=null) { singleSelectionModel.getSelectedObject().setBlatDb(blatdb.getText()); updateOrganismInfo(); } } @UiHandler("species") public void handleSpeciesChange(ChangeEvent changeEvent) { if(singleSelectionModel.getSelectedObject()!=null) { singleSelectionModel.getSelectedObject().setSpecies(species.getText()); updateOrganismInfo(); } } @UiHandler("genus") public void handleGenusChange(ChangeEvent changeEvent) { if(singleSelectionModel.getSelectedObject()!=null) { singleSelectionModel.getSelectedObject().setGenus(genus.getText()); updateOrganismInfo(); } } @UiHandler("sequenceFile") public void handleOrganismDirectory(ChangeEvent changeEvent) { if(singleSelectionModel.getSelectedObject()!=null) { singleSelectionModel.getSelectedObject().setDirectory(sequenceFile.getText()); updateOrganismInfo(); } } @UiHandler("reloadButton") public void handleReloadButton(ClickEvent clickEvent) { updateOrganismInfo(true); } private void updateOrganismInfo() { updateOrganismInfo(false); } private void updateOrganismInfo(boolean forceReload) { OrganismRestService.updateOrganismInfo(singleSelectionModel.getSelectedObject(), forceReload); } public void reload() { dataGrid.redraw(); // List<OrganismInfo> trackInfoList = dataProvider.getList(); // OrganismRestService.loadOrganisms(trackInfoList); // return trackInfoList; } // public List<OrganismInfo> reload() { // List<OrganismInfo> trackInfoList = dataProvider.getList(); // OrganismRestService.loadOrganisms(trackInfoList); // return trackInfoList; // Clear textboxes and make them unselectable private void setNoSelection() { organismName.setText(""); sequenceFile.setText(""); species.setText(""); genus.setText(""); blatdb.setText(""); sequenceFile.setEnabled(false); organismName.setEnabled(false); genus.setEnabled(false); species.setEnabled(false); blatdb.setEnabled(false); annotationCount.setText(""); validDirectory.setVisible(false); deleteButton.setVisible(false); } // Set the button states/visibility depending on whether there is a selection or not public void setDefaultButtonState(boolean selection){ if(selection){ newButton.setEnabled(true); newButton.setVisible(true); createButton.setVisible(false); cancelButton.setVisible(false); deleteButton.setVisible(true); } else{ newButton.setEnabled(true); newButton.setVisible(true); createButton.setVisible(false); cancelButton.setVisible(false); deleteButton.setVisible(false); } } public void setNewOrganismButtonState(){ createButton.setText("Create Organism"); singleSelectionModel.clear(); newButton.setEnabled(false); newButton.setVisible(true); createButton.setVisible(true); createButton.setEnabled(true); cancelButton.setVisible(true); cancelButton.setEnabled(true); deleteButton.setVisible(false); organismName.setText(""); sequenceFile.setText(""); genus.setText(""); species.setText(""); blatdb.setText(""); validDirectory.setVisible(false); organismName.setEnabled(true); sequenceFile.setEnabled(true); genus.setEnabled(true); species.setEnabled(true); blatdb.setEnabled(true); } public void setThinkingInterface(){ } public void unsetThinkingInterface(){ } }
package com.jaeksoft.searchlib.snippet; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.index.memory.MemoryIndex; import org.apache.lucene.search.Query; import com.jaeksoft.searchlib.util.StringUtils; public class Fragment { private String originalText; private String highlightedText; private String finalText; private boolean inSnippet; protected int vectorOffset; private boolean isEdge; private float score; private Fragment previousFragment; private Fragment nextFragment; protected Fragment(Fragment previousFragment, String originalText, int vectorOffset, boolean isEdge) { this.originalText = originalText; this.highlightedText = null; this.finalText = null; this.inSnippet = false; this.vectorOffset = vectorOffset; this.isEdge = isEdge; this.previousFragment = previousFragment; this.nextFragment = null; if (previousFragment != null) previousFragment.nextFragment = this; } protected boolean isHighlighted() { return highlightedText != null; } /** * True if getFinalText or getOriginalText has been called * * @return */ protected boolean isInSnippet() { return inSnippet; } /** * True if this fragment is the first fragment of a new value (multivalue * suport) * * @return */ protected boolean isEdge() { return isEdge; } public void setEdge(boolean isEdge) { this.isEdge = isEdge; } protected void setHighlightedText(String highlightedText) { this.highlightedText = highlightedText; } protected String getOriginalText() { return originalText; } protected String getFinalText(String[] allowedTags) { inSnippet = true; if (finalText != null) return finalText; if (highlightedText != null && score > 0) { finalText = StringUtils.removeTag(highlightedText, allowedTags); } else finalText = originalText; return finalText; } protected String getFinalText(String[] allowedTags, int maxLength) { String text = getFinalText(allowedTags); if (maxLength > text.length()) return text; int pos = maxLength; while (pos if (Character.isWhitespace(text.indexOf(pos))) break; if (pos == 0) pos = maxLength; return text.substring(0, pos); } public float score(String fieldName, Analyzer analyzer, Query query, int maxLength) { if (query == null || analyzer == null) return 0; MemoryIndex index = new MemoryIndex(); index.addField(fieldName, originalText, analyzer); float searchScore = index.search(query); float sizeScore = (originalText.length() < maxLength) ? (float) originalText .length() / (float) maxLength : maxLength; score = searchScore * sizeScore; return score; } /** * Returns the fragment which have the higher score. If the fragments has * the same score, the fragment1 is returned. * * @param fragment1 * @param fragment2 * @return */ public static final Fragment bestScore(Fragment fragment1, Fragment fragment2) { if (fragment1 == null) return fragment2; if (fragment2 == null) return fragment1; return fragment2.score > fragment1.score ? fragment2 : fragment1; } public final Fragment next() { return nextFragment; } public final Fragment previous() { return previousFragment; } /** * Find the next highlighted fragment * * @param iterator * @return */ final static protected Fragment findNextHighlightedFragment( Fragment fragment) { while (fragment != null) { if (fragment.isHighlighted() && !fragment.isInSnippet()) return fragment; fragment = fragment.next(); } return null; } }
// $Id: ImageManager.java,v 1.48 2003/04/25 15:51:34 mdb Exp $ package com.threerings.media.image; import java.awt.Component; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.Rectangle; import java.awt.Transparency; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.stream.ImageInputStream; import com.samskivert.io.NestableIOException; import com.samskivert.util.LRUHashMap; import com.samskivert.util.RuntimeAdjust; import com.samskivert.util.StringUtil; import com.samskivert.util.Throttle; import com.samskivert.util.Tuple; import com.threerings.media.Log; import com.threerings.media.MediaPrefs; import com.threerings.resource.ResourceManager; /** * Provides a single point of access for image retrieval and caching. */ public class ImageManager { /** * Used to identify an image for caching and reconstruction. */ public static class ImageKey { /** The data provider from which this image's data is loaded. */ public ImageDataProvider daprov; /** The path used to identify the image to the data provider. */ public String path; protected ImageKey (ImageDataProvider daprov, String path) { this.daprov = daprov; this.path = path; } public int hashCode () { return path.hashCode() ^ daprov.getIdent().hashCode(); } public boolean equals (Object other) { if (other == null || !(other instanceof ImageKey)) { return false; } ImageKey okey = (ImageKey)other; return ((okey.daprov.getIdent().equals(daprov.getIdent())) && (okey.path.equals(path))); } public String toString () { return daprov.getIdent() + ":" + path; } } /** * Construct an image manager with the specified {@link * ResourceManager} from which it will obtain its data. A non-null * <code>context</code> must be provided if there is any expectation * that the image manager will not be able to load images via the * ImageIO services and will have to fallback to Toolkit-style * loading. */ public ImageManager (ResourceManager rmgr, Component context) { _rmgr = rmgr; // create our image cache int icsize = _cacheSize.getValue(); Log.debug("Creating image cache [size=" + icsize + "k]."); _ccache = new LRUHashMap(icsize * 1024, new LRUHashMap.ItemSizer() { public int computeSize (Object value) { return (int)((CacheRecord)value).getEstimatedMemoryUsage(); } }); _ccache.setTracking(true); // obtain our graphics configuration if (context != null) { _gc = context.getGraphicsConfiguration(); } else { _gc = ImageUtil.getDefGC(); } } /** * Creates a buffered image, optimized for display on our graphics * device. */ public BufferedImage createImage (int width, int height, int transparency) { // DEBUG: override transparency for the moment on all images transparency = Transparency.TRANSLUCENT; return _gc.createCompatibleImage(width, height, transparency); } /** * Loads (and caches) the specified image from the resource manager * using the supplied path to identify the image. */ public BufferedImage getImage (String path) { return getImage(null, path, null); } /** * Like {@link #getImage(String)} but the specified colorizations are * applied to the image before it is returned. */ public BufferedImage getImage (String path, Colorization[] zations) { return getImage(null, path, zations); } /** * Like {@link #getImage(String)} but the image is loaded from the * specified resource set rathern than the default resource set. */ public BufferedImage getImage (String rset, String path) { return getImage(rset, path, null); } /** * Like {@link #getImage(String,String)} but the specified * colorizations are applied to the image before it is returned. */ public BufferedImage getImage (String rset, String path, Colorization[] zations) { if (StringUtil.blank(path)) { String errmsg = "Invalid image path [rset=" + rset + ", path=" + path + "]"; throw new IllegalArgumentException(errmsg); } return getImage(getImageKey(rset, path), zations); } /** * Returns an image key that can be used to fetch the image identified * by the specified resource set and image path. */ public ImageKey getImageKey (String rset, String path) { return getImageKey(getDataProvider(rset), path); } /** * Returns an image key that can be used to fetch the image identified * by the specified data provider and image path. */ public ImageKey getImageKey (ImageDataProvider daprov, String path) { return new ImageKey(daprov, path); } /** * Obtains the image identified by the specified key, caching if * possible. The image will be recolored using the supplied * colorizations if requested. */ public BufferedImage getImage (ImageKey key, Colorization[] zations) { CacheRecord crec = (CacheRecord)_ccache.get(key); if (crec != null) { // Log.info("Cache hit [key=" + key + ", crec=" + crec + "]."); return crec.getImage(zations); } // Log.info("Cache miss [key=" + key + ", crec=" + crec + "]."); // load up the raw image BufferedImage image = loadImage(key); if (image == null) { Log.warning("Failed to load image " + key + "."); // create a blank image instead image = new BufferedImage(10, 10, BufferedImage.TYPE_BYTE_INDEXED); } // Log.info("Loaded " + key.path + ", image=" + image + // ", size=" + ImageUtil.getEstimatedMemoryUsage(image)); // create a cache record crec = new CacheRecord(key, image); _ccache.put(key, crec); _keySet.add(key); // periodically report our image cache performance reportCachePerformance(); return crec.getImage(zations); } /** * Returns the data provider configured to obtain image data from the * specified resource set. */ protected ImageDataProvider getDataProvider (final String rset) { if (rset == null) { return _defaultProvider; } ImageDataProvider dprov = (ImageDataProvider)_providers.get(rset); if (dprov == null) { dprov = new ImageDataProvider() { public ImageInputStream loadImageData (String path) throws IOException { // first attempt to load the image from the specified // resource set try { return _rmgr.getImageResource(rset, path); } catch (FileNotFoundException fnfe) { // fall back to trying the classpath return _rmgr.getImageResource(path); } } public String getIdent () { return "rmgr:" + rset; } }; _providers.put(rset, dprov); } return dprov; } /** * Loads and returns the image with the specified key from the * supplied data provider. */ protected BufferedImage loadImage (ImageKey key) { BufferedImage image = null; ImageInputStream imgin = null; try { Log.debug("Loading image " + key + "."); imgin = key.daprov.loadImageData(key.path); image = loadImage(imgin); if (image == null) { Log.warning("ImageIO.read(" + key + ") returned null."); } } catch (Exception e) { Log.warning("Unable to load image '" + key + "'."); Log.logStackTrace(e); // create a blank image in its stead image = createImage(1, 1, Transparency.OPAQUE); } if (imgin != null) { try { imgin.close(); } catch (IOException ioe) { // jesus fucking hoppalong cassidy christ on a polyester // pogo stick! those fuckers at sun have // ImageInputStreamImpl.close() throwing a fucking // IOException if it's already closed; there's no way to // find out if it's already closed or not, so we have to // check for their bullshit exception; as if we should // just "trust" ImageIO.read() to close the fucking input // stream when it's done, especially after the goddamned // fiasco with PNGImageReader not closing it's fucking // inflaters; for the love of humanity if (!"closed".equals(ioe.getMessage())) { Log.warning("Failure closing image input '" + key + "'."); Log.logStackTrace(ioe); } } } return image; } /** * Called by {@link #loadImage(ImageKey)} to do the actual image * loading. */ protected BufferedImage loadImage (ImageInputStream imgin) throws IOException { // ParameterBlock pb = new ParameterBlock(); // pb.add(imgin); // return JAI.create("BMP", pb); return ImageIO.read(imgin); } /** * Creates a mirage which is an image optimized for display on our * current display device and which will be stored into video memory * if possible. */ public Mirage getMirage (ImageKey key) { return getMirage(key, null, null); } /** * Like {@link #getMirage(ImageKey)} but that only the specified * subimage of the source image is used to build the mirage. */ public Mirage getMirage (ImageKey key, Rectangle bounds) { return getMirage(key, bounds, null); } /** * Like {@link #getMirage(ImageKey)} but the supplied colorizations * are applied to the source image before creating the mirage. */ public Mirage getMirage (ImageKey key, Colorization[] zations) { return getMirage(key, null, zations); } /** * Like {@link #getMirage(ImageKey,Colorization[])} except that the * mirage is created using only the specified subset of the original * image. */ public Mirage getMirage (ImageKey key, Rectangle bounds, Colorization[] zations) { BufferedImage src = null; if (bounds == null) { // if they specified no bounds, we need to load up the raw // image and determine its bounds so that we can pass those // along to the created mirage src = getImage(key, zations); bounds = new Rectangle(0, 0, src.getWidth(), src.getHeight()); } else if (!_prepareImages.getValue()) { src = getImage(key, zations); src = src.getSubimage(bounds.x, bounds.y, bounds.width, bounds.height); } if (_runBlank.getValue()) { return new BlankMirage(bounds.width, bounds.height); } else if (_prepareImages.getValue()) { return new CachedVolatileMirage(this, key, bounds, zations); } else { return new BufferedMirage(src); } } /** * Returns the graphics configuration that should be used to optimize * images for display. */ public GraphicsConfiguration getGraphicsConfiguration () { return _gc; } /** * Reports statistics detailing the image manager cache performance * and the current size of the cached images. */ protected void reportCachePerformance () { if (/* Log.getLevel() != Log.log.DEBUG || */ _cacheStatThrottle.throttleOp()) { return; } // compute our estimated memory usage long size = 0; Iterator iter = _ccache.values().iterator(); while (iter.hasNext()) { size += ((CacheRecord)iter.next()).getEstimatedMemoryUsage(); } int[] eff = _ccache.getTrackedEffectiveness(); Log.info("ImageManager LRU [mem=" + (size / 1024) + "k" + ", size=" + _ccache.size() + ", hits=" + eff[0] + ", misses=" + eff[1] + ", totalKeys=" + _keySet.size() + "]."); } /** Maintains a source image and a set of colorized versions in the * image cache. */ protected static class CacheRecord { public CacheRecord (ImageKey key, BufferedImage source) { _key = key; _source = source; } public BufferedImage getImage (Colorization[] zations) { if (zations == null) { return _source; } if (_colorized == null) { _colorized = new ArrayList(); } // we search linearly through our list of colorized copies // because it is not likely to be very long int csize = _colorized.size(); for (int ii = 0; ii < csize; ii++) { Tuple tup = (Tuple)_colorized.get(ii); Colorization[] tzations = (Colorization[])tup.left; if (Arrays.equals(zations, tzations)) { return (BufferedImage)tup.right; } } try { BufferedImage cimage = ImageUtil.recolorImage(_source, zations); _colorized.add(new Tuple(zations, cimage)); return cimage; } catch (Exception re) { Log.warning("Failure recoloring image [source" + _key + ", zations=" + StringUtil.toString(zations) + ", error=" + re + "]."); // return the uncolorized version return _source; } } public long getEstimatedMemoryUsage () { return ImageUtil.getEstimatedMemoryUsage(_source); } public String toString () { return "[key=" + _key + ", wid=" + _source.getWidth() + ", hei=" + _source.getHeight() + ", ccount=" + ((_colorized == null) ? 0 : _colorized.size()) + "]"; } protected ImageKey _key; protected BufferedImage _source; protected ArrayList _colorized; } /** A reference to the resource manager via which we load image data * by default. */ protected ResourceManager _rmgr; /** A cache of loaded images. */ protected LRUHashMap _ccache; /** The set of all keys we've ever seen. */ protected HashSet _keySet = new HashSet(); /** Throttle our cache status logging to once every 30 seconds. */ protected Throttle _cacheStatThrottle = new Throttle(1, 30000L); /** The graphics configuration for the default screen device. */ protected GraphicsConfiguration _gc; /** Our default data provider. */ protected ImageDataProvider _defaultProvider = new ImageDataProvider() { public ImageInputStream loadImageData (String path) throws IOException { return _rmgr.getImageResource(path); } public String getIdent () { return "rmgr:default"; } }; /** Data providers for different resource sets. */ protected HashMap _providers = new HashMap(); /** Register our image cache size with the runtime adjustments * framework. */ protected static RuntimeAdjust.IntAdjust _cacheSize = new RuntimeAdjust.IntAdjust( "Size (in kb of memory used) of the image manager LRU cache " + "[requires restart]", "narya.media.image.cache_size", MediaPrefs.config, 1024); /** Controls whether or not we prepare images or use raw versions. */ protected static RuntimeAdjust.BooleanAdjust _prepareImages = new RuntimeAdjust.BooleanAdjust( "Cause image manager to optimize all images for display.", "narya.media.image.prep_images", MediaPrefs.config, true); /** A debug toggle for running entirely without rendering images. */ protected static RuntimeAdjust.BooleanAdjust _runBlank = new RuntimeAdjust.BooleanAdjust( "Cause image manager to return blank images.", "narya.media.image.run_blank", MediaPrefs.config, false); }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.media.sound; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Properties; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.FloatControl; import javax.sound.sampled.Line; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.UnsupportedAudioFileException; import org.apache.commons.io.IOUtils; import com.samskivert.util.Config; import com.samskivert.util.ConfigUtil; import com.samskivert.util.Interval; import com.samskivert.util.LRUHashMap; import com.samskivert.util.Queue; import com.samskivert.util.RuntimeAdjust; import com.samskivert.util.StringUtil; import com.threerings.resource.ResourceManager; import com.threerings.util.RandomUtil; import com.threerings.media.Log; import com.threerings.media.MediaPrefs; /** * Manages the playing of audio files. */ public class SoundManager { /** A pan value indicating that a sound should play from the left only. */ public static final float PAN_LEFT = -1f; /** A pan value indicating that a sound should play from the right only. */ public static final float PAN_RIGHT = 1f; /** A pan value indicating that a sound should play from center. */ public static final float PAN_CENTER = 0f; /** * Create instances of this for your application to differentiate * between different types of sounds. */ public static class SoundType { /** * Construct a new SoundType. * Which should be a static variable stashed somewhere for the * entire application to share. * * @param strname a short string identifier, preferably without spaces. */ public SoundType (String strname) { _strname = strname; } public String toString () { return _strname; } protected String _strname; } /** * A control for sounds. */ public static interface Frob { /** * Stop playing or looping the sound. * At present, the granularity of this command is limited to the * buffer size of the line spooler, or about 8k of data. Thus, * if playing an 11khz sample, it could take 8/11ths of a second * for the sound to actually stop playing. */ public void stop (); /** * Set the volume of the sound. */ public void setVolume (float vol); /** * Get the volume of this sound. */ public float getVolume (); /** * Set the pan value for the sound. Valid values are * -1 for left-only, 0 is centered, all the way to +1 for right-only. */ public void setPan (float pan); /** * Get the pan value of this sound. */ public float getPan (); } /** The default sound type. */ public static final SoundType DEFAULT = new SoundType("default"); /** * Constructs a sound manager. */ public SoundManager (ResourceManager rmgr) { this(rmgr, null, null); } /** * Constructs a sound manager. * * @param defaultClipBundle * @param defaultClipPath The pathname of a sound clip to use as a * fallback if another sound clip cannot be located. */ public SoundManager ( ResourceManager rmgr, String defaultClipBundle, String defaultClipPath) { // save things off _rmgr = rmgr; _defaultClipBundle = defaultClipBundle; _defaultClipPath = defaultClipPath; } /** * Shut the damn thing off. */ public void shutdown () { // TODO: we need to stop any looping sounds synchronized (_queue) { _queue.clear(); if (_spoolerCount > 0) { _queue.append(new SoundKey(DIE)); // signal death } } synchronized (_clipCache) { _lockedClips.clear(); _configs.clear(); } } /** * Returns a string summarizing our volume settings and disabled sound * types. */ public String summarizeState () { StringBuffer buf = new StringBuffer(); buf.append("clipVol=").append(_clipVol); buf.append(", disabled=["); int ii = 0; for (Iterator iter = _disabledTypes.iterator(); iter.hasNext(); ) { if (ii++ > 0) { buf.append(", "); } buf.append(iter.next()); } return buf.append("]").toString(); } /** * Is the specified soundtype enabled? */ public boolean isEnabled (SoundType type) { // by default, types are enabled.. return (!_disabledTypes.contains(type)); } /** * Turns on or off the specified sound type. */ public void setEnabled (SoundType type, boolean enabled) { if (enabled) { _disabledTypes.remove(type); } else { _disabledTypes.add(type); } } /** * Sets the volume for all sound clips. * * @param vol a volume parameter between 0f and 1f, inclusive. */ public void setClipVolume (float vol) { _clipVol = Math.max(0f, Math.min(1f, vol)); } /** * Get the volume for all sound clips. */ public float getClipVolume () { return _clipVol; } /** * Optionally lock the sound data prior to playing, to guarantee * that it will be quickly available for playing. */ public void lock (String pkgPath, String key) { enqueue(new SoundKey(LOCK, pkgPath, key), true); } /** * Unlock the specified sound so that its resources can be freed. */ public void unlock (String pkgPath, String key) { enqueue(new SoundKey(UNLOCK, pkgPath, key), true); } /** * Batch lock a list of sounds. */ public void lock (String pkgPath, String[] keys) { for (int ii=0; ii < keys.length; ii++) { enqueue(new SoundKey(LOCK, pkgPath, keys[ii]), (ii == 0)); } } /** * Batch unlock a list of sounds. */ public void unlock (String pkgPath, String[] keys) { for (int ii=0; ii < keys.length; ii++) { enqueue(new SoundKey(UNLOCK, pkgPath, keys[ii]), (ii == 0)); } } /** * Play the specified sound as the specified type of sound, immediately. * Note that a sound need not be locked prior to playing. */ public void play (SoundType type, String pkgPath, String key) { play(type, pkgPath, key, 0, 0f); } /** * Play the specified sound as the specified type of sound, immediately, * with the specified pan value. * Note that a sound need not be locked prior to playing. * * @param pan a value from -1f (all left) to +1f (all right). */ public void play (SoundType type, String pkgPath, String key, float pan) { play(type, pkgPath, key, 0, pan); } /** * Play the specified sound after the specified delay. * @param delay the delay in milliseconds. */ public void play (SoundType type, String pkgPath, String key, int delay) { play(type, pkgPath, key, delay, 0f); } /** * Play the specified sound after the specified delay. * @param delay the delay in milliseconds. * @param pan a value from -1f (all left) to +1f (all right). */ public void play ( SoundType type, String pkgPath, String key, int delay, float pan) { if (type == null) { type = DEFAULT; // let the lazy kids play too } if ((_clipVol != 0f) && isEnabled(type)) { final SoundKey skey = new SoundKey(PLAY, pkgPath, key, delay, _clipVol, pan); if (delay > 0) { new Interval() { public void expired () { addToPlayQueue(skey); } }.schedule(delay); } else { addToPlayQueue(skey); } } } /** * Loop the specified sound. */ public Frob loop (SoundType type, String pkgPath, String key) { SoundKey skey = new SoundKey(LOOP, pkgPath, key, 0, _clipVol, 0f); addToPlayQueue(skey); return skey; // it is a frob } /** * Add the sound clip key to the queue to be played. */ protected void addToPlayQueue (SoundKey skey) { boolean queued = enqueue(skey, true); if (queued) { if (_verbose.getValue()) { Log.info("Sound request [key=" + skey.key + "]."); } } else /* if (_verbose.getValue()) */ { Log.warning("SoundManager not playing sound because " + "too many sounds in queue [key=" + skey + "]."); } } /** * Enqueue a new SoundKey. */ protected boolean enqueue (SoundKey key, boolean okToStartNew) { boolean add; boolean queued; synchronized (_queue) { if (key.cmd == PLAY && _queue.size() > MAX_QUEUE_SIZE) { queued = add = false; } else { _queue.appendLoud(key); queued = true; add = okToStartNew && (_freeSpoolers == 0) && (_spoolerCount < MAX_SPOOLERS); if (add) { _spoolerCount++; } } } // and if we need a new thread, add it if (add) { Thread spooler = new Thread("narya SoundManager line spooler") { public void run () { spoolerRun(); } }; spooler.setDaemon(true); spooler.start(); } return queued; } /** * This is the primary run method of the sound-playing threads. */ protected void spoolerRun () { while (true) { try { SoundKey key; synchronized (_queue) { _freeSpoolers++; key = (SoundKey) _queue.get(MAX_WAIT_TIME); _freeSpoolers if (key == null || key.cmd == DIE) { _spoolerCount // if dieing and there are others to kill, do so if (key != null && _spoolerCount > 0) { _queue.appendLoud(key); } return; } } // process the command processKey(key); } catch (Exception e) { Log.logStackTrace(e); } } } /** * Process the requested command in the specified SoundKey. */ protected void processKey (SoundKey key) throws Exception { switch (key.cmd) { case PLAY: case LOOP: playSound(key); break; case LOCK: if (!isTesting()) { synchronized (_clipCache) { try { getClipData(key); // preload // copy cached to lock map _lockedClips.put(key, _clipCache.get(key)); } catch (Exception e) { // don't whine about LOCK failures unless // we are verbosely logging if (_verbose.getValue()) { throw e; } } } } break; case UNLOCK: synchronized (_clipCache) { _lockedClips.remove(key); } break; } } /** * On a spooling thread, */ protected void playSound (SoundKey key) { if (!key.running) { return; } key.thread = Thread.currentThread(); SourceDataLine line = null; try { // get the sound data from our LRU cache byte[] data = getClipData(key); if (data == null) { return; // borked! } else if (key.isExpired()) { if (_verbose.getValue()) { Log.info("Sound expired [key=" + key.key + "]."); } return; } AudioInputStream stream = AudioSystem.getAudioInputStream( new ByteArrayInputStream(data)); if (key.cmd == LOOP) { stream.mark(data.length); } // open the sound line AudioFormat format = stream.getFormat(); line = (SourceDataLine) AudioSystem.getLine( new DataLine.Info(SourceDataLine.class, format)); line.open(format, LINEBUF_SIZE); float setVolume = 1; float setPan = 0f; line.start(); _soundSeemsToWork = true; byte[] buffer = new byte[LINEBUF_SIZE]; do { // play the sound int count = 0; while (key.running && count != -1) { float vol = key.volume; if (vol != setVolume) { adjustVolume(line, vol); setVolume = vol; } float pan = key.pan; if (pan != setPan) { adjustPan(line, pan); setPan = pan; } try { count = stream.read(buffer, 0, buffer.length); } catch (IOException e) { // this shouldn't ever ever happen because the stream // we're given is from a reliable source Log.warning("Error reading clip data! [e=" + e + "]."); return; } if (count >= 0) { line.write(buffer, 0, count); } } // if we're going to loop, reset the stream to the beginning if (key.cmd == LOOP) { stream.reset(); } } while (key.cmd == LOOP && key.running); // sleep the drain time. We never trust line.drain() because // it is buggy and locks up on natively multithreaded systems // (linux, winXP with HT). float sampleRate = format.getSampleRate(); if (sampleRate == AudioSystem.NOT_SPECIFIED) { sampleRate = 11025; // most of our sounds are } int sampleSize = format.getSampleSizeInBits(); if (sampleSize == AudioSystem.NOT_SPECIFIED) { sampleSize = 16; } int drainTime = (int) Math.ceil( (LINEBUF_SIZE * 8 * 1000) / (sampleRate * sampleSize)); // add in a fudge factor of half a second drainTime += 500; try { Thread.sleep(drainTime); } catch (InterruptedException ie) { } } catch (IOException ioe) { Log.warning("Error loading sound file [key=" + key + ", e=" + ioe + "]."); } catch (UnsupportedAudioFileException uafe) { Log.warning("Unsupported sound format [key=" + key + ", e=" + uafe + "]."); } catch (LineUnavailableException lue) { String err = "Line not available to play sound [key=" + key.key + ", e=" + lue + "]."; if (_soundSeemsToWork) { Log.warning(err); } else { // this error comes every goddamned time we play a sound on // someone with a misconfigured sound card, so let's just keep // it to ourselves Log.debug(err); } } finally { if (line != null) { line.close(); } key.thread = null; } } /** * @return true if we're using a test sound directory. */ protected boolean isTesting () { return !StringUtil.isBlank(_testDir.getValue()); } /** * Called by spooling threads, loads clip data from the resource * manager or the cache. */ protected byte[] getClipData (SoundKey key) throws IOException, UnsupportedAudioFileException { byte[][] data; boolean verbose = _verbose.getValue(); synchronized (_clipCache) { // if we're testing, clear all non-locked sounds every time if (isTesting()) { _clipCache.clear(); } data = (byte[][]) _clipCache.get(key); // see if it's in the locked cache (we first look in the regular // clip cache so that locked clips that are still cached continue // to be moved to the head of the LRU queue) if (data == null) { data = (byte[][]) _lockedClips.get(key); } if (data == null) { // if there is a test sound, JUST use the test sound. InputStream stream = getTestClip(key); if (stream != null) { data = new byte[1][]; data[0] = IOUtils.toByteArray(stream); } else { // otherwise, randomize between all available sounds Config c = getConfig(key); String[] names = c.getValue(key.key, (String[])null); if (names == null) { Log.warning("No such sound [key=" + key + "]."); return null; } data = new byte[names.length][]; String bundle = c.getValue("bundle", (String)null); for (int ii=0; ii < names.length; ii++) { data[ii] = loadClipData(bundle, names[ii]); } } _clipCache.put(key, data); } } return (data.length > 0) ? data[RandomUtil.getInt(data.length)] : null; } protected InputStream getTestClip (SoundKey key) { String testDirectory = _testDir.getValue(); if (StringUtil.isBlank(testDirectory)) { return null; } final String namePrefix = key.key; File f = new File(testDirectory); File[] list = f.listFiles(new FilenameFilter() { public boolean accept (File f, String name) { if (name.startsWith(namePrefix)) { String backhalf = name.substring(namePrefix.length()); int dot = backhalf.indexOf('.'); if (dot == -1) { dot = backhalf.length(); } // allow the file if the portion of the name // after the prefix but before the extension is blank // or a parsable integer String extra = backhalf.substring(0, dot); if ("".equals(extra)) { return true; } else { try { Integer.parseInt(extra); // success! return true; } catch (NumberFormatException nfe) { // not a number, we fall through... } } // else fall through } return false; } }); int size = (list == null) ? 0 : list.length; if (size > 0) { File pick = list[RandomUtil.getInt(size)]; try { return new FileInputStream(pick); } catch (Exception e) { Log.warning("Error reading test sound [e=" + e + ", file=" + pick + "]."); } } return null; } /** * Read the data from the resource manager. */ protected byte[] loadClipData (String bundle, String path) throws IOException { InputStream clipin = null; try { clipin = _rmgr.getResource(bundle, path); } catch (FileNotFoundException fnfe) { // try from the classpath try { clipin = _rmgr.getResource(path); } catch (FileNotFoundException fnfe2) { // only play the default sound if we have verbose sound // debuggin turned on. if (_verbose.getValue()) { Log.warning("Could not locate sound data [bundle=" + bundle + ", path=" + path + "]."); if (_defaultClipPath != null) { try { clipin = _rmgr.getResource( _defaultClipBundle, _defaultClipPath); } catch (FileNotFoundException fnfe3) { try { clipin = _rmgr.getResource(_defaultClipPath); } catch (FileNotFoundException fnfe4) { Log.warning("Additionally, the default " + "fallback sound could not be located " + "[bundle=" + _defaultClipBundle + ", path=" + _defaultClipPath + "]."); } } } else { Log.warning("No fallback default sound specified!"); } } // if we couldn't load the default, rethrow if (clipin == null) { throw fnfe2; } } } return IOUtils.toByteArray(clipin); } /** * Get the cached Config. */ protected Config getConfig (SoundKey key) { Config c = (Config) _configs.get(key.pkgPath); if (c == null) { String propPath = key.pkgPath + Sounds.PROP_NAME; Properties props = new Properties(); try { props = ConfigUtil.loadInheritedProperties( propPath + ".properties", _rmgr.getClassLoader()); } catch (IOException ioe) { Log.warning("Failed to load sound properties " + "[path=" + propPath + ", error=" + ioe + "]."); } c = new Config(propPath, props); _configs.put(key.pkgPath, c); } return c; } // /** // * Adjust the volume of this clip. // */ // protected static void adjustVolumeIdeally (Line line, float volume) // if (line.isControlSupported(FloatControl.Type.VOLUME)) { // FloatControl vol = (FloatControl) // line.getControl(FloatControl.Type.VOLUME); // float min = vol.getMinimum(); // float max = vol.getMaximum(); // float ourval = (volume * (max - min)) + min; // Log.debug("adjust vol: [min=" + min + ", ourval=" + ourval + // ", max=" + max + "]."); // vol.setValue(ourval); // } else { // // fall back // adjustVolume(line, volume); /** * Use the gain control to implement volume. */ protected static void adjustVolume (Line line, float vol) { FloatControl control = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN); // the only problem is that gain is specified in decibals, // which is a logarithmic scale. // Since we want max volume to leave the sample unchanged, our // maximum volume translates into a 0db gain. float gain; if (vol == 0f) { gain = control.getMinimum(); } else { gain = (float) ((Math.log(vol) / Math.log(10.0)) * 20.0); } control.setValue(gain); //Log.info("Set gain: " + gain); } /** * Set the pan value for the specified line. */ protected static void adjustPan (Line line, float pan) { try { FloatControl control = (FloatControl) line.getControl(FloatControl.Type.PAN); control.setValue(pan); } catch (Exception e) { Log.debug("Cannot set pan on line: " + e); } } /** * A key for tracking sounds. */ protected static class SoundKey implements Frob { public byte cmd; public String pkgPath; public String key; public long stamp; /** Should we still be running? */ public volatile boolean running = true; public volatile float volume; /** The pan, or 0 to center the sound. */ public volatile float pan; /** The player thread, if it's playing us. */ public Thread thread; /** * Create a SoundKey that just contains the specified command. * DIE. */ public SoundKey (byte cmd) { this.cmd = cmd; } /** * Quicky constructor for music keys and lock operations. */ public SoundKey (byte cmd, String pkgPath, String key) { this(cmd); this.pkgPath = pkgPath; this.key = key; } /** * Constructor for a sound effect soundkey. */ public SoundKey (byte cmd, String pkgPath, String key, int delay, float volume, float pan) { this(cmd, pkgPath, key); stamp = System.currentTimeMillis() + delay; setVolume(volume); setPan(pan); } // documentation inherited from interface Frob public void stop () { running = false; Thread t = thread; if (t != null) { // doesn't actually ever seem to do much t.interrupt(); } } // documentation inherited from interface Frob public void setVolume (float vol) { volume = Math.max(0f, Math.min(1f, vol)); } // documentation inherited from interface Frob public float getVolume () { return volume; } // documentation inherited from interface Frob public void setPan (float newPan) { pan = Math.max(-1f, Math.min(1f, newPan)); } // documentation inherited from interface Frob public float getPan () { return pan; } /** * Has this sound key expired. */ public boolean isExpired () { return (stamp + MAX_SOUND_DELAY < System.currentTimeMillis()); } // documentation inherited public String toString () { return "SoundKey{cmd=" + cmd + ", pkgPath=" + pkgPath + ", key=" + key + "}"; } // documentation inherited public int hashCode () { return pkgPath.hashCode() ^ key.hashCode(); } // documentation inherited public boolean equals (Object o) { if (o instanceof SoundKey) { SoundKey that = (SoundKey) o; return this.pkgPath.equals(that.pkgPath) && this.key.equals(that.key); } return false; } } /** The path of the default sound to use for missing sounds. */ protected String _defaultClipBundle, _defaultClipPath; /** The resource manager from which we obtain audio files. */ protected ResourceManager _rmgr; /** The queue of sound clips to be played. */ protected Queue _queue = new Queue(); /** The number of currently active LineSpoolers. */ protected int _spoolerCount, _freeSpoolers; /** If we every play a sound successfully, this is set to true. */ protected boolean _soundSeemsToWork = false; /** Volume level for sound clips. */ protected float _clipVol = 1f; /** The cache of recent audio clips . */ protected LRUHashMap _clipCache = new LRUHashMap(10); /** The set of locked audio clips; this is separate from the LRU so * that locking clips doesn't booch up an otherwise normal caching * agenda. */ protected HashMap _lockedClips = new HashMap(); /** A set of soundTypes for which sound is enabled. */ protected HashSet _disabledTypes = new HashSet(); /** A cache of config objects we've created. */ protected LRUHashMap _configs = new LRUHashMap(5); /** Soundkey command constants. */ protected static final byte PLAY = 0; protected static final byte LOCK = 1; protected static final byte UNLOCK = 2; protected static final byte DIE = 3; protected static final byte LOOP = 4; /** A pref that specifies a directory for us to get test sounds from. */ protected static RuntimeAdjust.FileAdjust _testDir = new RuntimeAdjust.FileAdjust( "Test sound directory", "narya.media.sound.test_dir", MediaPrefs.config, true, ""); protected static RuntimeAdjust.BooleanAdjust _verbose = new RuntimeAdjust.BooleanAdjust( "Verbose sound event logging", "narya.media.sound.verbose", MediaPrefs.config, false); /** The queue size at which we start to ignore requests to play sounds. */ protected static final int MAX_QUEUE_SIZE = 25; /** The maximum time after which we throw away a sound rather * than play it. */ protected static final long MAX_SOUND_DELAY = 400L; /** The size of the line's buffer. */ protected static final int LINEBUF_SIZE = 8 * 1024; /** The maximum time a spooler will wait for a stream before * deciding to shut down. */ protected static final long MAX_WAIT_TIME = 30000L; /** The maximum number of spoolers we'll allow. This is a lot. */ protected static final int MAX_SPOOLERS = 12; }
package net.sf.jabref.export.layout; import java.util.ArrayList; import java.util.Map; import java.util.Vector; import net.sf.jabref.BibtexDatabase; import net.sf.jabref.BibtexEntry; import net.sf.jabref.Globals; import net.sf.jabref.NameFormatterTab; import net.sf.jabref.Util; import net.sf.jabref.export.layout.format.NameFormat; import wsi.ra.tool.WSITools; import wsi.ra.types.StringInt; /** * DOCUMENT ME! * * @author $author$ * @version $Revision$ */ public class LayoutEntry { // ~ Instance fields private LayoutFormatter[] option; private String text; private LayoutEntry[] layoutEntries; private int type; private String classPrefix; // ~ Constructors public LayoutEntry(StringInt si, String classPrefix_) throws Exception { type = si.i; classPrefix = classPrefix_; if (si.i == LayoutHelper.IS_LAYOUT_TEXT) { text = si.s; } else if (si.i == LayoutHelper.IS_SIMPLE_FIELD) { text = si.s.trim(); } else if (si.i == LayoutHelper.IS_FIELD_START) { } else if (si.i == LayoutHelper.IS_FIELD_END) { } else if (si.i == LayoutHelper.IS_OPTION_FIELD) { Vector v = new Vector(); WSITools.tokenize(v, si.s, "\n"); if (v.size() == 1) { text = (String) v.get(0); } else { text = ((String) v.get(0)).trim(); // try option = getOptionalLayout((String) v.get(1), classPrefix); // catch (Exception e) // e.printStackTrace(); } } // else if (si.i == LayoutHelper.IS_OPTION_FIELD_PARAM) } public LayoutEntry(Vector parsedEntries, String classPrefix_, int layoutType) throws Exception { classPrefix = classPrefix_; String blockStart = null; String blockEnd = null; StringInt si; Vector blockEntries = null; Vector tmpEntries = new Vector(); LayoutEntry le; si = (StringInt) parsedEntries.get(0); blockStart = si.s; si = (StringInt) parsedEntries.get(parsedEntries.size() - 1); blockEnd = si.s; if (!blockStart.equals(blockEnd)) { System.err.println("Field start and end entry must be equal."); } type = layoutType; text = si.s; for (int i = 1; i < (parsedEntries.size() - 1); i++) { si = (StringInt) parsedEntries.get(i); // System.out.println("PARSED-ENTRY: "+si.s+"="+si.i); if (si.i == LayoutHelper.IS_LAYOUT_TEXT) { } else if (si.i == LayoutHelper.IS_SIMPLE_FIELD) { } else if ((si.i == LayoutHelper.IS_FIELD_START) || (si.i == LayoutHelper.IS_GROUP_START)) { blockEntries = new Vector(); blockStart = si.s; } else if ((si.i == LayoutHelper.IS_FIELD_END) || (si.i == LayoutHelper.IS_GROUP_END)) { if (blockStart.equals(si.s)) { blockEntries.add(si); if (si.i == LayoutHelper.IS_GROUP_END) le = new LayoutEntry(blockEntries, classPrefix, LayoutHelper.IS_GROUP_START); else le = new LayoutEntry(blockEntries, classPrefix, LayoutHelper.IS_FIELD_START); tmpEntries.add(le); blockEntries = null; } else { System.out.println("Nested field entries are not implemented !!!"); } } else if (si.i == LayoutHelper.IS_OPTION_FIELD) { } // else if (si.i == LayoutHelper.IS_OPTION_FIELD_PARAM) if (blockEntries == null) { // System.out.println("BLOCK ADD: "+si.s+"="+si.i); tmpEntries.add(new LayoutEntry(si, classPrefix)); } else { blockEntries.add(si); } } layoutEntries = new LayoutEntry[tmpEntries.size()]; for (int i = 0; i < tmpEntries.size(); i++) { layoutEntries[i] = (LayoutEntry) tmpEntries.get(i); // System.out.println(layoutEntries[i].text); } } // ~ Methods public String doLayout(BibtexEntry bibtex, BibtexDatabase database) { if (type == LayoutHelper.IS_LAYOUT_TEXT) { return text; } else if (type == LayoutHelper.IS_SIMPLE_FIELD) { if (text.equals("bibtextype")) { return bibtex.getType().getName(); } String field = getField(bibtex, text, database); if (field == null) { return null; } else { return field; } } else if ((type == LayoutHelper.IS_FIELD_START) || (type == LayoutHelper.IS_GROUP_START)) { String field = getField(bibtex, text, database); // String field = (String) bibtex.getField(text); if ((field == null) || ((type == LayoutHelper.IS_GROUP_START) && (field.equalsIgnoreCase(LayoutHelper .getCurrentGroup())))) { return null; } else { if (type == LayoutHelper.IS_GROUP_START) { LayoutHelper.setCurrentGroup(field); } StringBuffer sb = new StringBuffer(100); String fieldText; boolean previousSkipped = false; for (int i = 0; i < layoutEntries.length; i++) { fieldText = layoutEntries[i].doLayout(bibtex, database); // System.out.println("'" + fieldText + "'"); if (fieldText == null) { if ((i + 1) < layoutEntries.length) { if (layoutEntries[i + 1].doLayout(bibtex, database).trim().length() == 0) { // System.out.println("MISSING: "+bibtex); i++; previousSkipped = true; continue; } } } else { // if previous was skipped --> remove leading line // breaks if (previousSkipped) { int eol = 0; while ((eol < fieldText.length()) && ((fieldText.charAt(eol) == '\n') || (fieldText.charAt(eol) == '\r'))) { eol++; } if (eol < fieldText.length()) { sb.append(fieldText.substring(eol)); } } else { // System.out.println("ENTRY-BLOCK: " + // layoutEntries[i].doLayout(bibtex)); sb.append(fieldText); } } previousSkipped = false; } return sb.toString(); } } else if ((type == LayoutHelper.IS_FIELD_END) || (type == LayoutHelper.IS_GROUP_END)) { } else if (type == LayoutHelper.IS_OPTION_FIELD) { // System.out.println("doLayout IS_OPTION_FIELD '"+text+"'"); String fieldEntry; if (text.equals("bibtextype")) { fieldEntry = bibtex.getType().getName(); } else { // changed section begin - arudert // resolve field (recognized by leading backslash) or text String field = text.startsWith("\\") ? getField(bibtex, text.substring(1), database) : getText(text, database); // changed section end - arudert // String field = (String) bibtex.getField(text); if (field == null) { fieldEntry = ""; } else { fieldEntry = field; } } // System.out.println("OPTION: "+option); if (option != null) { for (int i = 0; i < option.length; i++) { fieldEntry = option[i].format(fieldEntry); } } return fieldEntry; } // else if (type == LayoutHelper.IS_OPTION_FIELD_PARAM) return ""; } // added section - begin (arudert) /** * Do layout for general formatters (no bibtex-entry fields). * * @param database * Bibtex Database * @return */ public String doLayout(BibtexDatabase database) { if (type == LayoutHelper.IS_LAYOUT_TEXT) { return text; } else if (type == LayoutHelper.IS_SIMPLE_FIELD) { throw new UnsupportedOperationException( "bibtext entry fields not allowed in begin or end layout"); } else if ((type == LayoutHelper.IS_FIELD_START) || (type == LayoutHelper.IS_GROUP_START)) { throw new UnsupportedOperationException( "field and group starts not allowed in begin or end layout"); } else if ((type == LayoutHelper.IS_FIELD_END) || (type == LayoutHelper.IS_GROUP_END)) { throw new UnsupportedOperationException( "field and group ends not allowed in begin or end layout"); } else if (type == LayoutHelper.IS_OPTION_FIELD) { String field = getText(text, database); if (option != null) { for (int i = 0; i < option.length; i++) { field = option[i].format(field); } } return field; } return ""; } // added section - end (arudert) public static LayoutFormatter getLayoutFormatter(String className, String classPrefix) throws Exception { LayoutFormatter f = null; if (className.length() > 0) { try { try { f = (LayoutFormatter) Class.forName(classPrefix + className).newInstance(); } catch (Throwable ex2) { f = (LayoutFormatter) Class.forName(className).newInstance(); } } catch (ClassNotFoundException ex) { throw new Exception(Globals.lang("Formatter not found") + ": " + className); } catch (InstantiationException ex) { throw new Exception(className + " can not be instantiated."); } catch (IllegalAccessException ex) { throw new Exception(className + " can't be accessed."); } } return f; } /** * Return an array of LayoutFormatters found in the given formatterName * string (in order of appearance). * */ public static LayoutFormatter[] getOptionalLayout(String formatterName, String classPrefix) throws Exception { ArrayList formatterStrings = Util.parseMethodsCalls(formatterName); ArrayList results = new ArrayList(formatterStrings.size()); Map userNameFormatter = NameFormatterTab.getNameFormatters(); for (int i = 0; i < formatterStrings.size(); i++) { String[] strings = (String[]) formatterStrings.get(i); String className = strings[0].trim(); try { LayoutFormatter f = getLayoutFormatter(className, classPrefix); results.add(f); } catch (Exception e) { String formatterParameter = (String) userNameFormatter.get(className); if (formatterParameter == null) { throw new Exception(Globals.lang("Formatter not found") + ": " + className); } else { NameFormat nf = new NameFormat(); nf.setParameter(formatterParameter); results.add(nf); } } } return (LayoutFormatter[]) results.toArray(new LayoutFormatter[] {}); } // changed section begin - arudert /** * Returns a text with references resolved according to an optionally given * database. */ private String getText(String text, BibtexDatabase database) { String res = text; // changed section end - arudert if ((res != null) && (database != null)) res = database.resolveForStrings(res); return res; } // changed section end - arudert private String getField(BibtexEntry bibtex, String field, BibtexDatabase database) { // Change: Morten Alver, May 23, 2006. Formatter argument uses this // method to // resolve field values. We need this part to resolve \bibtextype // correctly in // constructs like \format[ToLowerCase]{\bibtextype}: if (field.equals("bibtextype")) { return bibtex.getType().getName(); } // end change Morten Alver String res = (String) bibtex.getField(field); if ((res != null) && (database != null)) res = database.resolveForStrings(res); return res; } } // END OF FILE.
package org.concord.sensor.nativelib; import org.concord.framework.data.stream.DataListener; import org.concord.framework.data.stream.DataStreamEvent; import org.concord.framework.text.UserMessageHandler; import org.concord.sensor.DeviceConfig; import org.concord.sensor.SensorConfig; import org.concord.sensor.SensorDataManager; import org.concord.sensor.SensorDataProducer; import org.concord.sensor.SensorRequest; import org.concord.sensor.device.impl.DeviceConfigImpl; import org.concord.sensor.device.impl.InterfaceManager; import org.concord.sensor.device.impl.JavaDeviceFactory; import org.concord.sensor.impl.ExperimentRequestImpl; import org.concord.sensor.impl.SensorRequestImpl; import org.concord.sensor.state.PrintUserMessageHandler; /** * @author Informaiton Services * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class TestNative { public static void main(String[] args) { UserMessageHandler messenger = new PrintUserMessageHandler(); SensorDataManager sdManager = new InterfaceManager(messenger); // This should be loaded from the OTrunk. Each computer // might have a different set of devices configured. DeviceConfig [] dConfigs = new DeviceConfig[1]; dConfigs[0] = new DeviceConfigImpl(JavaDeviceFactory.VERNIER_GO_LINK, null); ((InterfaceManager)sdManager).setDeviceConfigs(dConfigs); ExperimentRequestImpl request = new ExperimentRequestImpl(); request.setPeriod(0.1f); request.setNumberOfSamples(-1); SensorRequestImpl sensor = new SensorRequestImpl(); sensor.setDisplayPrecision(-2); sensor.setRequiredMax(Float.NaN); sensor.setRequiredMin(Float.NaN); sensor.setPort(0); sensor.setStepSize(0.1f); sensor.setType(SensorConfig.QUANTITY_TEMPERATURE); request.setSensorRequests(new SensorRequest [] {sensor}); SensorDataProducer sDataProducer = sdManager.createDataProducer(); sDataProducer.configure(request); sDataProducer.addDataListener(new DataListener(){ public void dataReceived(DataStreamEvent dataEvent) { int numSamples = dataEvent.getNumSamples(); float [] data = dataEvent.getData(); if(numSamples > 0) { System.out.println("" + numSamples + " " + data[0]); System.out.flush(); } else { System.out.println("" + numSamples); } } public void dataStreamEvent(DataStreamEvent dataEvent) { String eventString; int eventType = dataEvent.getType(); if(eventType == 1001) return; switch(eventType) { case DataStreamEvent.DATA_READY_TO_START: eventString = "Ready to start"; break; case DataStreamEvent.DATA_STOPPED: eventString = "Stopped"; break; case DataStreamEvent.DATA_DESC_CHANGED: eventString = "Description changed"; break; default: eventString = "Unknown event type"; } System.out.println("Data Event: " + eventString); } }); sDataProducer.start(); System.out.println("started device"); try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } sDataProducer.stop(); sDataProducer.close(); System.exit(0); } }
package org.jivesoftware.messenger; import org.xmpp.packet.Packet; /** * <p>An uber router that can handle any packet type.</p> * <p>The interface is provided primarily as a convenience for services * that must route all packet types (e.g. s2s routing, e2e encryption, etc).</p> * * @author Iain Shigeoka */ public interface PacketRouter extends IQRouter, MessageRouter, PresenceRouter { public void route(Packet packet) throws IllegalArgumentException, NullPointerException; }
package us.kbase.mobu.validator; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.yaml.snakeyaml.Yaml; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import us.kbase.kidl.KbFuncdef; import us.kbase.kidl.KbList; import us.kbase.kidl.KbModule; import us.kbase.kidl.KbModuleComp; import us.kbase.kidl.KbScalar; import us.kbase.kidl.KbService; import us.kbase.kidl.KbStruct; import us.kbase.kidl.KbStructItem; import us.kbase.kidl.KbTuple; import us.kbase.kidl.KbType; import us.kbase.kidl.KbTypedef; import us.kbase.kidl.KidlParser; import us.kbase.mobu.util.TextUtils; import us.kbase.narrativemethodstore.NarrativeMethodStoreClient; import us.kbase.narrativemethodstore.ValidateMethodParams; import us.kbase.narrativemethodstore.ValidationResults; public class ModuleValidator { private static final String KBASE_YML_FILE = "kbase.yml"; protected List<String> modulePaths; protected boolean verbose; protected String methodStoreUrl; protected boolean allowSyncMethods; public ModuleValidator(List<String> modulePaths, boolean verbose, String methodStoreUrl, boolean allowSyncMethods) { this.modulePaths = modulePaths; this.verbose = verbose; this.methodStoreUrl = methodStoreUrl; this.allowSyncMethods = allowSyncMethods; } private static boolean isModuleDir(File dir) { return new File(dir, "Dockerfile").exists() && new File(dir, "Makefile").exists() && new File(dir, "kbase.yml").exists() && new File(dir, "lib").exists() && new File(dir, "scripts").exists() && new File(dir, "test").exists() && new File(dir, "ui").exists(); } public int validateAll() { int errors = 0; for(String modulePathString : modulePaths) { File module = new File(modulePathString); System.out.println("\nValidating module in ("+module+")"); if(!module.exists()) { System.err.println(" **ERROR** - the module does not exist"); errors++; continue; } if(!module.isDirectory()) { System.err.println(" **ERROR** - the module location is not a directory."); errors++; continue; } try { if(verbose) System.out.println(" - canonical path = "+module.getCanonicalPath()+""); File dir = module.getCanonicalFile(); while (!isModuleDir(dir)) { dir = dir.getParentFile(); if (dir == null) throw new IllegalStateException(" **ERROR** - cannot find folder with module structure"); } module = dir; } catch (IOException e) { System.err.println(" **ERROR** - unable to extract module canonical path:"); System.err.println(" "+e.getMessage()); } // 1) Validate the configuration file try { int status = validateKBaseYmlConfig(module); if(status!=0) { errors++; continue; } } catch (Exception e) { System.err.println(" **ERROR** - configuration file validation failed:"); System.err.println(" "+e.getMessage()); errors++; continue; } KbModule parsedKidl = null; try { Map<String,Object> config = parseKBaseYaml(new File(module, KBASE_YML_FILE)); String moduleName = (String)config.get("module-name"); if (moduleName == null) throw new IllegalStateException("\"module-name\" key isn't found in " + KBASE_YML_FILE); File specFile = new File(module, moduleName + ".spec"); if (!specFile.exists()) throw new IllegalStateException("Spec-file isn't found: " + specFile); List<KbService> services = KidlParser.parseSpec(KidlParser.parseSpecInt(specFile, null)); if (services.size() != 1) throw new IllegalStateException("Unexpected number of services found: " + services.size()); KbService srv = services.get(0); if (srv.getModules().size() != 1) throw new IllegalStateException("Unexpected number of modules found: " + srv.getModules().size()); parsedKidl = srv.getModules().get(0); } catch (Exception e) { System.err.println(" **ERROR** - KIDL-spec validation failed:"); System.err.println(" "+e.getMessage()); errors++; continue; } // 2) Validate UI components // 2a) Validate Narrative Methods File uiNarrativeMethodsDir = new File(new File(new File(module, "ui"), "narrative"), "methods"); if (uiNarrativeMethodsDir.exists()) { for (File methodDir : uiNarrativeMethodsDir.listFiles()) { if (methodDir.isDirectory()) { System.out.println("\nValidating method in ("+methodDir+")"); try { int status = validateMethodSpec(methodDir, parsedKidl, this.allowSyncMethods); if (status != 0) { errors++; continue; } } catch (Exception e) { System.err.println(" **ERROR** - method-spec validation failed:"); System.err.println(" "+e.getMessage()); errors++; continue; } } } } } if(errors>0) { if(modulePaths.size()==1) { System.out.println("\n\nThis module contains errors.\n"); } else { System.out.println("\n\nErrors detected in "+errors +" of "+modulePaths.size()+" modules.\n"); } return 1; } if(modulePaths.size()==1) { System.out.println("\n\nCongrats- this module is valid.\n"); } else { System.out.println("\n\nCongrats- all "+modulePaths.size()+" modules are valid.\n"); } return 0; } protected int validateKBaseYmlConfig(File module) throws IOException { File kbaseYmlFile = new File(module.getCanonicalPath()+File.separator+KBASE_YML_FILE); if(verbose) System.out.println(" - configuration file = "+kbaseYmlFile); if(!kbaseYmlFile.exists()) { System.err.println(" **ERROR** - "+KBASE_YML_FILE+" configuration file does not exist in module directory."); return 1; } if(kbaseYmlFile.isDirectory()) { System.err.println(" **ERROR** - "+KBASE_YML_FILE+" configuration file location is a directory, not a file."); return 1; } try { parseKBaseYaml(kbaseYmlFile); if(verbose) System.out.println(" - configuration file is valid YAML"); } catch(Exception e) { System.err.println(" **ERROR** - "+KBASE_YML_FILE+" configuration file location is invalid:"); System.err.println(" "+e.getMessage()); return 1; } return 0; } @SuppressWarnings("unchecked") public Map<String,Object> parseKBaseYaml(File kbaseYmlFile) throws IOException { Yaml yaml = new Yaml(); String kbaseYml = TextUtils.readFileText(kbaseYmlFile); return (Map<String, Object>) yaml.load(kbaseYml); } protected int validateMethodSpec(File methodDir, KbModule parsedKidl, boolean allowSyncMethods) throws IOException { NarrativeMethodStoreClient nms = new NarrativeMethodStoreClient(new URL(methodStoreUrl)); nms.setAllSSLCertificatesTrusted(true); nms.setIsInsecureHttpConnectionAllowed(true); String spec = FileUtils.readFileToString(new File(methodDir, "spec.json")); String display = FileUtils.readFileToString(new File(methodDir, "display.yaml")); Map<String, String> extraFiles = new LinkedHashMap<String, String>(); for (File f : methodDir.listFiles()) { if (f.isFile() && f.getName().endsWith(".html")) extraFiles.put(f.getName(), FileUtils.readFileToString(f)); } try { ValidationResults vr = nms.validateMethod(new ValidateMethodParams().withId( methodDir.getName()).withSpecJson(spec).withDisplayYaml(display) .withExtraFiles(extraFiles)); if (vr.getIsValid() == 1L) { if (vr.getWarnings().size() > 0) { System.err.println(" **WARNINGS** - method-spec validation:"); for (int num = 0; num < vr.getWarnings().size(); num++) { String warn = vr.getWarnings().get(num); System.err.println(" (" + (num + 1) + ") " + warn); } } validateMethodSpecMapping(spec, parsedKidl, allowSyncMethods); return 0; } System.err.println(" **ERROR** - method-spec validation failed:"); for (int num = 0; num < vr.getErrors().size(); num++) { String error = vr.getErrors().get(num); System.err.println(" (" + (num + 1) + ") " + error); } return 1; } catch (Exception e) { System.err.println(" **ERROR** - method-spec validation failed:"); System.err.println(" "+e.getMessage()); return 1; } } protected void validateMethodSpecMapping(String specText, KbModule parsedKidl, boolean allowSyncMethods) throws IOException { JsonNode spec = new ObjectMapper().readTree(specText); if (!allowSyncMethods) { String jobId = get("/", spec, "job_id_output_field").asText(); if (!jobId.equals("docker")) { throw new IllegalStateException(" **ERROR** - can't find \"docker\" value within path " + "[job_id_output_field] in spec.json"); } } else if (spec.get("job_id_output_field") == null || !spec.get("job_id_output_field").asText().equals("docker")) { System.err.println(" **WARNINGS** - method is declared as synchronous and " + "will be skipped"); return; } JsonNode parametersNode = get("/", spec, "parameters"); Map<String, JsonNode> inputParamIdToType = new TreeMap<String, JsonNode>(); for (int i = 0; i < parametersNode.size(); i++) { JsonNode paramNode = parametersNode.get(i); String paramPath = "parameters/" + i; String paramId = get(paramPath, paramNode, "id").asText(); inputParamIdToType.put(paramId, paramNode); } JsonNode behaviorNode = get("/", spec, "behavior"); JsonNode serviceMappingNode = get("behavior", behaviorNode, "service-mapping"); String moduleName = get("behavior/service-mapping", serviceMappingNode, "name").asText(); String methodName = get("behavior/service-mapping", serviceMappingNode, "method").asText(); if (methodName.contains(".")) { String[] parts = methodName.split(Pattern.quote(".")); moduleName = parts[0]; methodName = parts[1]; } KbFuncdef func = null; for (KbModuleComp mc : parsedKidl.getModuleComponents()) { if (mc instanceof KbFuncdef) { KbFuncdef f = (KbFuncdef)mc; if (f.getName().equals(methodName)) { func = f; break; } } } if (func == null) { throw new IllegalStateException(" **ERROR** - unknown method \"" + methodName + "\" defined within path " + "[behavior/service-mapping/method] in spec.json"); } if (!parsedKidl.getModuleName().equals(moduleName)) { throw new IllegalStateException(" **ERROR** - value doesn't match " + "\"" + parsedKidl.getModuleName() + "\" within path " + "[behavior/service-mapping/name] in spec.json"); } String serviceUrl = get("behavior/service-mapping", serviceMappingNode, "url").asText(); if (serviceUrl.length() > 0) { throw new IllegalStateException(" **ERROR** - async method has non-empty value within path " + "[behavior/service-mapping/url] in spec.json"); } JsonNode paramsMappingNode = get("behavior/service-mapping", serviceMappingNode, "input_mapping"); Set<String> paramsUsed = new TreeSet<String>(); Set<Integer> argsUsed = new TreeSet<Integer>(); for (int j = 0; j < paramsMappingNode.size(); j++) { JsonNode paramMappingNode = paramsMappingNode.get(j); String path = "behavior/service-mapping/input_mapping/" + j; JsonNode targetArgPosNode = paramMappingNode.get("target_argument_position"); int targetArgPos = 0; if (targetArgPosNode != null && !targetArgPosNode.isNull()) targetArgPos = targetArgPosNode.asInt(); if (targetArgPos >= func.getParameters().size()) { throw new IllegalStateException(" **ERROR** - value " + targetArgPos + " within " + "path [" + path + "/target_argument_position] in spec.json is out of " + "bounds (number of arguments defined for function \"" + methodName + "\" " + "is " + func.getParameters().size() + ")"); } argsUsed.add(targetArgPos); KbType argType = func.getParameters().get(targetArgPos).getType(); while (argType instanceof KbTypedef) { KbTypedef ref = (KbTypedef)argType; argType = ref.getAliasType(); } JsonNode targetPropNode = paramMappingNode.get("target_property"); if (targetPropNode != null && !targetPropNode.isNull()) { String targetProp = targetPropNode.asText(); if (argType instanceof KbScalar || argType instanceof KbList || argType instanceof KbTuple) { throw new IllegalStateException(" **ERROR** - value " + targetProp + " within " + "path [" + path + "/target_property] in spec.json can't be applied to " + "type " + argType.getClass().getSimpleName() + " (defined for argument " + targetArgPos + ")"); } if (argType instanceof KbStruct) { KbStruct struct = (KbStruct)argType; boolean found = false; for (KbStructItem item : struct.getItems()) { if (item.getName() != null && item.getName().equals(targetProp)) { found = true; break; } } if (!found) { System.err.println(" **WARNINGS** - value \"" + targetProp + "\" within " + "path [" + path + "/target_property] in spec.json doesn't match " + "any field of structure defined as argument type" + (struct.getName() != null ? (" (" + struct.getName() + ")") : "")); } } } JsonNode inputParamObj = paramMappingNode.get("input_parameter"); if (inputParamObj != null && !inputParamObj.isNull()) { String inputParamId = inputParamObj.asText(); if (!inputParamIdToType.containsKey(inputParamId)) { throw new IllegalStateException(" **ERROR** - value \"" + inputParamId + "\" " + "within path [" + path + "/input_parameter] in spec.json is not any " + "input ID listed in \"parameters\" block"); } paramsUsed.add(inputParamId); } } if (func.getParameters().size() != argsUsed.size()) { throw new IllegalStateException(" **ERROR** - not all arguments are set for function " + "\"" + func.getName() + "\", list of defined arguments is: " + argsUsed); } if (inputParamIdToType.size() != paramsUsed.size()) { Set<String> paramsNotUsed = new TreeSet<String>(inputParamIdToType.keySet()); paramsNotUsed.removeAll(paramsUsed); System.err.println(" **WARNINGS** - some of input parameters are not used: " + paramsNotUsed); } } private static JsonNode get(String nodePath, JsonNode node, String childName) { JsonNode ret = node.get(childName); if (ret == null) throw new IllegalStateException(" **ERROR** - can't find sub-node [" + childName + "] within path [" + nodePath + "] in spec.json"); return ret; } }
package abra.cadabra; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import abra.SAMRecordUtils; import htsjdk.samtools.CigarElement; import htsjdk.samtools.SAMFileHeader; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SamReader; public class SpliceJunctionCounter { Map<SpliceJunction, Integer> uniqueReads = new HashMap<SpliceJunction, Integer>(); Map<SpliceJunction, Integer> multiMapReads = new HashMap<SpliceJunction, Integer>(); public void countSplices(String input) { SamReader reader = SAMRecordUtils.getSamReader(input); for (SAMRecord read : reader) { if (read.getCigarString().contains("N")) { for (SpliceJunction junc : getJunctions(read)) { incrementCount(junc, read); } } } List<SpliceJunction> junctions = new ArrayList<SpliceJunction>(uniqueReads.keySet()); Collections.sort(junctions, new SpliceJunctionComparator(reader.getFileHeader())); for (SpliceJunction junction : junctions) { String rec = String.format("%s\t%d\t%d\t.\t.\t.\t%d\t%d\t.", junction.chrom, junction.start, junction.stop, uniqueReads.get(junction), multiMapReads.get(junction)); System.out.println(rec); } } private void incrementCount(SpliceJunction junction, SAMRecord read) { if (!uniqueReads.containsKey(junction)) { uniqueReads.put(junction, 0); } if (!multiMapReads.containsKey(junction)) { multiMapReads.put(junction, 0); } // TODO: Hardcoded to STAR values here. if (read.getMappingQuality() == 255) { uniqueReads.put(junction, uniqueReads.get(junction)+1); } else { multiMapReads.put(junction, multiMapReads.get(junction)+1); } } private List<SpliceJunction> getJunctions(SAMRecord read) { List<SpliceJunction> junctions = new ArrayList<SpliceJunction>(); int pos = read.getAlignmentStart(); for (CigarElement elem : read.getCigar()) { switch (elem.getOperator()) { case D: case M: pos += elem.getLength(); break; case N: junctions.add(new SpliceJunction(read.getReferenceName(), pos+1, pos+elem.getLength()-1)); pos += elem.getLength(); break; case S: case I: case H: // NOOP break; default: throw new UnsupportedOperationException("Unsupported Cigar Operator: " + elem.getOperator()); } } return junctions; } static class SpliceJunctionComparator implements Comparator<SpliceJunction> { private SAMFileHeader header; public SpliceJunctionComparator(SAMFileHeader header) { this.header = header; } @Override public int compare(SpliceJunction j1, SpliceJunction j2) { int idx1 = header.getSequenceIndex(j1.chrom); int idx2 = header.getSequenceIndex(j2.chrom); if (idx1 != idx2) { return idx1-idx2; } if (j1.start != j2.start) { return j1.start - j2.start; } return j1.stop - j2.stop; } } static class SpliceJunction { String chrom; int start; int stop; public SpliceJunction(String chrom, int start, int stop) { this.chrom = chrom; this.start = start; this.stop = stop; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((chrom == null) ? 0 : chrom.hashCode()); result = prime * result + start; result = prime * result + stop; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SpliceJunction other = (SpliceJunction) obj; if (chrom == null) { if (other.chrom != null) return false; } else if (!chrom.equals(other.chrom)) return false; if (start != other.start) return false; if (stop != other.stop) return false; return true; } } public static void main(String[] args) { String input = args[0]; SpliceJunctionCounter counter = new SpliceJunctionCounter(); counter.countSplices(input); } }
package ameba.db.migration; import ameba.core.Application; import ameba.db.migration.models.MigrationInfo; import ameba.exception.AmebaException; import ameba.i18n.Messages; import ameba.util.IOUtils; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.text.StrSubstitutor; import org.flywaydb.core.Flyway; import javax.annotation.Priority; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.HttpMethod; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.PreMatching; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; import java.net.URI; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.Map; import static ameba.db.migration.MigrationFeature.migrationMap; import static ameba.db.migration.MigrationFeature.uri; /** * @author icode */ @PreMatching @Priority(Integer.MIN_VALUE) @Singleton public class MigrationFilter implements ContainerRequestFilter { private static final String MIGRATION_HTML; private static final String FAVICON_ICO = "favicon.ico"; static { try { MIGRATION_HTML = IOUtils.readFromResource("db/migration/migration.html"); } catch (IOException e) { throw new AmebaException(e); } } @Inject private Application application; @Inject private Application.Mode mode; private boolean ran = false; private boolean rewriteMethod = false; private List<Migration> migrations; @Override public void filter(ContainerRequestContext req) throws IOException { if (!ran) { String path = req.getUriInfo().getPath(); if (path.equals(FAVICON_ICO) || path.endsWith("/" + FAVICON_ICO)) { return; } if (path.equals(uri) && req.getMethod().equalsIgnoreCase(HttpMethod.POST) && migrations.size() > 0) { migrate(req); } else { migrations = Lists.newArrayList(); for (Migration migration : migrationMap.values()) { if (migration.hasChanged()) { migrations.add(migration); } } if (migrations.size() > 0) { // todo Migration migration = migrations.get(0); MigrationInfo info = migration.generate().get(0); String dbName = info.getDatabaseName(); Flyway flyway = MigrationFeature.getMigration(dbName); boolean hasTable; try (Connection connection = flyway.getDataSource().getConnection()) { hasTable = connection.getMetaData().getTables(null, null, flyway.getTable(), null).next(); } catch (SQLException e) { throw new AmebaException(e); } if (mode.isDev() || path.equals(uri) && req.getMethod().equals(HttpMethod.GET)) { Map<String, String> valuesMap = Maps.newHashMap(); valuesMap.put("migrationUri", "/" + uri); valuesMap.put("pageTitle", Messages.get("view.app.database.migration.page.title")); valuesMap.put("title", Messages.get("view.app.database.migration.title", dbName)); if (hasTable) { valuesMap.put("subTitle", Messages.get("view.app.database.migration.subTitle")); valuesMap.put("description", Messages.get("view.app.database.migration.description")); valuesMap.put("applyButtonText", Messages.get("view.app.database.migration.apply.button")); } else { valuesMap.put("applyButtonText", Messages.get("view.app.database.migration.baseline.button")); valuesMap.put("subTitle", Messages.get("view.app.database.migration.baseline.subTitle")); valuesMap.put("description", Messages.get("view.app.database.migration.baseline.description")); } valuesMap.put("applyDdl", info.getDiffDdl()); StrSubstitutor sub = new StrSubstitutor(valuesMap); req.abortWith( Response.serverError() .entity(sub.replace(MIGRATION_HTML)) .type(MediaType.TEXT_HTML_TYPE) .build() ); } } else if (!mode.isDev()) { ran = true; } } } else if (rewriteMethod) { if (HttpMethod.POST.equals(req.getMethod())) { req.setMethod(HttpMethod.GET); rewriteMethod = false; } } } private void migrate(ContainerRequestContext req) { Map<String, Object> properties = application.getProperties(); //todo ,dev //todo //todo {dbName} {generatedName} from web ui //todo flyway.getTable()migrationInfomigrationInfoflyway.baseline() for (String dbName : migrationMap.keySet()) { if (!"false".equals(properties.get("db." + dbName + ".migration.enabled"))) { Migration migration = migrationMap.get(dbName); String generatedName = (mode.isDev() ? "dev " : "") + "migrate"; MigrationInfo info = migration.generate().get(0); info.setName(generatedName); Flyway flyway = MigrationFeature.getMigration(dbName); flyway.setBaselineDescription(info.getName()); flyway.setBaselineVersionAsString(info.getRevision()); flyway.migrate(); migration.persist(); migration.reset(); ran = true; rewriteMethod = true; } } String referer = req.getHeaders().getFirst("Referer"); if (StringUtils.isBlank(referer)) { referer = "/"; } req.abortWith(Response.temporaryRedirect(URI.create(referer)).build()); } }
package ca.etsmtl.gti710.openErp; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import org.apache.xmlrpc.XmlRpcException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; public class ClientAPI { private String host = null; private int port = 0; private String login = null; private String password = null; private String database = null; private int userId; public ClientAPI() { } public void connect() { Object[] params; XmlRpcClient xmlrpcLogin = new XmlRpcClient(); XmlRpcClientConfigImpl xmlrpcConfigLogin = new XmlRpcClientConfigImpl(); xmlrpcConfigLogin.setEnabledForExtensions(true); try { xmlrpcConfigLogin.setServerURL(new URL("http", host, port, "/xmlrpc/common")); } catch (MalformedURLException e) { e.printStackTrace(); } xmlrpcLogin.setConfig(xmlrpcConfigLogin); try { //Connect params = new Object[] {database, login, password}; Object id = xmlrpcLogin.execute("login", params); if (id instanceof Integer) { userId = (Integer)id; } } catch (XmlRpcException e) { //logger.warn("XmlException Error while logging to OpenERP: ",e); System.out.println(e); } catch (Exception e) { //logger.warn("Error while logging to OpenERP: ",e); System.out.println(e); } } public HashMap<String, Object> readProduct(int product_id) { XmlRpcClient xmlrpcLogin = new XmlRpcClient(); XmlRpcClientConfigImpl xmlrpcConfigLogin = new XmlRpcClientConfigImpl(); xmlrpcConfigLogin.setEnabledForExtensions(true); try { xmlrpcConfigLogin.setServerURL(new URL("http", host, port, "/xmlrpc/object")); } catch (MalformedURLException e) { e.printStackTrace(); } xmlrpcLogin.setConfig(xmlrpcConfigLogin); try { Object read[]=new Object[7]; read[0]=database; read[1]=userId; // ID de l'utilisateur read[2]=password; //mot de passe //TODO Put those elements in the method parameters read[3]="product.product"; read[4]="read"; read[5] = product_id; read[6] = null; @SuppressWarnings("unchecked") HashMap<String, Object> result = (HashMap<String, Object>)xmlrpcLogin.execute("execute", read); return result; } catch (XmlRpcException e) { //logger.warn("XmlException Error while logging to OpenERP: ",e); System.out.println(e); } catch (Exception e) { //logger.warn("Error while logging to OpenERP: ",e); System.out.println(e); } return null; } public void setHost(String host) { this.host = host; } public void setPort(int port) { this.port = port; } public void setLogin(String login) { this.login = login; } public void setPassword(String password) { this.password = password; } public void setDatabase(String database) { this.database = database; } }
package com.arangodb.model; import java.util.Collection; import java.util.Map; public class AqlQueryOptions { private Boolean count; private Integer ttl; private Integer batchSize; private Boolean cache; private Map<String, Object> bindVars; private String query; private Options options; public AqlQueryOptions() { super(); } public Boolean getCount() { return count; } /** * @param count * indicates whether the number of documents in the result set should be returned in the "count" * attribute of the result. Calculating the "count" attribute might have a performance impact for some * queries in the future so this option is turned off by default, and "count" is only returned when * requested. * @return options */ public AqlQueryOptions count(final Boolean count) { this.count = count; return this; } public Integer getTtl() { return ttl; } /** * @param ttl * The time-to-live for the cursor (in seconds). The cursor will be removed on the server automatically * after the specified amount of time. This is useful to ensure garbage collection of cursors that are * not fully fetched by clients. If not set, a server-defined value will be used. * @return options */ public AqlQueryOptions ttl(final Integer ttl) { this.ttl = ttl; return this; } public Integer getBatchSize() { return batchSize; } /** * @param batchSize * maximum number of result documents to be transferred from the server to the client in one roundtrip. * If this attribute is not set, a server-controlled default value will be used. A batchSize value of 0 * is disallowed. * @return options */ public AqlQueryOptions batchSize(final Integer batchSize) { this.batchSize = batchSize; return this; } public Boolean getCache() { return cache; } /** * @param cache * flag to determine whether the AQL query cache shall be used. If set to false, then any query cache * lookup will be skipped for the query. If set to true, it will lead to the query cache being checked * for the query if the query cache mode is either on or demand. * @return options */ public AqlQueryOptions cache(final Boolean cache) { this.cache = cache; return this; } protected Map<String, Object> getBindVars() { return bindVars; } protected AqlQueryOptions bindVars(final Map<String, Object> bindVars) { this.bindVars = bindVars; return this; } protected String getQuery() { return query; } protected AqlQueryOptions query(final String query) { this.query = query; return this; } public Boolean getProfile() { return options != null ? options.profile : null; } /** * @param profile * If set to true, then the additional query profiling information will be returned in the sub-attribute * profile of the extra return attribute if the query result is not served from the query cache. * @return options */ public AqlQueryOptions profile(final Boolean profile) { getOptions().profile = profile; return this; } public Boolean getFullCount() { return options != null ? options.fullCount : null; } /** * @param fullCount * if set to true and the query contains a LIMIT clause, then the result will have an extra attribute * with the sub-attributes stats and fullCount, { ... , "extra": { "stats": { "fullCount": 123 } } }. The * fullCount attribute will contain the number of documents in the result before the last LIMIT in the * query was applied. It can be used to count the number of documents that match certain filter criteria, * but only return a subset of them, in one go. It is thus similar to MySQL's SQL_CALC_FOUND_ROWS hint. * Note that setting the option will disable a few LIMIT optimizations and may lead to more documents * being processed, and thus make queries run longer. Note that the fullCount attribute will only be * present in the result if the query has a LIMIT clause and the LIMIT clause is actually used in the * query. * @return options */ public AqlQueryOptions fullCount(final Boolean fullCount) { getOptions().fullCount = fullCount; return this; } public Integer getMaxPlans() { return options != null ? options.maxPlans : null; } public AqlQueryOptions maxPlans(final Integer maxPlans) { getOptions().maxPlans = maxPlans; return this; } public Collection<String> getRules() { return options != null ? options.optimizer != null ? options.optimizer.rules : null : null; } /** * * @param rules * A list of to-be-included or to-be-excluded optimizer rules can be put into this attribute, telling the * optimizer to include or exclude specific rules. To disable a rule, prefix its name with a -, to enable * a rule, prefix it with a +. There is also a pseudo-rule all, which will match all optimizer rules * @return options */ public AqlQueryOptions rules(final Collection<String> rules) { getOptions().getOptimizer().rules = rules; return this; } protected Options getOptions() { if (options == null) { options = new Options(); } return options; } public static class Options { private Boolean profile; private Optimizer optimizer; private Boolean fullCount; private Integer maxPlans; protected Optimizer getOptimizer() { if (optimizer == null) { optimizer = new Optimizer(); } return optimizer; } } public static class Optimizer { private Collection<String> rules; } }
package com.areen.jlib.pattern; /** * An empty interface which is going to be used to specify that a certain object * is going to be used as a (Data) Transfer Object. I have decided to rename it * to "Value Object" because acronym "VO" is less confusing than "TO" (for Transfer * Object). * * @author dejan */ public interface ValueObject { /** * A Field interface to be implemented by a SimpleObject nested enum type. * DO NOT implement it inside a ValueObject implementation because it will just make things complicated. * Instead, as noted above, implement it in the SimpleObject implementation. */ public interface Field { } } // ValueObject interface
package com.blobcity.db.search; import com.blobcity.db.exceptions.InternalAdapterException; import static com.blobcity.db.search.ParamOperator.BETWEEN; import static com.blobcity.db.search.ParamOperator.EQ; import static com.blobcity.db.search.ParamOperator.GT; import static com.blobcity.db.search.ParamOperator.GT_EQ; import static com.blobcity.db.search.ParamOperator.IN; import static com.blobcity.db.search.ParamOperator.LT; import static com.blobcity.db.search.ParamOperator.LT_EQ; import static com.blobcity.db.search.ParamOperator.NOT_EQ; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import java.util.*; /** * Class to create Search parameters to be used as the WHERE clause in a query which helps in filtering result sets. * * @author Karun AB */ public class SearchParam implements ArrayJsonable, Sqlable { private final String paramName; private ParamOperator condition; private JsonArray args; private final Map<String, Object> baseParamMap; private final List<SearchOperator> operators; private final List<SearchParam> conditions; /** * Private initializer for the class. Use {@link #create(java.lang.String)} for creating an object * * @param paramName name of the parameter which is being searched */ private SearchParam(final String paramName) { this.paramName = paramName; this.operators = new ArrayList<SearchOperator>(); this.conditions = new ArrayList<SearchParam>(); this.baseParamMap = new HashMap<String, Object>(); this.baseParamMap.put("c", paramName); } /** * Creates a new {@link SearchParam} for a parameter * * @param paramName name of the parameter which is being searched * @return an instance of {@link SearchParam} */ public static SearchParam create(final String paramName) { return new SearchParam(paramName); } /** * Sets the condition for this search param as {@link ParamOperator#IN} along with the arguments for it. Any earlier conditions and arguments on this * {@link SearchParam} will be replaced. * * @see ParamOperator#IN * @param args arguments for the IN condition * @return updated current instance of {@link SearchParam} */ public SearchParam in(final Object... args) { this.condition = ParamOperator.IN; addArgs(args); return updateBaseParams(); } public SearchParam in(final Collection<Object> args) { this.condition = ParamOperator.IN; addArgs(args); return updateBaseParams(); } /** * Sets the condition for this search param as {@link ParamOperator#EQ} along with the argument for it. Any earlier conditions and arguments on this * {@link SearchParam} will be replaced. * * @see ParamOperator#EQ * @param arg argument for the EQ condition * @return updated current instance of {@link SearchParam} */ public SearchParam eq(final Object arg) { this.condition = ParamOperator.EQ; addArgs(arg); return updateBaseParams(); } /** * Sets the condition for this search param as {@link ParamOperator#NOT_EQ} along with the argument for it. Any earlier conditions and arguments on this * {@link SearchParam} will be replaced. * * @see ParamOperator#NOT_EQ * @param arg argument for the NOT_EQ condition * @return updated current instance of {@link SearchParam} */ public SearchParam noteq(final Object arg) { this.condition = ParamOperator.NOT_EQ; addArgs(arg); return updateBaseParams(); } /** * Sets the condition for this search param as {@link ParamOperator#GT} along with the argument for it. Any earlier conditions and arguments on this * {@link SearchParam} will be replaced. * * @see ParamOperator#GT * @param arg argument for the GT condition * @return updated current instance of {@link SearchParam} */ public SearchParam gt(final Object arg) { this.condition = ParamOperator.GT; addArgs(arg); return updateBaseParams(); } /** * Sets the condition for this search param as {@link ParamOperator#LT} along with the argument for it. Any earlier conditions and arguments on this * {@link SearchParam} will be replaced. * * @see ParamOperator#LT * @param arg argument for the LT condition * @return updated current instance of {@link SearchParam} */ public SearchParam lt(final Object arg) { this.condition = ParamOperator.LT; addArgs(arg); return updateBaseParams(); } /** * Sets the condition for this search param as {@link ParamOperator#GT_EQ} along with the argument for it. Any earlier conditions and arguments on this * {@link SearchParam} will be replaced. * * @see ParamOperator#GT_EQ * @param arg argument for the GT_EQ condition * @return updated current instance of {@link SearchParam} */ public SearchParam gteq(final Object arg) { this.condition = ParamOperator.GT_EQ; addArgs(arg); return updateBaseParams(); } /** * Sets the condition for this search param as {@link ParamOperator#LT_EQ} along with the argument for it. Any earlier conditions and arguments on this * {@link SearchParam} will be replaced. * * @see ParamOperator#LT_EQ * @param arg argument for the LT_EQ condition * @return updated current instance of {@link SearchParam} */ public SearchParam lteq(final Object arg) { this.condition = ParamOperator.LT_EQ; addArgs(arg); return updateBaseParams(); } /** * Sets the condition for this search param as {@link ParamOperator#BETWEEN} along with the arguments for it. Any earlier conditions and arguments on this * {@link SearchParam} will be replaced. * * @see ParamOperator#BETWEEN * @param arg1 left hand bound argument for the BETWEEN condition * @param arg2 right hand bound argument for the BETWEEN condition * @return updated current instance of {@link SearchParam} */ public SearchParam between(final Object arg1, final Object arg2) { this.condition = ParamOperator.BETWEEN; addArgs(arg1, arg2); return updateBaseParams(); } /** * Allows other {@link SearchParam}s to be linked to the existing one using an {@link SearchOperator#AND} operator * * @see SearchOperator#AND * @param param another {@link SearchParam} to be linked to the existing one * @return updated current instance of {@link SearchParam} */ public SearchParam and(final SearchParam param) { operators.add(SearchOperator.AND); conditions.add(param); return this; } /** * Allows other {@link SearchParam}s to be linked to the existing one using an {@link SearchOperator#OR} operator * * @see SearchOperator#OR * @param param another {@link SearchParam} to be linked to the existing one * @return updated current instance of {@link SearchParam} */ public SearchParam or(final SearchParam param) { operators.add(SearchOperator.OR); conditions.add(param); return this; } @Override public JsonArray asJson() { final JsonArray jsonArray = new JsonArray(); final JsonObject baseJson = new JsonObject(); baseJson.addProperty("c", paramName); baseJson.addProperty("x", condition.toString()); baseJson.add("v", getJsonPrimitive(padJsonArgs())); jsonArray.add(baseJson); if (!operators.isEmpty()) { final int operatorCount = operators.size(); final int conditionCount = conditions.size(); for (int i = 0; i < operatorCount && i < conditionCount; i++) { jsonArray.add(new JsonPrimitive(operators.get(i).toString())); jsonArray.add(conditions.get(i).asJson()); } } return jsonArray; } @Override public String asSql() { final StringBuffer sb = new StringBuffer("`").append(paramName).append("` ").append(condition.asSql()); switch (condition) { case EQ: case NOT_EQ: case LT: case LT_EQ: case GT: case GT_EQ: sb.append(" ").append(padSqlArg(args.get(0))); break; case BETWEEN: sb.append(" ").append(padSqlArg(args.get(0))).append(" and ").append(padSqlArg(args.get(1))); //sb.append(" (").append(padSqlArg(args.get(0))).append(",").append(padSqlArg(args.get(1))).append(") "); break; case IN: sb.append(" (").append(padSqlArgs(args)).append(")"); break; default: throw new InternalAdapterException("Unknown condition applied. Value found was " + condition + " and is not (yet) supported. Please contact BlobCity Tech Support for more details."); } if (!operators.isEmpty()) { final int operatorCount = operators.size(); final int conditionCount = conditions.size(); for (int i = 0; i < operatorCount && i < conditionCount; i++) { sb.append(" ").append(operators.get(i)).append(" ").append(conditions.get(i).asSql()); } } return sb.toString(); } @Override public String asSql(final String ds) { throw new RuntimeException("Incorrect invocation. Sqlable.asSql(ds) should not be invoked by SearchParam class"); } /** * Method is internally called whenever the {@link #condition} and/or {@link #args} are updated. * * @see #in(java.lang.Object[]) * @see #eq(java.lang.Object) * @see #noteq(java.lang.Object) * @see #lt(java.lang.Object) * @see #gt(java.lang.Object) * @see #lteq(java.lang.Object) * @see #gteq(java.lang.Object) * @see #between(java.lang.Object, java.lang.Object) * @return current instance of {@link SearchParam} */ private SearchParam updateBaseParams() { baseParamMap.put("x", condition); baseParamMap.put("v", padJsonArgs()); return this; } /** * Pads an argument for a JSON query * * @return if the operator only requires a single element, that element is returned, else a {@link JSONArray} is returned for the same. */ private Object padJsonArgs() { switch (condition) { case EQ: case NOT_EQ: case LT: case LT_EQ: case GT: case GT_EQ: return args.get(0); case BETWEEN: case IN: return args; default: throw new InternalAdapterException("Unknown condition applied. Value found was " + condition + " and is not (yet) supported. Please contact BlobCity Tech Support for more details."); } } /** * Pads arguments for SQL by quoting them as per SQL spec. Internally uses {@link #padSqlArg(java.lang.Object)} * * @see #padSqlArg(java.lang.Object) * @param jsonArr Array of objects to be escaped * @return SQL compliant form for the arguments * @throws JSONException th */ private String padSqlArgs(final JsonArray jsonArr) { final StringBuffer sb = new StringBuffer(); final int length = jsonArr.size(); for (int i = 0; i < length; i++) { sb.append(padSqlArg(jsonArr.get(i))); if (i < length - 1) { sb.append(","); } } return sb.toString(); } /** * Pads an argument for an SQL query's WHERE clause as required by the SQL spec. * * @param obj Object to the quote escaped (if required) * @return SQL compliant form of the argument ready for consumption by a query */ private String padSqlArg(final JsonElement obj) { if (obj.getAsJsonPrimitive().isString()) { // Strings and chars return "'" + obj.getAsJsonPrimitive().getAsString() + "'"; } return obj.getAsString(); } private void addArgs(final Object... objs) { args = new JsonArray(); for (final Object obj : objs) { args.add(getJsonPrimitive(obj)); } } private void addArgs(final Collection<Object> objs) { args = new JsonArray(); for (final Object obj : objs) { args.add(getJsonPrimitive(obj)); } } private JsonPrimitive getJsonPrimitive(final Object obj) { final Class clazz = obj.getClass(); if (obj instanceof String) { return new JsonPrimitive((String) obj); } if (clazz == int.class || clazz == Integer.class) { return new JsonPrimitive((Integer) obj); } if (clazz == long.class || clazz == Long.class) { return new JsonPrimitive((Long) obj); } if (clazz == short.class || clazz == Short.class) { return new JsonPrimitive((Short) obj); } if (clazz == float.class || clazz == Float.class) { return new JsonPrimitive((Float) obj); } if (clazz == double.class || clazz == Double.class) { return new JsonPrimitive((Double) obj); } if (clazz == byte.class || clazz == Byte.class) { return new JsonPrimitive((Byte) obj); } if (clazz == boolean.class || clazz == Boolean.class) { return new JsonPrimitive((Boolean) obj); } if (clazz == char.class || clazz == Character.class) { return new JsonPrimitive((Character) obj); } return new JsonPrimitive(obj.toString()); } }
package com.bpl.tucao.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.bpl.tucao.entity.BplComment; import com.bpl.tucao.entity.BplFeedback; import com.bpl.tucao.service.BplCommentService; import com.bpl.tucao.service.BplFeedbackService; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.thinkgem.jeesite.common.config.Global; import com.thinkgem.jeesite.common.persistence.Page; import com.thinkgem.jeesite.common.web.BaseController; import com.thinkgem.jeesite.common.utils.StringUtils; import com.bpl.tucao.entity.BplHot; import com.bpl.tucao.service.BplHotService; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Controller * * @author yongdaicui * @version 2017-08-11 */ @Controller @RequestMapping(value = "${adminPath}/tucao/bplHot") public class BplHotController extends BaseController { @Autowired private BplHotService bplHotService; @Autowired private BplCommentService bplCommentService; @Autowired private BplFeedbackService bplFeedbackService; @ModelAttribute public BplHot get(@RequestParam(required = false) String id) { BplHot entity = null; if (StringUtils.isNotBlank(id)) { entity = bplHotService.get(id); } if (entity == null) { entity = new BplHot(); } return entity; } @RequiresPermissions("tucao:bplHot:view") @RequestMapping(value = {"list", ""}) public String list(BplHot bplHot, HttpServletRequest request, HttpServletResponse response, Model model) { Page<BplHot> page = bplHotService.findPage(new Page<BplHot>(request, response), bplHot); model.addAttribute("page", page); List<BplHot> hotList = page.getList(); //TODO List<BplComment> commentList = bplCommentService.findList(new BplComment()); List<BplFeedback> feedbackList = bplFeedbackService.findList(new BplFeedback()); for (BplHot hot : hotList) { Map<String, String> objMap = new HashMap<String, String>(); hot.setSqlMap(objMap); for (BplComment comment : commentList) { if (comment.getHotid().toString().equals(hot.getId())) { String newComment = hot.getSqlMap().get("comments") + "," + comment.getContent(); hot.getSqlMap().put("comments", newComment); } } for (BplFeedback feedback : feedbackList) { if (feedback.getHotid().toString().equals(hot.getId())) { String newFeedback = hot.getSqlMap().get("feedbacks") == null ? "" : hot.getSqlMap().get("feedbacks") + "," + feedback.getContent(); hot.getSqlMap().put("feedbacks", newFeedback); } } logger.debug("hot:{}", hot); } model.addAttribute("page", page); return "bpl/tucao/bplHotList"; } @RequiresPermissions("tucao:bplHot:view") @RequestMapping(value = "form") public String form(BplHot bplHot, Model model) { model.addAttribute("bplHot", bplHot); return "bpl/tucao/bplHotForm"; } @RequiresPermissions("tucao:bplHot:edit") @RequestMapping(value = "save") public String save(BplHot bplHot, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, bplHot)) { return form(bplHot, model); } bplHotService.save(bplHot); if (bplHot.getRemarks() != null) { Date time = new Date(); BplFeedback feedback = new BplFeedback(); feedback.setHotid(Integer.valueOf(bplHot.getId())); feedback.setContent(bplHot.getRemarks()); feedback.setStatus(bplHot.getStatus()); feedback.setCreateTime(time); feedback.setUpdateTime(time); bplFeedbackService.save(feedback); } addMessage(redirectAttributes, ""); return "redirect:" + Global.getAdminPath() + "/tucao/bplHot/?repage"; } @RequiresPermissions("tucao:bplHot:edit") @RequestMapping(value = "delete") public String delete(BplHot bplHot, RedirectAttributes redirectAttributes) { bplHotService.delete(bplHot); addMessage(redirectAttributes, ""); return "redirect:" + Global.getAdminPath() + "/tucao/bplHot/?repage"; } }
package com.enow.persistence.redis; import com.enow.daos.redisDAO.INodeDAO; import com.enow.daos.redisDAO.IStatusDAO; import com.enow.daos.redisDAO.ITerminateDAO; import com.enow.persistence.dto.NodeDTO; import com.enow.facility.DAOFacility; import com.enow.persistence.dto.StatusDTO; import org.json.simple.JSONObject; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.util.Iterator; import java.util.List; import java.util.Set; public class RedisDB implements IRedisDB { private static RedisDB instance; private static JedisPool connection; public RedisDB(String IP, int PORT) { JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxTotal(128); connection = new JedisPool( poolConfig, IP, PORT ); } public JedisPool getConnection(String IP, int PORT) { return getInstance(IP, PORT).connection; } static public RedisDB getInstance(String IP, int PORT) { if (instance == null) { instance = new RedisDB(IP, PORT); } return instance; } /* static public RedisDB getInstance(String IP, int PORT) { if(instance == null) { instance = new RedisDB(IP, PORT); } return instance; } static public Jedis getConnection(String IP, int PORT) { return getInstance(IP, PORT).connection; } public RedisDB(String IP, int PORT) { // connection = new Jedis("192.168.99.100", 6379); connection = new Jedis(IP, PORT); } */ // public void setTestDb() {connection.select(10);} @Override public void clear() { Set<String> keys = connection.getResource().keys("*"); Iterator<String> iter = keys.iterator(); while(iter.hasNext()) { connection.getResource().del(iter.next()); } } @Override public void shutdown() { connection.close(); } @Override public String toID(String roadMapID, String nodeID) { INodeDAO dao = DAOFacility.getInstance().createNodeDAO(); return dao.toID(roadMapID, nodeID); } @Override public NodeDTO jsonObjectToNode(JSONObject jsonObject){ INodeDAO dao = DAOFacility.getInstance().createNodeDAO(); dao.setJedisConnection(connection.getResource()); return dao.jsonObjectToNode(jsonObject); } @Override public String addNode(NodeDTO dto) { INodeDAO dao = DAOFacility.getInstance().createNodeDAO(); dao.setJedisConnection(connection.getResource()); return dao.addNode(dto); } @Override public NodeDTO getNode(String ID){ INodeDAO dao = DAOFacility.getInstance().createNodeDAO(); dao.setJedisConnection(connection.getResource()); return dao.getNode(ID); } @Override public List<NodeDTO> getAllNodes() { INodeDAO dao = DAOFacility.getInstance().createNodeDAO(); dao.setJedisConnection(connection.getResource()); return dao.getAllNodes(); } @Override public void updateNode(NodeDTO dto) { INodeDAO dao = DAOFacility.getInstance().createNodeDAO(); dao.setJedisConnection(connection.getResource()); dao.updateNode(dto); } @Override public void updateRefer(NodeDTO dto) { INodeDAO dao = DAOFacility.getInstance().createNodeDAO(); dao.setJedisConnection(connection.getResource()); dao.updateRefer(dto); } @Override public void deleteNode(String ID) { INodeDAO dao = DAOFacility.getInstance().createNodeDAO(); dao.setJedisConnection(connection.getResource()); dao.deleteNode(ID); } @Override public void deleteAllNodes() { INodeDAO dao = DAOFacility.getInstance().createNodeDAO(); dao.setJedisConnection(connection.getResource()); dao.deleteAllNodes(); } @Override public void deleteLastNode(NodeDTO dto) { INodeDAO dao = DAOFacility.getInstance().createNodeDAO(); dao.setJedisConnection(connection.getResource()); dao.deleteLastNode(dto); } @Override public StatusDTO jsonObjectToStatus(JSONObject jsonObject) { IStatusDAO dao = DAOFacility.getInstance().createStatusDAO(); return dao.jsonObjectToStatus(jsonObject); } @Override public String addStatus(StatusDTO dto) { IStatusDAO dao = DAOFacility.getInstance().createStatusDAO(); dao.setJedisConnection(connection.getResource()); return dao.addStatus(dto); } @Override public StatusDTO getStatus(String topic) { IStatusDAO dao = DAOFacility.getInstance().createStatusDAO(); dao.setJedisConnection(connection.getResource()); return dao.getStatus(topic); } @Override public List<StatusDTO> getAllStatus() { IStatusDAO dao = DAOFacility.getInstance().createStatusDAO(); dao.setJedisConnection(connection.getResource()); return dao.getAllStatus(); } @Override public void updateStatus(StatusDTO dto) { IStatusDAO dao = DAOFacility.getInstance().createStatusDAO(); dao.setJedisConnection(connection.getResource()); dao.updateStatus(dto); } @Override public void deleteStatus(String topic) { IStatusDAO dao = DAOFacility.getInstance().createStatusDAO(); dao.setJedisConnection(connection.getResource()); dao.deleteStatus(topic); } @Override public void deleteAllStatus() { IStatusDAO dao = DAOFacility.getInstance().createStatusDAO(); dao.setJedisConnection(connection.getResource()); dao.deleteAllStatus(); } @Override public String addTerminate(String roadMapID) { ITerminateDAO dao = DAOFacility.getInstance().createTerminateDAO(); dao.setJedisConnection(connection.getResource()); return dao.addTerminate(roadMapID); } @Override public boolean isTerminate(String roadMapID) { ITerminateDAO dao = DAOFacility.getInstance().createTerminateDAO(); dao.setJedisConnection(connection.getResource()); return dao.isTerminate(roadMapID); } @Override public void deleteAllTerminate() { ITerminateDAO dao = DAOFacility.getInstance().createTerminateDAO(); dao.setJedisConnection(connection.getResource()); dao.deleteAllTerminate(); } @Override public void deleteTerminate(String roadMapID) { ITerminateDAO dao = DAOFacility.getInstance().createTerminateDAO(); dao.setJedisConnection(connection.getResource()); dao.deleteTerminate(roadMapID); } }
package com.falcon.suitagent.util; import lombok.extern.slf4j.Slf4j; import java.io.*; import java.util.ArrayList; import java.util.List; /* * : * guqiu@yiji.com 2016-06-22 17:48 */ /** * @author guqiu@yiji.com */ @Slf4j public class FileUtil { /** * * @param filePath * @return * false */ public static boolean isExist(String filePath){ File file = new File(filePath); return file.exists(); } /** * * * @param fileName * @return * @throws IOException */ public static String getTextFileContent(String fileName){ StringBuilder text = new StringBuilder(); File f = new File(fileName); if (!f.exists()) { log.error("{}",fileName); return ""; } try (FileInputStream fis = new FileInputStream(f); InputStreamReader read = new InputStreamReader(fis,"UTF-8"); BufferedReader reader = new BufferedReader(read);){ String line; while((line = reader.readLine()) != null){ text.append(line).append("\n"); } } catch (Exception e) { log.error("",e); } return text.toString(); } /** * * * @param path * @return * @throws Exception */ public static List<String> getAllFileTextFromDir(String path){ List<String> filesText = new ArrayList<String>(); File f = new File(path); if (!f.exists()) { if(!f.mkdirs()){ log.warn(""); } } File[] fs = f.listFiles(); if(fs == null){ return new ArrayList<>(); } for (File file : fs) { try (FileInputStream fis = new FileInputStream(file); InputStreamReader read = new InputStreamReader(fis,"UTF-8"); BufferedReader reader = new BufferedReader(read);){ StringBuilder text = new StringBuilder(); String line; while((line = reader.readLine()) != null){ text.append(line).append("\n"); } filesText.add(text.toString()); } catch (Exception e) { log.error("",e); return new ArrayList<>(); } } return filesText; } /** * * * @param path * @param fileName * @return * @throws Exception */ public static String getFileTextFromDirFile(String path, String fileName){ StringBuilder text = new StringBuilder(); File f = new File(path); if (!f.exists()) { if(!f.mkdirs()){ log.warn(""); } } f = new File(path + File.separator + fileName); if(!f.exists()){ try { if(!f.createNewFile()){ log.warn(""); } } catch (IOException e) { log.error("",e); } } try (FileInputStream fis = new FileInputStream(f); InputStreamReader read = new InputStreamReader(fis,"UTF-8"); BufferedReader reader = new BufferedReader(read);){ String line; while((line = reader.readLine()) != null){ text.append(line).append("\n"); } } catch (Exception e) { log.error("",e); return ""; } return text.toString(); } /** * * * @param text * @param path * @param fileName * @param append : true * @return */ public static boolean writeTextToTextFile(String text,String path, String fileName,boolean append) { File f = new File(path); if(!f.exists()){ if(!f.mkdirs()){ log.warn(""); } } f = new File(path + File.separator + fileName); if(!f.exists()){ try { if(!f.createNewFile()){ log.warn(""); return false; } } catch (IOException e) { log.error("",e); return false; } } try (FileOutputStream fos = new FileOutputStream(f, append); OutputStreamWriter write = new OutputStreamWriter(fos,"UTF-8"); BufferedWriter writer = new BufferedWriter(write);){ writer.write(text); return true; } catch (Exception e) { log.error("",e); return false; } } /** * * false * @param text * @param file * @param append : true * @return */ public static boolean writeTextToTextFile(String text,File file,boolean append) { if(!file.exists()){ return false; } try (FileOutputStream fos = new FileOutputStream(file, append); OutputStreamWriter write = new OutputStreamWriter(fos,"UTF-8"); BufferedWriter writer = new BufferedWriter(write);){ writer.write(text); return true; } catch (Exception e) { log.error("",e); return false; } } /** * InputStreamFile * @param ins * @param file */ public static boolean inputStreamToFile(InputStream ins,File file) { try (OutputStream os = new FileOutputStream(file);){ int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } return true; } catch (Exception e) { log.error("",e); return false; }finally { try { ins.close(); } catch (IOException ignored) { } } } /** * * * @param path * @return * @throws Exception */ public static List<String> getAllFileNamesFromDir(String path){ List<String> fileNames = new ArrayList<>(); File dir = new File(path); if (!dir.exists()) { if(!dir.mkdirs()){ log.warn(""); } } File[] fs = dir.listFiles(); if(fs == null){ return new ArrayList<>(); } try { for (File file : fs) { appendFileNames(file.getPath(),fileNames); } } catch (Exception e) { log.error("",e); return new ArrayList<>(); } return fileNames; } private static void appendFileNames(String dir,List<String> fileNames){ File file = new File(dir); if(file.isFile()){ fileNames.add(file.getPath()); }else { File[] fs = file.listFiles(); if(fs != null){ for (File f : fs) { if(f.isDirectory()){ appendFileNames(f.getPath(),fileNames); }else if(f.isFile()){ fileNames.add(f.getPath()); }else { log.warn("" + f.getPath()); } } } } } }
package com.gamingmesh.jobs.Signs; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Skull; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.CMILib.ItemManager.CMIMaterial; import com.gamingmesh.jobs.CMILib.VersionChecker.Version; import com.gamingmesh.jobs.config.CommentedYamlConfiguration; import com.gamingmesh.jobs.container.Job; import com.gamingmesh.jobs.container.TopList; import com.gamingmesh.jobs.stuff.Debug; public class SignUtil { private HashMap<String, HashMap<String, jobsSign>> SignsByType = new HashMap<String, HashMap<String, jobsSign>>(); private HashMap<String, jobsSign> SignsByLocation = new HashMap<String, jobsSign>(); private Jobs plugin; public SignUtil(Jobs plugin) { this.plugin = plugin; } public HashMap<String, HashMap<String, jobsSign>> getSigns() { return SignsByType; } public boolean removeSign(Location loc) { jobsSign jSign = SignsByLocation.remove(jobsSign.locToBlockString(loc)); if (jSign == null) return false; HashMap<String, jobsSign> sub = SignsByType.get(jSign.getIdentifier().toLowerCase()); if (sub != null) { sub.remove(jSign.locToBlockString()); } return true; } public jobsSign getSign(Location loc) { if (loc == null) return null; return SignsByLocation.get(jobsSign.locToBlockString(loc)); } public void addSign(jobsSign jSign) { if (jSign == null) return; SignsByLocation.put(jSign.locToBlockString(), jSign); HashMap<String, jobsSign> old = SignsByType.get(jSign.getIdentifier().toLowerCase()); if (old == null) { old = new HashMap<String, jobsSign>(); SignsByType.put(jSign.getIdentifier().toLowerCase(), old); } String loc = jSign.locToBlockString(); if (loc == null) { return; } old.put(loc, jSign); } public void cancelSignTask() { if (update > -1) { Bukkit.getScheduler().cancelTask(update); update = -1; } } // Sign file public void LoadSigns() { // Boolean false does not create a file if (!Jobs.getGCManager().SignsEnabled) return; SignsByType.clear(); SignsByLocation.clear(); File file = new File(Jobs.getFolder(), "Signs.yml"); YamlConfiguration f = YamlConfiguration.loadConfiguration(file); if (!f.isConfigurationSection("Signs")) return; ConfigurationSection ConfCategory = f.getConfigurationSection("Signs"); ArrayList<String> categoriesList = new ArrayList<>(ConfCategory.getKeys(false)); if (categoriesList.isEmpty()) return; for (String category : categoriesList) { ConfigurationSection NameSection = ConfCategory.getConfigurationSection(category); jobsSign newTemp = new jobsSign(); if (NameSection.isString("World")) { newTemp.setWorldName(NameSection.getString("World")); newTemp.setX((int) NameSection.getDouble("X")); newTemp.setY((int) NameSection.getDouble("Y")); newTemp.setZ((int) NameSection.getDouble("Z")); } else { newTemp.setLoc(NameSection.getString("Loc")); } if (NameSection.isString("Type")) newTemp.setType(SignTopType.getType(NameSection.getString("Type"))); newTemp.setNumber(NameSection.getInt("Number")); if (NameSection.isString("JobName")) { SignTopType t = SignTopType.getType(NameSection.getString("JobName")); if (t == null) newTemp.setJobName(NameSection.getString("JobName")); } newTemp.setSpecial(NameSection.getBoolean("Special")); HashMap<String, jobsSign> old = SignsByType.get(newTemp.getIdentifier().toLowerCase()); if (old == null) { old = new HashMap<String, jobsSign>(); SignsByType.put(newTemp.getIdentifier().toLowerCase(), old); } String loc = newTemp.locToBlockString(); if (loc == null) { Jobs.consoleMsg("&cFailed to load (" + category + ") sign location"); continue; } old.put(loc, newTemp); SignsByLocation.put(loc, newTemp); } if (!SignsByLocation.isEmpty()) { Jobs.consoleMsg("&e[Jobs] Loaded " + SignsByLocation.size() + " top list signs"); } cancelSignTask(); } // Signs save file public void saveSigns() { File f = new File(Jobs.getFolder(), "Signs.yml"); YamlConfiguration conf = YamlConfiguration.loadConfiguration(f); CommentedYamlConfiguration writer = new CommentedYamlConfiguration(); conf.options().copyDefaults(true); writer.addComment("Signs", "DO NOT EDIT THIS FILE BY HAND!"); if (!conf.isConfigurationSection("Signs")) conf.createSection("Signs"); int i = 0; for (Entry<String, jobsSign> one : SignsByLocation.entrySet()) { jobsSign sign = one.getValue(); ++i; String path = "Signs." + i; writer.set(path + ".Loc", sign.locToBlockString()); writer.set(path + ".Number", sign.getNumber()); writer.set(path + ".Type", sign.getType().toString()); writer.set(path + ".JobName", sign.getJobName()); writer.set(path + ".Special", sign.isSpecial()); } try { writer.save(f); } catch (IOException e) { e.printStackTrace(); } cancelSignTask(); } private int update = -1; public boolean SignUpdate(Job job) { return SignUpdate(job, SignTopType.toplist); } public boolean SignUpdate(SignTopType type) { return SignUpdate(null, type); } public boolean SignUpdate(Job job, SignTopType type) { if (!Jobs.getGCManager().SignsEnabled) return true; if (type == null) type = SignTopType.toplist; String JobNameOrType = null; HashMap<String, jobsSign> signs = null; if (job != null) { JobNameOrType = jobsSign.getIdentifier(job, type); signs = this.SignsByType.get(JobNameOrType.toLowerCase()); } if (signs == null) return false; int timelapse = 1; List<TopList> PlayerList = new ArrayList<>(); switch (type) { case toplist: break; case gtoplist: PlayerList = Jobs.getJobsDAO().getGlobalTopList(0); break; case questtoplist: PlayerList = Jobs.getJobsDAO().getQuestTopList(0); break; default: break; } HashMap<String, List<TopList>> temp = new HashMap<>(); boolean save = false; for (Entry<String, jobsSign> one : (new HashMap<String, jobsSign>(signs)).entrySet()) { jobsSign jSign = one.getValue(); String SignJobName = jSign.getJobName(); Location loc = jSign.getLocation(); if (loc == null) continue; int number = jSign.getNumber() - 1; switch (type) { case toplist: PlayerList = temp.get(SignJobName); if (PlayerList == null) { PlayerList = Jobs.getJobsDAO().toplist(SignJobName); temp.put(SignJobName, PlayerList); } break; default: break; } if (PlayerList.isEmpty()) continue; Block block = loc.getBlock(); if (!(block.getState() instanceof org.bukkit.block.Sign)) { if (JobNameOrType != null) { HashMap<String, jobsSign> tt = this.SignsByType.get(JobNameOrType.toLowerCase()); if (tt != null) { tt.remove(jSign.locToBlockString()); } } this.SignsByLocation.remove(jSign.locToBlockString()); save = true; continue; } org.bukkit.block.Sign sign = (org.bukkit.block.Sign) block.getState(); if (!jSign.isSpecial()) { for (int i = 0; i < 4; i++) { if (i + number >= PlayerList.size()) { sign.setLine(i, ""); continue; } String PlayerName = PlayerList.get(i + number).getPlayerName(); if (PlayerName == null) PlayerName = "Unknown"; if (PlayerName.length() > 15) { PlayerName = PlayerName.split("(?<=\\G.{15})")[0] + "~"; } String line = ""; switch (type) { case toplist: case gtoplist: line = Jobs.getLanguage().getMessage("signs.List", "[number]", i + number + 1, "[player]", PlayerName, "[level]", PlayerList.get(i + number).getLevel()); break; case questtoplist: line = Jobs.getLanguage().getMessage("signs.questList", "[number]", i + number + 1, "[player]", PlayerName, "[quests]", PlayerList.get(i + number).getLevel()); break; default: break; } sign.setLine(i, line); } sign.update(); if (!UpdateHead(sign, ((TopList) PlayerList.get(0)).getPlayerName(), timelapse)) { timelapse } } else { if (jSign.getNumber() > PlayerList.size()) continue; TopList pl = PlayerList.get(jSign.getNumber() - 1); String PlayerName = pl.getPlayerName(); if (PlayerName == null) PlayerName = "Unknown"; if (PlayerName.length() > 15) { PlayerName = PlayerName.split("(?<=\\G.{15})")[0] + "~"; } int no = jSign.getNumber() + number + 1; sign.setLine(0, translateSignLine("signs.SpecialList.p" + jSign.getNumber(), no, PlayerName, pl.getLevel(), SignJobName)); sign.setLine(1, translateSignLine("signs.SpecialList.name", no, PlayerName, pl.getLevel(), SignJobName)); switch (type) { case toplist: case gtoplist: sign.setLine(2, Jobs.getLanguage().getMessage("signs.SpecialList.level", "[number]", no, "[player]", PlayerName, "[level]", pl.getLevel(), "[job]", SignJobName)); break; case questtoplist: sign.setLine(2, Jobs.getLanguage().getMessage("signs.SpecialList.quests", "[number]", no, "[player]", PlayerName, "[quests]", pl.getLevel(), "[job]", SignJobName)); break; default: break; } sign.setLine(3, translateSignLine("signs.SpecialList.bottom", no, PlayerName, pl.getLevel(), SignJobName)); sign.update(); if (!UpdateHead(sign, pl.getPlayerName(), timelapse)) { timelapse } } timelapse++; } if (save) saveSigns(); return true; } private static String translateSignLine(String path, int number, String playerName, int level, String jobname) { return Jobs.getLanguage().getMessage(path, "[number]", number, "[player]", playerName, "[level]", level, "[job]", jobname); } public boolean UpdateHead(final org.bukkit.block.Sign sign, final String Playername, int timelapse) { try { timelapse = timelapse < 1 ? 1 : timelapse; BlockFace directionFacing = null; if (Version.isCurrentEqualOrLower(Version.v1_13_R2)) { org.bukkit.material.Sign signMat = (org.bukkit.material.Sign) sign.getData(); directionFacing = signMat.getFacing(); } else { if (CMIMaterial.isWallSign(sign.getType())) { org.bukkit.block.data.type.WallSign data = (org.bukkit.block.data.type.WallSign) sign.getBlockData(); directionFacing = data.getFacing(); } else { org.bukkit.block.data.type.Sign data = (org.bukkit.block.data.type.Sign) sign.getBlockData(); directionFacing = data.getRotation(); } } final Location loc = sign.getLocation().clone(); loc.add(0, 1, 0); if (Playername == null) return false; Block block = loc.getBlock(); if (block == null || !(block.getState() instanceof Skull)) loc.add(directionFacing.getOppositeFace().getModX(), 0, directionFacing.getOppositeFace().getModZ()); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new Runnable() { @Override public void run() { Block b = loc.getBlock(); if (b == null || !(b.getState() instanceof Skull)) return; Skull skull = (Skull) b.getState(); if (skull == null) return; if (skull.getOwner() != null && skull.getOwner().equalsIgnoreCase(Playername)) return; skull.setOwner(Playername); skull.update(); } }, timelapse * Jobs.getGCManager().InfoUpdateInterval * 20L); } catch (Throwable e) { e.printStackTrace(); } return true; } }
package com.github.ansell.csv.db; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.jooq.lambda.Unchecked; import com.github.ansell.csv.util.CSVUtil; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; /** * Uploads from a CSV file to a database. * * @author Peter Ansell p_ansell@yahoo.com */ public final class CSVUpload { /** * Private constructor for static only class */ private CSVUpload() { } public static void main(String... args) throws Exception { final OptionParser parser = new OptionParser(); final OptionSpec<Void> help = parser.accepts("help").forHelp(); final OptionSpec<File> input = parser.accepts("input").withRequiredArg().ofType(File.class).required() .describedAs("The input CSV file to be mapped."); final OptionSpec<String> database = parser.accepts("database").withRequiredArg().ofType(String.class).required() .describedAs("The JDBC connection string for the database to upload to."); final OptionSpec<String> table = parser.accepts("table").withRequiredArg().ofType(String.class).required() .describedAs("The database table to upload to."); final OptionSpec<Boolean> dropTable = parser.accepts("drop-existing-table").withRequiredArg() .ofType(Boolean.class).defaultsTo(Boolean.FALSE) .describedAs("True to drop an existing table with this name and false otherwise."); OptionSet options = null; try { options = parser.parse(args); } catch (final OptionException e) { System.out.println(e.getMessage()); parser.printHelpOn(System.out); throw e; } if (options.has(help)) { parser.printHelpOn(System.out); return; } final Path inputPath = input.value(options).toPath(); if (!Files.exists(inputPath)) { throw new FileNotFoundException("Could not find input CSV file: " + inputPath.toString()); } final String databaseConnectionString = database.value(options); final String tableString = table.value(options); final Boolean dropTableBoolean = dropTable.value(options); try (final Connection conn = DriverManager.getConnection(databaseConnectionString);) { conn.setAutoCommit(false); if (dropTableBoolean) { dropExistingTable(tableString, conn); } try (final Reader inputReader = Files.newBufferedReader(inputPath);) { upload(tableString, inputReader, conn); } conn.commit(); } } static void dropExistingTable(String tableString, Connection conn) throws SQLException { try (final Statement stmt = conn.createStatement();) { stmt.executeUpdate("DROP TABLE IF EXISTS " + tableString + ";"); } } static void createTable(String tableName, List<String> h, StringBuilder insertStmt, Connection conn) throws SQLException { final StringBuilder createStmt = new StringBuilder(); createStmt.append("CREATE TABLE ").append(tableName).append(" ( \n"); insertStmt.append("INSERT INTO ").append(tableName).append(" ( "); for (int i = 0; i < h.size(); i++) { if (i > 0) { createStmt.append(", \n"); insertStmt.append(", \n"); } createStmt.append(h.get(i)).append(" VARCHAR(MAX) "); insertStmt.append(h.get(i)).append(" "); } createStmt.append(")\n"); insertStmt.append(" ) "); insertStmt.append(" VALUES ( "); for (int i = 0; i < h.size(); i++) { if (i > 0) { insertStmt.append(", "); } insertStmt.append("?"); } insertStmt.append(");"); insertStmt.trimToSize(); try (final Statement stmt = conn.createStatement();) { stmt.executeUpdate(createStmt.toString()); } } static void upload(String tableName, Reader input, Connection conn) throws IOException, SQLException { final AtomicReference<PreparedStatement> preparedStmt = new AtomicReference<>(); try { CSVUtil.streamCSV(input, Unchecked.consumer(h -> { final StringBuilder insertStatement = new StringBuilder(2048); createTable(tableName, h, insertStatement, conn); preparedStmt.set(conn.prepareStatement(insertStatement.toString())); }), Unchecked.biFunction((h, l) -> { uploadLine(h, l, preparedStmt.get()); return l; }), l -> { }); } finally { PreparedStatement closeable = preparedStmt.get(); if (closeable != null) { closeable.close(); } preparedStmt.set(null); } } static void uploadLine(List<String> h, List<String> l, PreparedStatement stmt) throws SQLException { for (int i = 0; i < h.size(); i++) { stmt.setString(i, l.get(i)); } stmt.executeUpdate(); } }
package com.jaamsim.render; import com.jaamsim.Graphics.PolylineInfo; public interface HasScreenPoints { public static class PointsInfo extends PolylineInfo {} }
package com.msh.room.model.role.impl; import com.msh.room.dto.event.PlayerEventType; import com.msh.room.dto.response.PlayerDisplayInfo; import com.msh.room.dto.room.RoomStateData; import com.msh.room.dto.room.RoomStatus; import com.msh.room.dto.room.record.NightRecord; import com.msh.room.dto.room.result.GameResult; import com.msh.room.dto.room.seat.PlayerSeatInfo; import com.msh.room.exception.RoomBusinessException; import com.msh.room.model.role.Roles; public class Witch extends AssignedPlayer { private boolean alive; public Witch(RoomStateData roomState, int number) { super(roomState, number); alive = roomState.getPlaySeatInfoBySeatNumber(number).isAlive(); } @Override public void calculateScore() { //TODO if (GameResult.VILLAGERS_WIN.equals(roomState.getGameResult())) { PlayerSeatInfo seatInfo = roomState.getPlaySeatInfoBySeatNumber(this.number); seatInfo.setFinalScore(5); } } @Override public PlayerDisplayInfo displayInfo() { PlayerDisplayInfo displayInfo = new PlayerDisplayInfo(); resolveCommonDisplayInfo(displayInfo); if (alive) { if (RoomStatus.NIGHT.equals(roomState.getStatus())) { NightRecord nightRecord = roomState.getLastNightRecord(); PlayerEventType eventType = getWitchNightEvent(nightRecord); if (eventType != null) { displayInfo.addAcceptableEventType(eventType); } } } return displayInfo; } public PlayerEventType getWitchNightEvent(NightRecord nightRecord) { Integer wolfKilledSeat = nightRecord.getWolfKilledSeat(); if (wolfKilledSeat == null) { return null; } //==null: WITCH_SAVE if (nightRecord.getWitchSaved() == null && roomState.getWitchState().isAntidoteAvailable() && !wolfKilledSeat.equals(number)) { return PlayerEventType.WITCH_SAVE; } //==null( ) FAKE_WITCH_SAVE else if (nightRecord.getWitchSaved() == null && (!roomState.getWitchState().isAntidoteAvailable() || wolfKilledSeat.equals(number))) { return PlayerEventType.FAKE_WITCH_SAVE; } //,==0==null WITCH_POISON else if (nightRecord.getWitchSaved() == 0 && nightRecord.getWitchPoisoned() == null && roomState.getWitchState().isPoisonAvailable()) { return PlayerEventType.WITCH_POISON; } //,==0==null FAKE_WITCH_POISON else if (nightRecord.getWitchSaved() == 0 && nightRecord.getWitchPoisoned() == null && !roomState.getWitchState().isPoisonAvailable()) { return PlayerEventType.FAKE_WITCH_POISON; } //!=0 FAKE_WITCH_POISON else if (nightRecord.getWitchSaved() != 0 && nightRecord.getWitchPoisoned() == null) { return PlayerEventType.FAKE_WITCH_POISON; } return null; } public void save(boolean witchSave) { if (roomState.getWitchState().isAntidoteAvailable()) { Integer killedSeat = roomState.getLastNightRecord().getWolfKilledSeat(); if (killedSeat.equals(this.number)) { throw new RoomBusinessException(""); } if (witchSave && killedSeat != 0) { roomState.getLastNightRecord().setWitchSaved(killedSeat); roomState.getWitchState().setAntidoteAvailable(false); } else { roomState.getLastNightRecord().setWitchSaved(0); } } else { throw new RoomBusinessException(""); } } public void poison(Integer witchPoisonNumber) { if (roomState.getWitchState().isPoisonAvailable()) { roomState.getLastNightRecord().setWitchPoisoned(witchPoisonNumber); roomState.getWitchState().setPoisonAvailable(false); } else { throw new RoomBusinessException(""); } } public void fakePoison() { roomState.getLastNightRecord().setWitchPoisoned(0); } public void fakeSave() { roomState.getLastNightRecord().setWitchSaved(0); } }
package com.rox.emu; /** * Exception for when an op-code is unknown * * @author Ross Drew */ public class UnknownOpCodeException extends RuntimeException{ private final Object opCode; public UnknownOpCodeException(String message, Object opCode, Exception cause) { super(message, cause); this.opCode = opCode; } public UnknownOpCodeException(String message, Object opCode) { super(message); this.opCode = opCode; } public Object getOpCode() { return opCode; } }
package com.wiley.autotest.selenium; import org.slf4j.LoggerFactory; import org.testng.Reporter; import ru.yandex.qatools.allure.annotations.Step; /** * Transfers message to necessary end point * TestNG * Allure * Jenkins console */ public class Report { private String message; public Report(String message) { this.message = message; } public void testNG() { Reporter.log(message + "<br/>"); } public void allure() { allure(message); } /** * hack to send message to allure */ @Step("{0}") private void allure(String message) { } public void jenkins() { LoggerFactory.getLogger(this.getClass()).info(message); } public void everywhere() { testNG(); allure(); jenkins(); } }
package crazypants.enderio.item; import java.util.List; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import baubles.api.BaubleType; import baubles.api.IBauble; import cofh.api.energy.ItemEnergyContainer; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Optional; import cpw.mods.fml.common.Optional.Method; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import crazypants.enderio.EnderIO; import crazypants.enderio.EnderIOTab; import crazypants.enderio.ModObject; import crazypants.enderio.config.Config; import crazypants.enderio.gui.IResourceTooltipProvider; import crazypants.enderio.machine.power.PowerDisplayUtil; import crazypants.util.BaublesUtil; import crazypants.util.ItemUtil; @Optional.Interface(iface = "baubles.api.IBauble", modid = "Baubles|API") public class ItemMagnet extends ItemEnergyContainer implements IResourceTooltipProvider, IBauble { private static final String ACTIVE_KEY = "magnetActive"; public static void setActive(ItemStack item, boolean active) { if(item == null) { return; } NBTTagCompound nbt = ItemUtil.getOrCreateNBT(item); nbt.setBoolean(ACTIVE_KEY, active); } public static boolean isActive(ItemStack item) { if(item == null) { return false; } if(item.stackTagCompound == null) { return false; } if(!item.stackTagCompound.hasKey(ACTIVE_KEY)) { return false; } return item.stackTagCompound.getBoolean(ACTIVE_KEY); } public static boolean hasPower(ItemStack itemStack) { return EnderIO.itemMagnet.getEnergyStored(itemStack) > 0; } public static void drainPerSecondPower(ItemStack itemStack) { EnderIO.itemMagnet.extractEnergy(itemStack, Config.magnetPowerUsePerSecondRF, false); } static MagnetController controller = new MagnetController(); public static ItemMagnet create() { ItemMagnet result = new ItemMagnet(); result.init(); FMLCommonHandler.instance().bus().register(controller); return result; } protected ItemMagnet() { super(Config.magnetPowerCapacityRF, Config.magnetPowerCapacityRF / 100); setCreativeTab(EnderIOTab.tabEnderIO); setUnlocalizedName(ModObject.itemMagnet.unlocalisedName); setMaxDamage(16); setMaxStackSize(1); setHasSubtypes(true); } protected void init() { GameRegistry.registerItem(this, ModObject.itemMagnet.unlocalisedName); } @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister IIconRegister) { itemIcon = IIconRegister.registerIcon("enderio:magnet"); } @Override @SideOnly(Side.CLIENT) public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List par3List) { ItemStack is = new ItemStack(this); setFull(is); par3List.add(is); is = new ItemStack(this); setEnergy(is, 0); par3List.add(is); } @Override @SideOnly(Side.CLIENT) public void addInformation(ItemStack itemStack, EntityPlayer par2EntityPlayer, List list, boolean par4) { super.addInformation(itemStack, par2EntityPlayer, list, par4); String str = PowerDisplayUtil.formatPower(getEnergyStored(itemStack)) + "/" + PowerDisplayUtil.formatPower(getMaxEnergyStored(itemStack)) + " " + PowerDisplayUtil.abrevation(); list.add(str); } @Override @SideOnly(Side.CLIENT) public boolean hasEffect(ItemStack item, int pass) { return isActive(item); } @Override public void onCreated(ItemStack itemStack, World world, EntityPlayer entityPlayer) { setEnergy(itemStack, 0); } @Override public int receiveEnergy(ItemStack container, int maxReceive, boolean simulate) { int res = super.receiveEnergy(container, maxReceive, simulate); if(res != 0 && !simulate) { updateDamage(container); } return res; } @Override public int extractEnergy(ItemStack container, int maxExtract, boolean simulate) { int res = super.extractEnergy(container, maxExtract, simulate); if(res != 0 && !simulate) { updateDamage(container); } return res; } void setEnergy(ItemStack container, int energy) { if(container.stackTagCompound == null) { container.stackTagCompound = new NBTTagCompound(); } container.stackTagCompound.setInteger("Energy", energy); updateDamage(container); } void setFull(ItemStack container) { setEnergy(container, Config.magnetPowerCapacityRF); } private void updateDamage(ItemStack stack) { float r = (float) getEnergyStored(stack) / getMaxEnergyStored(stack); int res = 16 - (int) (r * 16); stack.setItemDamage(res); } @Override public ItemStack onItemRightClick(ItemStack equipped, World world, EntityPlayer player) { if(player.isSneaking()) { setActive(equipped, !isActive(equipped)); } return equipped; } @Override public String getUnlocalizedNameForTooltip(ItemStack stack) { return getUnlocalizedName(); } @Override @Method(modid = "Baubles|API") public BaubleType getBaubleType(ItemStack itemstack) { BaubleType t = null; try { t = BaubleType.valueOf(Config.magnetBaublesType); } catch (Exception e) { //NOP } return t != null ? t : BaubleType.AMULET; } @Override public void onWornTick(ItemStack itemstack, EntityLivingBase player) { if (player instanceof EntityPlayer && hasPower(itemstack) && ((EntityPlayer) player).getHealth() > 0f) { controller.doHoover((EntityPlayer) player); if(!player.worldObj.isRemote && player.worldObj.getTotalWorldTime() % 20 == 0) { ItemMagnet.drainPerSecondPower(itemstack); IInventory baubles = BaublesUtil.instance().getBaubles((EntityPlayer) player); if(baubles != null) { for (int i = 0; i < baubles.getSizeInventory(); i++) { if(baubles.getStackInSlot(i) == itemstack) { baubles.setInventorySlotContents(i, itemstack); } } } } } } @Override public void onEquipped(ItemStack itemstack, EntityLivingBase player) { } @Override public void onUnequipped(ItemStack itemstack, EntityLivingBase player) { } @Override public boolean canEquip(ItemStack itemstack, EntityLivingBase player) { return Config.magnetAllowInBaublesSlot && (Config.magnetAllowDeactivatedInBaublesSlot || isActive(itemstack)); } @Override public boolean canUnequip(ItemStack itemstack, EntityLivingBase player) { return true; } }
package cz.muni.fi.mias.math; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.io.input.ReaderInputStream; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.PayloadAttribute; import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute; import org.apache.lucene.util.BytesRef; import org.jdom2.output.DOMOutputter; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import cz.muni.fi.mir.mathmlcanonicalization.MathMLCanonicalizer; import cz.muni.fi.mir.mathmlunificator.MathMLUnificator; import cz.muni.fi.mir.mathmlunificator.utils.XMLOut; /** * Implementation of Lucene Tokenizer. Provides math formulae contained in the * input as string tokens and their weight. These attributes are held in * TermAttribute and PayloadAttribute and carried over the stream. * * @author Martin Liska * @since 14.5.2010 */ public class MathTokenizer extends Tokenizer { private static final Logger LOG = Logger.getLogger(MathTokenizer.class.getName()); private static FormulaValuator valuator = new CountNodesFormulaValuator(); private static Map<String, List<String>> ops = MathMLConf.getOperators(); private static Map<String, String> eldict = MathMLConf.getElementDictionary(); private static Map<String, String> attrdict = MathMLConf.getAttrDictionary(); // statistics private static AtomicLong inputF = new AtomicLong(0); private static AtomicLong producedF = new AtomicLong(0); // utilities private final MathMLCanonicalizer canonicalizer = MathMLCanonicalizer.getDefaultCanonicalizer(); private final DOMOutputter outputter = new DOMOutputter(); // configuration private float lCoef = 0.7f; private float vCoef = 0.8f; private float vCoefGen = 0.8f; private float cCoef = 0.5f; private float oCoef = 0.8f; private final float aCoef = 1.2f; private final boolean subformulae; private final MathMLType mmlType; private int formulaPosition = 1; // fields with state related to tokenization of current input; // fields must be correctly reset in order for this tokenizer to be re-usable // (see javadoc of org.apache.lucene.analysis.TokenStream.reset() method) private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class); private final PayloadAttribute payAtt = addAttribute(PayloadAttribute.class); private final PositionIncrementAttribute posAtt = addAttribute(PositionIncrementAttribute.class); private final Map<Integer, List<Formula>> formulae = new LinkedHashMap<Integer, List<Formula>>(); private Iterator<List<Formula>> itMap = Collections.<List<Formula>>emptyList().iterator(); private Iterator<Formula> itForms = Collections.<Formula>emptyList().iterator(); private int increment; private static final boolean[] trueFalseCollection = {true, false}; public enum MathMLType { CONTENT, PRESENTATION, BOTH } /** * @param input Reader containing the input to process * @param subformulae if true, subformulae will be extracted * @param type type of MathML that should be processed */ public MathTokenizer(Reader input, boolean subformulae, MathMLType type) { super(input); this.mmlType = type; this.subformulae = subformulae; if (!subformulae) { lCoef = 1; vCoef = 1; cCoef = 1; } } /** * Overrides the position attribute for all processed formulae * * @param formulaPosition Position number to be used for all processed * formulae */ public void setFormulaPosition(int formulaPosition) { this.formulaPosition = formulaPosition; increment = formulaPosition; } @Override // NB: TokenStream implementation classes or at least their incrementToken() implementation must be final public final boolean incrementToken() { clearAttributes(); if (nextIt()) { Formula f = itForms.next(); termAtt.setEmpty(); termAtt.append(nodeToString(f.getNode(), false)); byte[] payload = PayloadHelper.encodeFloatToShort(f.getWeight()); payAtt.setPayload(new BytesRef(payload)); posAtt.setPositionIncrement(increment); increment = 0; return true; } return false; } /** * Shifts iterator in the formulae map, helping incrementToken() to decide * whether or not is there another token available. * * @return true if there is another formulae in the map, false otherwise */ private boolean nextIt() { while (!itForms.hasNext() && itMap.hasNext()) { itForms = itMap.next().iterator(); increment++; } return itForms.hasNext(); } @Override public void reset() throws IOException { super.reset(); processFormulae(input); } @Override public void end() throws IOException { super.end(); clearFormulae(); } @Override public void close() throws IOException { super.close(); clearFormulae(); } private void clearFormulae() { formulae.clear(); itMap = Collections.<List<Formula>>emptyList().iterator(); itForms = Collections.<Formula>emptyList().iterator(); } /** * Performs all the parsing, sorting, modifying and ranking of the formulae * contained in the given InputStream. Internal representation of the * formula is w3c.dom.Node. * * @param input InputStream with the formuale. * @return Collection of the formulae in the form of Map&lt;Double, * List&lt;String&gt;&gt;. this map gives pairs {created formula, it's * rank}. Key of the map is the rank of the all formulae located in the list * specified by the value of the Map.Entry. */ private void processFormulae(Reader input) { try { clearFormulae(); Document doc = parseMathML(input); if (doc != null) { load(doc); order(); modify(); //printMap(formulae); if (subformulae) { for (List<Formula> forms : formulae.values()) { producedF.addAndGet(forms.size()); } } } itMap = formulae.values().iterator(); itForms = Collections.<Formula>emptyList().iterator(); increment = formulaPosition - 1; // NB: itForms is set to empty iterator and so increment will get incremented by one in nextIt() } catch (Exception e) { LOG.log(Level.SEVERE, "Could not process formulae.", e); } } private Document parseMathML(Reader input) { Document doc; try { org.jdom2.Document jdom2Doc = canonicalizer.canonicalize(new ReaderInputStream(input, "UTF-8")); doc = outputter.output(jdom2Doc); } catch (Exception e) { LOG.log(Level.WARNING, "Input could not be parsed (probably it is not valid MathML)", e); doc = null; } return doc; } /** * Loads all the formulae located in given w3c.dom.Document. * * @param doc DOM Document with formulae */ private void load(Document doc) { String mathMLNamespace = MathMLConf.MATHML_NAMESPACE_URI; if (!subformulae) { mathMLNamespace = "*"; } NodeList list = doc.getElementsByTagNameNS(mathMLNamespace, MathMLConstants.MML_MATH); inputF.addAndGet(list.getLength()); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); formulae.put(i, new ArrayList<Formula>()); float rank = subformulae ? (1 / valuator.count(node, mmlType)) : valuator.count(node, mmlType); loadNode(node, rank, i); } } /** * Recursively called when loading also subformulae. Adds all the relevant * nodes to the formuale1 map. * * @param n Node current MathML node. * @param level current depth in the original formula tree which is also * rank of the this Node */ private void loadNode(Node n, float level, int position) { if (n instanceof Element) { String name = n.getLocalName(); if (!MathMLConf.ignoreNodeAndChildren(name)) { boolean store = false; if ((mmlType == MathMLType.BOTH && MathMLConf.isIndexableElement(name)) || (mmlType == MathMLType.PRESENTATION && MathMLConf.isIndexablePresentationElement(name)) || (mmlType == MathMLType.CONTENT && MathMLConf.isIndexableContentElement(name))) { store = true; } removeTextNodes(n); NodeList nl = n.getChildNodes(); int length = nl.getLength(); if (subformulae || !store) { for (int j = 0; j < length; j++) { Node node = nl.item(j); loadNode(node, store ? level * lCoef : level, position); } } if (store && !MathMLConf.ignoreNode(name)) { formulae.get(position).add(new Formula(n, level)); loadUnifiedNodes(n, level, position); } } } } /** * Called when loading formulae from the document one for every formula from * the document. For the given node generates its structurally unified * variants and adds them to the formulae map. * * @param n Node current MathML node. * @param basicRank current depth in the original formula tree which is also * rank of the this Node * @param position position of the original formula in the map of formulae */ private void loadUnifiedNodes(Node n, float basicWeight, int position) { if (n.getNodeType() == Node.ELEMENT_NODE) { HashMap<Integer, Node> unifiedMathMLNodes = MathMLUnificator.getUnifiedMathMLNodes(n, false); int maxUniLevel = unifiedMathMLNodes.size() + 1; // Add 1 for the original formula that is not part of the set of unified formulae for (int uniLevel : unifiedMathMLNodes.keySet()) { Node un = unifiedMathMLNodes.get(uniLevel); float nodeWeightCoef = ((float) (maxUniLevel - uniLevel) / maxUniLevel); if (nodeWeightCoef >= MathMLConf.unifiedNodeWeightCoefThreshold) { float weight = basicWeight * nodeWeightCoef; formulae.get(position).add(new Formula(un, weight)); } } } } /** * Removes unnecessary text nodes from the markup * * @param node */ private void removeTextNodes(Node node) { NodeList nl = node.getChildNodes(); int length = nl.getLength(); int removed = 0; for (int j = 0; j < length; j++) { Node n = nl.item(removed); if ((n instanceof Text) && (n.getTextContent().trim().length() == 0)) { node.removeChild(n); } else { removed++; removeTextNodes(n); } } } /** * Removes all attributes except those specified in the attr-dict * configuration file * * @param rank factor by which the formulae keeping the attributes increase * their weight */ private void processAttributes(float rank) { List<Formula> result = new ArrayList<Formula>(); for (List<Formula> forms : formulae.values()) { result.clear(); for (Formula f : forms) { Node node = f.getNode(); Node newNode = node.cloneNode(true); removeAttributes(node); boolean changed = processAttributesNode(newNode); if (changed) { result.add(new Formula(newNode, f.getWeight() * rank)); } } forms.addAll(result); } } private boolean processAttributesNode(Node node) { boolean result = false; NodeList nl = node.getChildNodes(); int length = nl.getLength(); for (int j = 0; j < length; j++) { Node n = nl.item(j); result = processAttributesNode(n) == false ? result : true; } if (node.hasAttributes()) { NamedNodeMap attrs = node.getAttributes(); Set<Node> keepAttrs = new HashSet<Node>(); for (String dictAttr : attrdict.keySet()) { Node keepAttr = attrs.getNamedItem(dictAttr); if (keepAttr != null) { keepAttrs.add(keepAttr); } } removeAttributes(node); for (Node n : keepAttrs) { attrs.setNamedItem(n); result = true; } } return result; } private void removeAttributes(Node node) { removeAttributesNode(node); NodeList nl = node.getChildNodes(); int length = nl.getLength(); for (int j = 0; j < length; j++) { removeAttributes(nl.item(j)); } } private void removeAttributesNode(Node node) { if (node.hasAttributes()) { NamedNodeMap attrs = node.getAttributes(); String[] names = new String[attrs.getLength()]; for (int i = 0; i < names.length; i++) { names[i] = attrs.item(i).getNodeName(); } for (int i = 0; i < names.length; i++) { attrs.removeNamedItem(names[i]); } } } /** * Provides sorting of elements in MathML formula based on the NodeName. * Sorting is done for operators from the operators configuration file. All * sorted formulae replace their original forms in the formulae map. */ private void order() { for (List<Formula> forms : formulae.values()) { for (Formula f : forms) { Node newNode = f.getNode().cloneNode(true); f.setNode(orderNode(newNode)); } } } private Node orderNode(Node node) { if (node instanceof Element) { List<Node> nodes = new ArrayList<Node>(); NodeList nl = node.getChildNodes(); if (nl.getLength() > 1) { for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); orderNode(n); nodes.add(n); } if (mmlType == MathMLType.PRESENTATION) { boolean switched; for (Node justCycle : nodes) { switched = false; for (int i = 1; i < nodes.size() - 1; i++) { Node n = nodes.get(i); String name = n.getLocalName(); if (MathMLConstants.PMML_MO.equals(name)) { String text = n.getTextContent(); if (ops.containsKey(text)) { Node n1 = nodes.get(i - 1); Node n2 = nodes.get(i + 1); boolean toSwap = toSwapNodes(n1, n2); if (toSwap && canSwap(text, i, nodes)) { nodes.set(i - 1, n2); nodes.set(i + 1, n1); switched = true; } } } } if (!switched) { break; } } } if (mmlType == MathMLType.CONTENT) { Node n = node.getFirstChild(); String name = n.getLocalName(); if (MathMLConstants.CMML_TIMES.equals(name) || MathMLConstants.CMML_PLUS.equals(name)) { boolean swapped = true; while (swapped) { swapped = false; for (int j = 1; j < nodes.size() - 1; j++) { Node n1 = nodes.get(j); Node n2 = nodes.get(j + 1); if (toSwapNodes(n1, n2)) { nodes.set(j, n2); nodes.set(j + 1, n1); swapped = true; } } } } } for (Node n : nodes) { node.appendChild(n); } } } return node; } private boolean toSwapNodes(Node n1, Node n2) { int c = n1.getNodeName().compareTo(n2.getNodeName()); if (c == 0) { String n1Children = getNodeChildren(n1); String n2Children = getNodeChildren(n2); c = n1Children.compareTo(n2Children); } return c > 0 ? true : false; } private String getNodeChildren(Node node) { String result = ""; result = nodeToString(node, true); return result; } /** * Converts a node to M-term styled string representation */ private String nodeToString(Node node, boolean withoutTextContent) { StringBuilder builder = new StringBuilder(); Formula.nodeToString(builder, node, withoutTextContent, eldict, attrdict, MathMLConf.getIgnoreNode()); return builder.toString(); } /** * Determines if nodes around Node i in given list of Nodes can be swapped. * * @param i number of Node in the given list that sorrounding are to be swap * @param nodes List of childNodes of some formula, that are to be sorted * @return true if the Node i was operation + or * and the surrounding can * be swapped, false otherwise */ private boolean canSwap(String text, int i, List<Node> nodes) { boolean result = true; List<String> priorOps = ops.get(text); if (i - 2 >= 0) { Node n11 = nodes.get(i - 2); String n11text = n11.getTextContent(); if (MathMLConstants.PMML_MO.equals(n11.getLocalName()) && priorOps.contains(n11text)) { result = false; } } if (i + 2 < nodes.size()) { Node n22 = nodes.get(i + 2); String n22text = n22.getTextContent(); if (MathMLConstants.PMML_MO.equals(n22.getLocalName()) && priorOps.contains(n22text)) { result = false; } } return result; } /** * Provides all the modifying on the loaded formulae located in formuale * map. Calls several modifiing methods and specifies how they should alter * the rank of modified formula. */ private void modify() { unifyVariables(vCoef); unifyConst(cCoef); unifyOperators(oCoef); processAttributes(aCoef); } /** * Unifies variables of each formula in formulae map * * @param rank Specifies the factor by which it should alter the rank of * modified formula */ private void unifyVariables(float rank) { List<Formula> result = new ArrayList<Formula>(); for (List<Formula> forms : formulae.values()) { result.clear(); for (Formula f : forms) { Node node = f.getNode(); NodeList nl = node.getChildNodes(); boolean hasElement = true; if (((nl.getLength() == 1) && !(nl.item(0) instanceof Element)) || nl.getLength() == 0) { hasElement = false; } if (hasElement) { for (boolean keepAlphaEquivalence : trueFalseCollection) { Map<String, String> changes = new HashMap<String, String>(); Node newNode = node.cloneNode(true); boolean changed = unifyVariablesNode(newNode, changes, keepAlphaEquivalence); if (changed) { result.add(new Formula(newNode, f.getWeight() * (keepAlphaEquivalence ? rank : vCoefGen * rank))); } } } } forms.addAll(result); } } /** * Recursively modifying variables of the formula or subformula specified by * given Node * * @param node Node representing current formula or subformula that is being * modified * @param changes Map holding the performed changes, so that the variables * with the same name are always substituted with the same unified name * within the scope of each formula. * @param keepAlphaEquivalence If <code>true</code> variable unification * will preserve alfa equivalence, i.e. identical variables will be * preserved with one symbol distinct from substituing symbols used for * different variable using <code>changes</code> map. If <code>false</code>, * variable will be unified with general unification symbol (see * {@link MathMLUnificator#replaceNodeWithUnificator(org.w3c.dom.Node)}). * @return Saying whether or not this formula was modified */ private boolean unifyVariablesNode(Node node, Map<String, String> changes, boolean keepAlphaEquivalence) { boolean result = false; if (node instanceof Element) { NodeList nl = node.getChildNodes(); for (int j = 0; j < nl.getLength(); j++) { result = unifyVariablesNode(nl.item(j), changes, keepAlphaEquivalence) == false ? result : true; } if (MathMLConstants.PMML_MI.equals(node.getLocalName()) || MathMLConstants.CMML_CI.equals(node.getLocalName())) { String oldVar = node.getTextContent(); if (oldVar != null && !oldVar.equals(Constants.UNIFICATOR)) { if (keepAlphaEquivalence) { String newVar = toVar(oldVar, changes); node.setTextContent(newVar); result = true; } else { MathMLUnificator.replaceNodeWithUnificator(node); result = true; } } } } return result; } /** * Helping method performs substitution of the variable based on the given * map of already done changes. * * @param oldVar Variable to be unified * @param changes Map with already done changes. * @return new name of the variable */ private String toVar(String oldVar, Map<String, String> changes) { String newVar = changes.get(oldVar); if (newVar == null) { newVar = "" + (changes.size() + 1); changes.put(oldVar, newVar); } return newVar; } /** * Performing unifying of all the constants in the formula by substituting * them for "const" string. * * @param rank Specifies how the method should alter modified formulae */ private void unifyConst(float rank) { List<Formula> result = new ArrayList<Formula>(); for (List<Formula> forms : formulae.values()) { result.clear(); for (Formula f : forms) { Node node = f.getNode(); NodeList nl = node.getChildNodes(); boolean hasElement = true; if (((nl.getLength() == 1) && !(nl.item(0) instanceof Element)) || nl.getLength() == 0) { hasElement = false; } if (hasElement) { Node newNode = node.cloneNode(true); boolean changed = unifyConstNode(newNode); if (changed) { result.add(new Formula(newNode, f.getWeight() * rank)); } } } forms.addAll(result); } } /** * Recursively modifying constants of the formula or subformula specified by * given Node * * @param node Node representing current formula or subformula that is being * modified * @return Saying whether or not this formula was modified */ private boolean unifyConstNode(Node node) { boolean result = false; if (node instanceof Element) { NodeList nl = node.getChildNodes(); for (int j = 0; j < nl.getLength(); j++) { result = unifyConstNode(nl.item(j)) == false ? result : true; } if (MathMLConstants.PMML_MN.equals(node.getLocalName()) || MathMLConstants.CMML_CN.equals(node.getLocalName())) { node.setTextContent("\u00B6"); return true; } } return result; } private void unifyOperators(float rank) { List<Formula> result = new ArrayList<Formula>(); for (List<Formula> forms : formulae.values()) { result.clear(); for (Formula f : forms) { Node node = f.getNode(); NodeList nl = node.getChildNodes(); boolean hasElement = true; if (((nl.getLength() == 1) && !(nl.item(0) instanceof Element)) || nl.getLength() == 0) { hasElement = false; } if (hasElement) { Node newNode = node.cloneNode(true); boolean changed = unifyOperatorsNode(newNode); if (changed) { result.add(new Formula(newNode, f.getWeight() * rank)); } } } forms.addAll(result); } } private boolean unifyOperatorsNode(Node node) { boolean result = false; if (node instanceof Element) { NodeList nl = node.getChildNodes(); for (int j = 0; j < nl.getLength(); j++) { result = unifyOperatorsNode(nl.item(j)) == false ? result : true; } if (node.getLocalName() != null && node.getLocalName().equals(MathMLConstants.PMML_MO) && MathMLConf.additiveOperators.contains(node.getTextContent())) { node.setTextContent("+"); result = true; } else if (node.getLocalName() != null && MathMLConf.additiveOperators.contains(node.getLocalName())) { Node unifiedCmmlOperator = node.getOwnerDocument().createElement("op"); node.getParentNode().replaceChild(unifiedCmmlOperator, node); result = true; } } return result; } /** * @return Processed formulae to be used for a query. No subformulae are * extracted. */ public Map<String, Float> getQueryFormulae() { Map<String, Float> result = new HashMap<String, Float>(); for (List<Formula> forms : formulae.values()) { for (Formula f : forms) { result.put(nodeToString(f.getNode(), false), f.getWeight()); } } return result; } private void printMap(Map<Integer, List<Formula>> formulae) { for (Map.Entry<Integer, List<Formula>> entry : formulae.entrySet()) { List<Formula> forms = entry.getValue(); int counter = 1; for (Formula f : forms) { StringBuilder sb = new StringBuilder(" sb.append(entry.getKey() + " " + nodeToString(f.getNode(), false) + " " + f.getWeight() + "\n"); sb.append(XMLOut.xmlStringSerializer(f.getNode())); System.out.println(sb.toString()); } } } /** * Prints numbers of processed formulae to standard output */ public static void printFormulaeCount() { LOG.info("Input formulae: " + inputF.get()); LOG.info("Indexed formulae: " + producedF.get()); } /** * @return A map with formulae as if they are indexed. Key of the map is the * original document position of the extracted formulae contained in the * value of the map. */ public Map<Integer, List<Formula>> getFormulae() { return formulae; } }
package de.bmoth.backend; import java.util.List; import com.microsoft.z3.ArithExpr; import com.microsoft.z3.ArrayExpr; import com.microsoft.z3.BoolExpr; import com.microsoft.z3.Context; import com.microsoft.z3.Expr; import com.microsoft.z3.IntExpr; import com.microsoft.z3.Sort; import com.microsoft.z3.Symbol; import com.microsoft.z3.TupleSort; import de.bmoth.parser.Parser; import de.bmoth.parser.ast.AbstractVisitor; import de.bmoth.parser.ast.nodes.ExprNode; import de.bmoth.parser.ast.nodes.ExpressionOperatorNode; import de.bmoth.parser.ast.nodes.FormulaNode; import de.bmoth.parser.ast.nodes.FormulaNode.FormulaType; import de.bmoth.parser.ast.nodes.IdentifierExprNode; import de.bmoth.parser.ast.nodes.IdentifierPredicateNode; import de.bmoth.parser.ast.nodes.NumberNode; import de.bmoth.parser.ast.nodes.ParallelSubstitutionNode; import de.bmoth.parser.ast.nodes.PredicateNode; import de.bmoth.parser.ast.nodes.PredicateOperatorNode; import de.bmoth.parser.ast.nodes.PredicateOperatorWithExprArgsNode; import de.bmoth.parser.ast.nodes.QuantifiedExpressionNode; import de.bmoth.parser.ast.nodes.QuantifiedPredicateNode; import de.bmoth.parser.ast.nodes.SelectSubstitutionNode; import de.bmoth.parser.ast.nodes.SingleAssignSubstitution; import de.bmoth.parser.ast.types.BoolType; import de.bmoth.parser.ast.types.CoupleType; import de.bmoth.parser.ast.types.IntegerType; import de.bmoth.parser.ast.types.SetType; import de.bmoth.parser.ast.types.Type; /** * This class translates a FormulaNode of the parser to a z3 backend node. * * The second parameter of the AbstractVisitor class is the method parameter of * each method which is inherited form the AbstractVisitor class. In the * FormulaTranslator this parameter is not needed. Hence, the placeholder class * Void is used. Furthermore, each call to a visitXXX method of the * AbstractVisitor class should use the argument null. **/ public class FormulaTranslator extends AbstractVisitor<Expr, Void> { private Context z3Context; public FormulaTranslator(Context z3Context) { this.z3Context = z3Context; } public static BoolExpr translatePredicate(String formula, Context z3Context) { FormulaNode node = Parser.getFormulaAsSemanticAst(formula); if (node.getFormulaType() != FormulaType.PREDICATE_FORMULA) { throw new RuntimeException("Expected predicate."); } FormulaTranslator formulaTranslator = new FormulaTranslator(z3Context); Expr constraint = formulaTranslator.visitPredicateNode((PredicateNode) node.getFormula(), null); if (!(constraint instanceof BoolExpr)) { throw new RuntimeException("Invalid translation. Expected BoolExpr but found " + constraint.getClass()); } BoolExpr boolExpr = (BoolExpr) constraint; return boolExpr; } @Override public Expr visitIdentifierExprNode(IdentifierExprNode node, Void n) { Type type = node.getDeclarationNode().getType(); return z3Context.mkConst(node.getName(), bTypeToZ3Sort(type)); } @Override public Expr visitIdentifierPredicateNode(IdentifierPredicateNode node, Void n) { return z3Context.mkBoolConst(node.getName()); } @Override public Expr visitPredicateOperatorWithExprArgs(PredicateOperatorWithExprArgsNode node, Void n) { final List<ExprNode> expressionNodes = node.getExpressionNodes(); switch (node.getOperator()) { case EQUAL: { Expr left = visitExprNode(expressionNodes.get(0), null); Expr right = visitExprNode(expressionNodes.get(1), null); return z3Context.mkEq(left, right); } case NOT_EQUAL: { Expr left = visitExprNode(expressionNodes.get(0), null); Expr right = visitExprNode(expressionNodes.get(1), null); return z3Context.mkNot(z3Context.mkEq(left, right)); } case ELEMENT_OF: case LESS_EQUAL: break; case LESS: { ArithExpr left = (ArithExpr) visitExprNode(expressionNodes.get(0), null); ArithExpr right = (ArithExpr) visitExprNode(expressionNodes.get(1), null); return z3Context.mkLt(left, right); } case GREATER_EQUAL: break; case GREATER: default: break; } // TODO throw new AssertionError("Not implemented: " + node.getOperator()); } @Override public Expr visitExprOperatorNode(ExpressionOperatorNode node, Void n) { List<ExprNode> expressionNodes = node.getExpressionNodes(); switch (node.getOperator()) { case PLUS: { ArithExpr left = (ArithExpr) visitExprNode(expressionNodes.get(0), null); ArithExpr right = (ArithExpr) visitExprNode(expressionNodes.get(1), null); return z3Context.mkAdd(left, right); } case MINUS: { ArithExpr left = (ArithExpr) visitExprNode(expressionNodes.get(0), null); ArithExpr right = (ArithExpr) visitExprNode(expressionNodes.get(1), null); return z3Context.mkSub(left, right); } case MOD: { IntExpr left = (IntExpr) visitExprNode(expressionNodes.get(0), null); IntExpr right = (IntExpr) visitExprNode(expressionNodes.get(1), null); return z3Context.mkMod(left, right); } case MULT: { ArithExpr left = (ArithExpr) visitExprNode(expressionNodes.get(0), null); ArithExpr right = (ArithExpr) visitExprNode(expressionNodes.get(1), null); return z3Context.mkMul(left, right); } case DIVIDE: { ArithExpr left = (ArithExpr) visitExprNode(expressionNodes.get(0), null); ArithExpr right = (ArithExpr) visitExprNode(expressionNodes.get(1), null); return z3Context.mkDiv(left, right); } case POWER_OF: { ArithExpr left = (ArithExpr) visitExprNode(expressionNodes.get(0), null); ArithExpr right = (ArithExpr) visitExprNode(expressionNodes.get(1), null); return z3Context.mkPower(left, right); } case INTERVAL: break; case INTEGER: break; case NATURAL1: break; case NATURAL: break; case FALSE: return z3Context.mkFalse(); case TRUE: return z3Context.mkTrue(); case BOOL: break; case UNION: break; case COUPLE: { CoupleType type = (CoupleType) node.getType(); TupleSort bTypeToZ3Sort = (TupleSort) bTypeToZ3Sort(type); Expr left = visitExprNode(node.getExpressionNodes().get(0), null); Expr right = visitExprNode(node.getExpressionNodes().get(1), null); return bTypeToZ3Sort.mkDecl().apply(left, right); } case DOMAIN: break; case INTERSECTION: break; case RANGE: break; case SET_ENUMERATION: { SetType type = (SetType) node.getType(); Type subType = type.getSubtype(); ArrayExpr z3Set = z3Context.mkEmptySet(bTypeToZ3Sort(subType)); for (ExprNode exprNode : expressionNodes) { z3Set = z3Context.mkSetAdd(z3Set, visitExprNode(exprNode, null)); } return z3Set; } case SET_SUBTRACTION: break; default: break; } // TODO throw new AssertionError("Not implemented: " + node.getOperator()); } @Override public Expr visitNumberNode(NumberNode node, Void n) { return this.z3Context.mkInt(node.getValue()); } @Override public Expr visitPredicateOperatorNode(PredicateOperatorNode node, Void n) { List<PredicateNode> predicateArguments = node.getPredicateArguments(); switch (node.getOperator()) { case AND: { BoolExpr left = (BoolExpr) visitPredicateNode(predicateArguments.get(0), null); BoolExpr right = (BoolExpr) visitPredicateNode(predicateArguments.get(1), null); return z3Context.mkAnd(left, right); } case OR: { BoolExpr left = (BoolExpr) visitPredicateNode(predicateArguments.get(0), null); BoolExpr right = (BoolExpr) visitPredicateNode(predicateArguments.get(1), null); return z3Context.mkOr(left, right); } case IMPLIES: { BoolExpr left = (BoolExpr) visitPredicateNode(predicateArguments.get(0), null); BoolExpr right = (BoolExpr) visitPredicateNode(predicateArguments.get(1), null); return z3Context.mkImplies(left, right); } case EQUIVALENCE: case NOT: case TRUE: break; case FALSE: return z3Context.mkFalse(); default: break; } // TODO throw new AssertionError("Not implemented: " + node.getOperator()); } @Override public Expr visitSelectSubstitutionNode(SelectSubstitutionNode node, Void expected) { throw new AssertionError("Not reachable"); } @Override public Expr visitSingleAssignSubstitution(SingleAssignSubstitution node, Void expected) { throw new AssertionError("Not reachable"); } @Override public Expr visitParallelSubstitutionNode(ParallelSubstitutionNode node, Void expected) { throw new AssertionError("Not reachable"); } public Sort bTypeToZ3Sort(Type t) { if (t instanceof IntegerType) { return z3Context.getIntSort(); } if (t instanceof BoolType) { return z3Context.getBoolSort(); } if (t instanceof SetType) { SetType s = (SetType) t; Sort subSort = bTypeToZ3Sort(s.getSubtype()); return z3Context.mkSetSort(subSort); } if (t instanceof CoupleType) { CoupleType c = (CoupleType) t; Sort[] subSorts = new Sort[2]; subSorts[0] = bTypeToZ3Sort(c.getLeft()); subSorts[1] = bTypeToZ3Sort(c.getRight()); return z3Context.mkTupleSort(z3Context.mkSymbol("couple"), new Symbol[] { z3Context.mkSymbol("left"), z3Context.mkSymbol("right") }, subSorts); } throw new AssertionError("Missing Type Conversion: " + t.getClass()); } @Override public Expr visitQuantifiedExpressionNode(QuantifiedExpressionNode node, Void expected) { throw new AssertionError("Implement: " + node.getClass()); } @Override public Expr visitQuantifiedPredicateNode(QuantifiedPredicateNode node, Void expected) { throw new AssertionError("Implement: " + node.getClass()); } }
package de.jkitberatung.player; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.logging.Logger; import javax.swing.JCheckBox; import javax.swing.JComboBox; import org.apache.jmeter.config.CSVDataSet; import org.apache.jmeter.gui.GuiPackage; import org.apache.jmeter.gui.tree.JMeterTreeModel; import org.apache.jmeter.gui.tree.JMeterTreeNode; import org.apache.jmeter.samplers.AbstractSampler; import org.apache.jmeter.samplers.Entry; import org.apache.jmeter.samplers.Interruptible; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.util.JMeterUtils; import de.jkitberatung.ica.wsh.IICAClient; import de.jkitberatung.ica.wsh.IKeyboard; import de.jkitberatung.ica.wsh.IMouse; import de.jkitberatung.ica.wsh.IScreenShot; import de.jkitberatung.player.gui.PlaySamplerControlGui; import de.jkitberatung.recorder.Interaction; import de.jkitberatung.recorder.RecordingStep; import de.jkitberatung.recorder.StringInteraction; import de.jkitberatung.recorder.Interaction.Label; import de.jkitberatung.util.IcaConnector; public class PlaySampler extends AbstractSampler implements Interruptible{ // -Djava.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n' static final Logger L= Logger.getLogger(PlaySampler.class.getName()); private static final long serialVersionUID = 2454380067430756308L; private static final String SCREENSHOTS_PATH = "PlaySampler.screenshots_path"; private static final String SCREENSHOTS_FOLDER_PATH = "PlaySampler.screenshots_folder_path"; private static final String VALUES_SEPARATOR = ","; private static final String DEFAULT_SLEEP_TIME = "75"; private transient RecordingStep crtPlayingStep; private transient IICAClient ica; private double sleepFactor; private RecordingStep step; private HashMap<String, String> stringInput; private int interval = JMeterUtils.getPropDefault("ica.polling.interval", 100); private int maxduration = JMeterUtils.getPropDefault("ica.max.duration", 30000); private boolean isInterrupted = false; private PlaySamplerControl samplerController; @Override public Object clone() { Object clone = super.clone(); ((PlaySampler) clone).setCrtPlayingStep(crtPlayingStep); ((PlaySampler) clone).setIca(ica); if (null == samplerController) // setController((PlaySamplerControl) IcaConnector.getInstance().getSamplerController().clone()); setController(IcaConnector.getInstance().getSamplerController()); ((PlaySampler) clone).setController((PlaySamplerControl) samplerController.clone()); ((PlaySampler) clone).setSleepFactor(sleepFactor); ((PlaySampler) clone).setStep(step); ((PlaySampler) clone).setStringInput(stringInput); return clone; } public void setCrtPlayingStep(RecordingStep crtPlayingStep) { this.crtPlayingStep = crtPlayingStep; } public HashMap<String, String> getStringInput() { return stringInput; } public void setStringInput(HashMap<String, String> stringInput) { this.stringInput = stringInput; } public void setIca(IICAClient ica) { this.ica = ica; } public void setStep(RecordingStep step) { this.step = step; } public void setSleepFactor(double sleepFactor) { this.sleepFactor = sleepFactor; } protected void playInteractions(PlaySampleResult result) { try { if (null == samplerController) setController((PlaySamplerControl) IcaConnector.getInstance().getSamplerController().clone()); if (IcaConnector.getInstance().getIcaMap().containsKey(getThreadName()) && IcaConnector.getInstance().getIcaMap().get(getThreadName()).session() != null) { ica = IcaConnector.getInstance().getIcaMap().get(getThreadName()); L.fine("footprint } else { if (step.isFirst()) { setController((PlaySamplerControl) samplerController.clone()); // samplerController.getIcaConnector().setIca(null); // samplerController.getIcaConnector().setIcaLoggedOn(false); L.fine(getThreadName() + ": " + "Forcing new connection..."); } ica = samplerController.getIcaConnector().getIca(); IcaConnector.getInstance().getIcaMap().put(getThreadName(), ica); L.fine("footprint } if (ica == null || ica.session() == null) { L.fine(getThreadName() + ": " + "Failed playing interactions of step: " + step.getName()); return; } IKeyboard keyboard = ica.session().keyboard(); IMouse mouse = ica.session().mouse(); crtPlayingStep = new RecordingStep(step.getName(), step.isAutoAddSleeptimes()); List<Interaction> interactionList = step.getInteractionList(); L.fine(getThreadName() + ": " + "Playing step " + step.getName() + "..."); setSleepFactor(); Interaction lastMouseDown = null; for (Interaction interaction : interactionList) { if (ica == null || ica.session() == null) return;//abort playback due to session interruption if (isInterrupted) { result.setResponseMessage("Sampler interrupted !"); return; } Label label = interaction.getLabel(); if (label.equals(Interaction.Label.MouseDown)) lastMouseDown = new Interaction(interaction.getLabel(), interaction.getValue()); if (label.equals(Interaction.Label.StringTag)) playStringInteraction(interaction, lastMouseDown, keyboard, mouse, crtPlayingStep.getName(), result); else playInteraction(interaction, lastMouseDown, keyboard, mouse, result); } } catch (Exception e) { e.printStackTrace(); } } private void setSleepFactor() { JCheckBox sleepingCheckBox = IcaConnector.getInstance().getSleepingCheckBox(); if (!sleepingCheckBox.isSelected()) { sleepFactor = 0.00; return; } JComboBox sleepingComboBox = IcaConnector.getInstance().getSleepingComboBox(); String sleepFactorStr = sleepingComboBox.getSelectedItem().toString(); sleepFactor = sleepFactorStr.equals(PlaySamplerControlGui.DEFAULT_SLEEP_FACTOR) ? 1.00 : Double.valueOf(sleepFactorStr).doubleValue(); } private void playStringInteraction(Interaction interaction, Interaction lastMouseDown, IKeyboard keyboard, IMouse mouse, String stepName, PlaySampleResult result) { L.fine(getThreadName() + ": " + "Playing tag " + interaction.getValue()); StringInteraction strInteraction = (StringInteraction) interaction; List<Interaction> interactions = strInteraction.getInteractions(); if (null == stringInput) stringInput = IcaConnector.getInstance().getTagsMap().get(stepName); // Check if we need to play custom csv input if (treeContainsCsvDataSetConfig() && tagIsCustomizable(strInteraction.getName())) interactions = buildInteractionsFromString(getTagInput(strInteraction.getName())); for (Interaction inter : interactions) playInteraction(inter, lastMouseDown, keyboard, mouse, result); } private boolean tagIsCustomizable(String tagName) { if (stringInput.size() > 0 && stringInput.containsKey(tagName) && !stringInput.get(tagName).isEmpty()) return true; return false; } private boolean treeContainsCsvDataSetConfig() { Enumeration<JMeterTreeNode> enumNode = threadGroupNode().children(); while (enumNode.hasMoreElements()) { JMeterTreeNode child = enumNode.nextElement(); if (child.getUserObject() instanceof CSVDataSet) return true; } return false; } private JMeterTreeNode threadGroupNode() { JMeterTreeModel treeModel = GuiPackage.getInstance().getTreeModel(); JMeterTreeNode myNode = treeModel.getNodeOf(IcaConnector.getInstance().getSamplerController()); if (myNode != null) return (JMeterTreeNode) myNode.getParent(); return null; } private List<Interaction> buildInteractionsFromString(String string) { // L.fine("Building interations from sting: " + string); List<Interaction> list = new ArrayList<Interaction>(); for (int i = 0; i < string.length(); i++) { int[] keyIds = charToKeyId(string.codePointAt(i)); list.add(new Interaction(Interaction.Label.KeyDown, keyIds[0] + ""));//keyDown ALT list.add(new Interaction(Interaction.Label.SleepTime, DEFAULT_SLEEP_TIME));//sleeptime for (int j = 1; j < keyIds.length; j++) { list.add(new Interaction(Interaction.Label.KeyDown, keyIds[j] + "")); list.add(new Interaction(Interaction.Label.SleepTime, DEFAULT_SLEEP_TIME));//sleeptime list.add(new Interaction(Interaction.Label.KeyUp, keyIds[j] + "")); list.add(new Interaction(Interaction.Label.SleepTime, DEFAULT_SLEEP_TIME));//sleeptime } list.add(new Interaction(Interaction.Label.KeyUp, keyIds[0] + ""));//keyUp ALT list.add(new Interaction(Interaction.Label.SleepTime, DEFAULT_SLEEP_TIME));//sleeptime } return list; } private void playInteraction(Interaction interaction, Interaction lastMouseDown, IKeyboard keyboard, IMouse mouse, PlaySampleResult result) { String[] tokens = null; Label label = interaction.getLabel(); L.fine(" playing " + interaction); switch (label) { case KeyUp: keyboard.sendKeyUp(Integer.parseInt((String) interaction.getValue())); break; case KeyDown: keyboard.sendKeyDown(Integer.parseInt((String) interaction.getValue())); break; case MouseDown: tokens = ((String)interaction.getValue()).split(","); mouse.sendMouseDown(Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Integer.parseInt(tokens[0]) , Integer.parseInt(tokens[1])); break; case MouseUp: tokens = ((String)interaction.getValue()).split(","); mouse.sendMouseUp(Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Integer.parseInt(tokens[0]) , Integer.parseInt(tokens[1])); break; case MouseDoubleClick: if (null != lastMouseDown) { tokens = ((String)lastMouseDown.getValue()).split(","); mouse.sendMouseDown(Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Integer.parseInt(tokens[0]) , Integer.parseInt(tokens[1])); mouse.sendMouseUp(Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Integer.parseInt(tokens[0]) , Integer.parseInt(tokens[1])); mouse.sendMouseDown(Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Integer.parseInt(tokens[0]) , Integer.parseInt(tokens[1])); mouse.sendMouseUp(Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Integer.parseInt(tokens[0]) , Integer.parseInt(tokens[1])); } break; case ScreenShot: String value = (String)interaction.getValue(); String[] split = value.split(VALUES_SEPARATOR); result.addHash(split[0], true); takeScreenShot(true, split[1], split[2], split[3], split[4], result); break; case SleepTime: try { L.fine(" sleeping with factor " + sleepFactor); Thread.sleep((long) (Integer.parseInt((String) interaction.getValue()) * sleepFactor)); } catch (NumberFormatException e) { e.printStackTrace(); } catch (InterruptedException e) { L.fine(getThreadName() + ": " + "Sleep interrupted"); } break; default: break; } } private int[] charToKeyId(int codePoint) { int[] keyIds = null; String pStr = Integer.valueOf(codePoint).toString();//code point for '' is 252; we turn it into "252" keyIds = new int[pStr.length() + 2];//keyIds must hold <ALT><NUMPAD0><NUMPAD2><NUMPAD5><NUMPAD2> to generate '' keyIds[0] = KeyEvent.VK_ALT; keyIds[1] = KeyEvent.VK_NUMPAD0; for (int index = 0; index < pStr.length(); index++) keyIds[index + 2] = KeyEvent.VK_NUMPAD0 + Integer.valueOf(pStr.substring(index,index+1)).intValue(); return keyIds; } /** * JK, 20131128, waitfor. * @param saveBitmap * @param x * @param y * @param width * @param height * @param result */ public void takeScreenShot(boolean saveBitmap, String x, String y, String width, String height, PlaySampleResult result) { boolean done = false; IScreenShot ss = null; String waitfor = (String) result.getRecordingHashes().get(result.getRecordingHashes().size() -1); int waitedFor = 0; while (!done) { ss = ica.session().createScreenShot(Integer.parseInt(x) , Integer.parseInt(y), Integer.parseInt(width), Integer.parseInt(height)); // log first try if (waitedFor==0) { L.fine(getThreadName() + ": " + "Creating a screenshot... Hash value " + ss.bitmapHash()); } if(ss.bitmapHash().equalsIgnoreCase(waitfor) || waitedFor >= maxduration) { done=true; } else { try { Thread.sleep(interval); waitedFor=waitedFor + interval; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } result.setLatency(waitedFor); crtPlayingStep.addInteraction(new Interaction(Interaction.Label.ScreenShot, ss.bitmapHash())); result.addHash(ss.bitmapHash(), false); if (saveBitmap) { ss.filename(IcaConnector.getInstance().getLocationHashFolder() + System.getProperty("file.separator") + System.currentTimeMillis() + ".bmp"); ss.save(); L.fine(getThreadName() + ": " + "Saving screenshot to file " + ss.filename()); } } public SampleResult sample(Entry e) { if (step == null) { String stepName = getName().substring(0,getName().indexOf(" Sampler")); setStep(IcaConnector.getInstance().getStepByName(stepName)); setTagsInput(IcaConnector.getInstance().getTagsMap().get(stepName)); } L.fine(getThreadName() + ": " + "Sampling step " + step.getName() + "..."); PlaySampleResult result = new PlaySampleResult(); result.setSampleLabel(step.getName()); result.sampleStart(); Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_NUM_LOCK, true); playInteractions(result); if (!isInterrupted) dumpScreenshotsHashes(result); result.sampleEnd(); L.fine(getThreadName() + ": " + "Sampling step " + step.getName() + " ended."); if (step.isLast()) { // samplerController.getIcaConnector().setIca(null); IcaConnector.getInstance().getIcaMap().remove(getThreadName()); L.fine(getThreadName() + ":" + "Removed entry from ICA connections map"); } return result; } private void setTagsInput(LinkedHashMap<String, String> tags) { for (String tagName : tags.keySet()) setTagInput(tagName, tags.get(tagName)); } private synchronized void dumpScreenshotsHashes(PlaySampleResult result) { L.fine(getThreadName() + ": " + "Dumping hash value to file " + IcaConnector.getInstance().getLocationHashFile()); if (crtPlayingStep == null) { L.fine(" failed: crtPlayingStep is null"); return; } File file = new File(IcaConnector.getInstance().getLocationHashFile()); FileWriter fw; try { fw = new FileWriter(file, true); fw.write("\n" + crtPlayingStep.toString()); fw.flush(); fw.close(); } catch (IOException e) { L.fine(getThreadName() + ": " + "Failed dumping hash value to file \n" + e.getMessage()); e.printStackTrace(); } } /** * Interrupt the sampling (When user hits Stop on the test) */ public boolean interrupt() { isInterrupted = true; L.fine(getThreadName() + ": " + "Player interrupted"); return true; } public void setScreenshotsHashesFilePath(String path) { setProperty(SCREENSHOTS_PATH, path); } public String getScreenshotsHashesFilePath() { return getPropertyAsString(SCREENSHOTS_PATH); } public void setScreenshotsForderPath(String path) { setProperty(SCREENSHOTS_FOLDER_PATH, path); } public String getScreenshotsFolderPath() { return getPropertyAsString(SCREENSHOTS_FOLDER_PATH); } public void setTagInput(String tagName, String tagInput) { setProperty(tagName, tagInput); } public String getTagInput(String tagName) { return getPropertyAsString(tagName); } public void setController(PlaySamplerControl samplerController) { this.samplerController = samplerController; } }
package de.prob2.ui.prob2fx; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import de.prob.statespace.AnimationSelector; import de.prob2.ui.internal.StageManager; import de.prob2.ui.project.Machine; import de.prob2.ui.project.Preference; import de.prob2.ui.project.Project; import de.prob2.ui.project.Runconfiguration; import de.prob2.ui.verifications.modelchecking.ModelcheckingController; import javafx.beans.binding.Bindings; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ListProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyBooleanProperty; import javafx.beans.property.ReadOnlyListProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleListProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; @Singleton public final class CurrentProject extends SimpleObjectProperty<Project> { private static final Charset PROJECT_CHARSET = Charset.forName("UTF-8"); private static final Logger LOGGER = LoggerFactory.getLogger(CurrentProject.class); private final Gson gson; private final BooleanProperty exists; private final StringProperty name; private final StringProperty description; private final ListProperty<Machine> machines; private final ListProperty<Preference> preferences; private final ReadOnlyListProperty<Runconfiguration> runconfigurations; private final ObjectProperty<File> location; private final ObjectProperty<Path> defaultLocation; private final StageManager stageManager; private final Injector injector; private final AnimationSelector animations; private final CurrentTrace currentTrace; private final ModelcheckingController modelCheckController; @Inject private CurrentProject(final StageManager stageManager, final Injector injector, final AnimationSelector animations, final CurrentTrace currentTrace, final ModelcheckingController modelCheckController) { this.stageManager = stageManager; this.injector = injector; this.animations = animations; this.currentTrace = currentTrace; this.modelCheckController = modelCheckController; this.gson = new GsonBuilder().setPrettyPrinting().create(); this.defaultLocation = new SimpleObjectProperty<>(this, "defaultLocation", Paths.get(System.getProperty("user.home"))); this.exists = new SimpleBooleanProperty(this, "exists", false); this.exists.bind(Bindings.isNotNull(this)); this.name = new SimpleStringProperty(this, "name", ""); this.description = new SimpleStringProperty(this, "description", ""); this.machines = new SimpleListProperty<>(this, "machines", FXCollections.observableArrayList()); this.preferences = new SimpleListProperty<>(this, "preferences", FXCollections.observableArrayList()); this.runconfigurations = new SimpleListProperty<>(this, "runconfigurations", FXCollections.observableArrayList()); this.location = new SimpleObjectProperty<>(this, "location", null); this.addListener((observable, from, to) -> { if (to == null) { this.name.set(""); this.description.set(""); this.machines.clear(); this.preferences.clear(); this.location.set(null); this.injector.getInstance(ModelcheckingController.class).resetView(); } else { this.name.set(to.getName()); this.description.set(to.getDescription()); this.machines.setAll(to.getMachines()); this.preferences.setAll(to.getPreferences()); this.runconfigurations.setAll(to.getRunconfigurations()); this.location.set(to.getLocation()); } }); } public void addMachine(Machine machine) { List<Machine> machinesList = this.getMachines(); machinesList.add(machine); this.update(new Project(this.getName(), this.getDescription(), machinesList, this.getPreferences(), this.getRunconfigurations(), this.getLocation())); } public void removeMachine(Machine machine) { List<Machine> machinesList = this.getMachines(); machinesList.remove(machine); List<Runconfiguration> runconfigsList = new ArrayList<>(); runconfigsList.addAll(this.getRunconfigurations()); for (Runconfiguration r : this.getRunconfigurations()) { if (r.getMachine().equals(machine.getName())) { runconfigsList.remove(r); } } this.update(new Project(this.getName(), this.getDescription(), machinesList, this.getPreferences(), runconfigsList, this.getLocation())); } public void updateMachine(Machine oldMachine, Machine newMachine) { this.removeMachine(oldMachine); this.addMachine(newMachine); } public void addPreference(Preference preference) { List<Preference> preferencesList = this.getPreferences(); preferencesList.add(preference); this.update(new Project(this.getName(), this.getDescription(), this.getMachines(), preferencesList, this.getRunconfigurations(), this.getLocation())); } public void removePreference(Preference preference) { List<Preference> preferencesList = this.getPreferences(); preferencesList.remove(preference); List<Runconfiguration> runconfigsList = new ArrayList<>(); runconfigsList.addAll(this.getRunconfigurations()); for (Runconfiguration r : this.getRunconfigurations()) { if (r.getPreference().equals(preference.getName())) { runconfigsList.remove(r); } } this.update(new Project(this.getName(), this.getDescription(), this.getMachines(), preferencesList, runconfigsList, this.getLocation())); } public void addRunconfiguration(Runconfiguration runconfiguration) { List<Runconfiguration> runconfigs = this.getRunconfigurations(); runconfigs.add(runconfiguration); this.update(new Project(this.getName(), this.getDescription(), this.getMachines(), this.getPreferences(), runconfigs, this.getLocation())); } public void removeRunconfiguration(Runconfiguration runconfiguration) { List<Runconfiguration> runconfigs = this.getRunconfigurations(); runconfigs.remove(runconfiguration); this.update(new Project(this.getName(), this.getDescription(), this.getMachines(), this.getPreferences(), runconfigs, this.getLocation())); } @Override public void set(Project project) { if (confirmReplacingProject()) { if(currentTrace.exists()) { animations.removeTrace(currentTrace.get()); modelCheckController.resetView(); } super.set(project); } } private void update(Project project) { super.set(project); } public void remove() { super.set(null); } public ReadOnlyBooleanProperty existsProperty() { return this.exists; } public boolean exists() { return this.existsProperty().get(); } public StringProperty nameProperty() { return this.name; } @Override public String getName() { return this.nameProperty().get(); } public StringProperty descriptionProperty() { return this.description; } public String getDescription() { return this.descriptionProperty().get(); } public ReadOnlyListProperty<Machine> machinesProperty() { return this.machines; } public List<Machine> getMachines() { return this.machinesProperty().get(); } public ReadOnlyListProperty<Preference> preferencesProperty() { return this.preferences; } public List<Preference> getPreferences() { return this.preferencesProperty().get(); } public ReadOnlyListProperty<Runconfiguration> runconfigurationsProperty() { return this.runconfigurations; } public List<Runconfiguration> getRunconfigurations() { return this.runconfigurationsProperty().get(); } public ObjectProperty<File> locationProperty() { return this.location; } public File getLocation() { return this.locationProperty().get(); } public ObjectProperty<Path> defaultLocationProperty() { return this.defaultLocation; } public Path getDefaultLocation() { return this.defaultLocationProperty().get(); } public void setDefaultLocation(Path defaultProjectLocation) { this.defaultLocationProperty().set(defaultProjectLocation); } public void save() { File loc = new File(this.getLocation() + File.separator + this.getName() + ".json"); try (final Writer writer = new OutputStreamWriter(new FileOutputStream(loc), PROJECT_CHARSET)) { gson.toJson(this.get(), writer); } catch (FileNotFoundException exc) { LOGGER.warn("Failed to create project data file", exc); } catch (IOException exc) { LOGGER.warn("Failed to save project", exc); } } public void open(File file) { Project project; try (final Reader reader = new InputStreamReader(new FileInputStream(file), PROJECT_CHARSET)) { project = gson.fromJson(reader, Project.class); project.setLocation(file.getParentFile()); project = replaceMissingWithDefaults(project); } catch (FileNotFoundException exc) { LOGGER.warn("Project file not found", exc); return; } catch (IOException exc) { LOGGER.warn("Failed to open project file", exc); return; } this.set(project); } private Project replaceMissingWithDefaults(Project project) { String nameString = (project.getName() == null) ? "" : project.getName(); String descriptionString = (project.getDescription() == null) ? "" : project.getDescription(); List<Machine> machineList = (project.getMachines() == null) ? new ArrayList<>() : project.getMachines(); List<Preference> preferenceList = (project.getPreferences() == null) ? new ArrayList<>() : project.getPreferences(); Set<Runconfiguration> runconfigurationSet = (project.getRunconfigurations() == null) ? new HashSet<>() : project.getRunconfigurations(); return new Project(nameString, descriptionString, machineList, preferenceList, runconfigurationSet, project.getLocation()); } public Machine getMachine(String machine) { for (Machine m : getMachines()) { if (m.getName().equals(machine)) { return m; } } return null; } public Map<String, String> getPreferencAsMap(String preference) { for (Preference p : getPreferences()) { if (p.getName().equals(preference)) { return p.getPreferences(); } } return null; } private boolean confirmReplacingProject() { if (exists()) { final Alert alert = stageManager.makeAlert(Alert.AlertType.CONFIRMATION); alert.setHeaderText("You've already opened a project."); alert.setContentText("Do you want to close the current project?"); Optional<ButtonType> result = alert.showAndWait(); return result.isPresent() && ButtonType.OK.equals(result.get()); } else { return true; } } }
package de.silef.service.file; import de.silef.service.file.hash.FileHash; import de.silef.service.file.index.*; import de.silef.service.file.util.ByteUtil; import org.apache.commons.cli.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Predicate; import java.util.stream.Collectors; public class FileIndexCli { private static final Logger LOG = LoggerFactory.getLogger(FileIndexCli.class); private CommandLine cmd; public FileIndexCli(CommandLine cmd) { this.cmd = cmd; } private void run() throws IOException, java.text.ParseException { Path base = getBase(); Path indexFile = getIndexFile(base); Predicate<Path> pathIndexFilter = p -> true; Predicate<IndexNode> hashNodeFilter = getHashNodeFilter(); final AtomicBoolean done = new AtomicBoolean(false); FileIndex index = readIndexMetaData(base, pathIndexFilter, hashNodeFilter); if (!Files.exists(indexFile)) { addShutdownHook(done, () -> { writeIndex(index, indexFile); return null; }); initializeIndex(index); writeIndex(index, indexFile); done.set(true); System.out.println("File index successfully created"); } else { IndexChange changes = getIndexChanges(base, pathIndexFilter, hashNodeFilter, indexFile, index); if (changes.hasChanges()) { addShutdownHook(done, () -> { writeIndex(index, indexFile); return null; }); updateIndex(index, changes); writeIndex(index, indexFile); done.set(true); System.exit(1); } } } private void addShutdownHook(AtomicBoolean done, Callable<Void> hook) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { if (!done.get()) { System.out.print("Interrupted. Cleaning up... "); hook.call(); System.out.println("Done"); } } catch (Exception e) { LOG.error("Could not execute shutdown hook"); } }; }); } private FileIndex readIndexMetaData(Path base, Predicate<Path> pathIndexFilter, Predicate<IndexNode> hashNodeFilter) throws IOException { LOG.debug("Reading file index data from {}", base.toAbsolutePath()); FileIndex index = new FileIndex(base, pathIndexFilter, hashNodeFilter); LOG.info("Found {} files of {}", index.getTotalFileCount(), ByteUtil.toHumanSize(index.getTotalFileSize())); return index; } private Predicate<IndexNode> getHashNodeFilter() throws java.text.ParseException { if (!cmd.hasOption('M')) { return node -> true; } long maxSize = ByteUtil.toByte(cmd.getOptionValue('M')); if (maxSize == 0) { LOG.info("Disable content integrity verification", ByteUtil.toHumanSize(maxSize), maxSize); return node -> false; } LOG.info("Limit content integrity verification to {} ({} bytes)", ByteUtil.toHumanSize(maxSize), maxSize); return node -> { if (node.getSize() > maxSize) { if (LOG.isDebugEnabled()) { LOG.debug("File exceeds verification size of {}: {} with {}", ByteUtil.toHumanSize(maxSize), node.getRelativePath(), ByteUtil.toHumanSize(node.getSize())); } return false; } return true; }; } private void writeIndex(FileIndex index, Path indexFile) throws IOException { LOG.debug("Writing file index data to {} with {} file of {}", indexFile, index.getTotalFileCount(), ByteUtil.toHumanSize(index.getTotalFileSize())); Path tmp = null; try { tmp = indexFile.getParent().resolve(indexFile.getFileName() + ".tmp"); new IndexNodeWriter().write(index.getRoot(), tmp); Files.move(tmp, indexFile); } catch (IOException e) { if (tmp != null) { Files.delete(tmp); } } LOG.info("Written file index data to {}. The index root hash is {}", indexFile, index.getRoot().getHash()); } private void initializeIndex(FileIndex index) throws IOException { LOG.info("Creating file index. This might take some time!"); index.initializeTreeHash(); LOG.debug("File index created"); } private void updateIndex(FileIndex index, IndexChange changes) throws IOException { LOG.info("Updating file index of {} files with {} by: ", index.getTotalFileCount(), ByteUtil.toHumanSize(index.getTotalFileSize()), changes); index.updateChanges(changes, false); LOG.debug("Updated file index"); } private IndexChange getIndexChanges(Path base, Predicate<Path> pathIndexFilter, Predicate<IndexNode> hashNodeFilter, Path indexFile, FileIndex index) throws IOException { LOG.debug("Reading existing file index from {}", indexFile); IndexNode root = new IndexNodeReader().read(base, indexFile); FileIndex old = new FileIndex(base, root, pathIndexFilter, hashNodeFilter); LOG.debug("Calculating file changes"); IndexChange changes = index.getChanges(old); // Add all empty hashes to the modified change to resume hash calculation Set<IndexNode> emptyHashes = index.getRoot().stream() .filter(n -> n.getMode() == FileMode.FILE) .filter(n -> n.getHash().equals(FileHash.ZERO)) .collect(Collectors.toSet()); LOG.info("Add {} files to resume integrity check", emptyHashes.size()); emptyHashes.addAll(changes.getModified()); IndexChange resumeChange = new IndexChange(changes.getBase(), new HashSet<>(changes.getCreated()), emptyHashes, changes.getRemoved()); if (!cmd.hasOption("q")) { printChange(resumeChange); } return resumeChange; } private Path getIndexFile(Path base) throws IOException { Path indexFile; if (cmd.hasOption("d")) { indexFile = Paths.get(cmd.getOptionValue("i")); } else { String indexName = base.toRealPath().getFileName() + ".index"; indexFile = Paths.get(System.getProperty("user.home")).resolve(".cache/filecache").resolve(indexName); LOG.debug("Use default index file: {}", indexFile); } Files.createDirectories(indexFile.getParent()); return indexFile; } private Path getBase() { if (cmd.getArgs().length > 0) { return Paths.get(cmd.getArgs()[0]); } else { LOG.debug("Use current working directory to index"); return Paths.get("."); } } private void printChange(IndexChange changes) { if (!changes.hasChanges()) { System.out.println("- No changes"); return; } long totalChange = changes.getCreated().size() + changes.getModified().size() + changes.getRemoved().size(); if (totalChange > 256) { System.out.println("Too many changes: " + totalChange + " modifications. Skip printing"); return; } List<String> lines = new LinkedList<>(); lines.addAll(createLines("C ", changes.getCreated())); lines.addAll(createLines("M ", changes.getModified())); lines.addAll(createLines("D ", changes.getRemoved())); lines.stream() .sorted((a, b) -> a.substring(3).compareTo(b.substring(3))) .forEach(System.out::println); } private List<String> createLines(String prefix, Collection<IndexNode> nodes) { return nodes.stream() .map(n -> prefix + n.getRelativePath().toString()) .collect(Collectors.toList()); } private static void printHelp(Options options) { HelpFormatter formatter = new HelpFormatter(); String header = "\nFollowing options are available:"; String footer = "\nPlease consult fileindex.log for detailed program information"; formatter.printHelp("fileindex <options> [path]", header, options, footer); System.exit(0); } private static Options createOptions() { Options options = new Options(); options.addOption("h", false, "Print this help"); options.addOption("i", true, "Index file to store. Default is ~/.cache/filecache/<dirname>.index"); options.addOption("q", false, "Quiet mode"); options.addOption(Option.builder("M") .longOpt("verify-max-size") .hasArg(true) .desc("Limit content integrity verification by file size. Use 0 to disable") .build()); return options; } public static void main(String[] args) { Options options = createOptions(); CommandLineParser parser = new DefaultParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { printHelp(options); } new FileIndexCli(cmd).run(); } catch (IOException | ParseException | java.text.ParseException e) { LOG.error("Failed to run fileindex", e); System.err.println("Failed to run fileindex: " + e.getMessage()); } } }
/* *\ ** SICU Stress Measurement System ** ** Project P04 | C380 Team A ** ** EBME 380: Biomedical Engineering Design Experience ** ** Case Western Reserve University ** ** 2016 Fall Semester ** \* */ package edu.cwru.sicu_sms; import javafx.application.Platform; import java.util.logging.Level; import java.util.logging.Logger; import jssc.SerialPort; import jssc.SerialPortEvent; import jssc.SerialPortException; /** * This class is an abstraction for building sub-controller classes to be most likely used by the main {@link Controller} to manage serial connections and other real-time activities pertaining to biomedical signal processing. * * @since December 3, 2016 * @author Ted Frohlich <ttf10@case.edu> * @author Abby Walker <amw138@case.edu> */ abstract class BiosigController { private SerialPort serialPort; boolean connect(String portName) { boolean success = false; final SerialPort serialPort = new SerialPort(portName); try { serialPort.openPort(); serialPort.setParams( SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); serialPort.setEventsMask(SerialPort.MASK_RXCHAR); serialPort.addEventListener((SerialPortEvent serialPortEvent) -> { if (serialPortEvent.isRXCHAR()) onSerialPortEvent(); }); this.serialPort = serialPort; success = true; } catch (SerialPortException e) { logSerialPortException(e); } return success; } /** * Task to be performed when the serial port detects data bytes in the input buffer. */ void onSerialPortEvent() { try { int byteCount = 1; // TODO: Customize byteCount based on needs in subclasses. byte[] bytes = serialPort.readBytes(byteCount); Platform.runLater(() -> updateSeriesWith(bytes[0])); } catch (SerialPortException e) { logSerialPortException(e); } } /** * Update the chart series with the given value, shifting all preceding data in the negative-time direction by one time step. * * @param newValue the new value to add to the chart series */ void updateSeriesWith(float newValue) { // TODO: 12/4/2016 } /** * Log the serial port exception thrown (and caught) in a quick, proper, and reusable way. * * @param thrown the serial port exception to be logged */ void logSerialPortException(SerialPortException thrown) { Logger.getLogger(getClass().getName()) .log( Level.SEVERE, thrown.getMessage(), thrown ); } }
package edu.emory.cellbio.svg; import ij.IJ; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Iterator; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageOutputStream; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.apache.commons.codec.binary.Base64OutputStream; /** * * @author Benjamin Nanes */ public class EmbedAndCrop { // -- Fields -- private String imgFileType = "png"; private float compQual = 0.8f; // -- Methods -- /** * Run the extension * @param args * <br>- The first argument should be the path of the * source svg file * <br>- The second (optional) command should be the image file type * <br>- The third (optional, but required if a file type is given) * command should be the compression quality. * <br><br>Example: "file.svg" "jpeg" "0.95" or "file.svg" "png" "1" */ public void runInkscapeExtension(String[] args) { File input = null; if(args == null || args.length<1) { System.err.println("Missing command line arguments"); input = openDialog(); } try { if(input == null && args != null) input = new File(args[0]); if(args != null && !(args.length < 3)) { imgFileType = args[1]; try{ compQual = Float.parseFloat(args[2]); } catch(NumberFormatException e){ throw new EmbedAndCropException(e.toString()); } } else getOutputParams(); if(input == null || !input.canRead()) throw new EmbedAndCropException("Can't read temporary input file " + input != null ? input.getPath() : "<null>"); Document dom = readSVG(input); process(dom); SVGToStream(dom, System.out); } catch(Throwable t) { t.printStackTrace(); JOptionPane.showMessageDialog(null, t.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); System.exit(1); } System.exit(0); } // -- Helper methods -- /** Process an SVG DOM */ private void process(Document dom) throws EmbedAndCropException { NodeList images = dom.getElementsByTagName("image"); for(int i=0; i<images.getLength(); i++) { Node img = images.item(i); if(img.getNodeType() == Node.ELEMENT_NODE) { Element clip = getClipPath((Element)img, dom); if(clip != null) { processImg((Element)img, clip); } else processImg((Element)img, null); } } } /** Push XML(SVG) to a stream */ private void SVGToStream(Document dom, OutputStream os) throws EmbedAndCropException { try{ Transformer xmlt = TransformerFactory.newInstance().newTransformer(); xmlt.setOutputProperty(OutputKeys.METHOD, "xml"); xmlt.transform(new DOMSource(dom), new StreamResult(os)); os.close(); } catch(Throwable t) { throw new EmbedAndCropException("XML write error: " + t); } } /** Harvest output parameters */ private void getOutputParams() throws EmbedAndCropException { OutputParamDialog opd = new OutputParamDialog(); opd.showAndWait(); if(!opd.wasOKd()) throw new EmbedAndCropException("Canceled by user"); imgFileType = opd.getImgFileMode(); compQual = opd.getCompressionQuality(); } /** Save an XML(SVG) file */ private void saveAs(Document dom) throws EmbedAndCropException { JFileChooser fd = new JFileChooser(); if(fd.showSaveDialog(null) != JFileChooser.APPROVE_OPTION) return; File f = fd.getSelectedFile(); if(f.exists() && JOptionPane.showConfirmDialog(null, "File exists. OK to overwite?", "", JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION) return; save(dom, f); } /** Save an XML(SVG) file */ private void save(Document dom, File f) throws EmbedAndCropException { try{ Transformer xmlt = TransformerFactory.newInstance().newTransformer(); xmlt.setOutputProperty(OutputKeys.METHOD, "xml"); xmlt.transform(new DOMSource(dom), new StreamResult(f)); } catch(Throwable t) { throw new EmbedAndCropException("XML write error: " + t); } } /** Process an image element */ private void processImg(Element img, Element clip) throws EmbedAndCropException { double[] cf = {0,0,0,0}; if(clip != null) cf = getCropFraction(img, clip); putImgData(img, cf); } /** * Load image data to embed * @param img Image element * @param crop Fraction of image to crop from each edge, {@code {top, bottom, left, right}} */ private void putImgData(Element img, double[] crop) throws EmbedAndCropException { String path = img.getAttribute("xlink:href"); if(path == null || path.equals("")) throw new EmbedAndCropException("No image file listed!"); if(path.startsWith("file: path = path.substring(8); path = path.replace("%20", " "); File imf = new File(path); if(!imf.canRead()) throw new EmbedAndCropException("Can't read file link: " + path); BufferedImage origImg; try{ origImg = IJ.openImage(path).getBufferedImage(); } catch(Throwable t) { throw new EmbedAndCropException("Problem reading image file; " + t); } if(origImg == null) throw new EmbedAndCropException("Couldn't load appropriate plugin for image"); int w = origImg.getWidth(); int h = origImg.getHeight(); int[] icrop = { (int)Math.floor(crop[0]*h), (int)Math.floor(crop[1]*h), (int)Math.floor(crop[2]*w), (int)Math.floor(crop[3]*w) }; for(int i=0; i<4; i++) icrop[i] = Math.max(icrop[i], 0); // Don't crop on outside BufferedImage cropImg = origImg.getSubimage( icrop[2], icrop[0], w - icrop[2] - icrop[3], h - icrop[0] - icrop[1]); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Base64OutputStream out64 = new Base64OutputStream(baos); try{ Iterator<ImageWriter> iws = ImageIO.getImageWritersByFormatName(imgFileType); if(!iws.hasNext()) throw new EmbedAndCropException ("Can't find image writer for " + imgFileType); ImageWriter iw = iws.next(); ImageWriteParam iwp = iw.getDefaultWriteParam(); if(iwp.canWriteCompressed()) { iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(compQual); } ImageOutputStream ios = ImageIO.createImageOutputStream(out64); iw.setOutput(ios); iw.write(cropImg); ios.close(); out64.close(); } catch(Throwable t) { throw new EmbedAndCropException("Problem writing/encoding image data; " + t); } String result = "data:image/" + imgFileType + ";base64," + baos.toString(); double[] acrop = { ((double)icrop[0])/h, ((double)icrop[1])/h, ((double)icrop[2])/w, ((double)icrop[3])/w }; adjustImgPlacement(img, acrop); img.setAttribute("xlink:href", result); } /** * Adjust placement of the image element to account for cropping * * @param img The image element * @param crop Fraction of image <em>actually</em> cropped from * each edge, {@code {top, bottom, left, right}}; * note that this must account for rounding to pixels */ private void adjustImgPlacement(Element img, double[] crop) { double w = new Double(img.getAttribute("width")); double h = new Double(img.getAttribute("height")); double nx = new Double(img.getAttribute("x")) + crop[2] * w; double ny = new Double(img.getAttribute("y")) + crop[0] * h; double nw = w * (1 - crop[2] - crop[3]); double nh = h * (1 - crop[0] - crop[1]); img.setAttribute("x", String.valueOf(nx)); img.setAttribute("y", String.valueOf(ny)); img.setAttribute("width", String.valueOf(nw)); img.setAttribute("height", String.valueOf(nh)); } /** * Get the fraction of image that should be cropped off each side * @param img The image element * @param clip The clip-path element * @return Fraction of image to crop from each edge, {@code {top, bottom, left, right}} */ private double[] getCropFraction(Element img, Element clip) throws EmbedAndCropException { double[] imgBounds = getRectBounds(img); System.err.println("Image bounds: (" + imgBounds[0] + "," + imgBounds[2] + "); (" + imgBounds[1] + "," + imgBounds[3] + ")"); double[][] clipPoints = getClipPoints(clip); double[] cf = {1,1,1,1}; if(clipPoints == null || clipPoints.length == 0) for(int i=0; i<4; i++) cf[i] = 0; for(int i=0; i<clipPoints.length; i++) { double[] pf = scaleToRectFraction( distanceFromRect(clipPoints[i], imgBounds), imgBounds); for(int j=0; j<4; j++) cf[j] = Math.min(cf[j], pf[j]); } System.err.println("Top clip, " + cf[0] + "; Bottom clip, " + cf[1] + "; Left clip, " + cf[2] + "; Right clip, " + cf[3]); return cf; } /** * Is a point within a rectangle (edges excluded)? * * @param p {@code {x,y}} * @param r Bounding points of the rectangle, {@code {x0, x1, y0, y1}} */ private boolean isPointInRect(double[] p, double[] r) { return ((p[0] < r[0] && p[0] > r[1]) || (p[0] < r[1] && p[0] > r[0])) && ((p[1] < r[2] && p[1] > r[3]) || (p[1] < r[3] && p[1] > r[2])); } /** * How far is a point from each edge of a rectangle? * * @param p {@code {x,y}} * @param r Bounding points of the rectangle, {@code {x0, x1, y0, y1}} * @return Distance from each edge (negative if point is on exterior side of the edge), * {@code {top, bottom, left, right}} */ private double[] distanceFromRect(double[] p, double[] r) { double top = Math.min(r[2], r[3]); double bot = Math.max(r[2], r[3]); double rit = Math.max(r[0], r[1]); double lef = Math.min(r[0], r[1]); double[] result = { p[1] - top, bot - p[1], p[0] - lef, rit - p[0] }; return result; } /** * Scale a set of distances from rectangle edges by the width and height of the rectangle. * * @param d Absolute distances, {@code {top, bottom, left, right}} * @param r Bounding points of the rectangle, {@code {x0, x1, y0, y1}} * @return Relative distances, {@code {top/height, bottom/height, left/width, right/width}} */ private double[] scaleToRectFraction(double[] d, double[] r) { d[0] = d[0] / Math.abs(r[2] - r[3]); d[1] = d[1] / Math.abs(r[2] - r[3]); d[2] = d[2] / Math.abs(r[0] - r[1]); d[3] = d[3] / Math.abs(r[0] - r[1]); return d; } /** * Get the minimum distance between a pont and a line defined by two other points * * @param lp0 1st point on the line, {@code {x,y}} * @param lp1 2nd point on the line, {@code {x,y}} * @param x How far is <em>this</em> point from the line, {@code {x,y}} * @return Distance of point {@code x} from the line */ private double distanceFromLine(double[] lp0, double[] lp1, double[] x) { double[] lpd = { lp1[0] - lp0[0], lp1[1] - lp0[1] }; double tMin = ( x[0]*lpd[0] + x[1]*lpd[1] - lp0[0]*lpd[0] - lp0[1]*lpd[1]) / (Math.pow(lpd[0], 2) + Math.pow(lpd[1], 2)); System.err.println("Min t: " + tMin); double d2 = Math.pow(lp0[0] + tMin*(lp1[0] - lp0[0]) - x[0], 2) + Math.pow(lp0[1] + tMin*(lp1[1] - lp0[1]) - x[1], 2); System.err.println("r^2 = " + d2); return Math.sqrt(d2); } /** * Extract the coordinates of a clip path * @return {@code double[][] coordinates[point]{x,y}} */ private double[][] getClipPoints(Element clip) throws EmbedAndCropException { ArrayList<double[][]> pA = new ArrayList<double[][]>(); NodeList children = clip.getChildNodes(); for(int i=0; i<children.getLength(); i++) { if(children.item(i).getNodeType() == Node.ELEMENT_NODE) { Element child = (Element)children.item(i); String baseTransform = child.getAttribute("transform"); double[][] p = null; if(child.getNodeName().equals("rect")) p = rectBoundsToPointList(getRectBounds(child)); else throw new EmbedAndCropException( "Can't get points from element type " + child.getNodeName()); if(p != null) { if(baseTransform != null && !baseTransform.equals("")) { for(int j=0; j<4; j++) p[j] = parseTransform(p[j], baseTransform); } pA.add(p); } } } int n = 0; for(int i=0; i<pA.size(); i++) n += pA.get(i).length; double[][] points = new double[n][2]; n = 0; for(int i=0; i<pA.size(); i++) { double[][] p = pA.get(i); System.arraycopy(p, 0, points, 0, p.length); n += p.length; } return points; } /** * Get the points along a path ////Not working * @return {@code double[point][{x,y}]} */ private double[][] getPathPointList(Element path) throws EmbedAndCropException { if(path == null) throw new EmbedAndCropException("Null path"); String d = path.getAttribute("d"); if(d == null || d.equals("")) throw new EmbedAndCropException("Empty path"); String[] dd = d.split("[^\\d\\.]"); int n = 0; for(int i=0; i<dd.length; i++) if(!dd[i].equals("")) n++; double[][] p = new double[n/2][2]; return p; } /** * Get the boundaries of a rect element (or similar) without transformation * * @return An array: {@code {x0, x1, y0, y1}} */ private double[] getRectBounds(Element e) { double[] p0 = {new Double(e.getAttribute("x")), new Double(e.getAttribute("y"))}; double[] p1 = {p0[0] + new Double(e.getAttribute("width")), p0[1] + new Double(e.getAttribute("height"))}; double[] r = {p0[0], p1[0], p0[1], p1[1]}; return r; } /** * Convert rect boundary points to a list of corner points * @param b {@code {x0, x1, y0, y1}}, as returned by {@link #getRectBounds} * @return {@code double[point][{x,y}]} */ private double[][] rectBoundsToPointList(double[] b) { double[][] p = new double[4][2]; p[0][0] = b[0]; p[0][1] = b[2]; p[1][0] = b[0]; p[1][1] = b[3]; p[2][0] = b[1]; p[2][1] = b[2]; p[3][0] = b[1]; p[3][1] = b[3]; return p; } /** * Transform a point ({@code {x,y}}) to document space * by recursively looking for transform attributes in * the given nodes and all parent nodes. * @param point * @param n * @return {@code {x,y}} */ private double[] transformToDocumentSpace(double[] point, Node n) { if(n.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element)n; String transform = e.getAttribute("transform"); if(transform != null && !transform.equals("")) point = parseTransform(point, transform); } Node parent = n.getParentNode(); if(parent != null) point = transformToDocumentSpace(point, parent); return point; } /** * Transform a coordinate pair using a transform attribute * @param point {@code {x,y}} * @param transform The transform atribute value * @return {@code {x,y}} */ private double[] parseTransform(double[] point, String transform) { System.err.println("Transforming (" + point[0] + "," + point[1] + ") using attribute: " + transform); if(transform == null || transform.equals("")) return point; transform = transform.trim(); String[] tList = transform.split("\\s"); for(int i=0; i<tList.length; i++) { String t = tList[i].trim(); if(t.startsWith("matrix(")) { t = t.substring(t.indexOf("(") + 1, t.lastIndexOf(")")); String[] u = t.split(","); double[] m = new double[6]; m[0] = new Double(u[0]); m[1] = new Double(u[2]); m[2] = new Double(u[4]); m[3] = new Double(u[1]); m[4] = new Double(u[3]); m[5] = new Double(u[5]); point = transformMatrix(point, m); } else if(t.startsWith("translate(")) { t = t.substring(t.indexOf("(") + 1, t.lastIndexOf(")")); String[] u = t.split(","); double tx = new Double(u[0]); double ty; if(u.length > 1) ty = new Double(u[1]); else ty = 0; point = transformTranslate(point, tx, ty); } else if(t.startsWith("scale(")) { t = t.substring(t.indexOf("(") + 1, t.lastIndexOf(")")); String[] u = t.split(","); double sx = new Double(u[0]); double sy; if(u.length > 1) sy = new Double(u[1]); else sy = 1; point = transformScale(point, sx, sy); } else if(t.startsWith("rotate(")) { t = t.substring(t.indexOf("(") + 1, t.lastIndexOf(")")); String[] u = t.split(","); double a = new Double(u[0]); if(u.length == 1) point = transformRotate(point, a); else if(u.length == 3) { double cx = new Double(u[1]); double cy = new Double(u[2]); point = transformRotate(point, a, cx, cy); } } else if(t.startsWith("skewX(")) { t = t.substring(t.indexOf("(") + 1, t.lastIndexOf(")")); point = transformSkewX(point, new Double(t)); } else if(t.startsWith("skewY(")) { t = t.substring(t.indexOf("(") + 1, t.lastIndexOf(")")); point = transformSkewY(point, new Double(t)); } } System.err.println("Result: (" + point[0] + "," + point[1] + ")"); return point; } /** * Apply a matrix transformation. * <p><b>WARNING</b> - <em>Matrix specification (by row) * differs from standard SVG order (by column)</em> * @param point {@code {x,y}} * @param matrix {@code {a,c,e,b,d,f}} * @return {@code {x,y}} */ private double[] transformMatrix(double[] point, double[] matrix) { if(point == null || matrix == null || point.length != 2 || matrix.length != 6) throw new IllegalArgumentException("Malformed matrices - point: " + point +"; matrix: " + matrix); double[] r = new double[2]; r[0] = point[0]*matrix[0] + point[1]*matrix[1] + 1*matrix[2]; r[1] = point[0]*matrix[3] + point[1]*matrix[4] + 1*matrix[5]; return r; } /** * Apply a translation * @param point {@code {x,y}} * @param tx Delta x * @param ty Delta y * @return {@code {x,y}} */ private double[] transformTranslate(double[] point, double tx, double ty) { double[] matrix = {1,0,tx,0,1,ty}; return transformMatrix(point, matrix); } /** * Apply a scale * @param point {@code {x,y}} * @param sx x scale factor * @param sy y scale factor * @return {@code {x,y}} */ private double[] transformScale(double[] point, double sx, double sy) { double[] matrix = {sx,0,0,0,sy,0}; return transformMatrix(point, matrix); } /** * Apply a rotation about the origin * @param point {@code {x,y}} * @param a Angle, in degrees * @return {@code {x,y}} */ private double[] transformRotate(double[] point, double a) { double[] matrix = {Math.cos(a), -Math.sin(a), 0, Math.sin(a), Math.cos(a), 0}; return transformMatrix(point, matrix); } /** * Apply a rotation about center point {@code {cx,cy}} * @param point {@code {x,y}} * @param a Angle, in degrees * @return {@code {x,y}} */ private double[] transformRotate(double[] point, double a, double cx, double cy) { return transformTranslate(transformRotate(transformTranslate(point, cx, cy), a), -cx, -cy); } /** * Skew along the x-axis * @param point {@code {x,y}} * @param a Angle, in degrees * @return {@code {x,y}} */ private double[] transformSkewX(double[] point, double a) { double[] matrix = {1, Math.tan(a), 0, 0,1,0}; return transformMatrix(point, matrix); } /** * Skew along the y-axis * @param point {@code {x,y}} * @param a Angle, in degrees * @return {@code {x,y}} */ private double[] transformSkewY(double[] point, double a) { double[] matrix = {1,0,0, Math.tan(a),1,0}; return transformMatrix(point, matrix); } /** Get the clipping path of an image */ private Element getClipPath(Element img, Document dom) { String clip = img.getAttribute("clip-path"); if(clip == null || clip.equals("")) return null; int a = clip.indexOf(" int b = clip.indexOf(")"); if(a >= 0 && b >= 0) clip = clip.substring(a+1, b); System.err.println("Image " + img.getAttribute("xlink:href") + " has clip-path " + clip); NodeList clips = dom.getElementsByTagName("clipPath"); Element clipElement = null; for(int i=0; i<clips.getLength(); i++) if(((Element)clips.item(i)).getAttribute("id").equals(clip)) { clipElement = (Element)clips.item(i); break; } return clipElement; } /** Get a file using a file open dialog */ private File openDialog() { JFileChooser fc = new JFileChooser(); if(fc.showOpenDialog(null) != JFileChooser.APPROVE_OPTION) return null; return fc.getSelectedFile(); } /** Read an XML file and return a DOM */ private Document readSVG(File f) throws EmbedAndCropException { Document svg; DocumentBuilder db; try { db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch(ParserConfigurationException e) { throw new EmbedAndCropException("Can't deal with XML: " + e.getMessage()); } try{ svg = db.parse(f); } catch(Throwable t) { throw new EmbedAndCropException("Can't read file: " + t.getMessage()); } return svg; } // -- Tests -- public void test() throws EmbedAndCropException { Document dom = readSVG(openDialog()); getOutputParams(); process(dom); saveAs(dom); } public static void main( String[] args ) { if(args != null) for(int i=0; i<args.length; i++) System.err.println(args[i]); System.out.println( "Hello World!" ); EmbedAndCrop ec = new EmbedAndCrop(); try{ ec.test(); } catch(Throwable t) { t.printStackTrace(); JOptionPane.showMessageDialog(null, t.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); System.exit(1); } System.exit(0); } }
package edu.hm.cs.vss.local; import edu.hm.cs.vss.*; import edu.hm.cs.vss.log.DummyLogger; import edu.hm.cs.vss.log.Logger; import edu.hm.cs.vss.remote.RemoteTable; import edu.hm.cs.vss.remote.RmiTable; import java.io.IOException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Stream; public class LocalTablePool implements Table { private final List<Table> tables = Collections.synchronizedList(new LinkedList<>()); private final List<Table> backedUpTables = Collections.synchronizedList(new LinkedList<>()); private final List<Philosopher> localPhilosophers = Collections.synchronizedList(new ArrayList<>()); private final Table localTable; private final TableMaster tableMaster; private final BackupRestorer tableBrokeUpObserver; private final Logger logger; private final AtomicBoolean backupLock = new AtomicBoolean(); public LocalTablePool() throws IOException { this(new DummyLogger()); } public LocalTablePool(final Logger logger) throws IOException { this.localTable = new LocalTable(logger); this.tableMaster = new DistributedTableMaster(); this.tableBrokeUpObserver = new BackupRestorer(); this.logger = logger; final Registry registry = LocateRegistry.createRegistry(NETWORK_PORT); registry.rebind(Table.class.getSimpleName(), UnicastRemoteObject.exportObject(new DistributedTableRmi(), NETWORK_PORT)); tables.add(localTable); (new Thread() { public void run() { while (true) { try { if (!backupLock.get()) { tables.stream().skip(1).map(table -> (RemoteTable) table).forEach(table -> { try { table.backupFinished(); } catch (RemoteException e) { table.handleRemoteTableDisconnected(e); throw new RuntimeException(e); } }); } Thread.sleep(1000); } catch (Exception e) { // ignore exception } } } }).start(); } @Override public void connectToTable(final String tableHost) { logger.log("Try to connect to remote table " + tableHost + "..."); if (tables.parallelStream().noneMatch(table -> table.getName().equals(tableHost))) { try { final RemoteTable table = new RemoteTable(tableHost, logger); table.addObserver(tableBrokeUpObserver); // Observe table for disconnection tables.add(table); // Removes backed up table on reconnection for (Iterator<Table> iter = backedUpTables.listIterator(); iter.hasNext(); ) { RemoteTable t = (RemoteTable) iter.next(); if (t.getHost().equals(tableHost)) { iter.remove(); } } // Send all available tables to the new table tables.stream() .map(Table::getName) .filter(name -> !name.equals(tableHost)) // Skip out the previous added table .forEach(table::connectToTable); // Backup the current status of this table and send it to the new table getLocalTable().getChairs().forEach(table::addChair); getPhilosophers().forEach(table::addPhilosopher); // Table is ready to use logger.log("Connected to remote table " + tableHost + "!"); } catch (Exception e) { logger.log(e.getMessage()); e.printStackTrace(); } } else { logger.log("Already connected to " + tableHost + "!"); } } @Override public void disconnectFromTable(final String tableHost) { logger.log("Try to disconnect from remote table " + tableHost + "..."); if (tables.parallelStream().noneMatch(table -> table.getName().equals(tableHost))) { tables.parallelStream() .skip(1) // Skip the current table -> it's already execution this statement .peek(table -> table.disconnectFromTable(tableHost)) .filter(table -> table.getName().equals(tableHost)) .findAny() .ifPresent(host -> { tables.remove(host); logger.log("Disconnected from remote table " + tableHost + "!"); }); } else { logger.log("Already disconnected from " + tableHost + "!"); } } @Override public Stream<Table> getTables() { return tables.stream(); } @Override public void addPhilosopher(final Philosopher philosopher) { localPhilosophers.add(philosopher); philosopher.start(); philosopher.addOnStandUpListener(tmp -> getTables().parallel() .skip(1) .map(table -> (Philosopher.OnStandUpListener) table) .forEach(listener -> listener.onStandUp(philosopher))); // Inform other tables getTables().parallel() .skip(1) .forEach(table -> table.addPhilosopher(philosopher)); } @Override public void removePhilosopher(Philosopher philosopher) { philosopher.interrupt(); localPhilosophers.remove(philosopher); // Inform other tables getTables().parallel() .skip(1) .forEach(table -> table.removePhilosopher(philosopher)); } @Override public Stream<Philosopher> getPhilosophers() { return localPhilosophers.stream(); } @Override public void addChair(Chair chair) { getLocalTable().addChair(chair); // Inform other tables getTables().parallel() .skip(1) .forEach(table -> table.addChair(chair)); } @Override public void removeChair(Chair chair) { getLocalTable().removeChair(chair); // Inform other tables getTables().parallel() .skip(1) .forEach(table -> table.removeChair(chair)); } @Override public Stream<Chair> getChairs() { return tables.stream().flatMap(Table::getChairs); } @Override public TableMaster getTableMaster() { return tableMaster; } @Override public void setTableMaster(TableMaster tableMaster) { getLocalTable().setTableMaster(tableMaster); } @Override public BackupService getBackupService() { throw new UnsupportedOperationException(); } private Table getLocalTable() { return localTable; } private final class DistributedTableRmi implements RmiTable { public void addTable(final String host) throws RemoteException { connectToTable(host); } public void removeTable(final String host) throws RemoteException { disconnectFromTable(host); } public void addPhilosopher(final String host, final String name, final boolean hungry, final int takenMeals) throws RemoteException { getTables().parallel() .skip(1) .filter(table -> table.getName().equals(host)) .findAny() .ifPresent(table -> table.getBackupService().addPhilosopher(LocalTablePool.this, name, hungry, takenMeals)); } public void removePhilosopher(final String host, final String name) throws RemoteException { getTables().parallel() .skip(1) .filter(table -> table.getName().equals(host)) .findAny() .ifPresent(table -> table.getBackupService().removePhilosopher(name)); } @Override public void onStandUp(String host, String philosopherName) throws RemoteException { getTables().parallel() .skip(1) .filter(table -> table.getName().equals(host)) .findAny() .ifPresent(table -> table.getBackupService().onPhilosopherStandUp(philosopherName)); } public void addChair(final String host, final String name) throws RemoteException { getTables().parallel() .skip(1) .filter(table -> table.getName().equals(host)) .findAny() .ifPresent(table -> table.getBackupService().addChair(name)); } public void removeChair(final String host, final String name) throws RemoteException { getTables().parallel() .skip(1) .filter(table -> table.getName().equals(host)) .findAny() .ifPresent(table -> table.getBackupService().removeChair(name)); } @Override public boolean blockChairIfAvailable(String name) throws RemoteException { return getLocalTable().getChairs().parallel() .filter(chair -> chair.toString().equals(name)) .findAny() .flatMap(chair -> { try { return chair.blockIfAvailable(); } catch (InterruptedException e) { return Optional.empty(); } }) .isPresent(); } @Override public void unblockChair(String name) throws RemoteException { getLocalTable().getChairs().parallel() .filter(chair -> chair.toString().equals(name)) .findAny() .ifPresent(Chair::unblock); } @Override public boolean blockForkIfAvailable(String name) throws RemoteException { return getLocalTable().getChairs().parallel() .map(Chair::getFork) .filter(fork -> fork.toString().equals(name)) .findAny() .flatMap(Fork::blockIfAvailable) .isPresent(); } @Override public void unblockFork(String name) throws RemoteException { getLocalTable().getChairs().parallel() .map(Chair::getFork) .filter(fork -> fork.toString().equals(name)) .findAny() .ifPresent(Fork::unblock); } @Override public int getChairWaitingPhilosophers(String name) throws RemoteException { return getLocalTable().getChairs().parallel() .filter(chair -> chair.toString().equals(name)) .findAny() .map(Chair::getWaitingPhilosopherCount) .orElse(0); } @Override public boolean backupFinished() throws RemoteException { return !backupLock.get(); } } private final class DistributedTableMaster extends LocalTableMaster { @Override public void register(Philosopher philosopher) { getLocalTable().getTableMaster().register(philosopher); } @Override public void unregister(Philosopher philosopher) { getLocalTable().getTableMaster().unregister(philosopher); } @Override public void onStandUp(Philosopher philosopher) { super.onStandUp(philosopher); // Inform all other tables that this philosopher stands up getTables().skip(1) .map(table -> (Philosopher.OnStandUpListener) table) .forEach(listener -> listener.onStandUp(philosopher)); } @Override public boolean isAllowedToTakeSeat(Integer mealCount) { return getTables() .filter(table -> table.getPhilosophers().count() > 0) .map(Table::getTableMaster) .allMatch(master -> master.isAllowedToTakeSeat(mealCount)); } } private final class BackupRestorer extends Thread implements Observer { @Override public void run() { super.run(); } @Override public void update(Observable observable, Object object) { // Only allow one thread to work here if (!backupLock.compareAndSet(false, true)) { return; } synchronized (tables) { final Table table = (Table) object; // This table as been disconnected! logger.log("Unreachable table " + table.getName() + " detected..."); if (backedUpTables.stream().anyMatch(t -> table.getName().equals(t.getName()))) { logger.log("table " + table.getName() + " already backed up, exiting"); return; } logger.log("suspending all local philosophers"); getPhilosophers().forEach(Philosopher::putToSleep); // There are enough tables to even consider that we are not responsible if (tables.size() > 2 && !tables.get(1).getName().equals(table.getName())) { // We are NOT on the left side of the dead table logger.log(table.getName() + " is not on the right of our table, yeah"); RemoteTable restoringTableTemp = (RemoteTable) tables.get(tables.indexOf(table) - 1); (new Thread() { public void run() { // TODO: Set lock in restoringTable try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } try { while (!restoringTableTemp.backupFinished()) { try { Thread.sleep(1000); } catch (InterruptedException e) { // ignore exception } } } catch (RemoteException e) { restoringTableTemp.handleRemoteTableDisconnected(e); } backupLock.set(false); getPhilosophers().forEach(Philosopher::wakeUp); } }).start(); return; } // "else" - either we are the only table left, or we are responsible for backing up final BackupService tableBackupService = table.getBackupService(); logger.log("Chair(s):"); tableBackupService.getChairs().forEach(tmp -> logger.log("\t- " + tmp.toString())); logger.log("Philosopher(s):"); tableBackupService.getPhilosophers().map(Philosopher::getName).map(name -> "\t- " + name).forEach(logger::log); tables.remove(table); // Remove the disconnected table logger.log("Try to restore unreachable table " + table.getName() + "..."); tableBackupService.restoreTo(LocalTablePool.this); logger.log("Restored unreachable table " + table.getName() + "!"); backedUpTables.add(table); getPhilosophers().forEach(Philosopher::wakeUp); backupLock.set(false); } } } }
package edu.uw.zookeeper.util; import com.google.common.base.Objects; /** * Helper class for implementing a two-element tuple. * * @param <U> * @param <V> */ public abstract class AbstractPair<U,V> { protected final U first; protected final V second; protected AbstractPair(U first, V second) { this.first = first; this.second = second; } @Override public String toString() { return String.format("(%s, %s)", first, second); } @Override public int hashCode() { return Objects.hashCode(first, second); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } AbstractPair<?,?> other = (AbstractPair<?,?>) obj; return Objects.equal(first, other.first) && Objects.equal(second, other.second); } }
package hudson.plugins.tasks; import hudson.FilePath; import hudson.maven.MavenBuildProxy; import hudson.maven.MojoInfo; import hudson.maven.MavenBuild; import hudson.maven.MavenModule; import hudson.model.Action; import hudson.plugins.analysis.core.BuildResult; import hudson.plugins.analysis.core.HealthAwareMavenReporter; import hudson.plugins.analysis.core.ParserResult; import hudson.plugins.analysis.util.PluginLogger; import hudson.plugins.tasks.parser.TasksParserResult; import hudson.plugins.tasks.parser.WorkspaceScanner; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.maven.model.Resource; import org.apache.maven.project.MavenProject; import org.kohsuke.stapler.DataBoundConstructor; /** * Publishes the results of the task scanner (maven 2 project type). * * @author Ulli Hafner */ // CHECKSTYLE:COUPLING-OFF public class TasksReporter extends HealthAwareMavenReporter { /** Unique identifier of this class. */ private static final long serialVersionUID = -4159947472293502606L; /** Default files pattern. */ private static final String DEFAULT_PATTERN = "**/*.java"; /** Ant file-set pattern of files to scan for open tasks in. */ private final String pattern; /** Ant file-set pattern of files to exclude from scan. */ private final String excludePattern; /** Tag identifiers indicating high priority. */ private final String high; /** Tag identifiers indicating normal priority. */ private final String normal; /** Tag identifiers indicating low priority. */ private final String low; /** Tag identifiers indicating case sensitivity. */ private final boolean ignoreCase; /** * Creates a new instance of <code>TasksReporter</code>. * * @param pattern * Ant file-set pattern of files to scan for open tasks in * @param excludePattern * Ant file-set pattern of files to exclude from scan * @param threshold * Annotation threshold to be reached if a build should be considered as * unstable. * @param newThreshold * New annotations threshold to be reached if a build should be * considered as unstable. * @param failureThreshold * Annotation threshold to be reached if a build should be considered as * failure. * @param newFailureThreshold * New annotations threshold to be reached if a build should be * considered as failure. * @param healthy * Report health as 100% when the number of open tasks is less * than this value * @param unHealthy * Report health as 0% when the number of open tasks is greater * than this value * @param thresholdLimit * determines which warning priorities should be considered when * evaluating the build stability and health * @param high * tag identifiers indicating high priority * @param normal * tag identifiers indicating normal priority * @param low * tag identifiers indicating low priority * @param ignoreCase * if case should be ignored during matching * @param canRunOnFailed * determines whether the plug-in can run for failed builds, too */ // CHECKSTYLE:OFF @SuppressWarnings("PMD.ExcessiveParameterList") @DataBoundConstructor public TasksReporter(final String pattern, final String excludePattern, final String threshold, final String newThreshold, final String failureThreshold, final String newFailureThreshold, final String healthy, final String unHealthy, final String thresholdLimit, final String high, final String normal, final String low, final boolean ignoreCase, final boolean canRunOnFailed) { super(threshold, newThreshold, failureThreshold, newFailureThreshold, healthy, unHealthy, thresholdLimit, canRunOnFailed, "TASKS"); this.pattern = pattern; this.excludePattern = excludePattern; this.high = high; this.normal = normal; this.low = low; this.ignoreCase = ignoreCase; } // CHECKSTYLE:ON /** * Returns the Ant file-set pattern to the workspace files. * * @return ant file-set pattern to the workspace files. */ public String getPattern() { return pattern; } /** * Returns the Ant file-set pattern of files to exclude from work. * * @return Ant file-set pattern of files to exclude from work. */ public String getExcludePattern() { return excludePattern; } /** * Returns the high priority task identifiers. * * @return the high priority task identifiers */ public String getHigh() { return high; } /** * Returns the normal priority task identifiers. * * @return the normal priority task identifiers */ public String getNormal() { return normal; } /** * Returns the low priority task identifiers. * * @return the low priority task identifiers */ public String getLow() { return low; } /** * Returns whether case should be ignored during the scanning. * * @return <code>true</code> if case should be ignored during the scanning */ public boolean getIgnoreCase() { return ignoreCase; } /** {@inheritDoc} */ @Override protected boolean acceptGoal(final String goal) { return true; } /** {@inheritDoc} */ @SuppressWarnings("PMD.AvoidFinalLocalVariable") @Override public TasksParserResult perform(final MavenBuildProxy build, final MavenProject pom, final MojoInfo mojo, final PluginLogger logger) throws InterruptedException, IOException { List<String> foldersToScan = new ArrayList<String>(pom.getCompileSourceRoots()); foldersToScan.addAll(pom.getTestCompileSourceRoots()); List<Resource> resources = pom.getResources(); for (Resource resource : resources) { foldersToScan.add(resource.getDirectory()); } resources = pom.getTestResources(); for (Resource resource : resources) { foldersToScan.add(resource.getDirectory()); } FilePath basedir = new FilePath(pom.getBasedir()); final TasksParserResult project = new TasksParserResult(); for (String sourcePath : foldersToScan) { if (StringUtils.isEmpty(sourcePath)) { continue; } FilePath filePath = new FilePath(basedir, sourcePath); if (filePath.exists()) { logger.log(String.format("Scanning folder '%s' for tasks ... ", sourcePath)); WorkspaceScanner workspaceScanner = new WorkspaceScanner(StringUtils.defaultIfEmpty(pattern, DEFAULT_PATTERN), excludePattern, getDefaultEncoding(), high, normal, low, ignoreCase, pom.getName()); workspaceScanner.setPrefix(sourcePath); TasksParserResult subProject = filePath.act(workspaceScanner); project.addAnnotations(subProject.getAnnotations()); project.addModule(pom.getName()); project.addScannedFiles(subProject.getNumberOfScannedFiles()); logger.log(String.format("Found %d.", subProject.getNumberOfAnnotations())); } else { logger.log(String.format("Skipping non-existent folder '%s'...", sourcePath)); } } return project; } /** {@inheritDoc} */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("BC") @Override protected BuildResult persistResult(final ParserResult project, final MavenBuild build) { TasksResult result = new TasksResult(build, getDefaultEncoding(), (TasksParserResult)project, high, normal, low); build.getActions().add(new MavenTasksResultAction(build, this, getDefaultEncoding(), high, normal, low, result)); build.registerAsProjectAction(TasksReporter.this); return result; } /** {@inheritDoc} */ @Override public List<TasksProjectAction> getProjectActions(final MavenModule module) { return Collections.singletonList(new TasksProjectAction(module)); } /** {@inheritDoc} */ @Override protected Class<? extends Action> getResultActionClass() { return MavenTasksResultAction.class; } // Backward compatibility. Do not remove. // CHECKSTYLE:OFF @edu.umd.cs.findbugs.annotations.SuppressWarnings("") @SuppressWarnings({"all", "PMD"}) @Deprecated private transient boolean isThresholdEnabled; @edu.umd.cs.findbugs.annotations.SuppressWarnings("") @SuppressWarnings({"all", "PMD"}) @Deprecated private transient boolean isHealthyReportEnabled; @edu.umd.cs.findbugs.annotations.SuppressWarnings("") @SuppressWarnings({"all", "PMD"}) @Deprecated private transient int healthyTasks; @edu.umd.cs.findbugs.annotations.SuppressWarnings("") @SuppressWarnings({"all", "PMD"}) @Deprecated private transient int unHealthyTasks; @edu.umd.cs.findbugs.annotations.SuppressWarnings("") @SuppressWarnings({"all", "PMD"}) @Deprecated private transient int minimumTasks; @edu.umd.cs.findbugs.annotations.SuppressWarnings("") @SuppressWarnings({"all", "PMD"}) @Deprecated private transient String height; }
package info.faceland.strife.util; import static info.faceland.strife.attributes.StrifeAttribute.*; import static org.bukkit.potion.PotionEffectType.FAST_DIGGING; import info.faceland.strife.StrifePlugin; import info.faceland.strife.attributes.StrifeAttribute; import info.faceland.strife.data.AttributedEntity; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class StatUtil { private static final double BASE_EVASION_MULT = 0.8D; private static final double EVASION_ACCURACY_MULT = 0.6D; public static double getRegen(AttributedEntity ae) { return ae.getAttribute(REGENERATION) * (1 + ae.getAttribute(REGEN_MULT) / 100); } public static double getHealth(AttributedEntity ae) { return ae.getAttribute(HEALTH) * (1 + ae.getAttribute(HEALTH_MULT) / 100); } public static double getBarrier(AttributedEntity ae) { return ae.getAttribute(BARRIER); } public static double getBarrierPerSecond(AttributedEntity ae) { return (4 + (ae.getAttribute(BARRIER) * 0.08)) * (1 + (ae.getAttribute(BARRIER_SPEED) / 100)); } public static double getDamageMult(AttributedEntity ae) { return 1 + ae.getAttribute(DAMAGE_MULT) / 100; } public static double getMeleeDamage(AttributedEntity ae) { return ae.getAttribute(MELEE_DAMAGE) * (1 + ae.getAttribute(MELEE_MULT) / 100); } public static double getRangedDamage(AttributedEntity ae) { return ae.getAttribute(RANGED_DAMAGE) * (1 + ae.getAttribute(RANGED_MULT) / 100); } public static double getMagicDamage(AttributedEntity ae) { return ae.getAttribute(MAGIC_DAMAGE) * (1 + ae.getAttribute(MAGIC_MULT) / 100); } public static double getBaseMeleeDamage(AttributedEntity attacker, AttributedEntity defender) { double rawDamage = getMeleeDamage(attacker); return rawDamage * getArmorMult(attacker, defender); } public static double getBaseRangedDamage(AttributedEntity attacker, AttributedEntity defender) { double rawDamage = getRangedDamage(attacker); return rawDamage * getArmorMult(attacker, defender); } public static double getBaseMagicDamage(AttributedEntity attacker, AttributedEntity defender) { double rawDamage = getMagicDamage(attacker); return rawDamage * getWardingMult(attacker, defender); } public static double getBaseExplosionDamage(AttributedEntity attacker, AttributedEntity defender) { double rawDamage = getMagicDamage(attacker); return rawDamage * getArmorMult(attacker, defender); } public static double getAttackTime(AttributedEntity ae) { double attackTime = 2; double attackBonus = ae.getAttribute(StrifeAttribute.ATTACK_SPEED); if (itemCanUseRage(ae.getEntity().getEquipment().getItemInMainHand())) { attackBonus += StrifePlugin.getInstance().getRageManager().getRage(ae.getEntity()); } if (ae.getEntity().hasPotionEffect(FAST_DIGGING)) { attackBonus += 0.15 * (1 + ae.getEntity().getPotionEffect(FAST_DIGGING).getAmplifier()); } if (attackBonus > 0) { attackTime /= 1 + attackBonus / 100; } else { attackTime *= 1 + Math.abs(attackBonus / 100); } return attackTime; } public static double getOverchargeMultiplier(AttributedEntity ae) { return 1 + (ae.getAttribute(OVERCHARGE) / 100); } public static double getCriticalMultiplier(AttributedEntity ae) { return 1 + (ae.getAttribute(CRITICAL_DAMAGE) / 100); } public static double getArmor(AttributedEntity ae) { return ae.getAttribute(ARMOR) * (1 + ae.getAttribute(ARMOR_MULT) / 100); } public static double getWarding(AttributedEntity ae) { return ae.getAttribute(WARDING) * (1 + ae.getAttribute(WARD_MULT) / 100); } public static double getMinimumEvasionMult(AttributedEntity ae) { return getFlatEvasion(ae) * (1 + ae.getAttribute(EVASION_MULT) / 100); } public static double getFlatEvasion(AttributedEntity ae) { return ae.getAttribute(EVASION); } public static double getArmorPen(AttributedEntity ae) { return ae.getAttribute(ARMOR_PENETRATION) * (1 + (ae.getAttribute(APEN_MULT) / 100)); } public static double getWardPen(AttributedEntity ae) { return ae.getAttribute(WARD_PENETRATION) * (1 + (ae.getAttribute(WPEN_MULT) / 100)); } public static double getAccuracy(AttributedEntity ae) { return ae.getAttribute(ACCURACY) * (1 + (ae.getAttribute(ACCURACY_MULT) / 100)); } public static double getArmorMult(AttributedEntity attacker, AttributedEntity defender) { double adjustedArmor = Math.max(getArmor(defender) - getArmorPen(attacker), 1); return Math.min(1, 100 / (100 + adjustedArmor)); } public static double getWardingMult(AttributedEntity attacker, AttributedEntity defender) { double adjustedWarding = Math.max(getWarding(defender) - getWardPen(attacker), 1); return Math.min(1, 80 / (80 + adjustedWarding)); } public static double getMinimumEvasionMult(AttributedEntity attacker, AttributedEntity defender) { double evasion = getMinimumEvasionMult(defender); double accuracy = getAccuracy(attacker); double bonusMultiplier = EVASION_ACCURACY_MULT * ((evasion - accuracy) / (1 + accuracy)); return Math.min(1, BASE_EVASION_MULT - bonusMultiplier); } public static double getFireResist(AttributedEntity ae) { double amount = ae.getAttribute(FIRE_RESIST) + ae.getAttribute(ALL_RESIST); return Math.min(amount, ae.getEntity() instanceof Player ? 80 : 99); } public static double getIceResist(AttributedEntity ae) { double amount = ae.getAttribute(ICE_RESIST) + ae.getAttribute(ALL_RESIST); return Math.min(amount, ae.getEntity() instanceof Player ? 80 : 99); } public static double getLightningResist(AttributedEntity ae) { double amount = ae.getAttribute(LIGHTNING_RESIST) + ae.getAttribute(ALL_RESIST); return Math.min(amount, ae.getEntity() instanceof Player ? 80 : 99); } public static double getEarthResist(AttributedEntity ae) { double amount = ae.getAttribute(EARTH_RESIST) + ae.getAttribute(ALL_RESIST); return Math.min(amount, ae.getEntity() instanceof Player ? 80 : 99); } public static double getLightResist(AttributedEntity ae) { double amount = ae.getAttribute(LIGHT_RESIST) + ae.getAttribute(ALL_RESIST); return Math.min(amount, ae.getEntity() instanceof Player ? 80 : 99); } public static double getShadowResist(AttributedEntity ae) { double amount = ae.getAttribute(DARK_RESIST) + ae.getAttribute(ALL_RESIST); return Math.min(amount, ae.getEntity() instanceof Player ? 80 : 99); } public static double getLifestealPercentage(AttributedEntity attacker) { return attacker.getAttribute(LIFE_STEAL) / 100; } public static double getFireDamage(AttributedEntity attacker) { return attacker.getAttribute(FIRE_DAMAGE) * getElementalMult(attacker); } public static double getIceDamage(AttributedEntity attacker) { return attacker.getAttribute(ICE_DAMAGE) * getElementalMult(attacker); } public static double getLightningDamage(AttributedEntity attacker) { return attacker.getAttribute(LIGHTNING_DAMAGE) * getElementalMult(attacker); } public static double getEarthDamage(AttributedEntity attacker) { return attacker.getAttribute(EARTH_DAMAGE) * getElementalMult(attacker); } public static double getLightDamage(AttributedEntity attacker) { return attacker.getAttribute(LIGHT_DAMAGE) * getElementalMult(attacker); } public static double getShadowDamage(AttributedEntity attacker) { return attacker.getAttribute(DARK_DAMAGE) * getElementalMult(attacker); } public static double getBaseFireDamage(AttributedEntity attacker, AttributedEntity defender) { double damage = attacker.getAttribute(StrifeAttribute.FIRE_DAMAGE); if (damage == 0) { return 0D; } damage *= 1 + attacker.getAttribute(StrifeAttribute.ELEMENTAL_MULT) / 100; damage *= 1 - getFireResist(defender) / 100; return damage; } public static double getBaseIceDamage(AttributedEntity attacker, AttributedEntity defender) { double damage = attacker.getAttribute(StrifeAttribute.ICE_DAMAGE); if (damage == 0) { return 0D; } damage *= 1 + attacker.getAttribute(StrifeAttribute.ELEMENTAL_MULT) / 100; damage *= 1 - getIceResist(defender) / 100; return damage; } public static double getBaseLightningDamage(AttributedEntity attacker, AttributedEntity defender) { double damage = attacker.getAttribute(StrifeAttribute.LIGHTNING_DAMAGE); if (damage == 0) { return 0D; } damage *= 1 + attacker.getAttribute(StrifeAttribute.ELEMENTAL_MULT) / 100; damage *= 1 - getLightningResist(defender) / 100; return damage; } public static double getBaseEarthDamage(AttributedEntity attacker, AttributedEntity defender) { double damage = attacker.getAttribute(StrifeAttribute.EARTH_DAMAGE); if (damage == 0) { return 0D; } damage *= 1 + attacker.getAttribute(StrifeAttribute.ELEMENTAL_MULT) / 100; damage *= 1 - getEarthResist(defender) / 100; return damage; } public static double getBaseLightDamage(AttributedEntity attacker, AttributedEntity defender) { double damage = attacker.getAttribute(StrifeAttribute.LIGHT_DAMAGE); if (damage == 0) { return 0D; } damage *= 1 + attacker.getAttribute(StrifeAttribute.ELEMENTAL_MULT) / 100; damage *= 1 - getLightResist(defender) / 100; return damage; } public static double getBaseShadowDamage(AttributedEntity attacker, AttributedEntity defender) { double damage = attacker.getAttribute(StrifeAttribute.DARK_DAMAGE); if (damage == 0) { return 0D; } damage *= 1 + attacker.getAttribute(StrifeAttribute.ELEMENTAL_MULT) / 100; damage *= 1 - getShadowResist(defender) / 100; return damage; } private static double getElementalMult(AttributedEntity pStats) { return 1 + (pStats.getAttribute(ELEMENTAL_MULT) / 100); } private static boolean itemCanUseRage(ItemStack item) { if (item.getType() == Material.BOW) { return false; } if (!ItemUtil.isMeleeWeapon(item.getType())) { return false; } if (ItemUtil.isWand(item)) { return false; } return true; } }
package io.cloudsoft.jmeter; import javax.annotation.concurrent.GuardedBy; import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JMeterNodeImpl extends SoftwareProcessImpl implements JMeterNode { private static final Logger LOG = LoggerFactory.getLogger(JMeterNodeImpl.class); private static final Object reconfigureLock = new Object[0]; @Override protected void connectSensors() { super.connectSensors(); connectServiceUpIsRunning(); } @Override protected void disconnectSensors() { disconnectServiceUpIsRunning(); super.disconnectSensors(); } @Override public Class getDriverInterface() { return JMeterDriver.class; } @Override public JMeterDriver getDriver() { return (JMeterDriver) super.getDriver(); } @Override public void pause() { if (getDriver() != null) { getDriver().stop(); } } /** * Copies new configuration and cycles the JMeter process. */ @GuardedBy("reconfigureLock") private void reconfigure() { if (getDriver() != null) { getDriver().reconfigure(true); LOG.debug("Reconfigured and restarted JMeter"); } } @Override public void increaseLoad(int threadStep, int delayStep) { threadStep = Math.max(0, threadStep); delayStep = Math.max(0, delayStep); synchronized (reconfigureLock) { // Increase number of threads and decrease the time each one waits int numThreads = getConfig(NUM_THREADS) + threadStep; setConfig(NUM_THREADS, numThreads); Long delay = Math.max(0, getConfig(REQUEST_DELAY) - delayStep); setConfig(REQUEST_DELAY, delay); LOG.info("{} increasing load generated in future runs of plan: numThreads={}, delay={}, approximately {} requests/second", new Object[]{this, numThreads, delay, getPotentialRequestsPerSecond(numThreads, delay)}); reconfigure(); } } @Override public void decreaseLoad(int threadStep, int delayStep) { threadStep = Math.max(0, threadStep); delayStep = Math.max(0, delayStep); synchronized (reconfigureLock) { // Decrease number of threads and increase the time each one waits Integer numThreads = Math.max(1, getConfig(NUM_THREADS) - threadStep); long delay = getConfig(REQUEST_DELAY) + delayStep; setConfig(NUM_THREADS, numThreads); setConfig(REQUEST_DELAY, delay); LOG.info("{} decreasing load generated in future runs of plan: numThreads={}, delay={}, approximately {} requests/second", new Object[]{this, numThreads, delay, getPotentialRequestsPerSecond(numThreads, delay)}); reconfigure(); } } private long getPotentialRequestsPerSecond(int numThreads, long delay) { delay = delay == 0 ? 1 : delay; return numThreads * (1000 / delay); } }
package io.github.repir.tools.Lib; import io.github.repir.tools.Content.Datafile; import static io.github.repir.tools.Lib.PrintTools.*; import java.io.PrintStream; import java.util.HashMap; /** * Tiny profiler. * <p/> * @author jeroen */ public class Profiler { public static Datafile out; public static PrintStream systemout = System.out; private static HashMap<String, Profile> profiles; public static int availableProcessor() { return Runtime.getRuntime().availableProcessors(); } public static long getFreeMemory() { return Runtime.getRuntime().freeMemory(); } static final long maxMemory = Runtime.getRuntime().maxMemory(); public static long getTotalMemory() { return Runtime.getRuntime().totalMemory(); } public static void s(String name) { Profile p = profiles.get(name); if (p == null) { p = new Profile(name); profiles.put(name, p); } p.startTime(); p.count++; } public void e(String name) { Profile p = profiles.get(name); if (p == null) { p = new Profile(name); profiles.put(name, p); } p.addTime(); } public static void setProfileFile(Datafile file) { out = file; } public final static void reportProfile() { for (Profile p : profiles.values()) { out("%s( count=%d sec=%f )", p.name, p.count, p.time / 1000.0); } } protected static void out(String s, Object... args) { if (out == null) { systemout.println(sprintf(s, args)); } else { out.printf(s + "\n", args); out.flush(); } } public static void print(String s) { if (out == null) { systemout.println(s); } else { out.printf(s + "\n"); out.flush(); } } public void printf(String message, Object... args) { print(sprintf(message, args)); } static class Profile { int count = 0; long time = 0; long starttime = 0; final String name; Profile(String name) { this.name = name; } void startTime() { starttime = System.currentTimeMillis(); } void addTime() { time += System.currentTimeMillis() - starttime; } } }
package io.sigpipe.sing.stat; import java.util.HashMap; import java.util.Map; import io.sigpipe.sing.dataset.feature.Feature; /** * 'Surveys' a set of features by maintaing a unique {@link RunningStatistics} * instance for each named feature. * * @author malensek */ public class FeatureSurvey { private Map<String, RunningStatistics> stats = new HashMap<>(); public FeatureSurvey() { } public void add(Feature feature) { RunningStatistics rs = stats.get(feature.getName()); if (rs == null) { rs = new RunningStatistics(); stats.put(feature.getName(), rs); } rs.put(feature.getDouble()); } public void printAll() { for (String featureName : stats.keySet()) { System.out.println(" RunningStatistics rs = stats.get(featureName); System.out.println(rs); System.out.println(); } } }
package it.near.sdk.Reactions.Coupon; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; import it.near.sdk.MorpheusNear.Annotations.Relationship; import it.near.sdk.MorpheusNear.Resource; /** * @author cattaneostefano. */ public class Claim extends Resource implements Parcelable { @SerializedName("serial_number") String serial_number; @SerializedName("claimed_at") String claimed_at; @SerializedName("redeemed_at") String redeemed_at; @Relationship("coupon") Coupon coupon; public Claim() { } public String getSerial_number() { return serial_number; } public void setSerial_number(String serial_number) { this.serial_number = serial_number; } public String getClaimed_at() { return claimed_at; } public void setClaimed_at(String claimed_at) { this.claimed_at = claimed_at; } public String getRedeemed_at() { return redeemed_at; } public void setRedeemed_at(String redeemed_at) { this.redeemed_at = redeemed_at; } public Coupon getCoupon() { return coupon; } public void setCoupon(Coupon coupon) { this.coupon = coupon; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(getId()); dest.writeString(serial_number); dest.writeString(claimed_at); dest.writeString(redeemed_at); } public static final Creator<Claim> CREATOR = new Creator<Claim>() { @Override public Claim createFromParcel(Parcel in) { return new Claim(in); } @Override public Claim[] newArray(int size) { return new Claim[size]; } }; protected Claim(Parcel in) { setId(in.readString()); serial_number = in.readString(); claimed_at = in.readString(); redeemed_at = in.readString(); } }
package jacz.util.stochastic; import jacz.util.numeric.NumericUtil; import java.util.ArrayList; /** * A random buffer that is fed from the mouse coordinates. Time values can also be used for randomisation */ public class MouseToRandom { private class Coordinate { private Coordinate(int x, int y) { this.x = x; this.y = y; } int x; int y; } private static final int COORDINATE_STACK_LENGTH = 10; private final byte[] randomBytes; private final boolean useTime; private int pos; private final int totalLength; private ArrayList<Coordinate> lastCoordinateStack; private String gainedBits; public MouseToRandom(int length) { this(length, false); } public MouseToRandom(int length, boolean useTime) { randomBytes = new byte[length]; this.useTime = useTime; pos = 0; totalLength = length; lastCoordinateStack = new ArrayList<>(); gainedBits = ""; } /** * Adds a new mouse coordinate for randomly generating bytes * * @param x random x coordinate * @param y random y coordinate * @return the progress of completion (from 0 to 1) */ public double mouseCoords(int x, int y) { if (!lastCoordinateStack.isEmpty()) { newRandomCoords(x, y); // store the new coordinate in the coordinate stack lastCoordinateStack.add(0, new Coordinate(x, y)); while (lastCoordinateStack.size() > COORDINATE_STACK_LENGTH) { lastCoordinateStack.remove(COORDINATE_STACK_LENGTH); } return progress(); } else { lastCoordinateStack.add(new Coordinate(x, y)); return 0; } } private double progress() { double progress = (double) (pos) / (double) totalLength; if (progress == 0) { return 0d; } else if (pos == totalLength) { return 1d; } else { return (double) (pos) / (double) totalLength; } } private void newRandomCoords(int x, int y) { int moveX = x - lastCoordinateStack.get(0).x; int moveY = y - lastCoordinateStack.get(0).y; String bitString = calculateBitString(moveX, moveY); gainedBits += bitString; if (useTime) { int randomTime = getRandomTime(); if (lastCoordinateStack.size() > randomTime) { // redo the bit gain with an older stored coordinate, obtained randomly with the nanoTime function moveX = x - lastCoordinateStack.get(randomTime).x; moveY = y - lastCoordinateStack.get(randomTime).y; bitString = calculateBitString(moveX, moveY); gainedBits += bitString; } } while (gainedBits.length() >= 8) { // move 8 bits to the byte array String eightBitString = gainedBits.substring(0, 8); addByteToBuffer((byte) Integer.parseInt(eightBitString, 2)); gainedBits = gainedBits.substring(8); } } private void addByteToBuffer(byte b) { if (pos < totalLength) { randomBytes[pos++] = b; } } private String calculateBitString(int x, int y) { int D = Math.max(Math.abs(x), Math.abs(y)); int n; if (x > y && x >= -y) { n = x + y; } else if (x <= y && x > -y) { n = y - x + 2 * D; } else if (x < y && x <= -y) { n = x - y + 4 * D; } else { n = x + y + 8 * D; } return NumericUtil.decimalToBitString(n, 0, 8 * D - 1); } private int getRandomTime() { long millis = System.currentTimeMillis(); return (int) (millis % COORDINATE_STACK_LENGTH); } public boolean hasFinished() { return pos == totalLength; } public byte[] getRandomBytes() { return randomBytes; } }
package javax.jmdns.impl; import java.io.IOException; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import javax.jmdns.impl.constants.DNSState; import javax.jmdns.impl.tasks.DNSTask; /** * Sets of methods to manage the state machine.<br/> * <b>Implementation note:</b> This interface is accessed from multiple threads. The implementation must be thread safe. * * @author Pierre Frisch */ public interface DNSStatefulObject { /** * This class define a semaphore. On this multiple threads can wait the arrival of one event. Thread wait for a maximum defined by the timeout. * <p> * Implementation note: this class is based on {@link java.util.concurrent.Semaphore} so that they can be released by the timeout timer. * </p> * * @author Pierre Frisch */ public static final class DNSStatefulObjectSemaphore { private static Logger logger = Logger.getLogger(DNSStatefulObjectSemaphore.class.getName()); private final String _name; private final ConcurrentMap<Thread, Semaphore> _semaphores; /** * @param name * Semaphore name for debugging purposes. */ public DNSStatefulObjectSemaphore(String name) { super(); _name = name; _semaphores = new ConcurrentHashMap<Thread, Semaphore>(50); } /** * Blocks the current thread until the event arrives or the timeout expires. * * @param timeout * wait period for the event */ public void waitForEvent(long timeout) { Thread thread = Thread.currentThread(); Semaphore semaphore = _semaphores.get(thread); if (semaphore == null) { semaphore = new Semaphore(1, true); semaphore.drainPermits(); _semaphores.putIfAbsent(thread, semaphore); } semaphore = _semaphores.get(thread); try { semaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException exception) { logger.log(Level.FINER, "Exception ", exception); } } /** * Signals the semaphore when the event arrives. */ public void signalEvent() { Collection<Semaphore> semaphores = _semaphores.values(); for (Semaphore semaphore : semaphores) { semaphore.release(); semaphores.remove(semaphore); } } @Override public String toString() { StringBuilder aLog = new StringBuilder(1000); aLog.append("Semaphore: "); aLog.append(this._name); if (_semaphores.size() == 0) { aLog.append(" no semaphores."); } else { aLog.append(" semaphores:\n"); for (Thread thread : _semaphores.keySet()) { aLog.append("\tThread: "); aLog.append(thread.getName()); aLog.append(' '); aLog.append(_semaphores.get(thread)); aLog.append('\n'); } } return aLog.toString(); } } public static class DefaultImplementation extends ReentrantLock implements DNSStatefulObject { private static Logger logger = Logger.getLogger(DefaultImplementation.class.getName()); private static final long serialVersionUID = -3264781576883412227L; private volatile JmDNSImpl _dns; protected volatile DNSTask _task; protected volatile DNSState _state; private final DNSStatefulObjectSemaphore _announcing; private final DNSStatefulObjectSemaphore _canceling; public DefaultImplementation() { super(); _dns = null; _task = null; _state = DNSState.PROBING_1; _announcing = new DNSStatefulObjectSemaphore("Announce"); _canceling = new DNSStatefulObjectSemaphore("Cancel"); } /** * {@inheritDoc} */ @Override public JmDNSImpl getDns() { return this._dns; } protected void setDns(JmDNSImpl dns) { this._dns = dns; } /** * {@inheritDoc} */ @Override public void associateWithTask(DNSTask task, DNSState state) { if (this._task == null && this._state == state) { this.lock(); try { if (this._task == null && this._state == state) { this.setTask(task); } } finally { this.unlock(); } } } /** * {@inheritDoc} */ @Override public void removeAssociationWithTask(DNSTask task) { if (this._task == task) { this.lock(); try { if (this._task == task) { this.setTask(null); } } finally { this.unlock(); } } } /** * {@inheritDoc} */ @Override public boolean isAssociatedWithTask(DNSTask task, DNSState state) { this.lock(); try { return this._task == task && this._state == state; } finally { this.unlock(); } } protected void setTask(DNSTask task) { this._task = task; } /** * @param state * the state to set */ protected void setState(DNSState state) { this.lock(); try { this._state = state; if (this.isAnnounced()) { _announcing.signalEvent(); } if (this.isCanceled()) { _canceling.signalEvent(); // clear any waiting announcing _announcing.signalEvent(); } } finally { this.unlock(); } } /** * {@inheritDoc} */ @Override public boolean advanceState(DNSTask task) { boolean result = true; if (this._task == task) { this.lock(); try { if (this._task == task) { this.setState(this._state.advance()); } else { logger.warning("Trying to advance state whhen not the owner. owner: " + this._task + " perpetrator: " + task); } } finally { this.unlock(); } } return result; } /** * {@inheritDoc} */ @Override public boolean revertState() { boolean result = true; if (!this.willCancel()) { this.lock(); try { if (!this.willCancel()) { this.setState(this._state.revert()); this.setTask(null); } } finally { this.unlock(); } } return result; } /** * {@inheritDoc} */ @Override public boolean cancelState() { boolean result = false; if (!this.willCancel()) { this.lock(); try { if (!this.willCancel()) { this.setState(DNSState.CANCELING_1); this.setTask(null); result = true; } } finally { this.unlock(); } } return result; } /** * {@inheritDoc} */ @Override public boolean closeState() { boolean result = false; if (!this.willClose()) { this.lock(); try { if (!this.willClose()) { this.setState(DNSState.CLOSING); this.setTask(null); result = true; } } finally { this.unlock(); } } return result; } /** * {@inheritDoc} */ @Override public boolean recoverState() { boolean result = false; this.lock(); try { this.setState(DNSState.PROBING_1); this.setTask(null); } finally { this.unlock(); } return result; } /** * {@inheritDoc} */ @Override public boolean isProbing() { return this._state.isProbing(); } /** * {@inheritDoc} */ @Override public boolean isAnnouncing() { return this._state.isAnnouncing(); } /** * {@inheritDoc} */ @Override public boolean isAnnounced() { return this._state.isAnnounced(); } /** * {@inheritDoc} */ @Override public boolean isCanceling() { return this._state.isCanceling(); } /** * {@inheritDoc} */ @Override public boolean isCanceled() { return this._state.isCanceled(); } /** * {@inheritDoc} */ @Override public boolean isClosing() { return this._state.isClosing(); } /** * {@inheritDoc} */ @Override public boolean isClosed() { return this._state.isClosed(); } private boolean willCancel() { return this._state.isCanceled() || this._state.isCanceling(); } private boolean willClose() { return this._state.isClosed() || this._state.isClosing(); } /** * {@inheritDoc} */ @Override public boolean waitForAnnounced(long timeout) { if (!this.isAnnounced() && !this.willCancel()) { _announcing.waitForEvent(timeout + 10); } if (!this.isAnnounced()) { // When we run multihomed we need to check twice _announcing.waitForEvent(10); if (!this.isAnnounced()) { if (this.willCancel() || this.willClose()) { logger.fine("Wait for announced cancelled: " + this); } else { logger.warning("Wait for announced timed out: " + this); } } } return this.isAnnounced(); } /** * {@inheritDoc} */ @Override public boolean waitForCanceled(long timeout) { if (!this.isCanceled()) { _canceling.waitForEvent(timeout); } if (!this.isCanceled()) { // When we run multihomed we need to check twice _canceling.waitForEvent(10); if (!this.isCanceled() && !this.willClose()) { logger.warning("Wait for canceled timed out: " + this); } } return this.isCanceled(); } /** * {@inheritDoc} */ @Override public String toString() { try { return (_dns != null ? "DNS: " + _dns.getName() + " [" + _dns.getInetAddress() + "]" : "NO DNS") + " state: " + _state + " task: " + _task; } catch (IOException exception) { return (_dns != null ? "DNS: " + _dns.getName() : "NO DNS") + " state: " + _state + " task: " + _task; } } } /** * Returns the DNS associated with this object. * * @return DNS resolver */ public JmDNSImpl getDns(); /** * Sets the task associated with this Object. * * @param task * associated task * @param state * state of the task */ public void associateWithTask(DNSTask task, DNSState state); /** * Remove the association of the task with this Object. * * @param task * associated task */ public void removeAssociationWithTask(DNSTask task); /** * Checks if this object is associated with the task and in the same state. * * @param task * associated task * @param state * state of the task * @return <code>true</code> is the task is associated with this object, <code>false</code> otherwise. */ public boolean isAssociatedWithTask(DNSTask task, DNSState state); /** * Sets the state and notifies all objects that wait on the ServiceInfo. * * @param task * associated task * @return <code>true</code if the state was changed by this thread, <code>false</code> otherwise. * @see DNSState#advance() */ public boolean advanceState(DNSTask task); /** * Sets the state and notifies all objects that wait on the ServiceInfo. * * @return <code>true</code if the state was changed by this thread, <code>false</code> otherwise. * @see DNSState#revert() */ public boolean revertState(); /** * Sets the state and notifies all objects that wait on the ServiceInfo. * * @return <code>true</code if the state was changed by this thread, <code>false</code> otherwise. */ public boolean cancelState(); /** * Sets the state and notifies all objects that wait on the ServiceInfo. * * @return <code>true</code if the state was changed by this thread, <code>false</code> otherwise. */ public boolean closeState(); /** * Sets the state and notifies all objects that wait on the ServiceInfo. * * @return <code>true</code if the state was changed by this thread, <code>false</code> otherwise. */ public boolean recoverState(); /** * Returns true, if this is a probing state. * * @return <code>true</code> if probing state, <code>false</code> otherwise */ public boolean isProbing(); /** * Returns true, if this is an announcing state. * * @return <code>true</code> if announcing state, <code>false</code> otherwise */ public boolean isAnnouncing(); /** * Returns true, if this is an announced state. * * @return <code>true</code> if announced state, <code>false</code> otherwise */ public boolean isAnnounced(); /** * Returns true, if this is a canceling state. * * @return <code>true</code> if canceling state, <code>false</code> otherwise */ public boolean isCanceling(); /** * Returns true, if this is a canceled state. * * @return <code>true</code> if canceled state, <code>false</code> otherwise */ public boolean isCanceled(); /** * Returns true, if this is a closing state. * * @return <code>true</code> if closing state, <code>false</code> otherwise */ public boolean isClosing(); /** * Returns true, if this is a closed state. * * @return <code>true</code> if closed state, <code>false</code> otherwise */ public boolean isClosed(); /** * Waits for the object to be announced. * * @param timeout * the maximum time to wait in milliseconds. * @return <code>true</code> if the object is announced, <code>false</code> otherwise */ public boolean waitForAnnounced(long timeout); /** * Waits for the object to be canceled. * * @param timeout * the maximum time to wait in milliseconds. * @return <code>true</code> if the object is canceled, <code>false</code> otherwise */ public boolean waitForCanceled(long timeout); }
// Project : Ever WebService // Package : com.ever.webservice.utils // DateUtils.java // Author : Simon CORSIN <simoncorsin@gmail.com> package me.corsin.javatools.date; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class DateUtils { // VARIABLES // CONSTRUCTORS // METHODS public static Date currentTimeGMT() { SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT")); //Local time zone SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); //Time in GMT try { return dateFormatLocal.parse(dateFormatGmt.format(new Date())); } catch (ParseException e) { e.printStackTrace(); return null; } } public static String toISO8601String(Date date) { TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'Z'"); // DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); df.setTimeZone(tz); String value = df.format(date); return value; } public static Date getDateOffsetedFromGMT(int calendarField, int amount) { return getDateOffseted(currentTimeGMT(), calendarField, amount); } public static Date getDateOffsetedFromNow(int calendarField, int amount) { return getDateOffseted(new Date(), calendarField, amount); } public static Date getDateOffseted(Date date, int calendarField, int amount) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(calendarField, amount); return calendar.getTime(); } public static long getTimeMillis(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.set(year, month - 1, day, 0, 0, 0); // System.out.println(); return calendar.getTimeInMillis(); } public static Date getDate(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.set(year, month - 1, day, 0, 0, 0); return calendar.getTime(); } // GETTERS/SETTERS }
package net.alpenblock.bungeeperms; import java.util.ArrayList; import java.util.List; import java.util.UUID; import net.md_5.bungee.BungeeCord; import net.md_5.bungee.api.connection.ProxiedPlayer; public class Statics { public static int countSequences(String s, String seq) { int count = 0; for (int i = 0; i < s.length() - seq.length() + 1; i++) { if (s.substring(i, i + seq.length()).equalsIgnoreCase(seq)) { count++; } } return count; } public static String getFullPlayerName(String player) { ProxiedPlayer p = BungeeCord.getInstance().getPlayer(player); if (p != null) { for (ProxiedPlayer pp : BungeeCord.getInstance().getPlayers()) { if (pp.getName().startsWith(player)) { return pp.getName(); } } return p.getName(); } else { return player; } } public static List<String> toList(String s, String seperator) { List<String> l = new ArrayList<>(); String ls = ""; for (int i = 0; i < (s.length() - seperator.length()) + 1; i++) { if (s.substring(i, i + seperator.length()).equalsIgnoreCase(seperator)) { l.add(ls); ls = ""; i = i + seperator.length() - 1; } else { ls += s.substring(i, i + 1); } } if (ls.length() > 0) { l.add(ls); } return l; } public static boolean argAlias(String arg, String... aliases) { for (int i = 0; i < aliases.length; i++) { if (aliases[i].equalsIgnoreCase(arg)) { return true; } } return false; } public static UUID parseUUID(String s) { try { return UUID.fromString(s); } catch (Exception e) { } if (s.length() == 32) { s = s.substring(0, 8) + "-" + s.substring(8, 12) + "-" + s.substring(12, 16) + "-" + s.substring(16, 20) + "-" + s.substring(20, 32) + "-"; try { return UUID.fromString(s); } catch (Exception e) { } } return null; } }
package net.gigimoi.zombietc; import cpw.mods.fml.common.registry.GameRegistry; import net.gigimoi.zombietc.event.GameManager; import net.gigimoi.zombietc.net.activates.MessageActivateRepairBarricade; import net.gigimoi.zombietc.proxy.ClientProxy; import net.gigimoi.zombietc.weapon.ItemWeapon; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; import net.minecraft.network.play.server.S35PacketUpdateTileEntity; import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.Vec3; import org.lwjgl.input.Keyboard; import java.util.List; public class TileBarricade extends TileEntity { public int damage = 0; public int ticker = 0; public int playerTicker = 0; public TileBarricade() { super(); } @Override public void readFromNBT(NBTTagCompound tag) { damage = tag.getInteger("Damage"); ticker = tag.getInteger("Ticker"); playerTicker = tag.getInteger("Player Ticker"); super.readFromNBT(tag); } @Override public void writeToNBT(NBTTagCompound tag) { tag.setInteger("Damage", damage); tag.setInteger("Ticker", ticker); tag.setInteger("Player Ticker", playerTicker); super.writeToNBT(tag); } public AxisAlignedBB getBoundsAround() { return AxisAlignedBB.getBoundingBox(xCoord - 0.5, yCoord - 0.5, zCoord - 0.5, xCoord + 1.5, yCoord + 1.5, zCoord + 1.5); } @Override public void updateEntity() { if(damage < 5) { List<EntityZZombie> zombies = worldObj.getEntitiesWithinAABB(EntityZZombie.class, getBoundsAround()); if(zombies.size() > 0) { ticker++; if(ticker > 30) { damage++; ticker = 0; } } } playerTicker = Math.max(0, playerTicker - 1); if(damage > 0 && worldObj.isRemote) { if(worldObj.getEntitiesWithinAABB(EntityPlayer.class, getBoundsAround()).contains(Minecraft.getMinecraft().thePlayer)) { ZombieTC.gameManager.setActivateMessage("Press [" + Keyboard.getKeyName(ClientProxy.activate.getKeyCode()) + "] to repair" + (playerTicker == 0 ? "" : "...")); if(playerTicker == 0 && Keyboard.isKeyDown(ClientProxy.activate.getKeyCode()) ) { playerTicker = 40; ZombieTC.network.sendToServer(new MessageActivateRepairBarricade(xCoord, yCoord, zCoord)); } } } } @Override public Packet getDescriptionPacket() { NBTTagCompound tagCompound = new NBTTagCompound(); writeToNBT(tagCompound); return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 1, tagCompound); } @Override public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { super.onDataPacket(net, pkt); readFromNBT(pkt.func_148857_g()); } }
package net.glider.src.utils; public class GliderModInfo { public static final String MOD_ID = "AdvancedSSMod"; public static final String MOD_NAME = "Advanced Space Staion mod"; public static final String ModTestures = "advancedssmod"; public static final String Version = "@VERSION@"; public static final String ChannelName = "AdvSS"; }
package net.md_5.specialsource; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.commons.Remapper; import org.objectweb.asm.commons.RemappingClassAdapter; public class JarRemapper extends Remapper { private static final int CLASS_LEN = ".class".length(); private final List<IInheritanceProvider> inheritanceProviders; private final JarMapping jarMapping; public JarRemapper(JarMapping jarMapping, List<IInheritanceProvider> inheritanceProviders) { this.jarMapping = jarMapping; this.inheritanceProviders = inheritanceProviders; } @Override public String map(String typeName) { return mapTypeName(typeName, jarMapping.packages, jarMapping.classes); } public static String mapTypeName(String typeName, Map<String, String> packageMap, Map<String, String> classMap) { int index = typeName.indexOf('$'); String key = (index == -1) ? typeName : typeName.substring(0, index); String mapped = mapClassName(key, packageMap, classMap); return mapped != null ? mapped + (index == -1 ? "" : typeName.substring(index, typeName.length())) : typeName; } /** * Helper method to map a class name by package (prefix) or class (exact) * map */ private static String mapClassName(String className, Map<String, String> packageMap, Map<String, String> classMap) { if (packageMap != null) { for (String oldPackage : packageMap.keySet()) { if (className.startsWith(oldPackage)) { String newPackage = packageMap.get(oldPackage); return newPackage + className.substring(oldPackage.length()); } } } return classMap != null ? classMap.get(className) : null; } @Override public String mapFieldName(String owner, String name, String desc) { String mapped = tryClimb(jarMapping.fields, NodeType.FIELD, owner, name); return mapped == null ? name : mapped; } private String tryClimb(Map<String, String> map, NodeType type, String owner, String name) { String key = owner + "/" + name; String mapped = map.get(key); if (mapped == null) { // ask each provider for inheritance information on the class, until one responds for (IInheritanceProvider inheritanceProvider : inheritanceProviders) { List<String> parents = inheritanceProvider.getParents(owner); if (parents != null) { // climb the inheritance tree for (String parent : parents) { mapped = tryClimb(map, type, parent, name); if (mapped != null) { return mapped; } } break; } } } return mapped; } @Override public String mapMethodName(String owner, String name, String desc) { String mapped = tryClimb(jarMapping.methods, NodeType.METHOD, owner, name + " " + desc); return mapped == null ? name : mapped; } /** * Remap all the classes in a jar, writing a new jar to the target */ public void remapJar(Jar jar, File target) throws IOException { JarOutputStream out = new JarOutputStream(new FileOutputStream(target)); try { if (jar == null) { return; } for (Enumeration<JarEntry> entr = jar.file.entries(); entr.hasMoreElements();) { JarEntry entry = entr.nextElement(); InputStream is = jar.file.getInputStream(entry); try { String name = entry.getName(); byte[] data; if (name.endsWith(".class")) { name = name.substring(0, name.length() - CLASS_LEN); data = remapClassFile(is); String newName = map(name); entry = new JarEntry(newName == null ? name : newName + ".class"); } else { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int n; byte[] b = new byte[1 << 15]; // Max class file size while ((n = is.read(b, 0, b.length)) != -1) { buffer.write(b, 0, n); } buffer.flush(); data = buffer.toByteArray(); } entry.setTime(0); out.putNextEntry(entry); out.write(data); } finally { is.close(); } } } finally { out.close(); } } /** * Remap an individual class given an InputStream to its bytecode */ public byte[] remapClassFile(InputStream is) throws IOException { ClassReader reader = new ClassReader(is); ClassWriter wr = new ClassWriter(0); RemappingClassAdapter mapper = new RemappingClassAdapter(wr, this); reader.accept(mapper, ClassReader.EXPAND_FRAMES); return wr.toByteArray(); } }
package nl.utwente.bigdata; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; /** * * @author thom */ public class GoalPlayerCount { public static class CountMapper extends Mapper<Text, Text, Text, IntWritable>{ private final static IntWritable one = new IntWritable(1); @Override public void map(Text key, Text value, Context context) throws IOException, InterruptedException { context.write(value, one); } } public static class CountReducer extends Reducer<Text,IntWritable,Text,IntWritable> { private IntWritable result = new IntWritable(); public void reduce(Text key, Iterable<IntWritable> values, Reducer.Context context ) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); context.write(key, result); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length < 2) { System.err.println("Usage: GoalPlayerCount <in> [<in>...] <out>"); System.exit(2); } Job job = new Job(conf, "GoldenBoot GoalPlayerCount"); job.setJarByClass(UserCount.class); job.setMapperClass(CountMapper.class); job.setCombinerClass(CountReducer.class); job.setReducerClass(CountReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); for (int i = 0; i < otherArgs.length - 1; ++i) { FileInputFormat.addInputPath(job, new Path(otherArgs[i])); } FileOutputFormat.setOutputPath(job, new Path(otherArgs[otherArgs.length - 1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }
package nuclibook.routes; import nuclibook.constants.P; import nuclibook.entity_utils.PatientUtils; import nuclibook.entity_utils.SecurityUtils; import nuclibook.entity_utils.TherapyUtils; import nuclibook.models.Patient; import nuclibook.models.Therapy; import nuclibook.server.HtmlRenderer; import spark.Request; import spark.Response; import java.util.List; public class AppointmentsRoute extends DefaultRoute { @Override public Object handle(Request request, Response response) throws Exception { // necessary prelim routine prepareToHandle(); // security check if (!SecurityUtils.requirePermission(P.VIEW_PATIENT_LIST, response)) return null; // start renderer HtmlRenderer renderer = getRenderer(); renderer.setTemplateFile("appointments.html"); // get patients and add to renderer List<Patient> allPatients = PatientUtils.getAllPatients(true); renderer.setCollection("patients", allPatients); // get therapies and add to renderer List<Therapy> allTherapies = TherapyUtils.getAllTherapies(true); renderer.setCollection("therapies", allTherapies); return renderer.render(); } }
package org.basex.io.serial; import static org.basex.data.DataText.*; import static org.basex.query.util.Err.*; import static org.basex.util.Token.*; import java.io.*; import org.basex.query.util.json.*; import org.basex.query.value.item.*; import org.basex.util.*; import org.basex.util.hash.*; import org.basex.util.list.*; public final class JSONSerializer extends OutputSerializer { /** Plural. */ private static final byte[] S = { 's' }; /** Global data type attributes. */ private static final byte[][] ATTRS = { concat(T_BOOLEAN, S), concat(T_NUMBER, S), concat(NULL, S), concat(T_ARRAY, S), concat(T_OBJECT, S), concat(T_STRING, S) }; /** Supported data types. */ private static final byte[][] TYPES = { T_BOOLEAN, T_NUMBER, NULL, T_ARRAY, T_OBJECT, T_STRING }; /** Cached data types. */ private final TokenSet[] typeCache = new TokenSet[TYPES.length]; /** Comma flag. */ private final BoolList comma = new BoolList(); /** Types. */ private final TokenList types = new TokenList(); /** * Constructor. * @param os output stream reference * @param props serialization properties * @throws IOException I/O exception */ public JSONSerializer(final OutputStream os, final SerializerProp props) throws IOException { super(os, props); for(int t = 0; t < typeCache.length; t++) typeCache[t] = new TokenMap(); } @Override protected void startOpen(final byte[] name) throws IOException { if(level == 0 && !eq(name, T_JSON)) error("<%> expected as root node", T_JSON); types.set(level, null); comma.set(level + 1, false); } @Override protected void attribute(final byte[] name, final byte[] value) throws IOException { if(level == 0) { final int tl = typeCache.length; for(int t = 0; t < tl; t++) { if(eq(name, ATTRS[t])) { for(final byte[] b : split(value, ' ')) typeCache[t].add(b); return; } } } if(eq(name, T_TYPE)) { types.set(level, value); if(!eq(value, TYPES)) error("Element <%> has invalid type \"%\"", elem, value); } else { error("Element <%> has invalid attribute \"%\"", elem, name); } } @Override protected void finishOpen() throws IOException { if(comma.get(level)) print(','); else comma.set(level, true); if(level > 0) { indent(level); final byte[] par = types.get(level - 1); if(eq(par, T_OBJECT)) { print('"'); print(name(elem)); print("\": "); } else if(!eq(par, T_ARRAY)) { error("Element <%> is typed as \"%\" and cannot be nested", tags.get(level - 1), par); } } byte[] type = types.get(level); if(type == null) { int t = -1; final int tl = typeCache.length; while(++t < tl && !typeCache[t].contains(elem)); if(t != tl) type = TYPES[t]; else type = T_STRING; types.set(level, type); } if(eq(type, T_OBJECT)) { print('{'); } else if(eq(type, T_ARRAY)) { print('['); } else if(level == 0) { error("Element <%> must be typed as \"%\" or \"%\"", T_JSON, T_OBJECT, T_ARRAY); } } @Override protected void finishText(final byte[] text) throws IOException { final byte[] type = types.get(level - 1); if(eq(type, T_STRING)) { print('"'); for(final byte ch : text) code(ch); print('"'); } else if(eq(type, T_BOOLEAN, T_NUMBER)) { print(text); } else if(trim(text).length != 0) { error("Element <%> is typed as \"%\" and cannot have a value", tags.get(level - 1), type); } } @Override protected void finishEmpty() throws IOException { finishOpen(); final byte[] type = types.get(level); if(eq(type, T_STRING)) { print("\"\""); } else if(eq(type, NULL)) { print(NULL); } else if(!eq(type, T_OBJECT, T_ARRAY)) { error("Value expected for type \"%\"", type); } finishClose(); } @Override protected void finishClose() throws IOException { final byte[] type = types.get(level); if(eq(type, T_ARRAY)) { indent(level); print(']'); } else if(eq(type, T_OBJECT)) { indent(level); print('}'); } } @Override protected void code(final int ch) throws IOException { switch(ch) { case '\b': print("\\b"); break; case '\f': print("\\f"); break; case '\n': print("\\n"); break; case '\r': print("\\r"); break; case '\t': print("\\t"); break; case '"': print("\\\""); break; case '/': print("\\/"); break; case '\\': print("\\\\"); break; default: print(ch); break; } } @Override protected void finishComment(final byte[] value) throws IOException { error("Comments cannot be serialized"); } @Override protected void finishPi(final byte[] name, final byte[] value) throws IOException { error("Processing instructions cannot be serialized"); } @Override protected void atomic(final Item value) throws IOException { error("Atomic values cannot be serialized"); } /** * Prints some indentation. * @param lvl level * @throws IOException I/O exception */ void indent(final int lvl) throws IOException { if(!indent) return; print(nl); final int ls = lvl * indents; for(int l = 0; l < ls; ++l) print(tab); } /** * Converts an XML element name to a JSON name. * @param name name * @return cached QName */ private static byte[] name(final byte[] name) { // convert name to valid XML representation final TokenBuilder tb = new TokenBuilder(); int uc = 0; // mode: 0=normal, 1=unicode, 2=underscore, 3=building unicode int mode = 0; for(int n = 0; n < name.length;) { final int cp = cp(name, n); if(mode >= 3) { uc = (uc << 4) + cp - (cp >= '0' && cp <= '9' ? '0' : 0x37); if(++mode == 7) { tb.add(uc); mode = 0; uc = 0; } } else if(cp == '_') { // limit underscore counter if(++mode == 3) { tb.add('_'); mode = 0; continue; } } else if(mode == 1) { // unicode mode = 3; continue; } else if(mode == 2) { // underscore tb.add('_'); mode = 0; continue; } else { // normal character tb.add(cp); mode = 0; } n += cl(name, n); } if(mode == 2) { tb.add('_'); } else if(mode > 0 && !tb.isEmpty()) { tb.add('?'); } return tb.finish(); } /** * Raises an error with the specified message. * @param msg error message * @param ext error details * @throws IOException I/O exception */ private static void error(final String msg, final Object... ext) throws IOException { throw BXJS_SER.thrwSerial(Util.inf(msg, ext)); } }
package org.batgen.generators; import java.util.ArrayList; import java.util.List; import org.batgen.BlobColumn; import org.batgen.Column; //import org.batgen.DatabaseType; import org.batgen.DoubleColumn; import org.batgen.IndexNode; import org.batgen.LengthColumn; import org.batgen.Table; import static org.batgen.generators.GenUtil.*; public class SqlGenerator extends Generator { private String key = "KEY"; private final int SPACE = 18; private String filePath; private List<IndexNode> indexList = new ArrayList<IndexNode>(); private List<String> fieldList = new ArrayList<String>(); public SqlGenerator( Table table ) { super( table ); filePath = "sql/" + table.getTableName() + ".sql"; } public String createSql() { StringBuilder sb = new StringBuilder(); sb.append( messageRemove() ); sb.append( drop() ); sb.append( messageCreate() ); sb.append( createTable() ); sb.append( messageSample() ); sb.append( createSample() ); sb.append( getProtectedJavaLines( filePath ) ); writeToFile( filePath, sb.toString() ); appendToFile( "sql/CreateTables.sql", writeColumns() ); writeDropsFile(); return filePath; } private String createTable() { StringBuilder sb = new StringBuilder(); sb.append( writeColumns() ); return sb.toString(); } private String writeColumns() { StringBuilder sb = new StringBuilder(); sb.append( "\nCREATE TABLE " + table.getTableName() + " (\n" ); for ( Column column : table.getColumns() ) { String name = column.getClass().getSimpleName(); if ( !name.equals( "ListColumn" ) ) { sb.append( " " + column.getColName().toUpperCase() + makeSpace( SPACE, column.getColName() ) ); if ( name.equals( "BlobColumn" ) ) { BlobColumn c = (BlobColumn) column; sb.append( column.getSqlType() ); if ( c.getColLen() != null ) sb.append( "(" + c.getColLen() + ")" ); } else if ( name.equals( "LengthColumn" ) ) { LengthColumn c = (LengthColumn) column; if ( c.getColLen() != null ) { if ( column.getSqlType().equals( "CHAR" ) ) { sb.append( column.getSqlType() ); } else { sb.append( column.getSqlType() + "(" + c.getColLen() + ")" ); } } } else if ( name.equals( "DoubleColumn" ) ) { DoubleColumn c = (DoubleColumn) column; if ( c.getColLen() != null ) { sb.append( column.getSqlType() + "(" + c.getColLen() + "," + c.getPrecision() + ")" ); } } else if ( name.equals( "Column" ) ) { Column c = column; sb.append( c.getSqlType() ); } if ( column.isRequired() ) sb.append( " NOT NULL" ); if ( column.isKey() ) key = column.getColName().toUpperCase(); sb.append( ",\n" ); } } sb.append( " CONSTRAINT " + table.getTableName() + "_PK PRIMARY KEY (" + key.toUpperCase() + ")" ); sb.append( ");\n" ); sb.append( "\nCREATE SEQUENCE " + table.getTableName() + "_SEQ;\n" ); sb.append( writeIndexes() ); return sb.toString(); } private String writeIndexes() { StringBuilder sb = new StringBuilder(); indexList = table.getIndexList(); for ( int i = 0; i < indexList.size(); i++ ) { sb.append( "\nCREATE INDEX " + indexList.get( i ).getIndexName() ); sb.append( " ON " + table.getTableName() + "( " ); fieldList = indexList.get( i ).getFieldList(); sb.append( fieldList.get( 0 ) ); for ( int j = 1; j < fieldList.size(); j++ ) { sb.append( ", " + fieldList.get( j ) ); } sb.append( " );" ); } sb.append( "\n" ); return sb.toString(); } private String createSample() { StringBuilder sb = new StringBuilder(); sb.append( "SELECT\n " ); for ( int i = 0; i < table.getColumns().size(); i++ ) { if ( !"ListColumn".equals( table.getColumn( i ).getClass() .getSimpleName() ) ) { sb.append( table.getColumn( i ).getColName().toUpperCase() + ", " ); } } sb.deleteCharAt( sb.length() - 2 ); sb.append( "\nfrom " + table.getTableName() + "\nWHERE\n " + key + " = 0;\n" ); return sb.toString(); } private void writeDropsFile() { appendToFile( "sql/DropTables.sql", drop() + "\n\n" ); } private String drop() { return "DROP TABLE " + table.getTableName() + ";\nDROP SEQUENCE " + table.getTableName() + "_SEQ;\n"; } private String messageRemove() { return "-- Remove Original Table and Sequence\n\n"; } private String messageCreate() { return "-- Create Table\n\n"; } private String messageSample() { return "\n-- Sample Select Statement\n\n"; } }
package org.c4sg.controller; import static org.c4sg.constant.Directory.AVATAR_UPLOAD; import static org.c4sg.constant.Directory.RESUME_UPLOAD; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigDecimal; import java.util.List; import java.util.Map; import org.apache.tomcat.util.codec.binary.Base64; import org.c4sg.dto.UserDTO; import org.c4sg.exception.NotFoundException; import org.c4sg.service.OrganizationService; import org.c4sg.service.UserService; import org.c4sg.util.FileUploadUtil; import org.c4sg.util.GeoCodeUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; @CrossOrigin(origins = "*") @RestController @RequestMapping(value = "/api/users") @Api(description = "Operations about Users", tags = "user") public class UserController { private static Logger LOGGER = LoggerFactory.getLogger(UserController.class); @Autowired private UserService userService; @CrossOrigin @RequestMapping(value = "/active", method = RequestMethod.GET) @ApiOperation(value = "Find active volunteer users", notes = "Returns a collection of active volunteer users") @ApiImplicitParams({ @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query", value = "Results page you want to retrieve (0..N)"), @ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", value = "Number of records per page."), @ApiImplicitParam(name = "sort", allowMultiple = true, dataType = "string", paramType = "query", value = "Sorting criteria in the format: property(,asc|desc). " + "Default sort order is ascending. " + "Multiple sort criteria are supported.")}) public Page<UserDTO> getActiveUsers(Pageable pageable) { LOGGER.debug("**************active**************"); return userService.findActiveVolunteers(pageable); } @RequestMapping(method = RequestMethod.GET) @ApiOperation(value = "Find all users", notes = "Returns a collection of users") public List<UserDTO> getUsers() { return userService.findAll(); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ApiOperation(value = "Find user by ID", notes = "Returns a user") public UserDTO getUser(@ApiParam(value = "ID of user to return", required = true) @PathVariable("id") int id) { return userService.findById(id); } @CrossOrigin @RequestMapping(value = "/email/{email}/", method = RequestMethod.GET) @ApiOperation(value = "Find user by email", notes = "Returns a user") public UserDTO getUserByEmail(@ApiParam(value = "email address", required = true) @PathVariable("email") String email) { return userService.findByEmail(email); } @RequestMapping(method = RequestMethod.POST) @ApiOperation(value = "Add a new user") public UserDTO createUser(@ApiParam(value = "User object to return", required = true) @RequestBody UserDTO userDTO) { //calculate lat and long try { GeoCodeUtil geoCodeUtil = new GeoCodeUtil(userDTO); Map<String,BigDecimal> geoCode = geoCodeUtil.getGeoCode(); userDTO.setLatitude(geoCode.get("lat")); userDTO.setLongitude(geoCode.get("lon")); } catch (Exception e) { throw new NotFoundException("Error getting geocode"); } return userService.saveUser(userDTO); } @RequestMapping(method = RequestMethod.PUT) @ApiOperation(value = "Update an existing user") public UserDTO updateUser(@ApiParam(value = "Updated user object", required = true) @RequestBody UserDTO userDTO) { LOGGER.debug("**************updateUser**************"); LOGGER.debug("ID = " + userDTO.getId()); return userService.saveUser(userDTO); } @CrossOrigin @RequestMapping(value = "/applicant/{id}", method = RequestMethod.GET) @ApiOperation(value = "Find applicants of a given project", notes = "Returns a collection of projects") @ApiResponses(value = {@ApiResponse(code = 404, message = "Applicants not found")}) public ResponseEntity<List<UserDTO>> getApplicants(@ApiParam(value = "ID of project", required = true) @PathVariable("id") Integer projectId) { List<UserDTO> applicants = userService.getApplicants(projectId); if (!applicants.isEmpty()) { return ResponseEntity.ok().body(applicants); } else { throw new NotFoundException("Applicants not found"); } } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ApiOperation(value = "Delete a user") public void deleteUser(@ApiParam(value = "User id to delete", required = true) @PathVariable("id") int id) { LOGGER.debug("************** Delete : id=" + id + "**************"); try { userService.deleteUser(id); } catch (Exception e) { LOGGER.error("Exception on delete user:", e); } } @RequestMapping(value = "/search", method = RequestMethod.GET) @ApiOperation(value = "Find a user by keyWord", notes = "Returns a collection of users") public List<UserDTO> search(@RequestParam(required = false) String keyWord, @RequestParam(required = false) List<Integer> skills){ return userService.search(keyWord,skills); } @RequestMapping(value = "/{id}/avatar", method = RequestMethod.POST) @ApiOperation(value = "Add new upload Avatar") public String uploadAvatar(@ApiParam(value = "user Id", required = true) @PathVariable("id") Integer id, @ApiParam(value = "Image File", required = true) @RequestPart("file") MultipartFile file) { String contentType = file.getContentType(); if (!FileUploadUtil.isValidImageFile(contentType)) { return "Invalid image File! Content Type :-" + contentType; } File directory = new File(AVATAR_UPLOAD.getValue()); if (!directory.exists()) { directory.mkdir(); } File f = new File(userService.getAvatarUploadPath(id)); try (FileOutputStream fos = new FileOutputStream(f)) { byte[] imageByte = file.getBytes(); fos.write(imageByte); return "Success"; } catch (Exception e) { return "Error saving avatar for User " + id + " : " + e; } } @CrossOrigin @RequestMapping(value = "/{id}/avatar", method = RequestMethod.GET) @ApiOperation(value = "Retrieves user avatar") public String retrieveAvatar(@ApiParam(value = "User id to get avatar for", required = true) @PathVariable("id") int id) { File avatar = new File(userService.getAvatarUploadPath(id)); try { FileInputStream fileInputStreamReader = new FileInputStream(avatar); byte[] bytes = new byte[(int) avatar.length()]; fileInputStreamReader.read(bytes); fileInputStreamReader.close(); return new String(Base64.encodeBase64(bytes)); } catch (IOException e) { e.printStackTrace(); return null; } } @CrossOrigin @RequestMapping(value = "/avatars/{id}", method = RequestMethod.PUT) @ApiOperation(value = "Delete avatar for a user") public ResponseEntity<File> deleteAvatar(@ApiParam(value = "ID of user", required = true) @PathVariable("id") int id) { File avatar = new File(userService.getAvatarUploadPath(id)); if (avatar.exists()) { avatar.delete(); return ResponseEntity.noContent().build(); } else { throw new NotFoundException("avatar not found"); } } @RequestMapping(value = "/{id}/resume", method = RequestMethod.POST) @ApiOperation(value = "Add new upload resume") public String uploadResume(@ApiParam(value = "user Id", required = true) @PathVariable("id") Integer id, @ApiParam(value = "Resume File(.pdf)", required = true) @RequestPart("file") MultipartFile file) { String contentType = file.getContentType(); if (!FileUploadUtil.isValidResumeFile(contentType)) { return "Invalid pdf File! Content Type :-" + contentType; } File directory = new File(RESUME_UPLOAD.getValue()); if (!directory.exists()) { directory.mkdir(); } File f = new File(userService.getResumeUploadPath(id)); try (FileOutputStream fos = new FileOutputStream(f)) { byte[] fileByte = file.getBytes(); fos.write(fileByte); return "Success"; } catch (Exception e) { return "Error saving resume for User " + id + " : " + e; } } @CrossOrigin @RequestMapping(value = "/{id}/resume", method = RequestMethod.GET) @ApiOperation(value = "Retrieves user resume") @ResponseBody public HttpEntity<byte[]> retrieveProjectImage(@ApiParam(value = "User id to get resume for", required = true) @PathVariable("id") int id) { File resume = new File(userService.getResumeUploadPath(id)); try { FileInputStream fileInputStreamReader = new FileInputStream(resume); byte[] bytes = new byte[(int) resume.length()]; fileInputStreamReader.read(bytes); fileInputStreamReader.close(); HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_PDF); header.setContentLength(bytes.length); return new HttpEntity<byte[]>(bytes, header); } catch (IOException e) { e.printStackTrace(); return null; } } }
package org.ihtsdo.json; import com.google.gson.Gson; import org.ihtsdo.json.model.*; import org.ihtsdo.json.utils.FileHelper; import org.mapdb.DBMaker; import java.io.*; import java.util.*; /** * * @author Alejandro Rodriguez */ public class TransformerOnePass { private String MODIFIER = "Existential restriction"; private String sep = System.getProperty("line.separator"); private Map<Long, ConceptDescriptor> concepts; private Map<Long, List<LightDescription>> descriptions; private Map<Long, List<LightRelationship>> relationships; private Map<Long, List<LightRefsetMembership>> simpleMembers; private Map<Long, List<LightRefsetMembership>> simpleMapMembers; private Map<Long, List<LightLangMembership>> languageMembers; private Map<String, String> langCodes; private String defaultLangCode = "en"; public String fsnType = "900000000000003001"; public String synType = "900000000000013009"; private Long inferred = 900000000000011006l; private Long stated = 900000000000010007l; private Long isaSCTId=116680003l; private String defaultTermType = fsnType; private Map<Long, List<LightDescription>> tdefMembers; private Map<Long, List<LightRefsetMembership>> attrMembers; private Map<Long, List<LightRefsetMembership>> assocMembers; private ArrayList<Long> listA; private Map<String, String> charConv; private Map<Long, String> cptFSN; private HashSet<Long> notLeafInferred; private HashSet<Long> notLeafStated; public TransformerOnePass() throws IOException { String fileName = "/Volumes/Macintosh HD2/conversiondb/conversiondb"; deleteDir(new File("/Volumes/Macintosh HD2/conversiondb")); concepts = DBMaker.newTempHashMap(); descriptions = DBMaker.newTempHashMap(); relationships = DBMaker.newTempHashMap(); simpleMembers = DBMaker.newTempHashMap(); assocMembers = DBMaker.newTempHashMap(); attrMembers = DBMaker.newTempHashMap(); tdefMembers = DBMaker.newTempHashMap(); simpleMapMembers = DBMaker.newTempHashMap(); languageMembers = DBMaker.newTempHashMap(); notLeafInferred=new HashSet<Long>(); notLeafStated=new HashSet<Long>(); cptFSN = DBMaker.newTempHashMap(); langCodes = new HashMap<String, String>(); langCodes.put("en", "english"); langCodes.put("es", "spanish"); langCodes.put("da", "danish"); langCodes.put("sv", "swedish"); langCodes.put("fr", "french"); langCodes.put("nl", "dutch"); } public static void deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { File child = new File(dir, children[i]); child.delete(); } } } public static void main(String[] args) throws Exception { TransformerOnePass tr = new TransformerOnePass(); tr.setDefaultLangCode("en"); tr.setDefaultTermType(tr.fsnType); HashSet<String> folders=new HashSet<String>(); folders.add("/Volumes/Macintosh HD2/uk_sct2cl_17/SnomedCT_Release_INT_20140131/RF2Release/Snapshot"); folders.add("/Volumes/Macintosh HD2/uk_sct2cl_17/SnomedCT2_GB1000000_20140401/RF2Release/Snapshot"); folders.add("/Users/termmed/Downloads/SnomedCT_Release_US1000124_20140301/RF2Release/Snapshot"); //folders.add("/Users/termmed/Downloads/SnomedCT_Release_AU1000036_20140531/RF2 Release/Snapshot"); String valConfig= "config/validation-rules.xml"; HashSet<String> files = tr.getFilesFromFolders(folders); tr.processFiles(files, valConfig); tr.createConceptsJsonFile("/Volumes/Macintosh HD2/Multi-english-data/concepts.json"); tr.createTextIndexFile("/Volumes/Macintosh HD2/Multi-english-data/text-index.json"); //tr.freeStep1(); //tr.createTClosures(folders, valConfig, "/Volumes/Macintosh HD2/Multi-english-data/tclosure-inferred.json", "/Volumes/Macintosh HD2/tclosure-stated.json"); } public void freeStep1() { descriptions = null; simpleMembers = null; assocMembers = null; attrMembers = null; tdefMembers = null; simpleMapMembers = null; languageMembers = null; notLeafInferred= null; notLeafStated= null; cptFSN = null; langCodes = null; System.gc(); } private void processFiles(HashSet<String> files, String validationConfig) throws IOException, Exception { File config=new File(validationConfig); for (String file:files){ String pattern=FileHelper.getFileTypeByHeader(new File(file), config); if (pattern.equals("rf2-relationships")){ loadRelationshipsFile(new File(file)); }else if(pattern.equals("rf2-textDefinition")){ loadTextDefinitionFile(new File(file)); }else if(pattern.equals("rf2-association")){ loadAssociationFile(new File(file)); }else if(pattern.equals("rf2-association-2")){ loadAssociationFile(new File(file)); }else if(pattern.equals("rf2-attributevalue")){ loadAttributeFile(new File(file)); }else if(pattern.equals("rf2-language")){ loadLanguageRefsetFile(new File(file)); }else if(pattern.equals("rf2-simple")){ loadSimpleRefsetFile(new File(file)); }else if(pattern.equals("rf2-orderRefset")){ // TODO: add process to order refset loadSimpleRefsetFile(new File(file)); }else if(pattern.equals("rf2-simplemaps")){ loadSimpleMapRefsetFile(new File(file)); }else if(pattern.equals("rf2-descriptions")){ loadDescriptionsFile(new File(file)); }else if(pattern.equals("rf2-concepts")){ loadConceptsFile(new File(file)); }else{} } completeDefaultTerm(); } private HashSet<String> getFilesFromFolders(HashSet<String> folders) throws IOException, Exception { HashSet<String> result = new HashSet<String>(); FileHelper fHelper=new FileHelper(); for (String folder:folders){ File dir=new File(folder); HashSet<String> files=new HashSet<String>(); fHelper.findAllFiles(dir, files); result.addAll(files); } return result; } public void createTClosures(HashSet<String> folders, String valConfig, String transitiveClosureInferredFile,String transitiveClosureStatedFile) throws Exception { if (relationships==null || relationships.size()==0){ getFilesForTransClosureProcess(folders,valConfig); } createTClosure(transitiveClosureInferredFile,inferred); createTClosure(transitiveClosureStatedFile,stated); } private void getFilesForTransClosureProcess(HashSet<String> folders, String validationConfig) throws IOException, Exception { concepts = new HashMap<Long, ConceptDescriptor>(); relationships = new HashMap<Long, List<LightRelationship>>(); File config=new File(validationConfig); FileHelper fHelper=new FileHelper(); for (String folder:folders){ File dir=new File(folder); HashSet<String> files=new HashSet<String>(); fHelper.findAllFiles(dir, files); for (String file:files){ String pattern=FileHelper.getFileTypeByHeader(new File(file), config); if (pattern.equals("rf2-relationships")){ loadRelationshipsFile(new File(file)); }else if(pattern.equals("rf2-concepts")){ loadConceptsFile(new File(file)); }else{} } } } public void loadConceptsFile(File conceptsFile) throws FileNotFoundException, IOException { System.out.println("Starting Concepts: " + conceptsFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(conceptsFile), "UTF8")); try { String line = br.readLine(); line = br.readLine(); // Skip header int count = 0; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); ConceptDescriptor loopConcept = new ConceptDescriptor(); Long conceptId = Long.parseLong(columns[0]); loopConcept.setConceptId(conceptId); loopConcept.setActive(columns[2].equals("1")); loopConcept.setEffectiveTime(columns[1]); loopConcept.setModule(Long.parseLong(columns[3])); loopConcept.setDefinitionStatus(columns[4].equals("900000000000074008") ? "Primitive" : "Fully defined"); concepts.put(conceptId, loopConcept); line = br.readLine(); count++; if (count % 100000 == 0) { System.out.print("."); } } System.out.println("."); System.out.println("Concepts loaded = " + concepts.size()); } finally { br.close(); } } public void loadDescriptionsFile(File descriptionsFile) throws FileNotFoundException, IOException { System.out.println("Starting Descriptions: " + descriptionsFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(descriptionsFile), "UTF8")); int descriptionsCount = 0; try { String line = br.readLine(); line = br.readLine(); // Skip header boolean act; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); LightDescription loopDescription = new LightDescription(); loopDescription.setDescriptionId(Long.parseLong(columns[0])); act = columns[2].equals("1"); loopDescription.setActive(act); loopDescription.setEffectiveTime(columns[1]); Long sourceId = Long.parseLong(columns[4]); loopDescription.setConceptId(sourceId); loopDescription.setType(Long.parseLong(columns[6])); loopDescription.setTerm(columns[7]); loopDescription.setIcs(Long.parseLong(columns[8])); loopDescription.setModule(Long.parseLong(columns[3])); loopDescription.setLang(columns[5]); List<LightDescription> list = descriptions.get(sourceId); if (list == null) { list = new ArrayList<LightDescription>(); } list.add(loopDescription); descriptions.put(sourceId, list); line = br.readLine(); descriptionsCount++; if (descriptionsCount % 100000 == 0) { System.out.print("."); } } System.out.println("."); System.out.println("Descriptions loaded = " + descriptions.size()); } finally { br.close(); } } public void completeDefaultTerm(){ boolean act; String type; String lang; ConceptDescriptor cdesc; for (Long sourceId:concepts.keySet()){ List<LightDescription> lDescriptions = descriptions.get(sourceId); if (lDescriptions!=null){ for (LightDescription desc:lDescriptions){ act=desc.getActive(); type=String.valueOf(desc.getType()); lang=desc.getLang(); if (act && type.equals("900000000000003001") && lang.equals("en")) { cdesc = concepts.get(sourceId); if (cdesc != null && (cdesc.getDefaultTerm() == null || cdesc.getDefaultTerm().isEmpty())) { cdesc.setDefaultTerm(desc.getTerm()); } if (getDefaultTermType()!=fsnType){ if (!cptFSN.containsKey(sourceId)){ cptFSN.put(sourceId, desc.getTerm()); } } } else if (act && type.equals(defaultTermType) && lang.equals(defaultLangCode)) { cdesc = concepts.get(sourceId); if (cdesc != null) { cdesc.setDefaultTerm(desc.getTerm()); } } if (getDefaultTermType()!=fsnType && act && type.equals("900000000000003001") && lang.equals(defaultLangCode)){ cptFSN.put(sourceId, desc.getTerm()); } } } } } public void loadTextDefinitionFile(File textDefinitionFile) throws FileNotFoundException, IOException { System.out.println("Starting Text Definitions: " + textDefinitionFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(textDefinitionFile), "UTF8")); int descriptionsCount = 0; try { String line = br.readLine(); line = br.readLine(); // Skip header boolean act; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); LightDescription loopDescription = new LightDescription(); loopDescription.setDescriptionId(Long.parseLong(columns[0])); act = columns[2].equals("1"); loopDescription.setActive(act); loopDescription.setEffectiveTime(columns[1]); Long sourceId = Long.parseLong(columns[4]); loopDescription.setConceptId(sourceId); loopDescription.setType(Long.parseLong(columns[6])); loopDescription.setTerm(columns[7]); loopDescription.setIcs(Long.parseLong(columns[8])); loopDescription.setModule(Long.parseLong(columns[3])); loopDescription.setLang(columns[5]); List<LightDescription> list = tdefMembers.get(sourceId); if (list == null) { list = new ArrayList<LightDescription>(); } list.add(loopDescription); tdefMembers.put(sourceId, list); line = br.readLine(); descriptionsCount++; if (descriptionsCount % 100000 == 0) { System.out.print("."); } } System.out.println("."); System.out.println("Text Definitions loaded = " + tdefMembers.size()); } finally { br.close(); } } public void loadRelationshipsFile(File relationshipsFile) throws FileNotFoundException, IOException { System.out.println("Starting Relationships: " + relationshipsFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(relationshipsFile), "UTF8")); try { String line = br.readLine(); line = br.readLine(); // Skip header int count = 0; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); LightRelationship loopRelationship = new LightRelationship(); loopRelationship.setActive(columns[2].equals("1")); loopRelationship.setEffectiveTime(columns[1]); loopRelationship.setModule(Long.parseLong(columns[3])); Long targetId=Long.parseLong(columns[5]); loopRelationship.setTarget(targetId); Long type=Long.parseLong(columns[7]); loopRelationship.setType(type); loopRelationship.setModifier(Long.parseLong(columns[9])); loopRelationship.setGroupId(Integer.parseInt(columns[6])); Long sourceId = Long.parseLong(columns[4]); loopRelationship.setSourceId(sourceId); Long charType=Long.parseLong(columns[8]); loopRelationship.setCharType(charType); List<LightRelationship> relList = relationships.get(sourceId); if (relList == null) { relList = new ArrayList<LightRelationship>(); } relList.add(loopRelationship); relationships.put(sourceId, relList); if (columns[2].equals("1") && type==isaSCTId){ if ( charType==inferred){ notLeafInferred.add(targetId); }else{ notLeafStated.add(targetId); } } line = br.readLine(); count++; if (count % 100000 == 0) { System.out.print("."); } } System.out.println("."); System.out.println("Relationships loaded = " + relationships.size()); } finally { br.close(); } } public void loadSimpleRefsetFile(File simpleRefsetFile) throws FileNotFoundException, IOException { System.out.println("Starting Simple Refset Members: " + simpleRefsetFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(simpleRefsetFile), "UTF8")); try { String line = br.readLine(); line = br.readLine(); // Skip header int count = 0; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); if (columns[2].equals("1")) { LightRefsetMembership loopMember = new LightRefsetMembership(); loopMember.setType(LightRefsetMembership.RefsetMembershipType.SIMPLE_REFSET.name()); loopMember.setUuid(UUID.fromString(columns[0])); loopMember.setActive(columns[2].equals("1")); loopMember.setEffectiveTime(columns[1]); loopMember.setModule(Long.parseLong(columns[3])); Long sourceId = Long.parseLong(columns[5]); loopMember.setReferencedComponentId(sourceId); loopMember.setRefset(Long.parseLong(columns[4])); List<LightRefsetMembership> list = simpleMembers.get(sourceId); if (list == null) { list = new ArrayList<LightRefsetMembership>(); } list.add(loopMember); simpleMembers.put(Long.parseLong(columns[5]), list); count++; if (count % 100000 == 0) { System.out.print("."); } } line = br.readLine(); } System.out.println("."); System.out.println("SimpleRefsetMember loaded = " + simpleMembers.size()); } finally { br.close(); } } public void loadAssociationFile(File associationsFile) throws FileNotFoundException, IOException { System.out.println("Starting Association Refset Members: " + associationsFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(associationsFile), "UTF8")); try { String line = br.readLine(); line = br.readLine(); // Skip header int count = 0; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); if (columns[2].equals("1")) { LightRefsetMembership loopMember = new LightRefsetMembership(); loopMember.setType(LightRefsetMembership.RefsetMembershipType.ASSOCIATION.name()); loopMember.setUuid(UUID.fromString(columns[0])); loopMember.setActive(columns[2].equals("1")); loopMember.setEffectiveTime(columns[1]); loopMember.setModule(Long.parseLong(columns[3])); Long sourceId = Long.parseLong(columns[5]); loopMember.setReferencedComponentId(sourceId); loopMember.setRefset(Long.parseLong(columns[4])); loopMember.setCidValue(Long.parseLong(columns[6])); List<LightRefsetMembership> list = assocMembers.get(sourceId); if (list == null) { list = new ArrayList<LightRefsetMembership>(); } list.add(loopMember); assocMembers.put(Long.parseLong(columns[5]), list); count++; if (count % 100000 == 0) { System.out.print("."); } } line = br.readLine(); } System.out.println("."); System.out.println("AssociationMember loaded = " + assocMembers.size()); } finally { br.close(); } } public void loadAttributeFile(File attributeFile) throws FileNotFoundException, IOException { System.out.println("Starting Attribute Refset Members: " + attributeFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(attributeFile), "UTF8")); try { String line = br.readLine(); line = br.readLine(); // Skip header int count = 0; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); if (columns[2].equals("1")) { LightRefsetMembership loopMember = new LightRefsetMembership(); loopMember.setType(LightRefsetMembership.RefsetMembershipType.ATTRIBUTE_VALUE.name()); loopMember.setUuid(UUID.fromString(columns[0])); loopMember.setActive(columns[2].equals("1")); loopMember.setEffectiveTime(columns[1]); loopMember.setModule(Long.parseLong(columns[3])); Long sourceId = Long.parseLong(columns[5]); loopMember.setReferencedComponentId(sourceId); loopMember.setRefset(Long.parseLong(columns[4])); loopMember.setCidValue(Long.parseLong(columns[6])); List<LightRefsetMembership> list = attrMembers.get(sourceId); if (list == null) { list = new ArrayList<LightRefsetMembership>(); } list.add(loopMember); attrMembers.put(Long.parseLong(columns[5]), list); count++; if (count % 100000 == 0) { System.out.print("."); } } line = br.readLine(); } System.out.println("."); System.out.println("AttributeMember loaded = " + attrMembers.size()); } finally { br.close(); } } public void loadSimpleMapRefsetFile(File simpleMapRefsetFile) throws FileNotFoundException, IOException { System.out.println("Starting SimpleMap Refset Members: " + simpleMapRefsetFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(simpleMapRefsetFile), "UTF8")); try { String line = br.readLine(); line = br.readLine(); // Skip header int count = 0; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); if (columns[2].equals("1")) { LightRefsetMembership loopMember = new LightRefsetMembership(); loopMember.setType(LightRefsetMembership.RefsetMembershipType.SIMPLEMAP.name()); loopMember.setUuid(UUID.fromString(columns[0])); loopMember.setActive(columns[2].equals("1")); loopMember.setEffectiveTime(columns[1]); loopMember.setModule(Long.parseLong(columns[3])); Long sourceId = Long.parseLong(columns[5]); loopMember.setReferencedComponentId(sourceId); loopMember.setRefset(Long.parseLong(columns[4])); loopMember.setOtherValue(columns[6]); List<LightRefsetMembership> list = simpleMapMembers.get(sourceId); if (list == null) { list = new ArrayList<LightRefsetMembership>(); } list.add(loopMember); simpleMapMembers.put(sourceId, list); count++; if (count % 100000 == 0) { System.out.print("."); } } line = br.readLine(); } System.out.println("."); System.out.println("SimpleMap RefsetMember loaded = " + simpleMapMembers.size()); } finally { br.close(); } } public void loadLanguageRefsetFile(File languageRefsetFile) throws FileNotFoundException, IOException { System.out.println("Starting Language Refset Members: " + languageRefsetFile.getName()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(languageRefsetFile), "UTF8")); try { String line = br.readLine(); line = br.readLine(); // Skip header int count = 0; while (line != null) { if (line.isEmpty()) { continue; } String[] columns = line.split("\\t"); if (columns[2].equals("1")) { LightLangMembership loopMember = new LightLangMembership(); loopMember.setUuid(UUID.fromString(columns[0])); loopMember.setActive(columns[2].equals("1")); loopMember.setEffectiveTime(columns[1]); loopMember.setModule(Long.parseLong(columns[3])); Long sourceId = Long.parseLong(columns[5]); loopMember.setDescriptionId(sourceId); loopMember.setRefset(Long.parseLong(columns[4])); loopMember.setAcceptability(Long.parseLong(columns[6])); List<LightLangMembership> list = languageMembers.get(sourceId); if (list == null) { list = new ArrayList<LightLangMembership>(); } list.add(loopMember); languageMembers.put(sourceId, list); count++; if (count % 100000 == 0) { System.out.print("."); } } line = br.readLine(); } System.out.println("."); System.out.println("LanguageMembers loaded = " + languageMembers.size()); } finally { br.close(); } } public void createConceptsJsonFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException, IOException { System.out.println("Starting creation of " + fileName); FileOutputStream fos = new FileOutputStream(fileName); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); BufferedWriter bw = new BufferedWriter(osw); Gson gson = new Gson(); List<LightDescription> listLD = new ArrayList<LightDescription>(); List<Description> listD = new ArrayList<Description>(); List<LightLangMembership> listLLM = new ArrayList<LightLangMembership>(); List<LangMembership> listLM = new ArrayList<LangMembership>(); List<LightRelationship> listLR = new ArrayList<LightRelationship>(); List<Relationship> listR = new ArrayList<Relationship>(); List<LightRefsetMembership> listLRM = new ArrayList<LightRefsetMembership>(); List<RefsetMembership> listRM = new ArrayList<RefsetMembership>(); // int count = 0; for (Long cptId : concepts.keySet()) { // count++; //if (count > 10) break; Concept cpt = new Concept(); ConceptDescriptor cptdesc = concepts.get(cptId); cpt.setConceptId(cptId); cpt.setActive(cptdesc.getActive()); cpt.setDefaultTerm(cptdesc.getDefaultTerm()); cpt.setEffectiveTime(cptdesc.getEffectiveTime()); cpt.setModule(cptdesc.getModule()); cpt.setDefinitionStatus(cptdesc.getDefinitionStatus()); cpt.setIsLeafInferred( (notLeafInferred.contains(cptId)? 0:1)); cpt.setIsLeafStated( (notLeafStated.contains(cptId)? 0:1)); listLD = descriptions.get(cptId); listD = new ArrayList<Description>(); if (listLD != null) { Long descId; for (LightDescription ldesc : listLD) { Description d = new Description(); d.setActive(ldesc.getActive()); d.setConceptId(ldesc.getConceptId()); descId = ldesc.getDescriptionId(); d.setDescriptionId(descId); d.setEffectiveTime(ldesc.getEffectiveTime()); d.setIcs(concepts.get(ldesc.getIcs())); d.setTerm(ldesc.getTerm()); d.setLength(ldesc.getTerm().length()); d.setModule(ldesc.getModule()); d.setType(concepts.get(ldesc.getType())); d.setLang(ldesc.getLang()); listLLM = languageMembers.get(descId); listLM = new ArrayList<LangMembership>(); if (listLLM != null) { for (LightLangMembership llm : listLLM) { LangMembership lm = new LangMembership(); lm.setActive(llm.getActive()); lm.setDescriptionId(descId); lm.setEffectiveTime(llm.getEffectiveTime()); lm.setModule(llm.getModule()); lm.setAcceptability(concepts.get(llm.getAcceptability())); lm.setRefset(concepts.get(llm.getRefset())); lm.setUuid(llm.getUuid()); listLM.add(lm); } if (listLM.isEmpty()) { d.setLangMemberships(null); } else { d.setLangMemberships(listLM); } } listLRM = attrMembers.get(descId); listRM = new ArrayList<RefsetMembership>(); if (listLRM != null) { for (LightRefsetMembership lrm : listLRM) { RefsetMembership rm = new RefsetMembership(); rm.setEffectiveTime(lrm.getEffectiveTime()); rm.setActive(lrm.getActive()); rm.setModule(lrm.getModule()); rm.setUuid(lrm.getUuid()); rm.setReferencedComponentId(descId); rm.setRefset(concepts.get(lrm.getRefset())); rm.setType(lrm.getType()); rm.setCidValue(concepts.get(lrm.getCidValue())); listRM.add(rm); } if (listRM.isEmpty()){ d.setRefsetMemberships(null); }else{ d.setRefsetMemberships(listRM); } }else{ d.setRefsetMemberships(null); } listD.add(d); } } listLD = tdefMembers.get(cptId); if (listLD != null) { Long descId; for (LightDescription ldesc : listLD) { Description d = new Description(); d.setActive(ldesc.getActive()); d.setConceptId(ldesc.getConceptId()); descId = ldesc.getDescriptionId(); d.setDescriptionId(descId); d.setEffectiveTime(ldesc.getEffectiveTime()); d.setIcs(concepts.get(ldesc.getIcs())); d.setTerm(ldesc.getTerm()); d.setLength(ldesc.getTerm().length()); d.setModule(ldesc.getModule()); d.setType(concepts.get(ldesc.getType())); d.setLang(ldesc.getLang()); listLLM = languageMembers.get(descId); listLM = new ArrayList<LangMembership>(); if (listLLM != null) { for (LightLangMembership llm : listLLM) { LangMembership lm = new LangMembership(); lm.setActive(llm.getActive()); lm.setDescriptionId(descId); lm.setEffectiveTime(llm.getEffectiveTime()); lm.setModule(llm.getModule()); lm.setAcceptability(concepts.get(llm.getAcceptability())); lm.setRefset(concepts.get(llm.getRefset())); lm.setUuid(llm.getUuid()); listLM.add(lm); } if (listLM.isEmpty()) { d.setLangMemberships(null); } else { d.setLangMemberships(listLM); } } listD.add(d); } } if (listD!=null && !listD.isEmpty()){ cpt.setDescriptions(listD); } else { cpt.setDescriptions(null); } listLR = relationships.get(cptId); listR = new ArrayList<Relationship>(); if (listLR != null) { for (LightRelationship lrel : listLR) { if (lrel.getCharType().equals(900000000000010007L)) { Relationship d = new Relationship(); d.setEffectiveTime(lrel.getEffectiveTime()); d.setActive(lrel.getActive()); d.setModule(lrel.getModule()); d.setGroupId(lrel.getGroupId()); d.setModifier(MODIFIER); d.setSourceId(cptId); d.setTarget(concepts.get(lrel.getTarget())); d.setType(concepts.get(lrel.getType())); d.setCharType(concepts.get(lrel.getCharType())); listR.add(d); } } if (listR.isEmpty()) { cpt.setStatedRelationships(null); } else { cpt.setStatedRelationships(listR); } } else { cpt.setStatedRelationships(null); } listLR = relationships.get(cptId); listR = new ArrayList<Relationship>(); if (listLR != null) { for (LightRelationship lrel : listLR) { if (lrel.getCharType().equals(900000000000011006L)) { Relationship d = new Relationship(); d.setEffectiveTime(lrel.getEffectiveTime()); d.setActive(lrel.getActive()); d.setModule(lrel.getModule()); d.setGroupId(lrel.getGroupId()); d.setModifier(MODIFIER); d.setSourceId(cptId); d.setTarget(concepts.get(lrel.getTarget())); d.setType(concepts.get(lrel.getType())); d.setCharType(concepts.get(lrel.getCharType())); listR.add(d); } } if (listR.isEmpty()) { cpt.setRelationships(null); } else { cpt.setRelationships(listR); } } else { cpt.setRelationships(null); } listLRM = simpleMembers.get(cptId); listRM = new ArrayList<RefsetMembership>(); if (listLRM != null) { for (LightRefsetMembership lrm : listLRM) { RefsetMembership d = new RefsetMembership(); d.setEffectiveTime(lrm.getEffectiveTime()); d.setActive(lrm.getActive()); d.setModule(lrm.getModule()); d.setUuid(lrm.getUuid()); d.setReferencedComponentId(cptId); d.setRefset(concepts.get(lrm.getRefset())); d.setType(lrm.getType()); listRM.add(d); } } listLRM = simpleMapMembers.get(cptId); if (listLRM != null) { for (LightRefsetMembership lrm : listLRM) { RefsetMembership d = new RefsetMembership(); d.setEffectiveTime(lrm.getEffectiveTime()); d.setActive(lrm.getActive()); d.setModule(lrm.getModule()); d.setUuid(lrm.getUuid()); d.setReferencedComponentId(cptId); d.setRefset(concepts.get(lrm.getRefset())); d.setType(lrm.getType()); d.setOtherValue(lrm.getOtherValue()); listRM.add(d); } } listLRM = assocMembers.get(cptId); if (listLRM != null) { for (LightRefsetMembership lrm : listLRM) { RefsetMembership d = new RefsetMembership(); d.setEffectiveTime(lrm.getEffectiveTime()); d.setActive(lrm.getActive()); d.setModule(lrm.getModule()); d.setUuid(lrm.getUuid()); d.setReferencedComponentId(cptId); d.setRefset(concepts.get(lrm.getRefset())); d.setType(lrm.getType()); d.setCidValue(concepts.get(lrm.getCidValue())); listRM.add(d); } } listLRM = attrMembers.get(cptId); if (listLRM != null) { for (LightRefsetMembership lrm : listLRM) { RefsetMembership d = new RefsetMembership(); d.setEffectiveTime(lrm.getEffectiveTime()); d.setActive(lrm.getActive()); d.setModule(lrm.getModule()); d.setUuid(lrm.getUuid()); d.setReferencedComponentId(cptId); d.setRefset(concepts.get(lrm.getRefset())); d.setType(lrm.getType()); d.setCidValue(concepts.get(lrm.getCidValue())); listRM.add(d); } } if (listRM.isEmpty()) { cpt.setMemberships(null); } else { cpt.setMemberships(listRM); } bw.append(gson.toJson(cpt).toString()); bw.append(sep); } bw.close(); System.out.println(fileName + " Done"); } public String getDefaultLangCode() { return defaultLangCode; } public void setDefaultLangCode(String defaultLangCode) { this.defaultLangCode = defaultLangCode; } private void createTClosure(String fileName,Long charType) throws IOException { System.out.println("Transitive Closure creation from " + fileName); FileOutputStream fos = new FileOutputStream(fileName); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); BufferedWriter bw = new BufferedWriter(osw); Gson gson = new Gson(); // int count = 0; for (Long cptId : concepts.keySet()) { listA = new ArrayList<Long>(); getAncestors(cptId,charType); if (!listA.isEmpty()){ ConceptAncestor ca=new ConceptAncestor(); ca.setConceptId(cptId); ca.setAncestor(listA); bw.append(gson.toJson(ca).toString()); bw.append(sep); } } bw.close(); System.out.println(fileName + " Done"); } private void getAncestors(Long cptId,Long charType) { List<LightRelationship> listLR = new ArrayList<LightRelationship>(); listLR = relationships.get(cptId); if (listLR != null) { for (LightRelationship lrel : listLR) { if (lrel.getCharType().equals(charType) && lrel.getType().equals(isaSCTId) && lrel.getActive()) { Long tgt=lrel.getTarget(); if (!listA.contains(tgt)){ listA.add(tgt); getAncestors(tgt,charType); } } } } return ; } public void createTextIndexFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException, IOException { getCharConvTable(); System.out.println("Starting creation of " + fileName); FileOutputStream fos = new FileOutputStream(fileName); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); BufferedWriter bw = new BufferedWriter(osw); Gson gson = new Gson(); // int count = 0; for (long conceptId : descriptions.keySet()) { // count++; //if (count > 10) break; for (LightDescription ldesc : descriptions.get(conceptId)) { TextIndexDescription d = new TextIndexDescription(); d.setActive(ldesc.getActive()); d.setTerm(ldesc.getTerm()); d.setLength(ldesc.getTerm().length()); d.setTypeId(ldesc.getType()); d.setConceptId(ldesc.getConceptId()); d.setDescriptionId(ldesc.getDescriptionId()); d.setModule(ldesc.getModule()); // using long lang names for Mongo 2.4.x text indexes d.setLang(langCodes.get(ldesc.getLang())); ConceptDescriptor concept = concepts.get(ldesc.getConceptId()); d.setConceptModule(concept.getModule()); d.setConceptActive(concept.getActive()); if (getDefaultTermType()!=fsnType){ String fsn= cptFSN.get(ldesc.getConceptId()); if (fsn!=null){ d.setFsn(fsn); } }else{ d.setFsn(concept.getDefaultTerm()); } if (d.getFsn() == null) { System.out.println("FSN Issue..." + d.getConceptId()); d.setFsn(d.getTerm()); } d.setSemanticTag(""); if (d.getFsn().endsWith(")")) { d.setSemanticTag(d.getFsn().substring(d.getFsn().lastIndexOf("(") + 1, d.getFsn().length() - 1)); } String cleanTerm = d.getTerm().replace("(", "").replace(")", "").trim().toLowerCase(); String convertedTerm=convertTerm(cleanTerm); String[] tokens = convertedTerm.toLowerCase().split("\\s+"); d.setWords(Arrays.asList(tokens)); bw.append(gson.toJson(d).toString()); bw.append(sep); } } bw.close(); System.out.println(fileName + " Done"); } private String convertTerm(String cleanTerm) { for (String code:charConv.keySet()){ String test="\\u" + code; String repl=charConv.get(code); cleanTerm=cleanTerm.replaceAll(test, repl); } return cleanTerm; } private void getCharConvTable() throws IOException { String charconvtable="src/main/resources/org/ihtsdo/util/char_conversion_table.txt"; BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(charconvtable), "UTF8")); br.readLine(); String line=null; charConv=new HashMap<String,String>(); while ((line=br.readLine())!=null){ String[] spl=line.split("\t",-1); String[]codes=spl[2].split(" "); for (String code:codes){ charConv.put(code,spl[0]); } } br.close(); System.gc(); } public String getDefaultTermType() { return defaultTermType; } public void setDefaultTermType(String defaultTermType) { this.defaultTermType = defaultTermType; } }
package com.yichiuan.common; import android.content.Context; import android.content.res.AssetManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import java.io.FileDescriptor; import java.io.IOException; import java.io.InputStream; public final class Bitmaps { public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); } public static Bitmap decodeSampledBitmapFromAssets(Context context, String filePath, int reqWidth, int reqHeight) throws IOException { final AssetManager assetManager = context.getAssets(); Bitmap bitmap = null; InputStream inputStream = null; try { inputStream = assetManager.open(filePath); // First decode with inJustDecodeBounds=true to check dimensions BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(inputStream, null, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; inputStream.reset(); bitmap = BitmapFactory.decodeStream(inputStream, null, options); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { ex.printStackTrace(); } } } return bitmap; } public static Bitmap decodeSampledBitmapFromFile(String filePath, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(filePath, options); } public static Bitmap decodeSampledBitmapFromInputStream(InputStream is, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeStream(is, null, options); } public static Bitmap decodeSampledBitmapFromFileDescriptor(FileDescriptor fd, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFileDescriptor(fd, null, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeFileDescriptor(fd, null, options); } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) { inSampleSize *= 2; } } return inSampleSize; } public static Bitmap rotateBitmap(Bitmap source, float degree) { Matrix matrix = new Matrix(); matrix.postRotate(degree); return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true); } }
package org.lightmare.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.lightmare.utils.StringUtils; /** * To define unit name of {@link javax.persistence.Entity} class * * @author Levan * @since 0.0.16-SNAPSHOT */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface UnitName { String value() default StringUtils.EMPTY_STRING; }
package com.intellij.codeInspection.ex; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInsight.daemon.InspectionProfileConvertor; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.WriteExternalException; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; /** * @author max */ public class InspectionProfileImpl implements InspectionProfile.ModifiableModel, InspectionProfile { public static final InspectionProfileImpl EMPTY_PROFILE = new InspectionProfileImpl("empty"); private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.ex.InspectionProfileImpl"); private static String VALID_VERSION = "1.0"; private String myName; private File myFile; //fiff from base // private HashMap<String, Boolean> myEnabledTools; private HashMap<String, InspectionTool> myTools = new HashMap<String, InspectionTool>(); private HashMap<String, LocalInspectionToolWrapper> myLocalTools = new HashMap<String, LocalInspectionToolWrapper>(); private InspectionProfileManager myManager; //diff map with base profile private LinkedHashMap<HighlightDisplayKey, ToolState> myDisplayLevelMap = new LinkedHashMap<HighlightDisplayKey, ToolState>(); private InspectionProfileImpl mySource; private InspectionProfileImpl myBaseProfile = null; //private String myBaseProfileName; public void setModified(final boolean modified) { myModified = modified; } private boolean myModified = false; private boolean myInitialized = false; private VisibleTreeState myVisibleTreeState = new VisibleTreeState(); private String myAdditionalJavadocTags = ""; public InspectionProfileImpl(File file, InspectionProfileManager manager) throws IOException, JDOMException { this(getProfileName(file), getBaseProfileName(file), file, manager); mySource = null; } public InspectionProfileImpl(String name, String baseProfileName, File file, InspectionProfileManager manager) { myName = name; myFile = file; myManager = manager; if (baseProfileName != null) { myBaseProfile = manager.getProfile(baseProfileName); if (myBaseProfile == null) {//was not init yet myBaseProfile = new InspectionProfileImpl(baseProfileName, manager); } } mySource = null; } public InspectionProfileImpl(String name, InspectionProfileManager manager) { myName = name; myFile = new File(InspectionProfileManager.getProfileDirectory(), myName + ".xml"); myManager = manager; mySource = null; } InspectionProfileImpl(InspectionProfileImpl inspectionProfile) { myName = inspectionProfile.getName(); myFile = inspectionProfile.getFile(); myManager = inspectionProfile.getManager(); myDisplayLevelMap = new LinkedHashMap<HighlightDisplayKey, ToolState>(inspectionProfile.myDisplayLevelMap); myLocalTools = new HashMap<String, LocalInspectionToolWrapper>(inspectionProfile.myLocalTools); myTools = new HashMap<String, InspectionTool>(inspectionProfile.myTools); myVisibleTreeState = new VisibleTreeState(inspectionProfile.myVisibleTreeState); myAdditionalJavadocTags = inspectionProfile.myAdditionalJavadocTags; myBaseProfile = inspectionProfile.myBaseProfile; mySource = inspectionProfile; } //for tests only public InspectionProfileImpl(final String inspectionProfile) { myName = inspectionProfile; myInitialized = true; setDefaultErrorLevels(); } public InspectionProfile getParentProfile() { return mySource; } public String getBaseProfileName() { if (myBaseProfile == null) return null; return myBaseProfile.getName(); } public void setBaseProfile(InspectionProfileImpl profile) { myBaseProfile = profile; } public void removeInheritance(boolean inheritFromBaseBase) { if (myBaseProfile != null) { LinkedHashMap<HighlightDisplayKey, ToolState> map = new LinkedHashMap<HighlightDisplayKey, ToolState>(); if (inheritFromBaseBase) { map.putAll(myBaseProfile.myDisplayLevelMap); myBaseProfile = myBaseProfile.myBaseProfile; } else { map.putAll(myBaseProfile.getFullDisplayMap()); myBaseProfile = null; } map.putAll(myDisplayLevelMap); myDisplayLevelMap = map; } } private HashMap<HighlightDisplayKey, ToolState> getFullDisplayMap() { final HashMap<HighlightDisplayKey, ToolState> map = new HashMap<HighlightDisplayKey, ToolState>(); if (myBaseProfile != null) { map.putAll(myBaseProfile.getFullDisplayMap()); } map.putAll(myDisplayLevelMap); return map; } public boolean isChanged() { return myModified; } public VisibleTreeState getExpandedNodes() { return myVisibleTreeState; } private boolean toolSettingsAreEqual(String toolDisplayName, InspectionProfileImpl profile1, InspectionProfileImpl profile2) { final InspectionTool tool1 = profile1.getInspectionTool(toolDisplayName);//findInspectionToolByName(profile1, toolDisplayName); final InspectionTool tool2 = profile2.getInspectionTool(toolDisplayName);//findInspectionToolByName(profile2, toolDisplayName); if (tool1 == null && tool2 == null) { return true; } if (tool1 != null && tool2 != null) { try { Element oldToolSettings = new Element("root"); tool1.writeExternal(oldToolSettings); Element newToolSettings = new Element("root"); tool2.writeExternal(newToolSettings); return JDOMUtil.areElementsEqual(oldToolSettings, newToolSettings); } catch (WriteExternalException e) { LOG.error(e); } } return false; } public boolean isProperSetting(HighlightDisplayKey key) { if (myBaseProfile == null) { return false; } final boolean toolsSettings = toolSettingsAreEqual(key.toString(), this, myBaseProfile); if (myDisplayLevelMap.keySet().contains(key)) { if (toolsSettings && myDisplayLevelMap.get(key).equals(myBaseProfile.getToolState(key))) { myDisplayLevelMap.remove(key); return false; } return true; } if (key == HighlightDisplayKey.UNKNOWN_JAVADOC_TAG && !myBaseProfile.getAdditionalJavadocTags().equals(getAdditionalJavadocTags())) { return true; } if (!toolsSettings) { myDisplayLevelMap.put(key, myBaseProfile.getToolState(key)); return true; } return false; } public void setAdditionalJavadocTags(String tags) { if (myBaseProfile != null && myBaseProfile.getAdditionalJavadocTags().length() > 0) { myAdditionalJavadocTags = tags.length() > myBaseProfile.getAdditionalJavadocTags().length() ? tags.substring(myBaseProfile.getAdditionalJavadocTags().length() + 1).trim() : ""; } else { myAdditionalJavadocTags = tags; } } public void resetToBase() { if (myBaseProfile != null) { myDisplayLevelMap = new LinkedHashMap<HighlightDisplayKey, ToolState>(myBaseProfile.myDisplayLevelMap); myBaseProfile = myBaseProfile.myBaseProfile; } else { boolean toolsWereNotInstantiated = false; if (myTools.isEmpty() || myLocalTools.isEmpty()) { getInspectionTools(null); toolsWereNotInstantiated = true; } myDisplayLevelMap.clear(); setDefaultErrorLevels(); final ArrayList<String> toolNames = new ArrayList<String>(myTools.keySet()); toolNames.addAll(myLocalTools.keySet()); for (Iterator<String> iterator = toolNames.iterator(); iterator.hasNext();) { final InspectionTool tool = getInspectionTool(iterator.next()); final HighlightDisplayLevel defaultLevel = tool.getDefaultLevel(); HighlightDisplayKey key = HighlightDisplayKey.find(tool.getShortName()); if (key == null) { key = HighlightDisplayKey.register(tool.getShortName()); } myDisplayLevelMap.put(key, new ToolState(defaultLevel, tool.isEnabledByDefault())); } if (toolsWereNotInstantiated) { //to instantiate tools correctly myTools.clear(); } } myInitialized = true; } private void setDefaultErrorLevels() { myDisplayLevelMap.put(HighlightDisplayKey.DEPRECATED_SYMBOL, new ToolState(HighlightDisplayLevel.WARNING)); myDisplayLevelMap.put(HighlightDisplayKey.UNUSED_IMPORT, new ToolState(HighlightDisplayLevel.WARNING)); myDisplayLevelMap.put(HighlightDisplayKey.UNUSED_SYMBOL, new ToolState(HighlightDisplayLevel.WARNING)); myDisplayLevelMap.put(HighlightDisplayKey.UNUSED_THROWS_DECL, new ToolState(HighlightDisplayLevel.WARNING)); myDisplayLevelMap.put(HighlightDisplayKey.SILLY_ASSIGNMENT, new ToolState(HighlightDisplayLevel.WARNING)); myDisplayLevelMap.put(HighlightDisplayKey.ACCESS_STATIC_VIA_INSTANCE, new ToolState(HighlightDisplayLevel.WARNING)); myDisplayLevelMap.put(HighlightDisplayKey.WRONG_PACKAGE_STATEMENT, new ToolState(HighlightDisplayLevel.WARNING)); myDisplayLevelMap.put(HighlightDisplayKey.JAVADOC_ERROR, new ToolState(HighlightDisplayLevel.ERROR)); myDisplayLevelMap.put(HighlightDisplayKey.UNKNOWN_JAVADOC_TAG, new ToolState(HighlightDisplayLevel.ERROR)); myDisplayLevelMap.put(HighlightDisplayKey.EJB_ERROR, new ToolState(HighlightDisplayLevel.ERROR)); myDisplayLevelMap.put(HighlightDisplayKey.EJB_WARNING, new ToolState(HighlightDisplayLevel.WARNING)); myDisplayLevelMap.put(HighlightDisplayKey.ILLEGAL_DEPENDENCY, new ToolState(HighlightDisplayLevel.WARNING)); myDisplayLevelMap.put(HighlightDisplayKey.UNCHECKED_WARNING, new ToolState(HighlightDisplayLevel.WARNING)); } public String getName() { return myName; } public void setName(String name) { myName = name; } public HighlightDisplayLevel getErrorLevel(HighlightDisplayKey inspectionToolKey) { return getToolState(inspectionToolKey).getLevel(); } private ToolState getToolState(HighlightDisplayKey key) { ToolState state = myDisplayLevelMap.get(key); if (state == null) { if (myBaseProfile != null) { state = myBaseProfile.getToolState(key); } } //default level for converted profiles if (state == null) { state = new ToolState(HighlightDisplayLevel.WARNING, false); } return state; } private void readExternal(Element element, boolean readLocalTools) throws InvalidDataException { myDisplayLevelMap.clear(); final String version = element.getAttributeValue("version"); if (version == null || !version.equals(VALID_VERSION)) { try { InspectionProfileConvertor.convertToNewFormat(myFile, this); element = JDOMUtil.loadDocument(myFile).getRootElement(); } catch (IOException e) { LOG.error(e); } catch (JDOMException e) { LOG.error(e); } } for (Iterator i = element.getChildren("inspection_tool").iterator(); i.hasNext();) { Element toolElement = (Element)i.next(); String toolClassName = toolElement.getAttributeValue("class"); HighlightDisplayKey key = HighlightDisplayKey.find(toolClassName); if (key == null) { key = HighlightDisplayKey.register(toolClassName); } final String levelName = toolElement.getAttributeValue("level"); HighlightDisplayLevel level = HighlightDisplayLevel.find(levelName); if (level == null || level == HighlightDisplayLevel.DO_NOT_SHOW) {//from old profiles level = HighlightDisplayLevel.WARNING; } final String enabled = toolElement.getAttributeValue("enabled"); myDisplayLevelMap.put(key, new ToolState(level, enabled != null && "true".equals(enabled))); InspectionTool tool = getInspectionTool(toolClassName); if (tool != null) { if (!(tool instanceof LocalInspectionToolWrapper) || readLocalTools) { tool.readExternal(toolElement); } } } myVisibleTreeState.readExternal(element); final Element additionalJavadocs = element.getChild("ADDITIONAL_JAVADOC_TAGS"); if (additionalJavadocs != null) { myAdditionalJavadocTags = additionalJavadocs.getAttributeValue("value"); } final String baseProfileName = element.getAttributeValue("base_profile"); if (baseProfileName != null && myBaseProfile == null) { myBaseProfile = InspectionProfileManager.getInstance().getProfile(baseProfileName); if (baseProfileName.equals("Default")) { myBaseProfile.resetToBase(); } if (!myBaseProfile.wasInitialized()) { myBaseProfile.load(readLocalTools); } } } public void writeExternal(Element element) throws WriteExternalException { element.setAttribute("version", VALID_VERSION); for (Iterator<HighlightDisplayKey> iterator = myDisplayLevelMap.keySet().iterator(); iterator.hasNext();) { final HighlightDisplayKey key = iterator.next(); Element inspectionElement = new Element("inspection_tool"); final String toolName = key.toString(); inspectionElement.setAttribute("class", toolName); inspectionElement.setAttribute("level", getErrorLevel(key).toString()); inspectionElement.setAttribute("enabled", isToolEnabled(key) ? "true" : "false"); final InspectionTool tool = getInspectionTool(toolName); if (tool != null) { tool.writeExternal(inspectionElement); } element.addContent(inspectionElement); } myVisibleTreeState.writeExternal(element); if (myAdditionalJavadocTags != null && myAdditionalJavadocTags.length() != 0) { final Element additionalTags = new Element("ADDITIONAL_JAVADOC_TAGS"); additionalTags.setAttribute("value", myAdditionalJavadocTags); element.addContent(additionalTags); } if (myBaseProfile != null) { element.setAttribute("base_profile", myBaseProfile.getName()); } } public InspectionTool getInspectionTool(String shortName) { if (myTools.get(shortName) != null) { return myTools.get(shortName); } if (myLocalTools.get(shortName) != null) { return myLocalTools.get(shortName); } return null; } public InspectionProfileManager getManager() { return myManager; } private static String getProfileName(File file) throws JDOMException, IOException { if (file.exists()) { Document doc = JDOMUtil.loadDocument(file); Element root = doc.getRootElement(); String profileName = root.getAttributeValue("profile_name"); if (profileName != null) return profileName; } String fileName = file.getName(); int extensionIndex = fileName.lastIndexOf(".xml"); return fileName.substring(0, extensionIndex); } private static String getBaseProfileName(File file) throws JDOMException, IOException { if (file.exists()) { Document doc = JDOMUtil.loadDocument(file); Element root = doc.getRootElement(); String profileName = root.getAttributeValue("base_profile"); if (profileName != null) return profileName; } return null; } void save(File file, String name) { try { Element root = new Element("inspections"); root.setAttribute("profile_name", name); writeExternal(root); if (file != null) { JDOMUtil.writeDocument(new Document(root), file, CodeStyleSettingsManager.getSettings(null).getLineSeparator()); } } catch (WriteExternalException e) { LOG.error(e); } catch (IOException e) { LOG.error(e); } } public void load(boolean readLocalTools) { try { if (myName.equals("Default")) { resetToBase(); return; } if (myFile == null || !myFile.exists()) { if (myBaseProfile != null) { loadAdditionalSettingsFromBaseProfile(); } return; } Document document = JDOMUtil.loadDocument(myFile); readExternal(document.getRootElement(), readLocalTools); myInitialized = true; } catch (JDOMException e) { LOG.error(e); } catch (IOException e) { LOG.error(e); } catch (InvalidDataException e) { LOG.error(e); } } public void loadAdditionalSettingsFromBaseProfile() {//load additional settings from base profile if (myBaseProfile == null) return; try { final ArrayList<String> toolNames = new ArrayList<String>(myTools.keySet()); toolNames.addAll(myLocalTools.keySet()); for (Iterator<String> iterator = toolNames.iterator(); iterator.hasNext();) { final String key = iterator.next(); if (myDisplayLevelMap.containsKey(HighlightDisplayKey.find(key))) { continue; } Element root = new Element("root"); final InspectionTool baseInspectionTool = myBaseProfile.getInspectionTool(key); if (baseInspectionTool != null) { baseInspectionTool.writeExternal(root); InspectionTool tool = getInspectionTool(key); tool.readExternal(root); } } } catch (WriteExternalException e) { LOG.error(e); } catch (InvalidDataException e) { LOG.error(e); } } public File getFile() { return myFile; } public InspectionTool[] getInspectionTools(Project project) { if (myBaseProfile != null && myBaseProfile.myTools.isEmpty()) { myBaseProfile.getInspectionTools(project); } if (myTools.isEmpty()) { boolean localToolsWereInitialized = true; final InspectionTool[] tools = InspectionToolRegistrar.getInstance().createTools(project); for (int i = 0; i < tools.length; i++) { if (!(tools[i] instanceof LocalInspectionToolWrapper)) { myTools.put(tools[i].getShortName(), tools[i]); } else { if (!myLocalTools.containsKey(tools[i].getShortName())) {//do not touch exist local tools localToolsWereInitialized = false; myLocalTools.put(tools[i].getShortName(), (LocalInspectionToolWrapper)tools[i]); } } } load(!localToolsWereInitialized); loadAdditionalSettingsFromBaseProfile(); } ArrayList<InspectionTool> result = new ArrayList<InspectionTool>(); result.addAll(myLocalTools.values()); result.addAll(myTools.values()); return result.toArray(new InspectionTool[result.size()]); } public LocalInspectionToolWrapper[] getLocalInspectionToolWrappers() { if (myBaseProfile != null && myBaseProfile.myLocalTools.isEmpty()) { myBaseProfile.getLocalInspectionToolWrappers(); } if (myLocalTools.isEmpty()) { final LocalInspectionTool[] localTools = InspectionToolRegistrar.getInstance().createLocalTools(); for (int i = 0; i < localTools.length; i++) { myLocalTools.put(localTools[i].getShortName(), new LocalInspectionToolWrapper(localTools[i])); } load(true); loadAdditionalSettingsFromBaseProfile(); } return myLocalTools.values().toArray(new LocalInspectionToolWrapper[myLocalTools.values().size()]); } public LocalInspectionTool[] getHighlightingLocalInspectionTools() { ArrayList<LocalInspectionTool> enabled = new ArrayList<LocalInspectionTool>(); final LocalInspectionToolWrapper[] tools = myLocalTools.isEmpty() ? getLocalInspectionToolWrappers() : myLocalTools.values().toArray( new LocalInspectionToolWrapper[myLocalTools.values().size()]); for (int i = 0; i < tools.length; i++) { LocalInspectionToolWrapper tool = tools[i]; final ToolState state = getToolState(HighlightDisplayKey.find(tool.getShortName())); if (state.isEnabled()) { enabled.add(tool.getTool()); } } return enabled.toArray(new LocalInspectionTool[enabled.size()]); } public ModifiableModel getModifiableModel() { return new InspectionProfileImpl(this); } public String getAdditionalJavadocTags() { if (myBaseProfile != null) { return myBaseProfile.getAdditionalJavadocTags().length() > 0 ? myBaseProfile.getAdditionalJavadocTags() + (myAdditionalJavadocTags.length() > 0 ? "," + myAdditionalJavadocTags : "") : myAdditionalJavadocTags; } return myAdditionalJavadocTags; } public void copyFrom(InspectionProfileImpl profile) { myDisplayLevelMap = new LinkedHashMap<HighlightDisplayKey, ToolState>(profile.myDisplayLevelMap); myBaseProfile = profile.myBaseProfile; myAdditionalJavadocTags = profile.myAdditionalJavadocTags; copyToolsConfigurations(profile); } public void inheritFrom(InspectionProfileImpl profile) { myBaseProfile = profile; copyToolsConfigurations(profile); } private void copyToolsConfigurations(InspectionProfileImpl profile) { try { if (!profile.myTools.isEmpty()) { final Project project = profile.myTools.get(0).getManager().getProject(); final InspectionTool[] inspectionTools = getInspectionTools(project); for (int i = 0; i < inspectionTools.length; i++) { readAndWriteToolsConfigs(inspectionTools[i], profile); } return; } //only local tools were initialized final LocalInspectionToolWrapper[] localInspectionToolWrappers = getLocalInspectionToolWrappers(); for (int i = 0; i < localInspectionToolWrappers.length; i++) { readAndWriteToolsConfigs(localInspectionToolWrappers[i], profile); } } catch (WriteExternalException e) { LOG.error(e); } catch (InvalidDataException e) { LOG.error(e); } } private void readAndWriteToolsConfigs(final InspectionTool inspectionTool, final InspectionProfileImpl profile) throws WriteExternalException, InvalidDataException { final String name = inspectionTool.getShortName(); Element config = new Element("config"); final InspectionTool tool = profile.getInspectionTool(name); if (tool != null){ tool.writeExternal(config); inspectionTool.readExternal(config); addInspectionTool(inspectionTool); } } private void addInspectionTool(InspectionTool inspectionTool){ if (inspectionTool instanceof LocalInspectionToolWrapper){ myLocalTools.put(inspectionTool.getShortName(), (LocalInspectionToolWrapper)inspectionTool); } else { myTools.put(inspectionTool.getShortName(), inspectionTool); } } public void cleanup() { if (myTools.isEmpty()) return; if (!myTools.isEmpty()) { for (Iterator<String> iterator = myTools.keySet().iterator(); iterator.hasNext();) { myTools.get(iterator.next()).cleanup(); } } if (!myLocalTools.isEmpty()) { for (Iterator<String> iterator = myLocalTools.keySet().iterator(); iterator.hasNext();) { myLocalTools.get(iterator.next()).cleanup(); } } myTools.clear(); } public boolean wasInitialized() { return myInitialized; } public void enableTool(String inspectionTool) { final HighlightDisplayKey key = HighlightDisplayKey.find(inspectionTool); setState(key, new ToolState(getErrorLevel(key), true)); } public void disableTool(String inspectionTool) { final HighlightDisplayKey key = HighlightDisplayKey.find(inspectionTool); setState(key, new ToolState(getErrorLevel(key), false)); } public void setErrorLevel(HighlightDisplayKey key, HighlightDisplayLevel level) { setState(key, new ToolState(level, isToolEnabled(key))); } private void setState(HighlightDisplayKey key, ToolState state) { if (myBaseProfile != null && state.equals(myBaseProfile.getToolState(key))) { myDisplayLevelMap.remove(key); } else { myDisplayLevelMap.put(key, state); } } public boolean isToolEnabled(HighlightDisplayKey key) { final ToolState toolState = getToolState(key); if (toolState != null) { return toolState.isEnabled(); } return false; } //invoke when isChanged() == true public void commit() { LOG.assertTrue(mySource != null); mySource.commit(this); mySource = null; myManager.initProfile(this); } private void commit(InspectionProfileImpl inspectionProfile) { myName = inspectionProfile.myName; myDisplayLevelMap = inspectionProfile.myDisplayLevelMap; myVisibleTreeState = inspectionProfile.myVisibleTreeState; myBaseProfile = inspectionProfile.myBaseProfile; myTools = inspectionProfile.myTools; myLocalTools = inspectionProfile.myLocalTools; myAdditionalJavadocTags = inspectionProfile.myAdditionalJavadocTags; save(new File(InspectionProfileManager.getProfileDirectory(), myName + ".xml"), myName); } private static class ToolState { private HighlightDisplayLevel myLevel; private boolean myEnabled; public ToolState(final HighlightDisplayLevel level, final boolean enabled) { myLevel = level; myEnabled = enabled; } public ToolState(final HighlightDisplayLevel level) { myLevel = level; myEnabled = true; } public HighlightDisplayLevel getLevel() { return myLevel; } public void setLevel(final HighlightDisplayLevel level) { myLevel = level; } public boolean isEnabled() { return myEnabled; } public void setEnabled(final boolean enabled) { myEnabled = enabled; } public boolean equals(Object object) { if (!(object instanceof ToolState)) return false; final ToolState state = (ToolState)object; return myLevel == state.getLevel() && myEnabled == state.isEnabled(); } public int hashCode() { return myLevel.hashCode(); } } }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.IOUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.yaml.snakeyaml.Yaml; /** * Retrieves and caches configuration properties from configuration file or from * {@link org.lightmare.deploy.MetaCreator.Builder} instance * * @author levan * @since 0.0.21-SNAPSHOT */ public class Configuration implements Cloneable { // Cache for all configuration passed from API or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); // Runtime to get available processors private static final Runtime RUNTIME = Runtime.getRuntime(); // Resource path (META-INF) private static final String META_INF_PATH = "META-INF/"; // Error messages private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration"; private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file"; private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist"; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } /** * Gets value on passed generic key K of passed {@link Map} as {@link Map} * of generic key values * * @param key * @param from * @return {@link Map}<code><K, V></code> */ private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } Map<K, V> value = ObjectUtils.cast(CollectionUtils.getAsMap(key, from)); return value; } /** * Gets value on passed generic key K of cached configuration as {@link Map} * of generic key values * * @param key * @return {@link Map}<code><K, V></code> */ private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } /** * Sets value of sub {@link Map} on passed sub key contained in cached * configuration on passed key * * @param key * @param subKey * @param value */ private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } /** * Gets value of sub {@link Map} on passed sub key contained in cached * configuration on passed key * * @param key * @param subKey * @param defaultValue * @return V */ private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (CollectionUtils.valid(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } /** * Check if sub {@link Map} contains passed sub key contained in cached * configuration on passed key * * @param key * @param subKey * @return <code>boolean</code> */ private <K> boolean containsSubConfigKey(Object key, K subKey) { boolean valid; Map<K, ?> subConfig = getAsMap(key); valid = CollectionUtils.valid(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(ConfigKeys.DEPLOY_CONFIG.key, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration if value is null then returns passed default value * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.PERSISTENCE_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.PERSISTENCE_CONFIG.key, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.POOL_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuration * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.POOL_CONFIG.key, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES.key); if (CollectionUtils.valid(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(ConfigKeys.POOL_PROVIDER_TYPE.key); if (StringUtils.valid(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES_PATH.key); if (StringUtils.valid(path)) { setPoolPropertiesPath(path); } } private <K, V> void setIfContains(K key, V value) { boolean contains = containsConfigKey(key); if (ObjectUtils.notTrue(contains)) { setConfigValue(key, value); } } /** * Configures server from properties and default values */ private void configureServer() { // Sets default values to remote server configuration setIfContains(ConfigKeys.IP_ADDRESS.key, ConfigKeys.IP_ADDRESS.value); setIfContains(ConfigKeys.PORT.key, ConfigKeys.PORT.value); setIfContains(ConfigKeys.BOSS_POOL.key, ConfigKeys.BOSS_POOL.value); boolean contains = containsConfigKey(ConfigKeys.WORKER_POOL.key); if (ObjectUtils.notTrue(contains)) { int defaultWorkers = ConfigKeys.WORKER_POOL.getValue(); int workers = (RUNTIME.availableProcessors() * defaultWorkers); String workerProperty = String.valueOf(workers); setConfigValue(ConfigKeys.WORKER_POOL.key, workerProperty); } setIfContains(ConfigKeys.CONNECTION_TIMEOUT.key, ConfigKeys.CONNECTION_TIMEOUT.value); } /** * Merges configuration with default properties */ public void configureDeployments() { // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); if (hotDeployment == null) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = ConfigKeys.DEMPLOYMENT_PATH.getValue(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } // Sets remote control check Boolean remoteControl = getConfigValue(ConfigKeys.REMOTE_CONTROL.key); if (ObjectUtils.notNull(remoteControl)) { setRemoteControl(remoteControl); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return <code>{@link Map}<Object, Object></code> */ protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Map<Object, Object> mapValue2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = CollectionUtils.getAsMap(key, map1); mapValue2 = ObjectUtils.cast(value2); mergedValue = deepMerge(value1, mapValue2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { Map<Object, Object> innerConfig = ObjectUtils .cast(configuration); configure(innerConfig); } } finally { IOUtils.close(stream); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { String textValue; Object value = config.get(key); if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) throws IOException { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } } catch (IOException ex) { LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex); } finally { IOUtils.close(propertiesStream); } } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { String configFilePath = ConfigKeys.CONFIG_FILE.getValue(); try { File configFile = new File(configFilePath); if (configFile.exists()) { InputStream propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { try { InputStream propertiesStream = new FileInputStream(new File( configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) throws IOException { InputStream resourceStream = loader.getResourceAsStream(StringUtils .concat(META_INF_PATH, resourceName)); if (resourceStream == null) { LOG.error(RESOURCE_NOT_EXISTS_ERROR); } else { loadFromStream(resourceStream); } } public static String getAdminUsersPath() { return ConfigKeys.ADMIN_USERS_PATH.getValue(); } public static void setAdminUsersPath(String adminUsersPath) { ConfigKeys.ADMIN_USERS_PATH.value = adminUsersPath; } public static void setRemoteControl(boolean remoteControl) { ConfigKeys.REMOTE_CONTROL.value = remoteControl; } public static boolean getRemoteControl() { return ConfigKeys.REMOTE_CONTROL.getValue(); } public boolean isRemote() { return ConfigKeys.REMOTE.getValue(); } public void setRemote(boolean remote) { ConfigKeys.REMOTE.value = remote; } public static boolean isServer() { return ConfigKeys.SERVER.getValue(); } public static void setServer(boolean server) { ConfigKeys.SERVER.value = server; } public boolean isClient() { return getConfigValue(ConfigKeys.CLIENT.key, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(ConfigKeys.CLIENT.key, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(ConfigKeys.DATA_SOURCE_PATH.key, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); } public Set<String> getDataSourcePath() { return getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); } public String[] getLibraryPaths() { return getConfigValue(ConfigKeys.LIBRARY_PATH.key); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(ConfigKeys.LIBRARY_PATH.key, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(ConfigKeys.WATCH_STATUS.key, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); } /** * Property for persistence configuration * * @return <code>boolean</code> */ public boolean isScanForEntities() { return getPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue( ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key, persistenceProperties); } /** * Gets cached {@link PoolConfig} instance a connection pool configuration * * @return {@link PoolConfig} */ public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { // Deep clone for configuration Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
package com.intellij.openapi.project.impl; import com.intellij.CommonBundle; import com.intellij.application.options.PathMacrosImpl; import com.intellij.ide.impl.ProjectUtil; import com.intellij.ide.startup.impl.StartupManagerImpl; import com.intellij.openapi.application.*; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.components.ExportableApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl; import com.intellij.openapi.help.HelpManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.options.ex.SingleConfigurableEditor; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.openapi.project.ProjectReloadState; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.ex.VirtualFileManagerEx; import com.intellij.util.ProfilingUtil; import com.intellij.util.containers.HashMap; import gnu.trove.TObjectLongHashMap; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import java.util.*; public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExternalizable, ExportableApplicationComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.project.impl.ProjectManagerImpl"); static final int CURRENT_FORMAT_VERSION = 4; private static final Key<ArrayList<ProjectManagerListener>> LISTENERS_IN_PROJECT_KEY = Key.create("LISTENERS_IN_PROJECT_KEY"); @NonNls private static final String OLD_PROJECT_SUFFIX = "_old."; @NonNls private static final String ELEMENT_DEFAULT_PROJECT = "defaultProject"; @SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"}) private ProjectImpl myDefaultProject; // Only used asynchronously in save and dispose, which itself are synchronized. @SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"}) private Element myDefaultProjectRootElement; // Only used asynchronously in save and dispose, which itself are synchronized. private final ArrayList<Project> myOpenProjects = new ArrayList<Project>(); private final ArrayList<ProjectManagerListener> myListeners = new ArrayList<ProjectManagerListener>(); /** * More then 0 while openProject is being executed: [openProject..runStartupActivities...runPostStartupActivitites]. * This flag is required by SaveAndSynchHandler. We do not save * anything while project is being opened. */ private int myCountOfProjectsBeingOpen; private boolean myIsInRefresh; private Map<VirtualFile, byte[]> mySavedCopies = new HashMap<VirtualFile, byte[]>(); private TObjectLongHashMap<VirtualFile> mySavedTimestamps = new TObjectLongHashMap<VirtualFile>(); private HashMap<Project, List<VirtualFile>> myChangedProjectFiles = new HashMap<Project, List<VirtualFile>>(); private PathMacrosImpl myPathMacros; private volatile int myReloadBlockCount = 0; private static ProjectManagerListener[] getListeners(Project project) { ArrayList<ProjectManagerListener> array = project.getUserData(LISTENERS_IN_PROJECT_KEY); if (array == null) return ProjectManagerListener.EMPTY_ARRAY; return array.toArray(new ProjectManagerListener[array.size()]); } public ProjectManagerImpl(VirtualFileManagerEx virtualFileManagerEx, PathMacrosImpl pathMacros) { addProjectManagerListener( new ProjectManagerListener() { public void projectOpened(Project project) { ProjectManagerListener[] listeners = getListeners(project); for (ProjectManagerListener listener : listeners) { listener.projectOpened(project); } } public void projectClosed(Project project) { ProjectManagerListener[] listeners = getListeners(project); for (ProjectManagerListener listener : listeners) { listener.projectClosed(project); } } public boolean canCloseProject(Project project) { ProjectManagerListener[] listeners = getListeners(project); for (ProjectManagerListener listener : listeners) { if (!listener.canCloseProject(project)) { return false; } } return true; } public void projectClosing(Project project) { ProjectManagerListener[] listeners = getListeners(project); for (ProjectManagerListener listener : listeners) { listener.projectClosing(project); } } } ); registerExternalProjectFileListener(virtualFileManagerEx); myPathMacros = pathMacros; } public void disposeComponent() { if (myDefaultProject != null) { Disposer.dispose(myDefaultProject); myDefaultProject = null; } } public void initComponent() { } public Project newProject(String filePath, boolean useDefaultProjectSettings, boolean isDummy) { filePath = canonicalize(filePath); ProjectImpl project = createProject(filePath, false, isDummy, ApplicationManager.getApplication().isUnitTestMode()); if (useDefaultProjectSettings) { ProjectImpl defaultProject = (ProjectImpl)getDefaultProject(); Element element = defaultProject.saveToXml(null, defaultProject.getProjectFile()); try { project.loadFromXml(element, filePath); } catch (Exception e) { LOG.error(e); } } project.init(); return project; } private ProjectImpl createProject(String filePath, boolean isDefault, boolean isDummy, boolean isOptimiseTestLoadSpeed) { final ProjectImpl project; if (isDummy) { project = new DummyProject(filePath, isDefault, isOptimiseTestLoadSpeed); project.setDummy(isDummy); } else { project = new ProjectImpl(this, filePath, isDefault, isOptimiseTestLoadSpeed, myPathMacros); } project.loadProjectComponents(); return project; } public Project loadProject(String filePath) throws IOException, JDOMException, InvalidDataException { filePath = canonicalize(filePath); ProjectImpl project = createProject(filePath, false, false, false); final ConfigurationFile[] files = project.getConfigurationFiles(); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { for (ConfigurationFile file : files) { LocalFileSystem.getInstance().refreshAndFindFileByPath(file.getFilePath().replace(File.separatorChar, '/')); } } }); final boolean macrosOk = checkMacros(project, getDefinedMacros()); if (!macrosOk) { throw new IOException(ProjectBundle.message("project.load.undefined.path.variables.error")); } project.loadSavedConfiguration(); project.init(); return project; } private static String canonicalize(final String filePath) { if (filePath == null) return null; try { String canonicalPath = new File(filePath).getCanonicalPath(); if (canonicalPath != null) { return canonicalPath; } } catch (IOException e) { // OK. File does not yet exist so it's canonical path will be equal to its original path. } return filePath; } private Set<String> getDefinedMacros() { Set<String> definedMacros = new HashSet<String>(myPathMacros.getUserMacroNames()); definedMacros.addAll(myPathMacros.getSystemMacroNames()); definedMacros = Collections.unmodifiableSet(definedMacros); return definedMacros; } private static boolean checkMacros(Project project, Set<String> definedMacros) throws IOException, JDOMException { String projectFilePath = project.getProjectFilePath(); if (projectFilePath == null) { return true; } Document document = JDOMUtil.loadDocument(new File(projectFilePath)); Element root = document.getRootElement(); final Set<String> usedMacros = new HashSet<String>(Arrays.asList(ProjectImpl.readUsedMacros(root))); usedMacros.removeAll(definedMacros); if (usedMacros.isEmpty()) { return true; // all macros in configuration files are defined } // there are undefined macros, need to define them before loading components final String text = ProjectBundle.message("project.load.undefined.path.variables.message"); return showMacrosConfigurationDialog(project, text, usedMacros); } private static boolean showMacrosConfigurationDialog(Project project, final String text, final Set<String> usedMacros) { final Application application = ApplicationManager.getApplication(); if (application.isHeadlessEnvironment() || application.isUnitTestMode()) { throw new RuntimeException(text + ": " + StringUtil.join(usedMacros, ", ")); } final UndefinedMacrosConfigurable configurable = new UndefinedMacrosConfigurable(text, usedMacros.toArray(new String[usedMacros.size()])); final SingleConfigurableEditor editor = new SingleConfigurableEditor(project, configurable) { protected void doOKAction() { if (!getConfigurable().isModified()) { Messages.showErrorDialog(getContentPane(), ProjectBundle.message("project.load.undefined.path.variables.all.needed"), ProjectBundle.message("project.load.undefined.path.variables.title")); return; } super.doOKAction(); } }; editor.show(); return editor.isOK(); } public synchronized Project getDefaultProject() { if (myDefaultProject == null) { myDefaultProject = createProject(null, true, false, ApplicationManager.getApplication().isUnitTestMode()); if (myDefaultProjectRootElement != null) { try { myDefaultProject.loadFromXml(myDefaultProjectRootElement, null); } catch (InvalidDataException e) { LOG.info(e); Messages.showErrorDialog(e.getMessage(), ProjectBundle.message("project.load.default.error")); } finally { myDefaultProjectRootElement = null; } } myDefaultProject.init(); } return myDefaultProject; } public Project[] getOpenProjects() { return myOpenProjects.toArray(new Project[myOpenProjects.size()]); } public boolean isProjectOpened(Project project) { return myOpenProjects.contains(project); } public boolean openProject(final Project project) { if (myOpenProjects.contains(project)) return false; if (!ApplicationManager.getApplication().isUnitTestMode() && !checkVersion(project)) return false; myCountOfProjectsBeingOpen++; myOpenProjects.add(project); fireProjectOpened(project); ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { public void run() { ((StartupManagerImpl)StartupManager.getInstance(project)).runStartupActivities(); } }, ProjectBundle.message("project.load.progress"), false, project); ((StartupManagerImpl)StartupManager.getInstance(project)).runPostStartupActivities(); // Hack. We need to initialize FileDocumentManagerImpl's dummy project since it is lazy initialized and initialization can happen in // non-swing thread which could lead to some dummy components fail to initialize. FileDocumentManager fdManager = FileDocumentManager.getInstance(); if (fdManager instanceof FileDocumentManagerImpl) { ((FileDocumentManagerImpl)fdManager).getDummyProject(); } myCountOfProjectsBeingOpen return true; } public Project loadAndOpenProject(String filePath) throws IOException, JDOMException, InvalidDataException { Project project = loadProject(filePath); if (!openProject(project)) { return null; } return project; } private void registerExternalProjectFileListener(VirtualFileManagerEx virtualFileManager) { virtualFileManager.addVirtualFileManagerListener(new VirtualFileManagerListener() { public void beforeRefreshStart(boolean asynchonous) { myIsInRefresh = true; } public void afterRefreshFinish(boolean asynchonous) { myIsInRefresh = false; askToReloadProjectIfConfigFilesChangedExternally(); } }); virtualFileManager.addVirtualFileListener(new VirtualFileAdapter() { public void contentsChanged(VirtualFileEvent event) { if (event.isFromRefresh() && myIsInRefresh) { // external change saveChangedProjectFile(event.getFile()); } } }); } private void askToReloadProjectIfConfigFilesChangedExternally() { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { if (myChangedProjectFiles.size() > 0 && myReloadBlockCount == 0) { Set<Project> projects = myChangedProjectFiles.keySet(); List<Project> projectsToReload = new ArrayList<Project>(); for (Project project : projects) { List<VirtualFile> causes = myChangedProjectFiles.get(project); Set<VirtualFile> liveCauses = new HashSet<VirtualFile>(causes); for (VirtualFile cause : causes) { if (!cause.isValid()) liveCauses.remove(cause); } if (!liveCauses.isEmpty()) { String message; if (liveCauses.size() == 1) { message = ProjectBundle.message("project.reload.external.change.single", causes.get(0).getPresentableUrl()); } else { StringBuffer filesBuilder = new StringBuffer(); boolean first = true; for (VirtualFile cause : liveCauses) { if (!first) filesBuilder.append("\n"); first = false; filesBuilder.append(cause.getPresentableUrl()); } message = ProjectBundle.message("project.reload.external.change.multiple", filesBuilder.toString()); } if (Messages.showYesNoDialog(project, message, ProjectBundle.message("project.reload.external.change.title"), Messages.getQuestionIcon()) == 0) { projectsToReload.add(project); } } for (final Project projectToReload : projectsToReload) { reloadProject(projectToReload); } } myChangedProjectFiles.clear(); } } }, ModalityState.NON_MODAL); } public boolean isFileSavedToBeReloaded(VirtualFile candidate) { return mySavedCopies.containsKey(candidate); } public void blockReloadingProjectOnExternalChanges() { myReloadBlockCount++; } public void unblockReloadingProjectOnExternalChanges() { myReloadBlockCount askToReloadProjectIfConfigFilesChangedExternally(); } public void saveChangedProjectFile(final VirtualFile file) { final Project[] projects = getOpenProjects(); for (Project project : projects) { if (file == project.getProjectFile() || file == project.getWorkspaceFile()) { copyToTemp(file); registerProjectToReload(project, file); } ModuleManager moduleManager = ModuleManager.getInstance(project); final Module[] modules = moduleManager.getModules(); for (Module module : modules) { if (module.getModuleFile() == file) { copyToTemp(file); registerProjectToReload(project, file); } } } } private void registerProjectToReload(final Project project, final VirtualFile cause) { List<VirtualFile> changedProjectFiles = myChangedProjectFiles.get(project); if (changedProjectFiles == null) { changedProjectFiles = new ArrayList<VirtualFile>(); myChangedProjectFiles.put(project, changedProjectFiles); } changedProjectFiles.add(cause); } private void copyToTemp(VirtualFile file) { try { final byte[] bytes = file.contentsToByteArray(); mySavedCopies.put(file, bytes); mySavedTimestamps.put(file, file.getTimeStamp()); } catch (IOException e) { LOG.error(e); } } private void restoreCopy(VirtualFile file) { try { if (file == null) return; // Externally deleted actually. if (!file.isWritable()) return; // IDEA was unable to save it as well. So no need to restore. final byte[] bytes = mySavedCopies.get(file); if (bytes != null) { try { file.setBinaryContent(bytes, -1, mySavedTimestamps.get(file)); } catch (IOException e) { Messages.showWarningDialog(ProjectBundle.message("project.reload.write.failed", file.getPresentableUrl()), ProjectBundle.message("project.reload.write.failed.title")); } } } finally { mySavedCopies.remove(file); mySavedTimestamps.remove(file); } } public void reloadProject(final Project p) { reloadProject(p, false); } public void reloadProject(final Project p, final boolean takeMemorySnapshot) { final Project[] project = new Project[]{p}; ProjectReloadState.getInstance(project[0]).onBeforeAutomaticProjectReload(); ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { LOG.info("Reloading project."); final String path = project[0].getProjectFilePath(); final List<VirtualFile> original = getAllProjectFiles(project[0]); if (project[0].isDisposed() || ProjectUtil.closeProject(project[0])) { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { for (final VirtualFile aOriginal : original) { restoreCopy(aOriginal); } } }); project[0] = null; // Let it go. if (takeMemorySnapshot) { String outputFileName = ProfilingUtil.createDumpFileName(ApplicationInfo.getInstance().getBuildNumber()); ProfilingUtil.forceCaptureMemorySnapshot(outputFileName); } ProjectUtil.openProject(path, null, true); } } }, ModalityState.NON_MODAL); } private static List<VirtualFile> getAllProjectFiles(Project project) { List<VirtualFile> files = new ArrayList<VirtualFile>(); files.add(project.getProjectFile()); files.add(project.getWorkspaceFile()); ModuleManager moduleManager = ModuleManager.getInstance(project); final Module[] modules = moduleManager.getModules(); for (Module module : modules) { files.add(module.getModuleFile()); } return files; } private static boolean checkVersion(final Project project) { int version = ((ProjectImpl)project).getOriginalVersion(); if (version >= 0 && version < CURRENT_FORMAT_VERSION) { final VirtualFile projectFile = project.getProjectFile(); LOG.assertTrue(projectFile != null); String name = projectFile.getNameWithoutExtension(); String message = ProjectBundle.message("project.convert.old.prompt", projectFile.getName(), ApplicationNamesInfo.getInstance().getProductName(), name + OLD_PROJECT_SUFFIX + projectFile.getExtension()); if (Messages.showYesNoDialog(message, CommonBundle.getWarningTitle(), Messages.getWarningIcon()) != 0) return false; final ArrayList<String> conversionProblems = ((ProjectImpl)project).getConversionProblemsStorage(); if (conversionProblems.size() > 0) { StringBuffer buffer = new StringBuffer(); buffer.append(ProjectBundle.message("project.convert.problems.detected")); for (String s : conversionProblems) { buffer.append('\n'); buffer.append(s); } buffer.append(ProjectBundle.message("project.convert.problems.help")); final int result = Messages.showDialog(project, buffer.toString(), ProjectBundle.message("project.convert.problems.title"), new String[]{ProjectBundle.message("project.convert.problems.help.button"), CommonBundle.getCloseButtonText()}, 0, Messages.getWarningIcon() ); if (result == 0) { HelpManager.getInstance().invokeHelp("project.migrationProblems"); } } ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { try { VirtualFile projectDir = projectFile.getParent(); assert projectDir != null; final String oldProjectName = projectFile.getNameWithoutExtension() + OLD_PROJECT_SUFFIX + projectFile.getExtension(); VirtualFile oldProject = projectDir.findChild(oldProjectName); if (oldProject == null) { oldProject = projectDir.createChildData(this, oldProjectName); } VfsUtil.saveText(oldProject, VfsUtil.loadText(projectFile)); VirtualFile workspaceFile = project.getWorkspaceFile(); if (workspaceFile != null) { final String oldWorkspaceName = workspaceFile.getNameWithoutExtension() + OLD_PROJECT_SUFFIX + project.getWorkspaceFile().getExtension(); VirtualFile oldWorkspace = projectDir.findChild(oldWorkspaceName); if (oldWorkspace == null) { oldWorkspace = projectDir.createChildData(this, oldWorkspaceName); } VfsUtil.saveText(oldWorkspace, VfsUtil.loadText(workspaceFile)); } } catch (IOException e) { LOG.error(e); } } }); } if (version > CURRENT_FORMAT_VERSION) { String message = ProjectBundle.message("project.load.new.version.warning", project.getName(), ApplicationNamesInfo.getInstance().getProductName()); if (Messages.showYesNoDialog(message, CommonBundle.getWarningTitle(), Messages.getWarningIcon()) != 0) return false; } return true; } /* public boolean isOpeningProject() { return myCountOfProjectsBeingOpen > 0; } */ public boolean closeProject(final Project project) { if (!isProjectOpened(project)) return true; if (!canClose(project)) return false; fireProjectClosing(project); ShutDownTracker.getInstance().registerStopperThread(Thread.currentThread()); try { FileDocumentManager.getInstance().saveAllDocuments(); project.save(); myOpenProjects.remove(project); fireProjectClosed(project); ApplicationManagerEx.getApplicationEx().saveSettings(); } finally { ShutDownTracker.getInstance().unregisterStopperThread(Thread.currentThread()); } return true; } protected void fireProjectClosing(Project project) { if (LOG.isDebugEnabled()) { LOG.debug("enter: fireProjectClosing()"); } synchronized (myListeners) { if (myListeners.size() > 0) { ProjectManagerListener[] listeners = myListeners.toArray(new ProjectManagerListener[myListeners.size()]); for (ProjectManagerListener listener : listeners) { listener.projectClosing(project); } } } } public void addProjectManagerListener(ProjectManagerListener listener) { synchronized (myListeners) { myListeners.add(listener); } } public void removeProjectManagerListener(ProjectManagerListener listener) { synchronized (myListeners) { boolean removed = myListeners.remove(listener); LOG.assertTrue(removed); } } public void addProjectManagerListener(Project project, ProjectManagerListener listener) { ArrayList<ProjectManagerListener> listeners = project.getUserData(LISTENERS_IN_PROJECT_KEY); if (listeners == null) { listeners = new ArrayList<ProjectManagerListener>(); project.putUserData(LISTENERS_IN_PROJECT_KEY, listeners); } listeners.add(listener); } public void removeProjectManagerListener(Project project, ProjectManagerListener listener) { ArrayList<ProjectManagerListener> listeners = project.getUserData(LISTENERS_IN_PROJECT_KEY); if (listeners != null) { boolean removed = listeners.remove(listener); LOG.assertTrue(removed); } else { LOG.assertTrue(false); } } private void fireProjectOpened(Project project) { if (LOG.isDebugEnabled()) { LOG.debug("projectOpened"); } synchronized (myListeners) { if (myListeners.size() > 0) { ProjectManagerListener[] listeners = myListeners.toArray(new ProjectManagerListener[myListeners.size()]); for (ProjectManagerListener listener : listeners) { listener.projectOpened(project); } } } } private void fireProjectClosed(Project project) { if (LOG.isDebugEnabled()) { LOG.debug("projectClosed"); } synchronized (myListeners) { if (myListeners.size() > 0) { ProjectManagerListener[] listeners = myListeners.toArray(new ProjectManagerListener[myListeners.size()]); for (ProjectManagerListener listener : listeners) { listener.projectClosed(project); } } } } public boolean canClose(Project project) { if (LOG.isDebugEnabled()) { LOG.debug("enter: canClose()"); } synchronized (myListeners) { if (myListeners.size() > 0) { ProjectManagerListener[] listeners = myListeners.toArray(new ProjectManagerListener[myListeners.size()]); for (ProjectManagerListener listener : listeners) { if (!listener.canCloseProject(project)) return false; } } } return true; } public void writeExternal(Element parentNode) throws WriteExternalException { if (myDefaultProject != null) { Element element = new Element(ELEMENT_DEFAULT_PROJECT); parentNode.addContent(element); myDefaultProject.saveToXml(element, myDefaultProject.getProjectFile()); } else if (myDefaultProjectRootElement != null) { parentNode.addContent((Element)myDefaultProjectRootElement.clone()); } } public void readExternal(Element parentNode) throws InvalidDataException { Element element = parentNode.getChild(ELEMENT_DEFAULT_PROJECT); if (element != null) { myDefaultProjectRootElement = element; } } public String getExternalFileName() { return "project.default"; } @NotNull public String getComponentName() { return "ProjectManager"; } @NotNull public File[] getExportFiles() { return new File[]{PathManager.getOptionsFile(this)}; } @NotNull public String getPresentableName() { return ProjectBundle.message("project.default.settings"); } private class DummyProject extends ProjectImpl { public DummyProject(final String filePath, final boolean aDefault, final boolean optimiseTestLoadSpeed) { super(ProjectManagerImpl.this, filePath, aDefault, optimiseTestLoadSpeed, ProjectManagerImpl.this.myPathMacros); } } }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.yaml.snakeyaml.Yaml; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * */ public class Configuration implements Cloneable { // Cache for all configuration passed programmatically or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // Path where stored administrative users public static final String ADMIN_USERS_PATH_KEY = "adminUsersPath"; // Netty server / client configuration properties for RPC calls public static final String IP_ADDRESS_KEY = "listeningIp"; public static final String PORT_KEY = "listeningPort"; public static final String BOSS_POOL_KEY = "bossPoolSize"; public static final String WORKER_POOL_KEY = "workerPoolSize"; public static final String CONNECTION_TIMEOUT_KEY = "timeout"; // Properties for data source path and deployment path public static final String DEMPLOYMENT_PATH_KEY = "deploymentPath"; public static final String DATA_SOURCE_PATH_KEY = "dataSourcePath"; // Runtime to get available processors private static final Runtime RUNTIME = Runtime.getRuntime(); // Default properties public static final String ADMIN_USERS_PATH_DEF = "./config/admin/users.properties"; public static final String IP_ADDRESS_DEF = "0.0.0.0"; public static final String PORT_DEF = "1199"; public static final String BOSS_POOL_DEF = "1"; public static final int WORKER_POOL_DEF = 3; public static final String CONNECTION_TIMEOUT_DEF = "1000"; public static final boolean SERVER_DEF = Boolean.TRUE; public static final String DATA_SOURCE_PATH_DEF = "./ds"; // Properties which version of server is running remote it requires server // client RPC infrastructure or local (embeddable mode) private static final String REMOTE_KEY = "remote"; private static final String SERVER_KEY = "server"; private static final String CLIENT_KEY = "client"; public static final Set<DeploymentDirectory> DEPLOYMENT_PATHS_DEF = new HashSet<DeploymentDirectory>( Arrays.asList(new DeploymentDirectory("./deploy", Boolean.TRUE))); public static final Set<String> DATA_SOURCES_PATHS_DEF = new HashSet<String>( Arrays.asList("./ds")); private static final String CONFIG_FILE = "./config/configuration.yaml"; // String prefixes for JNDI names public static final String JPA_NAME = "java:comp/env/"; public static final String EJB_NAME = "ejb:"; public static final int EJB_NAME_LENGTH = 4; // Configuration keys properties for deployment private static final String DEPLOY_CONFIG_KEY = "deployConfiguration"; private static final String ADMIN_USER_PATH_KEY = "adminPath"; private static final String HOT_DEPLOYMENT_KEY = "hotDeployment"; private static final String WATCH_STATUS_KEY = "watchStatus"; private static final String LIBRARY_PATH_KEY = "libraryPaths"; // Persistence provider property keys private static final String PERSISTENCE_CONFIG_KEY = "persistenceConfig"; private static final String SCAN_FOR_ENTITIES_KEY = "scanForEntities"; private static final String ANNOTATED_UNIT_NAME_KEY = "annotatedUnitName"; private static final String PERSISTENCE_XML_PATH_KEY = "persistanceXmlPath"; private static final String PERSISTENCE_XML_FROM_JAR_KEY = "persistenceXmlFromJar"; private static final String SWAP_DATASOURCE_KEY = "swapDataSource"; private static final String SCAN_ARCHIVES_KEY = "scanArchives"; private static final String POOLED_DATA_SOURCE_KEY = "pooledDataSource"; private static final String PERSISTENCE_PROPERTIES_KEY = "persistenceProperties"; // Connection pool provider property keys private static final String POOL_CONFIG_KEY = "poolConfig"; private static final String POOL_PROPERTIES_PATH_KEY = "poolPropertiesPath"; private static final String POOL_PROVIDER_TYPE_KEY = "poolProviderType"; private static final String POOL_PROPERTIES_KEY = "poolProperties"; // Configuration properties for deployment private static String ADMIN_USERS_PATH; // Is configuration server or client (default is server) private static boolean server = SERVER_DEF; private static boolean remote; // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); private static final String META_INF_PATH = "META-INF/"; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } @SuppressWarnings("unchecked") private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } Map<K, V> value = (Map<K, V>) ObjectUtils.getAsMap(key, from); return value; } private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (ObjectUtils.available(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } private <K> boolean containsSubConfigKey(Object key, K subKey) { Map<K, ?> subConfig = getAsMap(key); boolean valid = ObjectUtils.available(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(DEPLOY_CONFIG_KEY, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(DEPLOY_CONFIG_KEY, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(DEPLOY_CONFIG_KEY, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(DEPLOY_CONFIG_KEY, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration if value is null then returns passed default value * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, DEPLOY_CONFIG_KEY, PERSISTENCE_CONFIG_KEY, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(PERSISTENCE_CONFIG_KEY, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, DEPLOY_CONFIG_KEY, POOL_CONFIG_KEY, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuraion * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(POOL_CONFIG_KEY, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(POOL_PROPERTIES_KEY); if (ObjectUtils.available(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(POOL_PROVIDER_TYPE_KEY); if (ObjectUtils.available(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(POOL_PROPERTIES_PATH_KEY); if (ObjectUtils.available(path)) { setPoolPropertiesPath(path); } } /** * Configures server from properties */ private void configureServer() { // Sets default values to remote server configuration boolean contains = containsConfigKey(IP_ADDRESS_KEY); if (ObjectUtils.notTrue(contains)) { setConfigValue(IP_ADDRESS_KEY, IP_ADDRESS_DEF); } contains = containsConfigKey(PORT_KEY); if (ObjectUtils.notTrue(contains)) { setConfigValue(PORT_KEY, PORT_DEF); } contains = containsConfigKey(BOSS_POOL_KEY); if (ObjectUtils.notTrue(contains)) { setConfigValue(BOSS_POOL_KEY, BOSS_POOL_DEF); } contains = containsConfigKey(WORKER_POOL_KEY); if (ObjectUtils.notTrue(contains)) { int workers = RUNTIME.availableProcessors() * WORKER_POOL_DEF; String workerProperty = String.valueOf(workers); setConfigValue(WORKER_POOL_KEY, workerProperty); } contains = containsConfigKey(CONNECTION_TIMEOUT_KEY); if (ObjectUtils.notTrue(contains)) { setConfigValue(CONNECTION_TIMEOUT_KEY, CONNECTION_TIMEOUT_DEF); } // Sets default values is application on server or client mode Object serverValue = getConfigValue(SERVER_KEY); if (ObjectUtils.notNull(serverValue)) { if (serverValue instanceof Boolean) { server = (Boolean) serverValue; } else { server = Boolean.valueOf(serverValue.toString()); } } Object remoteValue = getConfigValue(REMOTE_KEY); if (ObjectUtils.notNull(remoteValue)) { if (remoteValue instanceof Boolean) { remote = (Boolean) remoteValue; } else { remote = Boolean.valueOf(remoteValue.toString()); } } } /** * Merges configuration with default properties */ public void configureDeployments() { // Sets administrator user configuration file path ADMIN_USERS_PATH = getConfigValue(ADMIN_USER_PATH_KEY, ADMIN_USERS_PATH_DEF); // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(HOT_DEPLOYMENT_KEY); if (hotDeployment == null) { setConfigValue(HOT_DEPLOYMENT_KEY, Boolean.FALSE); hotDeployment = getConfigValue(HOT_DEPLOYMENT_KEY); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(WATCH_STATUS_KEY, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(DEMPLOYMENT_PATH_KEY); if (deploymentPaths == null) { deploymentPaths = DEPLOYMENT_PATHS_DEF; setConfigValue(DEMPLOYMENT_PATH_KEY, deploymentPaths); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return {@link Map}<Object, Object> */ @SuppressWarnings("unchecked") protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = ObjectUtils.getAsMap(key, map1); mergedValue = deepMerge(value1, (Map<Object, Object>) value2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ @SuppressWarnings("unchecked") public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { configure((Map<Object, Object>) configuration); } } finally { ObjectUtils.close(stream); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { Object value = config.get(key); String textValue; if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { InputStream propertiesStream = null; try { File configFile = new File(CONFIG_FILE); if (configFile.exists()) { propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error("Could not open config file", ex); } finally { ObjectUtils.close(propertiesStream); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { InputStream propertiesStream = null; try { propertiesStream = new FileInputStream(new File(configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error("Could not open config file", ex); } finally { ObjectUtils.close(propertiesStream); } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) { InputStream resourceStream = loader.getResourceAsStream(StringUtils .concat(META_INF_PATH, resourceName)); if (resourceStream == null) { LOG.error("Configuration resource doesn't exist"); return; } loadFromStream(resourceStream); try { ObjectUtils.close(resourceStream); } catch (IOException ex) { LOG.error("Could not load resource", ex); } } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } ObjectUtils.close(propertiesStream); } catch (IOException ex) { LOG.error("Could not load configuration", ex); } } public static String getAdminUsersPath() { return ADMIN_USERS_PATH; } public static void setAdminUsersPath(String aDMIN_USERS_PATH) { ADMIN_USERS_PATH = aDMIN_USERS_PATH; } public boolean isRemote() { return remote; } public void setRemote(boolean remoteValue) { remote = remoteValue; } public static boolean isServer() { return server; } public static void setServer(boolean serverValue) { server = serverValue; } public boolean isClient() { return getConfigValue(CLIENT_KEY, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(CLIENT_KEY, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(DEMPLOYMENT_PATH_KEY); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(DEMPLOYMENT_PATH_KEY, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(DATA_SOURCE_PATH_KEY); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(DATA_SOURCE_PATH_KEY, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(DEMPLOYMENT_PATH_KEY); } public Set<String> getDataSourcePath() { return getConfigValue(DATA_SOURCE_PATH_KEY); } public String[] getLibraryPaths() { return getConfigValue(LIBRARY_PATH_KEY); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(LIBRARY_PATH_KEY, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(HOT_DEPLOYMENT_KEY, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(HOT_DEPLOYMENT_KEY, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(WATCH_STATUS_KEY, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(WATCH_STATUS_KEY, watchStatus); } // Persistence configuration public boolean isScanForEntities() { return getPersistenceConfigValue(SCAN_FOR_ENTITIES_KEY, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(SCAN_FOR_ENTITIES_KEY, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(ANNOTATED_UNIT_NAME_KEY); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(ANNOTATED_UNIT_NAME_KEY, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(PERSISTENCE_XML_PATH_KEY); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(PERSISTENCE_XML_PATH_KEY, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue(PERSISTENCE_XML_FROM_JAR_KEY, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(PERSISTENCE_XML_FROM_JAR_KEY, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(SWAP_DATASOURCE_KEY, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(SWAP_DATASOURCE_KEY, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(SCAN_ARCHIVES_KEY, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(SCAN_ARCHIVES_KEY, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(POOLED_DATA_SOURCE_KEY, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(POOLED_DATA_SOURCE_KEY, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(PERSISTENCE_PROPERTIES_KEY); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(PERSISTENCE_PROPERTIES_KEY, persistenceProperties); } // Pool configuration public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
package com.intellij.util.xml; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.util.PropertyUtil; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import com.intellij.psi.xml.XmlElement; import com.intellij.psi.PsiLock; import net.sf.cglib.proxy.InvocationHandler; import net.sf.cglib.proxy.Proxy; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.WildcardType; import java.util.*; /** * @author peter */ public class XmlAnnotatedElementManagerImpl extends XmlAnnotatedElementManager implements ApplicationComponent { private static final Key<NameStrategy> NAME_STRATEGY_KEY = Key.create("NameStrategy"); private static final Key CACHED_ELEMENT = Key.create("CachedXmlAnnotatedElement"); @NotNull protected <T extends XmlAnnotatedElement> T createXmlAnnotatedElement(final Class<T> aClass, final XmlTag tag) { synchronized (PsiLock.LOCK) { final T element = (T)Proxy.newProxyInstance(null, new Class[]{aClass}, new MyInvocationHandler<T>(tag, aClass)); setCachedElement(tag, element); return element; } } public void setNameStrategy(final XmlFile file, final NameStrategy strategy) { file.putUserData(NAME_STRATEGY_KEY, strategy); } @NotNull public NameStrategy getNameStrategy(final XmlFile file) { final NameStrategy strategy = file.getUserData(NAME_STRATEGY_KEY); return strategy == null ? NameStrategy.HYPHEN_STRATEGY : strategy; } @NotNull public <T extends XmlAnnotatedElement> XmlFileAnnotatedElement<T> getFileElement(final XmlFile file, final Class<T> aClass) { synchronized (PsiLock.LOCK) { XmlFileAnnotatedElement<T> element = getCachedElement(file); if (element == null) { element = new XmlFileAnnotatedElement<T>(file, this, aClass); setCachedElement(file, element); } return element; } } private <T extends XmlAnnotatedElement> void setCachedElement(final XmlElement xmlElement, final T element) { xmlElement.putUserData(CACHED_ELEMENT, element); } @Nullable public <T extends XmlAnnotatedElement> T getCachedElement(final XmlElement element) { return (T)element.getUserData(CACHED_ELEMENT); } @NonNls public String getComponentName() { return getClass().getName(); } public void initComponent() { } public void disposeComponent() { } private class MyInvocationHandler<T extends XmlAnnotatedElement> implements InvocationHandler { private final XmlTag myTag; private final XmlFile myFile; private final Class<T> myClass; private boolean myInitialized = false; private boolean myInitializing = false; public MyInvocationHandler(final XmlTag tag, final Class<T> aClass) { myTag = tag; myFile = (XmlFile)tag.getContainingFile(); myClass = aClass; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final AttributeValue attributeValue = method.getAnnotation(AttributeValue.class); if (attributeValue != null) { return myTag.getAttributeValue(guessName(attributeValue.value(), method)); } final TagValue tagValue = method.getAnnotation(TagValue.class); if (tagValue != null || isGetValueMethod(method)) { return myTag.getValue().getText(); } final SubTagValue subTagValue = method.getAnnotation(SubTagValue.class); if (subTagValue != null) { final String qname = guessName(subTagValue.value(), method); if (qname != null) { final XmlTag subTag = myTag.findFirstSubTag(qname); if (subTag != null) { return subTag.getValue().getText(); } } return null; } if (Object.class.equals(method.getDeclaringClass())) { final String name = method.getName(); if ("toString".equals(name)) { return StringUtil.getShortName(myClass) + " on tag " + myTag.getText() + " @" + System.identityHashCode(proxy); } if ("equals".equals(name)) { return proxy == args[0]; } if ("hashCode".equals(name)) { return System.identityHashCode(proxy); } } checkInitialized(); if (XmlAnnotatedElement.class.isAssignableFrom(method.getReturnType())) { final String qname = getSubTagName(method); if (qname != null) { final XmlTag subTag = myTag.findFirstSubTag(qname); if (subTag != null) { final XmlAnnotatedElement element = getCachedElement(subTag); assert element != null : "Null annotated element for " + myTag.getText() + "; " + qname; return element; } } } if (extractElementType(method.getGenericReturnType()) != null) { final String qname = getSubTagNameForCollection(method); if (qname != null) { final XmlTag[] subTags = myTag.findSubTags(qname); XmlAnnotatedElement[] elements = new XmlAnnotatedElement[subTags.length]; for (int i = 0; i < subTags.length; i++) { final XmlAnnotatedElement element = getCachedElement(subTags[i]); assert element != null : "Null annotated element for " + myTag.getText() + "; " + qname + "; " + i; elements[i] = element; } return Arrays.asList(elements); } } throw new UnsupportedOperationException("Cannot call " + method.toString()); } private void checkInitialized() { synchronized (PsiLock.LOCK) { if (myInitialized || myInitializing) return; myInitializing = true; try { for (Method method : myClass.getMethods()) { createElement(method); } } finally { myInitializing = false; myInitialized = true; } } } private void createElement(final Method method) { final Class<?> returnType = method.getReturnType(); if (XmlAnnotatedElement.class.isAssignableFrom(returnType)) { final String qname = getSubTagName(method); if (qname != null) { final XmlTag subTag = myTag.findFirstSubTag(qname); if (subTag != null) { createXmlAnnotatedElement((Class<XmlAnnotatedElement>)returnType, subTag); return; } } } final Class<? extends XmlAnnotatedElement> aClass = extractElementType(method.getGenericReturnType()); if (aClass != null) { final String qname = getSubTagNameForCollection(method); if (qname != null) { for (XmlTag xmlTag : myTag.findSubTags(qname)) { createXmlAnnotatedElement(aClass, xmlTag); } } } } @Nullable private String getSubTagName(final Method method) { final SubTag subTagAnnotation = method.getAnnotation(SubTag.class); if (subTagAnnotation == null || StringUtil.isEmpty(subTagAnnotation.value())) { return getNameFromMethod(method); } return subTagAnnotation.value(); } @Nullable private String getSubTagNameForCollection(final Method method) { final SubTagList subTagList = method.getAnnotation(SubTagList.class); if (subTagList == null || StringUtil.isEmpty(subTagList.value())) { final String propertyName = getPropertyName(method); return propertyName != null ? getNameStrategy(myFile).convertName(StringUtil.unpluralize(propertyName)) : null; } return subTagList.value(); } private boolean isGetValueMethod(final Method method) { return "getValue".equals(method.getName()) && String.class.equals(method.getReturnType()) && method.getParameterTypes().length == 0; } @Nullable private String guessName(final String value, final Method method) { if (StringUtil.isEmpty(value)) { return getNameFromMethod(method); } return value; } @Nullable private String getNameFromMethod(final Method method) { final String propertyName = getPropertyName(method); return propertyName == null ? null : getNameStrategy(myFile).convertName(propertyName); } } @Nullable private static Class<? extends XmlAnnotatedElement> extractElementType(Type returnType) { if (returnType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)returnType; final Type rawType = parameterizedType.getRawType(); if (rawType instanceof Class) { final Class<?> rawClass = (Class<?>)rawType; if (List.class.isAssignableFrom(rawClass) || Collection.class.equals(rawClass)) { final Type[] arguments = parameterizedType.getActualTypeArguments(); if (arguments.length == 1) { final Type argument = arguments[0]; if (argument instanceof WildcardType) { WildcardType wildcardType = (WildcardType)argument; final Type[] upperBounds = wildcardType.getUpperBounds(); if (upperBounds.length == 1) { final Type upperBound = upperBounds[0]; if (upperBound instanceof Class) { Class aClass1 = (Class)upperBound; if (XmlAnnotatedElement.class.isAssignableFrom(aClass1)) { return (Class<? extends XmlAnnotatedElement>)aClass1; } } } } else if (argument instanceof Class) { Class aClass1 = (Class)argument; if (XmlAnnotatedElement.class.isAssignableFrom(aClass1)) { return (Class<? extends XmlAnnotatedElement>)aClass1; } } } } } } return null; } private static String getPropertyName(Method method) { return PropertyUtil.getPropertyName(method.getName()); } }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.yaml.snakeyaml.Yaml; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * */ public class Configuration implements Cloneable { // Cache for all configuration passed programmatically or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // Runtime to get available processors private static final Runtime RUNTIME = Runtime.getRuntime(); public static final String DATA_SOURCE_PATH_DEF = "./ds"; // Properties which version of server is running remote it requires server // client RPC infrastructure or local (embedded mode) private static final String CONFIG_FILE = "./config/configuration.yaml"; // Persistence provider property keys private static final String PERSISTENCE_XML_PATH_KEY = "persistanceXmlPath"; private static final String PERSISTENCE_XML_FROM_JAR_KEY = "persistenceXmlFromJar"; private static final String SWAP_DATASOURCE_KEY = "swapDataSource"; private static final String SCAN_ARCHIVES_KEY = "scanArchives"; private static final String POOLED_DATA_SOURCE_KEY = "pooledDataSource"; private static final String PERSISTENCE_PROPERTIES_KEY = "persistenceProperties"; // Connection pool provider property keys private static final String POOL_CONFIG_KEY = "poolConfig"; private static final String POOL_PROPERTIES_PATH_KEY = "poolPropertiesPath"; private static final String POOL_PROVIDER_TYPE_KEY = "poolProviderType"; private static final String POOL_PROPERTIES_KEY = "poolProperties"; // Configuration properties for deployment private static String ADMIN_USERS_PATH; // Is configuration server or client (default is server) private static boolean server = (Boolean) Config.SERVER.value; private static boolean remote; // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); private static final String META_INF_PATH = "META-INF/"; // Error messages private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration"; private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file"; private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist"; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } @SuppressWarnings("unchecked") Map<K, V> value = (Map<K, V>) ObjectUtils.getAsMap(key, from); return value; } private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (ObjectUtils.available(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } private <K> boolean containsSubConfigKey(Object key, K subKey) { Map<K, ?> subConfig = getAsMap(key); boolean valid = ObjectUtils.available(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(Config.DEPLOY_CONFIG.key, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(Config.DEPLOY_CONFIG.key, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(Config.DEPLOY_CONFIG.key, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(Config.DEPLOY_CONFIG.key, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration if value is null then returns passed default value * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, Config.DEPLOY_CONFIG.key, Config.PERSISTENCE_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(Config.PERSISTENCE_CONFIG.key, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, Config.DEPLOY_CONFIG.key, Config.POOL_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuraion * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(Config.POOL_CONFIG.key, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(Config.POOL_PROPERTIES.key); if (ObjectUtils.available(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(Config.POOL_PROVIDER_TYPE.key); if (ObjectUtils.available(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(Config.POOL_PROPERTIES_PATH.key); if (ObjectUtils.available(path)) { setPoolPropertiesPath(path); } } /** * Configures server from properties */ private void configureServer() { // Sets default values to remote server configuration boolean contains = containsConfigKey(Config.IP_ADDRESS.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.IP_ADDRESS.key, Config.IP_ADDRESS.value); } contains = containsConfigKey(Config.PORT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.PORT.key, Config.PORT.value); } contains = containsConfigKey(Config.BOSS_POOL.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.BOSS_POOL.key, Config.BOSS_POOL.value); } contains = containsConfigKey(Config.WORKER_POOL.key); if (ObjectUtils.notTrue(contains)) { int workers = RUNTIME.availableProcessors() * (Integer) Config.WORKER_POOL.value; String workerProperty = String.valueOf(workers); setConfigValue(Config.WORKER_POOL.key, workerProperty); } contains = containsConfigKey(Config.CONNECTION_TIMEOUT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.CONNECTION_TIMEOUT.key, Config.CONNECTION_TIMEOUT.value); } // Sets default values is application on server or client mode Object serverValue = getConfigValue(Config.SERVER.key); if (ObjectUtils.notNull(serverValue)) { if (serverValue instanceof Boolean) { server = (Boolean) serverValue; } else { server = Boolean.valueOf(serverValue.toString()); } } Object remoteValue = getConfigValue(Config.REMOTE.key); if (ObjectUtils.notNull(remoteValue)) { if (remoteValue instanceof Boolean) { remote = (Boolean) remoteValue; } else { remote = Boolean.valueOf(remoteValue.toString()); } } } /** * Merges configuration with default properties */ @SuppressWarnings("unchecked") public void configureDeployments() { // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(Config.HOT_DEPLOYMENT.key); if (hotDeployment == null) { setConfigValue(Config.HOT_DEPLOYMENT.key, Boolean.FALSE); hotDeployment = getConfigValue(Config.HOT_DEPLOYMENT.key); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(Config.WATCH_STATUS.key, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(Config.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = (Set<DeploymentDirectory>) Config.DEMPLOYMENT_PATH.value; setConfigValue(Config.DEMPLOYMENT_PATH.key, deploymentPaths); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return <code>{@link Map}<Object, Object></code> */ @SuppressWarnings("unchecked") protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = ObjectUtils.getAsMap(key, map1); mergedValue = deepMerge(value1, (Map<Object, Object>) value2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { @SuppressWarnings("unchecked") Map<Object, Object> innerConfig = (Map<Object, Object>) configuration; configure(innerConfig); } } finally { ObjectUtils.close(stream); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { Object value = config.get(key); String textValue; if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) throws IOException { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } } catch (IOException ex) { LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex); } finally { ObjectUtils.close(propertiesStream); } } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { InputStream propertiesStream = null; try { File configFile = new File(CONFIG_FILE); if (configFile.exists()) { propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { InputStream propertiesStream = null; try { propertiesStream = new FileInputStream(new File(configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) throws IOException { InputStream resourceStream = loader.getResourceAsStream(StringUtils .concat(META_INF_PATH, resourceName)); if (resourceStream == null) { LOG.error(RESOURCE_NOT_EXISTS_ERROR); } else { loadFromStream(resourceStream); } } public static String getAdminUsersPath() { return ADMIN_USERS_PATH; } public static void setAdminUsersPath(String aDMIN_USERS_PATH) { ADMIN_USERS_PATH = aDMIN_USERS_PATH; } public boolean isRemote() { return remote; } public void setRemote(boolean remoteValue) { remote = remoteValue; } public static boolean isServer() { return server; } public static void setServer(boolean serverValue) { server = serverValue; } public boolean isClient() { return getConfigValue(Config.CLIENT.key, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(Config.CLIENT.key, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(Config.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(Config.DEMPLOYMENT_PATH.key, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(Config.DATA_SOURCE_PATH.key); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(Config.DATA_SOURCE_PATH.key, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(Config.DEMPLOYMENT_PATH.key); } public Set<String> getDataSourcePath() { return getConfigValue(Config.DATA_SOURCE_PATH.key); } public String[] getLibraryPaths() { return getConfigValue(Config.LIBRARY_PATH.key); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(Config.LIBRARY_PATH.key, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(Config.HOT_DEPLOYMENT.key, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(Config.HOT_DEPLOYMENT.key, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(Config.WATCH_STATUS.key, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(Config.WATCH_STATUS.key, watchStatus); } /** * Property for persistence configuration * * @return <code>boolean</code> */ public boolean isScanForEntities() { return getPersistenceConfigValue(Config.SCAN_FOR_ENTITIES.key, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(Config.SCAN_FOR_ENTITIES.key, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(Config.ANNOTATED_UNIT_NAME.key); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(Config.ANNOTATED_UNIT_NAME.key, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(Config.PERSISTENCE_XML_PATH.key); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(Config.PERSISTENCE_XML_PATH.key, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue(Config.PERSISTENCE_XML_FROM_JAR.key, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(Config.PERSISTENCE_XML_FROM_JAR.key, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(Config.SWAP_DATASOURCE.key, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(Config.SWAP_DATASOURCE.key, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(Config.SCAN_ARCHIVES.key, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(Config.SCAN_ARCHIVES.key, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(Config.POOLED_DATA_SOURCE.key, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(Config.POOLED_DATA_SOURCE.key, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(Config.PERSISTENCE_PROPERTIES.key); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(Config.PERSISTENCE_PROPERTIES.key, persistenceProperties); } /** * Property for connection pool configuration * * @return {@link PoolConfig} */ public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
package org.myrobotlab.service; import java.io.File; import java.io.IOException; import java.util.Map; import org.myrobotlab.framework.Platform; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.service.abstracts.AbstractSpeechSynthesis; import org.myrobotlab.service.data.AudioData; import org.myrobotlab.service.data.Locale; import org.slf4j.Logger; public class LocalSpeech extends AbstractSpeechSynthesis { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(LocalSpeech.class); protected String ttsPath = getResourceDir() + fs + "tts" + fs + "tts.exe"; protected String mimicPath = getResourceDir() + fs + "mimic" + fs + "mimic.exe"; protected String ttsCommand = null; protected String filterChars = "\"\'"; protected boolean removeExt = false; protected boolean ttsHack = false; public LocalSpeech(String n, String id) { super(n, id); // setup the default tts per os Platform platform = Runtime.getPlatform(); if (platform.isWindows()) { setTts(); } else if (platform.isMac()) { setSay(); } else if (platform.isLinux()) { setFestival(); } else { error("%s unknown platform %s", getName(), platform.getOS()); } } public void removeExt(boolean b) { removeExt = b; } public void setTtsHack(boolean b) { ttsHack = b; } /** * set the tts command template * * @param ttsCommand */ public void setTtsCommand(String ttsCommand) { info("LocalSpeech template is now: %s", ttsCommand); this.ttsCommand = ttsCommand; } /** * get the tts command template * * @return */ public String getTtsCommand() { return ttsCommand; } /** * setFestival sets the Windows tts template * * @return */ public boolean setTts() { removeExt(false); setTtsHack(true); setTtsCommand("\"" + ttsPath + "\" -f 9 -v {voice} -o {filename} -t \"{text}\""); if (!Runtime.getPlatform().isWindows()) { error("tts only supported on Windows"); return false; } return true; } /** * setMimic sets the Windows mimic template * * @return */ public boolean setMimic() { removeExt(false); setTtsHack(false); if (Runtime.getPlatform().isWindows()) { setTtsCommand(mimicPath + " -voice " + getVoice() + " -o {filename} -t \"{text}\""); } else { setTtsCommand("mimic -voice " + getVoice() + " -o {filename} -t \"{text}\""); } return true; } /** * setSay sets the Mac say template * * @return */ public boolean setSay() { removeExt(false); setTtsHack(false); setTtsCommand("say \"{text}\"" + "-o {filename}"); if (!Runtime.getPlatform().isMac()) { error("say only supported on Mac"); return false; } return true; } /** * setFestival sets the Linux tts to festival template * * @return */ public boolean setFestival() { removeExt(false); setTtsHack(false); setTtsCommand("echo \"{text}\" | text2wave -o {filename}"); if (!Runtime.getPlatform().isLinux()) { error("festival only supported on Linux"); return false; } return true; } /** * setEspeak sets the Linux tts to espeak template * * @return */ public boolean setEspeak() { removeExt(false); setTtsHack(false); setTtsCommand("espeak \"{text}\" -w {filename}"); return true; } /** * String of characters to filter out of text to create the tts command. * Typically double quotes should be filtered out of the command as creating * the text to speech process command can be broken by double quotes * * @param filter */ public void setFilter(String filter) { filterChars = filter; } public String getFilter() { return filterChars; } @Override public AudioData generateAudioData(AudioData audioData, String toSpeak) throws IOException, InterruptedException { // the actual filename on the file system String localFileName = getLocalFileName(toSpeak); // the cmd filename - in some cases cmd templates don't want the extension String filename = localFileName; if (removeExt) { // some cmd line require the filename without ext be supplied filename = localFileName.substring(0, localFileName.lastIndexOf(".")); } if (ttsHack) { // lame tts.exe on windows appends "0.mp3" to whatever filename was // supplied wtf? filename = filename.substring(0, filename.length() - 5); } // filter out breaking chars if (filterChars != null) { for (int i = 0; i < filterChars.length(); ++i) { toSpeak = toSpeak.replace(filterChars.charAt(i), ' '); } } Platform platform = Runtime.getPlatform(); String cmd = ttsCommand.replace("{text}", toSpeak); cmd = cmd.replace("{filename}", filename); if (getVoice() != null) { cmd = cmd.replace("{voice}", getVoice().getVoiceProvider().toString()); } if (platform.isWindows()) { Runtime.execute("cmd.exe", "/c", "\"" + cmd + "\""); } else if (platform.isMac()) { Runtime.execute(cmd); } else if (platform.isLinux()) { Runtime.execute("bash", "-c", cmd); } File fileTest = new File(localFileName); if (fileTest.exists() && fileTest.length() > 0) { return new AudioData(localFileName); } else { if (platform.isLinux()) { error("0 byte file - please install a speech program: sudo apt-get install -y festival espeak speech-dispatcher gnustep-gui-runtime"); } else { error("%s returned 0 byte file !!! - error with speech generation"); } return null; } } /** * overridden because mac is silly for not being mp3 and ms tts is a mess * because it appends 0.mp3 :P */ public String getAudioCacheExtension() { if (Platform.getLocalInstance().isMac()) { return ".aiff"; } else if (ttsHack) { return "0.mp3"; // ya stoopid no ? } return ".wav"; // hopefully Linux festival can do this (if not can we ?) } /** * one of the few methods a SpeechSynthesis service must implement if derived * from AbstractSpeechSynthesis - * * Use protected addVoice(name, gender, lang, voiceProvider) to add voices * Voice.voiceProvider allows a serializable key to map MRL's Voice to a * implementation of a voice */ @Override protected void loadVoices() { if (voices.size() > 0) { log.info("already loaded voices"); return; } Platform platform = Platform.getLocalInstance(); // voices returned from local app String voicesText = null; if (platform.isWindows()) { voicesText = Runtime.execute("cmd.exe", "/c", "\"\"" + ttsPath + "\"" + " -V" + "\""); log.info("cmd {}", voicesText); String[] lines = voicesText.split(System.getProperty("line.separator")); for (String line : lines) { // String[] parts = cmd.split(" "); // String gender = "female"; // unknown String lang = "en-US"; // unknown if (line.startsWith("Exit")) { break; } String[] parts = line.split(" "); if (parts.length < 2) { // some voices are not based on a standard // pattern continue; } // lame-ass parsing .. // standard sapi pattern is 5 parameters : // INDEX PROVIDER VOICE_NAME PLATEFORM - LANG // we need INDEX, VOICE_NAME, LANG // but .. some voices dont use it, we will try to detect pattern and // adapt if no respect about it : // INDEX : String voiceProvider = parts[0]; // VOICE_NAME String voiceName = "Unknown" + voiceProvider; // default name if there // is an issue // it is standard, cool if (parts.length >= 6) { voiceName = parts[2];// line.trim(); } // almost standard, we have INDEX PROVIDER VOICE_NAME else if (parts.length > 2) { voiceName = line.split(" ")[2]; } // non standard at all ... but we catch it ! else { voiceName = line.split(" ")[1]; } // LANG ( we just detect for a keyword inside the whole string, because // position is random sometime ) // TODO: locale converter from keyword somewhere ? if (line.toLowerCase().contains("french") || line.toLowerCase().contains("français")) { lang = "fr-FR"; } try { // verify integer Integer.parseInt(voiceProvider); // voice name cause issues because of spaces or (null), let's just use // original number as name... addVoice(voiceName, null, lang, voiceProvider); } catch (Exception e) { continue; } } } else if (platform.isMac()) { voicesText = Runtime.execute("say -v"); // FIXME - implement parse -v output addVoice("fred", "male", "en-US", "fred"); // in the interim added 1 voice } else if (platform.isLinux()) { addVoice("Linus", "male", "en-US", "festival"); } } /** * override default tts.exe path * * @param ttsPath * - full path to windows tts.exe executable TODO - override also * other os */ public void setTtsPath(String ttsPath) { this.ttsPath = ttsPath; } public String getTtsPath() { return ttsPath; } @Override public Map<String, Locale> getLocales() { return Locale.getLocaleMap("en-US"); } public static void main(String[] args) { try { Runtime.main(new String[] { "--id", "admin", "--from-launcher" }); // LoggingFactory.init("WARN"); WebGui webgui = (WebGui)Runtime.create("webgui", "WebGui"); webgui.autoStartBrowser(false); webgui.startService(); LocalSpeech mouth = (LocalSpeech) Runtime.start("mouth", "LocalSpeech"); mouth.setMimic(); mouth.speakBlocking("hello there mimic works"); boolean done = true; if (done) { return; } mouth.speakBlocking("hello my name is sam, sam i am yet again, how \"are you? do you 'live in a zoo too? "); mouth.setMimic(); mouth.speakBlocking("bork bork bork, hello my name is sam, sam i am yet again, how \"are you? do you 'live in a zoo too? "); // speech.setTtsCommand("espeak \"{text}\" -w {filename}"); mouth.setEspeak(); log.info("tts command template is {}", mouth.getTtsCommand()); mouth.speakBlocking("i can speak some more"); mouth.speakBlocking("my name is bob"); mouth.speakBlocking("i have a job"); mouth.speakBlocking("and i can dance in a mob"); // speech.parseEffects("#OINK##OINK# hey I thought #DOH# that was funny // #LAUGH01_F# very funny"); // speech.getVoices(); // speech.setVoice("1"); } catch (Exception e) { log.error("main threw", e); } } }
package org.neo4j.shell.kernel.apps; import static java.lang.management.ManagementFactory.getPlatformMBeanServer; import java.util.Hashtable; import java.util.Iterator; import javax.management.MBeanAttributeInfo; import javax.management.MBeanServer; import javax.management.ObjectName; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.kernel.EmbeddedGraphDatabase; import org.neo4j.kernel.management.Kernel; import org.neo4j.shell.AppCommandParser; import org.neo4j.shell.OptionDefinition; import org.neo4j.shell.OptionValueType; import org.neo4j.shell.Output; import org.neo4j.shell.Session; import org.neo4j.shell.ShellException; public class Dbinfo extends GraphDatabaseApp { { addOptionDefinition( "l", new OptionDefinition( OptionValueType.MAY, "List available attributes for the specified bean. " + "Including a description about each attribute." ) ); addOptionDefinition( "g", new OptionDefinition( OptionValueType.MUST, "Get the value of the specified attribute(s), " + "or all attributes of the specified bean " + "if no attributes are specified." ) ); } @Override public String getDescription() { final Kernel kernel; try { kernel = getKernel(); } catch ( ShellException e ) { return e.getMessage(); } MBeanServer mbeans = getPlatformMBeanServer(); StringBuilder result = new StringBuilder( "Get runtime information about the Graph Database.\n" + "This uses the Neo4j management beans to get" + " information about the Graph Database.\n\n" ); availableBeans( mbeans, kernel, result ); result.append( "\n" ); getUsage( result ); return result.toString(); } private void getUsage( StringBuilder result ) { result.append( "USAGE: " ); result.append( getName() ); result.append( " -(g|l) <bean name> [list of attribute names]" ); } private Kernel getKernel() throws ShellException { GraphDatabaseService graphDb = getServer().getDb(); Kernel kernel = null; if ( graphDb instanceof EmbeddedGraphDatabase ) { try { kernel = ( (EmbeddedGraphDatabase) graphDb ).getManagementBean( Kernel.class ); } catch ( Exception e ) { } } if ( kernel == null ) { throw new ShellException( getName() + " is not available for this graph database." ); } return kernel; } @Override protected String exec( AppCommandParser parser, Session session, Output out ) throws Exception { Kernel kernel = getKernel(); boolean list = parser.options().containsKey( "l" ), get = parser.options().containsKey( "g" ); if ( ( list && get ) || ( !list && !get ) ) { StringBuilder usage = new StringBuilder(); getUsage( usage ); usage.append( ".\n" ); out.print( usage.toString() ); return null; } MBeanServer mbeans = getPlatformMBeanServer(); String bean = null; String[] attributes = null; if ( list ) { bean = parser.options().get( "l" ); } else if ( get ) { bean = parser.options().get( "g" ); attributes = parser.arguments().toArray( new String[parser.arguments().size()] ); } if ( bean == null ) // list beans { StringBuilder result = new StringBuilder(); availableBeans( mbeans, kernel, result ); out.print( result.toString() ); return null; } ObjectName mbean; { mbean = kernel.getMBeanQuery(); Hashtable<String, String> properties = new Hashtable<String, String>( mbean.getKeyPropertyList() ); properties.put( "name", bean ); try { Iterator<ObjectName> names = mbeans.queryNames( new ObjectName( mbean.getDomain(), properties ), null ).iterator(); if ( names.hasNext() ) { mbean = names.next(); if ( names.hasNext() ) mbean = null; } else { mbean = null; } } catch ( Exception e ) { mbean = null; } } if ( mbean == null ) { throw new ShellException( "No such management bean \"" + bean + "\"." ); } if ( attributes == null ) // list attributes { for ( MBeanAttributeInfo attr : mbeans.getMBeanInfo( mbean ).getAttributes() ) { out.println( attr.getName() + " - " + attr.getDescription() ); } } else { if ( attributes.length == 0 ) // specify all attributes { MBeanAttributeInfo[] allAttributes = mbeans.getMBeanInfo( mbean ).getAttributes(); attributes = new String[allAttributes.length]; for ( int i = 0; i < allAttributes.length; i++ ) { attributes[i] = allAttributes[i].getName(); } } for ( Object value : mbeans.getAttributes( mbean, attributes ) ) { out.println( value.toString() ); } } return null; } private void availableBeans( MBeanServer mbeans, Kernel kernel, StringBuilder result ) { result.append( "Available Management Beans\n" ); for ( Object name : mbeans.queryNames( kernel.getMBeanQuery(), null ) ) { result.append( "* " ); result.append( ( (ObjectName) name ).getKeyProperty( "name" ) ); result.append( "\n" ); } } }
package org.openremote.security; import org.openremote.base.exception.IncorrectImplementationException; import org.openremote.base.exception.OpenRemoteException; import org.openremote.logging.Logger; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.net.URI; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Security; import java.security.UnrecoverableEntryException; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.ECGenParameterSpec; import java.security.spec.RSAKeyGenParameterSpec; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * This is an abstract base class for managing and storing key material. It is useful for * both generating keys (and associated certificates if desired) as well as optionally * persisting keys and key certificates on filesystem using secure keystores. <p> * * This abstract implementation contains several operations that the subclasses may or may not * choose to expose as part of their public API. If a subclass wants to expose a method * implementation as part of public API, it should create a public method that invokes one of * the protected methods in this class. Some of the method implementations in this class may * be unnecessarily generic to expose in API as-is, and therefore it may make sense to create * a more use-case specific method signatures in each subclass. For examples of protected * methods, see {@link #save(java.net.URI, char[])}, {@link #load(java.net.URI, char[])}, * {@link #add(String, java.security.KeyStore.Entry, java.security.KeyStore.ProtectionParameter)}, * {@link #remove(String)}. <p> * * For examples of subclasses that may expose parts of this class protected API, see * {@link PasswordManager}, {@link PrivateKeyManager} classes. * * @see #save(java.net.URI, char[]) * @see #load(java.net.URI, char[]) * @see #add(String, java.security.KeyStore.Entry, java.security.KeyStore.ProtectionParameter) * @see #remove(String) * @see PasswordManager * @see PrivateKeyManager * * @author <a href="mailto:juha@openremote.org">Juha Lindfors</a> */ public abstract class KeyManager { /** * This is the default key storage type used if nothing else is specified. <p> * * Note that the default storage format PKCS12 can only be used as an asymmetric public and * private key and a key certificate storage but not for other (symmetric) keys. For the latter, * other provider-specific storage types must be used. <p> * * Default: {@value} */ public final static Storage DEFAULT_KEYSTORE_STORAGE = Storage.PKCS12; /** * The default security provider used by this instance. Note that can contain a null value * if loading of the security provider fails. A null value should indicate using the system * installed security providers in their preferred order rather than this explicit security * provider. <p> * * Default: {@value} */ public final static SecurityProvider DEFAULT_SECURITY_PROVIDER = SecurityProvider.BC; /** * If no key-specific password is set for stored keys, use this default empty password instead. * Note, most keystore implementations don't allow passing a null password protection parameters * for keys, and some (e.g. BouncyCastle UBER) do not allow empty passwords (empty char arrays) * either. */ public static final char[] EMPTY_KEY_PASSWORD = new char[] { '0' }; /** * ASN.1 OID for NSA / NIST standard curve P-521. This is equivalent to SEC 2 prime curve * "secp521r1". OID = {@value} */ public final static String ASN_OID_STD_CURVE_NSA_NIST_P521 = "1.3.132.0.35"; /** * ASN.1 OID for NSA / NIST standard curve P-384. This is equivalent to SEC 2 prime curve * "secp384r1". OID = {@value} */ public final static String ASN_OID_STD_CURVE_NSA_NIST_P384 = "1.3.132.0.34"; /** * ASN.1 OID for NSA / NIST standard curve P-256. This is equivalent to SEC 2 prime curve * "secp256r1" and ANSI X9.62 "prime256v1". OID = {@value} */ public final static String ASN_OID_STD_CURVE_NSA_NIST_P256 = "1.2.840.10045.3.1.7"; /** * RSA key size : {@value} <p> * * This is recommended asymmetric RSA key size for classified, secret data, as per NSA Suite B. */ public final static int DEFAULT_RSA_KEY_SIZE = 3072; /** * Public exponent value used in RSA algorithm (increase impacts performance): {@value} * * @see java.security.spec.RSAKeyGenParameterSpec#F4 */ public final static BigInteger DEFAULT_RSA_PUBLIC_EXPONENT = RSAKeyGenParameterSpec.F4; /** * Default logger for the security package. */ protected final static Logger securityLog = Logger.getInstance(SecurityLog.DEFAULT); /** * The key storage type used by this instance. */ private Storage storage = DEFAULT_KEYSTORE_STORAGE; /** * The security provider used by this instance. <p> * * Note that may contain a null reference in which case implementation should delegate to the * JVM installed security providers in their preferred use order. */ private Provider provider = DEFAULT_SECURITY_PROVIDER.getProviderInstance(); /** * Reference to the internal keystore instance that is used to persist the key entries in * this key manager. */ private KeyStore keystore = null; /** * Creates a new key manager instance with a {@link #DEFAULT_KEYSTORE_STORAGE default} key * storage format using {@link #DEFAULT_SECURITY_PROVIDER default} security provider. * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if creating the keystore fails */ protected KeyManager() throws ConfigurationException, KeyManagerException { this(DEFAULT_KEYSTORE_STORAGE, DEFAULT_SECURITY_PROVIDER.getProviderInstance()); } /** * This constructor allows the subclasses to specify both the key storage format and explicit * security provider to use with this instance. The key storage format and security provider * given as arguments will be used instead of the default values for this instance. <p> * * Note that the security provider parameter allows a null value. This indicates that the * appropriate security provider should be searched from the JVM installed security providers * in their preferred order. * * * @param storage * key storage format to use with this instance * * @param provider * The explicit security provider to use with the key storage of this instance. If a * null value is specified, the implementations should opt to delegate the selection * of a security provider to the JVMs installed security provider implementations. * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if creating the keystore fails */ protected KeyManager(Storage storage, Provider provider) throws ConfigurationException, KeyManagerException { init(storage, provider); loadKeyStore((InputStream) null, null); } /** * This constructor will load an existing keystore into memory. It expects the keystore * to be in default key storage format as specified in {@link #DEFAULT_KEYSTORE_STORAGE}. <p> * * The URI to a keystore file must use a 'file' scheme. * * * @param keyStoreFile * a file URI pointing to a keystore file that should be loaded into this key * manager * * @param password * a master password to access the keystore file * * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if creating the keystore fails */ protected KeyManager(URI keyStoreFile, char[] password) throws ConfigurationException, KeyManagerException { this( keyStoreFile, password, DEFAULT_KEYSTORE_STORAGE, DEFAULT_SECURITY_PROVIDER.getProviderInstance() ); } /** * This constructor will load an existing keystore into memory. It allows the subclasses to * specify the expected key storage format used by the keystore file. The storage format * must be supported by the {@link #DEFAULT_SECURITY_PROVIDER} implementation. <p> * * The URI to a keystore file must use a 'file' scheme. * * * @param keyStoreFile * a file URI pointing to a keystore file that should be loaded into this key * manager * * @param password * a master password to access the keystore file * * @param storage * key storage format to use with this instance * * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if creating the keystore fails */ protected KeyManager(URI keyStoreFile, char[] password, Storage storage) throws ConfigurationException, KeyManagerException { this(keyStoreFile, password, storage, DEFAULT_SECURITY_PROVIDER.getProviderInstance()); } /** * This constructor will load an existing keystore into memory. It allows the subclasses to * specify both the expected key storage format and explicit security provider to be used * when the keystore is loaded. <p> * * Note that the security provider parameter allows a null value. This indicates that the * appropriate security provider should be searched from the JVM installed security providers * in their preferred order. <p> * * The URI to a keystore file must use a 'file' scheme. * * * @param keyStoreFile * a file URI pointing to a keystore file that should be loaded into this key * manager * * @param password * a master password to access the keystore file * * @param storage * key storage format to use with this instance * * @param provider * The explicit security provider to use with the key storage of this instance. If a * null value is specified, the implementations should opt to delegate the selection * of a security provider to the JVMs installed security provider implementations. * * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if creating the keystore fails */ protected KeyManager(URI keyStoreFile, char[] password, Storage storage, Provider provider) throws ConfigurationException, KeyManagerException { this(storage, provider); load(keyStoreFile, password); } /** * Indicates if this key manager contains a key with a given alias. * * @param keyAlias * key alias to check * * @return true if a key is associated with a given alias in this key manager; false * otherwise */ public boolean contains(String keyAlias) { try { return keystore.containsAlias(keyAlias); } catch (KeyStoreException exception) { securityLog.error( "Unable to retrieve key info for alias '{0}' : {1}", exception, keyAlias, exception.getMessage() ); return false; } } /** * Returns the number of keys currently managed in this key manager. * * @return number of keys in this key manager */ public int size() { try { return keystore.size(); } catch (KeyStoreException exception) { securityLog.error( "Unable to retrieve keystore size : {0}", exception, exception.getMessage() ); return -1; } } /** * Initialization method used by constructors to initialize this instance. Should not be * invoked outside of a constructor. <p> * * @param storage * The keystore storage type to use with this instance. * * @param provider * The security provider to use with this instance. Can be null in which case * the implementations should delegate to the JVM installed security providers * in their preferred use order. */ protected void init(Storage storage, Provider provider) { if (storage == null) { throw new IllegalArgumentException("Implementation Error: null storage type"); } this.provider = provider; this.storage = storage; } /** * Stores the keys in this key manager in a secure key store format. This implementation generates * a file-based, persistent key store which can be shared with other applications and processes. * <p> * IMPORTANT NOTE: Subclasses that invoke this method should clear the password character array * as soon as it is no longer needed. This prevents passwords from lingering * in JVM memory pool any longer than is necessary. Use the * {@link #clearPassword(char[])} method for this purpose. * * @param uri * The location of the file where the key store should be persisted. Must be * an URI with file scheme. * * @param password * A secret password used to access the keystore contents. NOTE: the character * array should be set to zero values after this method call completes, via * {@link #clearPassword(char[])} method. * * @see #clearPassword(char[]) * * @throws KeyManagerException * if loading or creating the keystore fails */ protected void save(URI uri, char[] password) throws ConfigurationException, KeyManagerException { if (uri == null) { throw new KeyManagerException("Save failed due to null URI."); } try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(uri))); // Persist... save(keystore, out, password); } catch (FileNotFoundException exception) { throw new KeyManagerException( "File ''{0}'' cannot be created or opened : {1}", exception, resolveFilePath(new File(uri)), exception.getMessage() ); } catch (SecurityException exception) { throw new KeyManagerException( "Security manager has denied access to file ''{0}'' : {1}", exception, resolveFilePath(new File(uri)), exception.getMessage() ); } } /** * Loads existing, persisted key store contents into this instance. Any previous keys in this * key manager instance are overridden. <p> * * IMPORTANT NOTE: Subclasses that invoke this method should clear the password character array * as soon as it is no longer needed. This prevents passwords from lingering * in JVM memory pool any longer than is necessary. Use the * {@link #clearPassword(char[])} method for this purpose. * * @param uri * URI with file scheme pointing to the file system location of the keystore * to load * * @param keystorePassword * The password to access the keystore. Note that the subclasses invoking this * method are responsible for resetting the password character array after use. * * @see #clearPassword(char[]) * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading the keystore fails */ protected void load(URI uri, char[] keystorePassword) throws KeyManagerException { if (uri == null) { throw new KeyManagerException("Implementation Error: null file URI."); } loadKeyStore(new File(uri), keystorePassword); } /** * Adds a key entry to this instance. Use {@link #save(URI, char[])} to persist * if desired. * * @param keyAlias * A lookup name of the key entry to be added. * * @param entry * Key entry to be added. Note that accepted entry types depend on the * keystore storage format. * * @param param * Protection parameters for the key entry. A null value is accepted for * trusted certificate entries, for other type of key entries a null value * is converted to an empty password character array. */ protected void add(String keyAlias, KeyStore.Entry entry, KeyStore.ProtectionParameter param) throws KeyManagerException { if (keyAlias == null || keyAlias.equals("")) { throw new KeyManagerException( "Implementation Error: null or empty key alias is not allowed." ); } if (entry == null) { throw new KeyManagerException( "Implementation Error: null keystore entry is not allowed." ); } // Key stores appear to behave differently with regards to key entries depending what // types of entries are stored (and possibly differing between store implementations too). // E.g. private keys may have a strict requirement for a key protection where public // certificates may not allow protection parameters at all. // Doing some special handling here depending what type of entry is being stored: // - if a null protection parameter is provided, it is converted to an empty password // protection unless the null protection parameter is for a trusted certificate // entry in which case it is accepted. if (param == null) { param = new KeyStore.PasswordProtection(EMPTY_KEY_PASSWORD); } if (entry instanceof KeyStore.TrustedCertificateEntry) { param = null; } try { keystore.setEntry(keyAlias, entry, param); } catch (KeyStoreException exception) { throw new KeyManagerException( "Failed to add key '{0}' to key store : {1}", exception, keyAlias, exception.getMessage()); } } /** * Removes a key entry from this instance. Use {@link #save(URI, char[])} to persist * if desired. * * @param keyAlias * A lookup name of the key entry to be removed. * * @return true if key was removed, false otherwise */ protected boolean remove(String keyAlias) { try { keystore.deleteEntry(keyAlias); return true; } catch (KeyStoreException exception) { securityLog.error( "Unable to remove key alias '{0}' : {1}", exception, keyAlias, exception.getMessage() ); return false; } } /** * Retrieves a key from underlying key storage. * * @param alias * Key alias of the key to retrieve. * * @param protection * Protection parameter to retrieve the key. * * @return a key store entry, or null if it was not found * * @throws KeyManagerException * if the key could not be retrieved, due to incorrect protection parameters, * unsupported algorithm or other reasons */ protected KeyStore.Entry retrieveKey(String alias, KeyStore.ProtectionParameter protection) throws KeyManagerException { try { return keystore.getEntry(alias, protection); } catch (KeyStoreException exception) { throw new IncorrectImplementationException( "Implementation Error: password manager has not been initialized.", exception ); } catch (NoSuchAlgorithmException exception) { throw new KeyManagerException( "Configuration error. Required key storage algorithm is not available: {0}", exception, exception.getMessage() ); } catch (UnrecoverableKeyException exception) { throw new KeyManagerException( "Password with alias ''{0}'' could not be retrieved, possibly due to incorrect " + "protection password: {1}", exception, alias, exception.getMessage() ); } catch (UnrecoverableEntryException exception) { throw new KeyManagerException( "Password with alias ''{0}'' could not be retrieved, possibly due to incorrect " + "protection password: {1}", exception, alias, exception.getMessage() ); } } /** * A convenience method to retrieve a certificate (rather than a private or secret key) * from the underlying keystore. * * @param alias * Certificate alias to retrieve. * * @return A certificate, or null if not found */ protected Certificate getCertificate(String alias) { try { return keystore.getCertificate(alias); } catch (KeyStoreException exception) { // This exception may happen if keystore is not initialized/loaded when asking for // a certificate -- since we initialize the keystore instance as part of the constructor // it should always be present. Therefore this exception should only occur in case of // an implementation error. throw new IncorrectImplementationException( "Could not retrieve certificate '{0}': {1}", exception, alias, exception.getMessage() ); } } /** * Generates a new asymmetric key pair using the given algorithm. * * @param keyAlgo * algorithm for the key generator * * @return generated key pair * * @throws KeyManagerException * in case any errors in key generation */ protected KeyPair generateKey(AsymmetricKeyAlgorithm keyAlgo) throws KeyManagerException { try { KeyPairGenerator keyGen; if (provider == null) { keyGen = KeyPairGenerator.getInstance(keyAlgo.getAlgorithmName()); } else { keyGen = KeyPairGenerator.getInstance(keyAlgo.getAlgorithmName(), provider); } keyGen.initialize(keyAlgo.algorithmSpec); return keyGen.generateKeyPair(); } catch (InvalidAlgorithmParameterException exception) { throw new KeyManagerException( "Invalid algorithm parameter in {0} : {1}", exception, keyAlgo, exception.getMessage() ); } catch (NoSuchAlgorithmException exception) { throw new KeyManagerException( "No security provider found for {0} : {1}", exception, keyAlgo, exception.getMessage() ); } } /** * Returns the key storage type used by this key manager. * * @return key storage type */ protected Storage getStorageType() { return storage; } /** * Checks if key store exists at given file URI. * * @param uri * the file URI to check * * @return true if file exists, false otherwise * * @throws KeyManagerException * if security manager has denied access to file information */ protected boolean exists(URI uri) throws KeyManagerException { File file = new File(uri); try { return file.exists(); } catch (SecurityException exception) { String path = resolveFilePath(file); throw new KeyManagerException( "Security manager has prevented access to file ''{0}'' : {1}", exception, path, exception.getMessage() ); } } /** * Clears the given password character array with zero values. * * @param password * password character array to erase */ protected void clearPassword(char[] password) { if (password != null) { for (int i = 0; i < password.length; ++i) { password[i] = 0; } } } /** * Clears the given password byte array with zero values. * * @param password * password byte array to erase */ protected void clearPassword(byte[] password) { if (password != null) { for (int i = 0; i< password.length; ++i) { password[i] = 0; } } } /** * Stores the key entries of this key manager into a keystore. The keystore is saved to the given * output stream. The keystore can be an existing, loaded keystore or a new, empty one. * * @param keystore * keystore to add keys from this key manager to * * @param out * the output stream for the keystore (can be used for persisting the keystore to disk) * * @param password * password to access the keystore * * @throws KeyManagerException * if the save operation fails */ private void save(KeyStore keystore, OutputStream out, char[] password) throws KeyManagerException { if (password == null || password.length == 0) { throw new KeyManagerException( "Null or empty password. Keystore must be protected with a password." ); } BufferedOutputStream bout = new BufferedOutputStream(out); try { keystore.store(bout, password); } catch (KeyStoreException exception) { throw new KeyManagerException( "Storing the key pair failed : {0}", exception, exception.getMessage() ); } catch (IOException exception) { throw new KeyManagerException( "Unable to write key to keystore : {0}", exception, exception.getMessage() ); } catch (NoSuchAlgorithmException exception) { throw new KeyManagerException( "Security provider does not support required key store algorithm: {0}", exception, exception.getMessage() ); } catch (CertificateException exception) { throw new KeyManagerException( "Cannot store certificate: {0}", exception, exception.getMessage() ); } finally { if (bout != null) { try { bout.flush(); bout.close(); } catch (IOException exception) { securityLog.warn( "Failed to close file output stream to keystore : {0}", exception, exception.getMessage() ); } } } } /** * Loads a key store from the given input stream or creates a new instance in case of a * null input stream. Configured key storage type and security provider instance are used * to load/create the keystore. * * @param file * file to load the key store from * * @param password * password to access the key store * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ private void loadKeyStore(File file, char[] password) throws ConfigurationException, KeyManagerException { // This is basically just a convenience method to actual implementation // in loadKeyStore(InputStream, char[])... if (file == null) { throw new KeyManagerException("Implementation Error: null file descriptor."); } try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); loadKeyStore(in, password); } catch (FileNotFoundException exception) { throw new KeyManagerException( "Keystore file ''{0}'' could not be created or opened : {1}", exception, resolveFilePath(file), exception.getMessage() ); } catch (SecurityException exception) { throw new KeyManagerException( "Security manager has denied access to keystore file ''{0}'' : {1}", exception, resolveFilePath(file), exception.getMessage() ); } } /** * Loads a key store from the given input stream or creates a new instance in case of a * null input stream. Configured key storage type and security provider instance are used * to load/create the keystore. * * @param in * input stream to key store file (or null to create a new one) * * @param password * shared secret (a password) used for protecting access to the key store * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ private void loadKeyStore(InputStream in, char[] password) throws ConfigurationException, KeyManagerException { try { if (provider == null) { // Use system installed security provider... keystore = KeyStore.getInstance(storage.getStorageName()); } else { keystore = KeyStore.getInstance(storage.getStorageName(), provider); } keystore.load(in, password); } catch (KeyStoreException exception) { // NOTE: If the algorithm is not recognized by a provider, it is indicated by a nested // NoSuchAlgorithmException. This is the behavior for both SUN default provider // in Java 6 and BouncyCastle. if (exception.getCause() != null && exception.getCause() instanceof NoSuchAlgorithmException) { String usedProviders; if (provider == null) { usedProviders = Arrays.toString(Security.getProviders()); } else { usedProviders = provider.getName(); } throw new ConfigurationException( "The security provider(s) '{0}' do not support keystore type '{1}' : {2}", exception, usedProviders, storage.name(), exception.getMessage() ); } throw new KeyManagerException( "Cannot load keystore: {0}", exception, exception.getMessage() ); } catch (NoSuchAlgorithmException exception) { // If part of the keystore load() the algorithm to verify the keystore contents cannot // be found... throw new KeyManagerException( "Required keystore verification algorithm not found: {0}", exception, exception.getMessage() ); } catch (CertificateException exception) { // Can happen if any of the certificates in the store cannot be loaded... throw new KeyManagerException( "Can't load keystore: {0}", exception, exception.getMessage() ); } catch (IOException exception) { // If there's an I/O problem, or if keystore has been corrupted, or if password is missing // if (e.getCause() != null && e.getCause() instanceof UnrecoverableKeyException) // // The Java 6 javadoc claims that an incorrect password can be detected by having // // a nested UnrecoverableKeyException in the wrapping IOException -- this doesn't // // seem to be the case or is not working... incorrect password is reported as an // // IOException just like other I/O errors with no root causes as far as I'm able to // // tell. So leaving this out for now // // [JPL] // throw new PasswordException( // "Cannot recover keys from keystore (was the provided password correct?) : {0}", // e.getMessage(), e // TODO : this error would be improved by reporting file location and keystore type.. throw new KeyManagerException( "I/O Error: Cannot load keystore: {0}", exception, exception.getMessage() ); } } /** * File utility to print file path. * * @param file * file path to print * * @return resolves to an absolute file path if allowed by the security manager, if not * returns the file path as defined in the file object parameter */ private String resolveFilePath(File file) { try { return file.getAbsolutePath(); } catch (SecurityException e) { return file.getPath(); } } public enum Storage { /** * PKCS #12 format. Used for storing asymmetric key pairs and X.509 public key certificates. * Standardized format. */ PKCS12, JCEKS, /** * BouncyCastle keystore format which is roughly equivalent to Sun's 'JKS' keystore format * and implementation, and therefore can be used with the standard Java SDK 'keytool'. <p> * * This format is resistant to tampering but not resistant to inspection, therefore in * typical cases the {@link #UBER} storage format is recommended. */ BKS(SecurityProvider.BC), /** * Recommended BouncyCastle keystore format. Requires password verification and is * resistant to inspection and tampering. */ UBER(SecurityProvider.BC); /** * Reference to the security provider with the implementation of the storage. Can be null * if no specific provider is used (relying on already installed security providers in the * JVM). */ private SecurityProvider provider = null; /** * Constructs a new storage instance without specific security provider. */ private Storage() { // no op } /** * Constructs a new storage instance linked to a specific security provider. * * @param provider * security provider */ private Storage(SecurityProvider provider) { this.provider = provider; } public String getStorageName() { return name(); } /** * Returns the security provider instance associated with this storage implementation. Can * return a null if no specific security provider has been associated with the storage * instance. * * @return security provider instance associated with the storage instance or null if * no specific provider is used */ public Provider getSecurityProvider() { return (provider == null) ? null : provider.getProviderInstance(); } @Override public String toString() { return getStorageName(); } } public enum AsymmetricKeyAlgorithm { EC( new ECGenParameterSpec(ASN_OID_STD_CURVE_NSA_NIST_P521), KeySigner.DEFAULT_EC_SIGNATURE_ALGORITHM ), RSA( new RSAKeyGenParameterSpec(DEFAULT_RSA_KEY_SIZE, DEFAULT_RSA_PUBLIC_EXPONENT), KeySigner.DEFAULT_RSA_SIGNATURE_ALGORITHM ); /** * Key generator algorithm configuration parameters. */ private AlgorithmParameterSpec algorithmSpec; /** * A default signature algorithm associated with this asymmetric key algorithm. */ private KeySigner.SignatureAlgorithm defaultSignatureAlgorithm; /** * Constructs a new asymmetric key algorithm enum. * * @param spec * algorithm parameters * * @param defaultSignatureAlgorithm * a corresponding default public key signature algorithm to associate with this * asymmetric key algorithm */ private AsymmetricKeyAlgorithm(AlgorithmParameterSpec spec, KeySigner.SignatureAlgorithm defaultSignatureAlgorithm) { this.algorithmSpec = spec; this.defaultSignatureAlgorithm = defaultSignatureAlgorithm; } public String getAlgorithmName() { return name(); } /** * Returns a default public key signature algorithm that should be used with this asymmetric * key algorithm. * * @return a public key signature algorithm associated with this asymmetric key algorithm */ public KeySigner.SignatureAlgorithm getDefaultSignatureAlgorithm() { return defaultSignatureAlgorithm; } @Override public String toString() { return getAlgorithmName(); } } /** * Exception type for the public API of this class to indicate errors. */ public static class KeyManagerException extends OpenRemoteException { protected KeyManagerException(String msg) { super(msg); } protected KeyManagerException(String msg, Throwable cause, Object... params) { super(msg, cause, params); } } /** * Specific subclass of KeyManagerException that indicates a security configuration issue. */ public static class ConfigurationException extends KeyManagerException { protected ConfigurationException(String msg, Throwable cause, Object... params) { super(msg, cause, params); } } }
package org.openspaces.core.space; import com.gigaspaces.internal.utils.StringUtils; import com.j_spaces.core.IJSpace; import com.j_spaces.kernel.Environment; import net.jini.core.discovery.LookupLocator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.webapp.WebAppContext; import org.jini.rio.boot.BootUtil; import org.openspaces.core.GigaSpace; import org.openspaces.core.cluster.ClusterInfo; import org.openspaces.core.cluster.ClusterInfoAware; import org.openspaces.pu.container.CannotCreateContainerException; import org.openspaces.pu.container.jee.JeeServiceDetails; import org.openspaces.pu.container.jee.JeeType; import org.openspaces.pu.container.jee.stats.RequestStatisticsFilter; import org.openspaces.pu.service.ServiceDetails; import org.openspaces.pu.service.ServiceDetailsProvider; import org.openspaces.pu.service.ServiceMonitors; import org.openspaces.pu.service.ServiceMonitorsProvider; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import javax.servlet.DispatcherType; import java.net.UnknownHostException; import java.util.EnumSet; import java.util.Properties; /** * * @since 10.1.0 * @author yohana */ public class RestBean implements InitializingBean, ClusterInfoAware, DisposableBean, ServiceDetailsProvider, ServiceMonitorsProvider { protected Log logger = LogFactory.getLog(getClass()); private Server server; private GigaSpace gigaspace; private String spaceName; private String groups; private String locators; private String port; int jettyPort; private FilterHolder filterHolder; private ClusterInfo clusterInfo; private WebAppContext webAppContext; private boolean jettyStarted = false; private Properties properties; @Override public void destroy() { if (jettyStarted) { logger.info("Stopping rest service"); try { webAppContext.stop(); } catch (Exception e) { logger.error("Unable to stop web context", e); } try { server.stop(); } catch (Exception e) { logger.error("Unable to stop rest service", e); } server.destroy(); } } public void setPort(String port) { this.port = port; } public void setGigaSpace(GigaSpace gigaSpace) { this.gigaspace = gigaSpace; } public void setSpaceName(String spaceName) { this.spaceName = spaceName; } public void setGroups(String groups) { this.groups = groups; } public void setLocators(String locators) { this.locators = locators; } public void setProperties(Properties properties) { this.properties= properties; } @Override public void afterPropertiesSet() throws Exception { int runningNumber = clusterInfo.getRunningNumber(); try { jettyPort = Integer.valueOf(this.port); } catch (NumberFormatException e) { throw new CannotCreateContainerException("Port should be number"); } jettyPort += runningNumber; server = new Server(); server.setStopAtShutdown(true); server.setGracefulShutdown(1000); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(jettyPort); server.setConnectors(new Connector[]{connector}); String ispaceName, igroups, ilocators; if (gigaspace == null && spaceName == null) { throw new CannotCreateContainerException("Either giga-space or space-name attribute should be specified."); } if (gigaspace != null && spaceName != null) { throw new CannotCreateContainerException("Either giga-space or space-name attribute can be specified but not both."); } if (spaceName != null) { ispaceName = spaceName; //TODO validate groups and locators ? igroups = (groups == null ? null : groups); ilocators = (locators == null ? null : locators); } else { IJSpace space = gigaspace.getSpace(); ispaceName = space.getName(); String[] lookupgroups = space.getFinderURL().getLookupGroups(); if (lookupgroups == null || lookupgroups.length == 0) { igroups = null; } else { igroups = StringUtils.join(lookupgroups, ",", 0, lookupgroups.length); } LookupLocator[] lookuplocators = space.getFinderURL().getLookupLocators(); if (lookuplocators == null || lookuplocators.length == 0) { ilocators = null; } else { ilocators = ""; for (int i=0 ; i<lookuplocators.length;i++) { ilocators+= lookuplocators[i].getHost()+":"+lookuplocators[i].getPort(); if (i != (lookuplocators.length - 1)) { ilocators += ","; } } } } logger.info("Starting REST service on port [" + jettyPort + "]"); webAppContext = new WebAppContext(); filterHolder = new FilterHolder(RequestStatisticsFilter.class);
package com.eta; import android.app.IntentService; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.location.Address; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.text.Html; import android.util.Log; import com.eta.util.ApplicationConstants; import com.eta.util.Utility; import com.google.android.gms.gcm.GoogleCloudMessaging; public class GcmIntentService extends IntentService { private static final String TAG = GcmIntentService.class.getSimpleName(); private NotificationManager mNotificationManager; public GcmIntentService() { super("GcmIntentService"); } @Override protected void onHandleIntent(Intent intent) { Bundle bundle = intent.getExtras(); Log.d(TAG, "extras : " + bundle.toString()); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); if (!bundle.isEmpty()) { // has effect of unparcelling Bundle /* * Filter messages based on message type. Since it is likely that GCM will be * extended in the future with new message types, just ignore any message types you're * not interested in, or that you don't recognize. */ if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { Log.i(TAG, "Send error: " + bundle.toString()); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { Log.i(TAG, "Deleted messages on server: " + bundle.toString()); // If it's a regular GCM message, do some work. } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { // Post notification of received message. sendNotification(bundle); } } // Release the wake lock provided by the WakefulBroadcastReceiver. GcmBroadcastReceiver.completeWakefulIntent(intent); } // Put the message into a notification and post it. //Here I am assuming that the Google Play Services sends all the information //in bundle private void sendNotification(Bundle bundle) { String senderName = bundle.getString(ApplicationConstants.GCM_MSG_SENDER_NAME); String senderPhone = bundle.getString(ApplicationConstants.GCM_MSG_SENDER_PHONE_NUMBER); Double srcLatitude = Double.valueOf(bundle.getString(ApplicationConstants.GCM_MSG_SRC_LATITUDE)); Double srcLongitude = Double.valueOf(bundle.getString(ApplicationConstants.GCM_MSG_SRC_LONGITUDE)); Double dstLatitude = Double.valueOf(bundle.getString(ApplicationConstants.GCM_MSG_DST_LATITUDE, "0.0D")); Double dstLongitude = Double.valueOf(bundle.getString(ApplicationConstants.GCM_MSG_DST_LONGITUDE, "0.0D")); Integer eta = Integer.valueOf(bundle.getString(ApplicationConstants.GCM_MSG_ETA)); String bigText = senderName + " sent you an ETA "; Address srcAddress = Utility.getSenderAddress(this, srcLatitude, srcLongitude); if(srcAddress != null) { //if Address is present then put it in intent bundle. It will be used by viewETAActivity. bundle.putParcelable(ApplicationConstants.GCM_MSG_SRC_ADDRESS, srcAddress); } String contentText = String.format("%s sent you an ETA.", senderName); Log.d(TAG, " Content Text : " + contentText); mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); // This intent will have almost the same parameters that are passed in // GCM broadcast intent. These parameters will be used by View Activity // to show the sender on the map. Intent viewETAIntent = new Intent(this, ViewETAActivity.class); viewETAIntent.putExtras(bundle); int iUniqueId = 0; //This logic will help to group the notification sent from same user(phone). if (senderPhone.length() > 5) { iUniqueId = Integer.valueOf(senderPhone.substring(senderPhone.length() - 5, senderPhone.length())); } else { iUniqueId = (int) (System.currentTimeMillis() & 0xFFFFFF); } Log.d(TAG, "iUniqueId : " + iUniqueId); PendingIntent contentIntent = PendingIntent.getActivity(this, iUniqueId, viewETAIntent, PendingIntent.FLAG_UPDATE_CURRENT); //Prepare the notification NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.eta_notification) .setContentTitle("ETA Notification") .setStyle(new NotificationCompat.BigTextStyle() .bigText(bigText)) .setContentText(contentText) .setAutoCancel(true) .setOngoing(false) .setGroup(ApplicationConstants.GCM_NOTIFICATION_GROUP_KEY); if(srcAddress != null) { NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); inboxStyle.setBigContentTitle("ETA Notification"); inboxStyle.addLine(Html.fromHtml(String.format("<strong>%s</strong>", contentText))); //Form the Bigger message inboxStyle.addLine(Html.fromHtml("<Strong>Currently near : </strong>")); for(int index = 0; index < srcAddress.getMaxAddressLineIndex(); index++) { inboxStyle.addLine(srcAddress.getAddressLine(index)); } inboxStyle.setSummaryText(Html.fromHtml("Click here to see his <strong>ETA</strong> on <strong>Map</strong>.")); mBuilder.setStyle(inboxStyle); } //Set the content intent. This intent will launch the ViewETAActicity mBuilder.setContentIntent(contentIntent); // to add sound to the notification Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); mBuilder.setSound(alarmSound); //Time to show the notification. mNotificationManager.notify(iUniqueId, mBuilder.build()); } }
package org.osiam.client.oauth; import org.apache.commons.codec.binary.Base64; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicNameValuePair; import org.codehaus.jackson.map.ObjectMapper; import org.osiam.client.exception.ConnectionInitializationException; import org.osiam.client.exception.UnauthorizedException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.apache.http.HttpStatus.*; public class AuthService { private static final Charset CHARSET = Charset.forName("UTF-8"); private final HttpPost post; private final String clientId; private final String endpoint; private AuthService(Builder builder) { post = new HttpPost(builder.endpoint); post.setHeaders(builder.headers); post.setEntity(builder.body); clientId = builder.clientId; endpoint = builder.endpoint; } public URI getUri() { return post.getURI(); } private HttpResponse perform() throws ConnectionInitializationException { HttpClient defaultHttpClient = new DefaultHttpClient(); final HttpResponse response; try { response = defaultHttpClient.execute(post); } catch (IOException e) { throw new ConnectionInitializationException("Unable to perform Request ", e); } return response; } public AccessToken retrieveAccessToken() { HttpResponse response = perform(); int status = response.getStatusLine().getStatusCode(); switch (status) { case SC_BAD_REQUEST: throw new ConnectionInitializationException("Unable to create Connection. Please make sure that you have the correct grants."); case SC_UNAUTHORIZED: StringBuilder errorMessage = new StringBuilder("You are not authorized to directly retrieve a access token."); if (response.toString().contains(clientId + " not found")) { errorMessage.append(" Unknown client-id"); } else { errorMessage.append(" Invalid client secret"); } throw new UnauthorizedException(errorMessage.toString()); case SC_NOT_FOUND: throw new ConnectionInitializationException("Unable to find the given OSIAM service (" + endpoint + ")"); } final AccessToken accessToken; try { InputStream content = response.getEntity().getContent(); ObjectMapper mapper = new ObjectMapper(); accessToken = mapper.readValue(content, AccessToken.class); } catch (IOException e) { throw new ConnectionInitializationException("Unable to retrieve access token: IOException", e); } return accessToken; } public static class Builder { private String clientId; private String clientSecret; private GrantType grantType; private final String DEFAULT_SCOPE = "GET POST PUT PATCH DELETE"; private Header[] headers; private Map<String, String> requestParameters = new HashMap<>(); private String endpoint; private HttpEntity body; public Builder(String endpoint) { requestParameters.put("scope", DEFAULT_SCOPE); this.endpoint = endpoint; } public Builder withGrantType(GrantType grantType) { if (!grantType.equals(GrantType.PASSWORD)) { throw new UnsupportedOperationException(grantType.getUrlParam() + " grant type not supported at this time"); } this.grantType = grantType; return this; } public Builder withClientId(String clientId) { this.clientId = clientId; return this; } public Builder withClientSecret(String clientSecret) { this.clientSecret = clientSecret; return this; } public Builder withUsername(String username) { requestParameters.put("username", username); return this; } public Builder withPassword(String password) { requestParameters.put("password", password); return this; } public AuthService build() { if (clientId == null || clientSecret == null) { throw new ConnectionInitializationException("The provided client credentials are incomplete."); } if (grantType.equals(GrantType.PASSWORD) && !(requestParameters.containsKey("username") && requestParameters.containsKey("password"))) { throw new ConnectionInitializationException("The grant type 'password' requires username and password"); } requestParameters.put("grant_type", grantType.getUrlParam()); this.body = buildBody(); this.headers = buildHead(); return new AuthService(this); } private String encodeClientCredentials(String clientId, String clientSecret) { String clientCredentials = clientId + ":" + clientSecret; return new String(Base64.encodeBase64(clientCredentials.getBytes(CHARSET)), CHARSET); } private Header[] buildHead() { String authHeaderValue = "Basic " + encodeClientCredentials(clientId, clientSecret); Header authHeader = new BasicHeader("Authorization", authHeaderValue); return new Header[]{ authHeader }; } private HttpEntity buildBody() { List<NameValuePair> nameValuePairs = new ArrayList<>(); for (String key : requestParameters.keySet()) { nameValuePairs.add(new BasicNameValuePair(key, requestParameters.get(key))); } try { return new UrlEncodedFormEntity(nameValuePairs); } catch (UnsupportedEncodingException e) { throw new ConnectionInitializationException("Unable to Build Request in this encoding.", e); } } } }
package org.parboiled.transform; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.LocalVariableNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.analysis.BasicValue; import org.parboiled.BaseParser; import org.parboiled.support.Var; import org.parboiled.transform.method.RuleAnnotation; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Set; import static org.objectweb.asm.Opcodes.ARETURN; import static org.objectweb.asm.Opcodes.INVOKESPECIAL; import static org.objectweb.asm.Opcodes.INVOKESTATIC; import static org.parboiled.transform.AsmUtils.getClassForType; import static org.parboiled.transform.AsmUtils.isActionRoot; import static org.parboiled.transform.AsmUtils.isAssignableTo; import static org.parboiled.transform.AsmUtils.isBooleanValueOfZ; import static org.parboiled.transform.AsmUtils.isVarRoot; import static org.parboiled.transform.method.RuleAnnotation.*; public class RuleMethod extends MethodNode { private final List<InstructionGroup> groups = new ArrayList<InstructionGroup>(); private final List<LabelNode> usedLabels = new ArrayList<LabelNode>(); private final Set<RuleAnnotation> ruleAnnotations = EnumSet .noneOf(RuleAnnotation.class); private final Class<?> ownerClass; private final int parameterCount; private boolean containsImplicitActions; // calls to Boolean.valueOf(boolean) private boolean containsExplicitActions; // calls to BaseParser.ACTION(boolean) private boolean containsVars; // calls to Var.<init>(T) private boolean containsPotentialSuperCalls; private boolean hasSkipNodeAnnotation; private boolean hasMemoMismatchesAnnotation; private boolean hasSkipActionsInPredicatesAnnotation; private int numberOfReturns; private InstructionGraphNode returnInstructionNode; private List<InstructionGraphNode> graphNodes; private List<LocalVariableNode> localVarVariables; private boolean bodyRewritten; private boolean skipGeneration; public RuleMethod(final Class<?> ownerClass, final int access, final String name, final String desc, final String signature, final String[] exceptions, final boolean hasExplicitActionOnlyAnno, final boolean hasDontLabelAnno, final boolean hasSkipActionsInPredicates) { super(Opcodes.ASM4, access, name, desc, signature, exceptions); this.ownerClass = ownerClass; parameterCount = Type.getArgumentTypes(desc).length; if (parameterCount == 0) ruleAnnotations.add(CACHED); if (hasDontLabelAnno) ruleAnnotations.add(DONT_LABEL); if (hasExplicitActionOnlyAnno) ruleAnnotations.add(EXPLICIT_ACTIONS_ONLY); if (hasSkipActionsInPredicates) ruleAnnotations.add(SKIP_ACTIONS_IN_PREDICATES); hasSkipActionsInPredicatesAnnotation = hasSkipActionsInPredicates; skipGeneration = isSuperMethod(); } public List<InstructionGroup> getGroups() { return groups; } public List<LabelNode> getUsedLabels() { return usedLabels; } public Class<?> getOwnerClass() { return ownerClass; } public boolean hasDontExtend() { return ruleAnnotations.contains(DONT_EXTEND); } public int getParameterCount() { return parameterCount; } public boolean containsImplicitActions() { return containsImplicitActions; } public void setContainsImplicitActions( final boolean containsImplicitActions) { this.containsImplicitActions = containsImplicitActions; } public boolean containsExplicitActions() { return containsExplicitActions; } public void setContainsExplicitActions( final boolean containsExplicitActions) { this.containsExplicitActions = containsExplicitActions; } public boolean containsVars() { return containsVars; } public boolean containsPotentialSuperCalls() { return containsPotentialSuperCalls; } public boolean hasCachedAnnotation() { return ruleAnnotations.contains(CACHED); } public boolean hasDontLabelAnnotation() { return ruleAnnotations.contains(DONT_LABEL); } public boolean hasSuppressNodeAnnotation() { return ruleAnnotations.contains(SUPPRESS_NODE); } public boolean hasSuppressSubnodesAnnotation() { return ruleAnnotations.contains(SUPPRESS_SUBNODES); } public boolean hasSkipActionsInPredicatesAnnotation() { return hasSkipActionsInPredicatesAnnotation; } public boolean hasSkipNodeAnnotation() { return hasSkipNodeAnnotation; } public boolean hasMemoMismatchesAnnotation() { return hasMemoMismatchesAnnotation; } public int getNumberOfReturns() { return numberOfReturns; } public InstructionGraphNode getReturnInstructionNode() { return returnInstructionNode; } public void setReturnInstructionNode( final InstructionGraphNode returnInstructionNode) { this.returnInstructionNode = returnInstructionNode; } public List<InstructionGraphNode> getGraphNodes() { return graphNodes; } public List<LocalVariableNode> getLocalVarVariables() { return localVarVariables; } public boolean isBodyRewritten() { return bodyRewritten; } public void setBodyRewritten() { this.bodyRewritten = true; } public boolean isSuperMethod() { Preconditions.checkState(!name.isEmpty()); return name.charAt(0) == '$'; } public InstructionGraphNode setGraphNode(final AbstractInsnNode insn, final BasicValue resultValue, final List<BasicValue> predecessors) { if (graphNodes == null) { // initialize with a list of null values graphNodes = Lists .newArrayList(new InstructionGraphNode[instructions.size()]); } final int index = instructions.indexOf(insn); InstructionGraphNode node = graphNodes.get(index); if (node == null) { node = new InstructionGraphNode(insn, resultValue); graphNodes.set(index, node); } node.addPredecessors(predecessors); return node; } @Override public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { recordDesc(ruleAnnotations, desc); if (Types.EXPLICIT_ACTIONS_ONLY_DESC.equals(desc)) { return null; // we do not need to record this annotation } if (Types.SUPPRESS_NODE_DESC.equals(desc)) { return null; // we do not need to record this annotation } if (Types.SUPPRESS_SUBNODES_DESC.equals(desc)) { return null; // we do not need to record this annotation } if (Types.SKIP_NODE_DESC.equals(desc)) { hasSkipNodeAnnotation = true; return null; // we do not need to record this annotation } if (Types.MEMO_MISMATCHES_DESC.equals(desc)) { hasMemoMismatchesAnnotation = true; return null; // we do not need to record this annotation } if (Types.SKIP_ACTIONS_IN_PREDICATES_DESC.equals(desc)) { hasSkipActionsInPredicatesAnnotation = true; return null; // we do not need to record this annotation } if (Types.DONT_SKIP_ACTIONS_IN_PREDICATES_DESC.equals(desc)) { hasSkipActionsInPredicatesAnnotation = false; return null; // we do not need to record this annotation } if (Types.DONT_LABEL_DESC.equals(desc)) { return null; // we do not need to record this annotation } if (Types.DONT_EXTEND_DESC.equals(desc)) { return null; } return visible ? super.visitAnnotation(desc, true) : null; // only keep visible annotations } @Override public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc) { switch (opcode) { case INVOKESTATIC: if (!ruleAnnotations.contains(EXPLICIT_ACTIONS_ONLY) && isBooleanValueOfZ(owner, name, desc)) { containsImplicitActions = true; } else if (isActionRoot(owner, name)) { containsExplicitActions = true; } break; case INVOKESPECIAL: if ("<init>".equals(name)) { if (isVarRoot(owner, name, desc)) { containsVars = true; } } else if (isAssignableTo(owner, BaseParser.class)) { containsPotentialSuperCalls = true; } break; } super.visitMethodInsn(opcode, owner, name, desc); } @Override public void visitInsn(final int opcode) { if (opcode == ARETURN) numberOfReturns++; super.visitInsn(opcode); } @Override public void visitJumpInsn(final int opcode, final Label label) { usedLabels.add(getLabelNode(label)); super.visitJumpInsn(opcode, label); } @Override public void visitTableSwitchInsn(final int min, final int max, final Label dflt, final Label[] labels) { usedLabels.add(getLabelNode(dflt)); for (final Label label : labels) usedLabels.add(getLabelNode(label)); super.visitTableSwitchInsn(min, max, dflt, labels); } @Override public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) { usedLabels.add(getLabelNode(dflt)); for (final Label label : labels) usedLabels.add(getLabelNode(label)); super.visitLookupSwitchInsn(dflt, keys, labels); } @Override public void visitLineNumber(final int line, final Label start) { // do not record line numbers } @Override public void visitLocalVariable(final String name, final String desc, final String signature, final Label start, final Label end, final int index) { // only remember the local variables of Type org.parboiled.support.Var that are not parameters if (index > parameterCount && Var.class .isAssignableFrom(getClassForType(Type.getType(desc)))) { if (localVarVariables == null) localVarVariables = new ArrayList<LocalVariableNode>(); localVarVariables.add( new LocalVariableNode(name, desc, null, null, null, index)); } } @Override public String toString() { return name; } public void moveFlagsTo(final RuleMethod method) { Preconditions.checkNotNull(method); moveTo(ruleAnnotations, method.ruleAnnotations); method.hasSkipNodeAnnotation |= hasSkipNodeAnnotation; method.hasMemoMismatchesAnnotation |= hasMemoMismatchesAnnotation; hasSkipNodeAnnotation = false; hasMemoMismatchesAnnotation = false; } public boolean isGenerationSkipped() { return skipGeneration; } public void dontSkipGeneration() { skipGeneration = false; } public void suppressNode() { ruleAnnotations.add(SUPPRESS_NODE); } }
package org.rakam.server.http; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.netty.util.AttributeKey; import java.util.AbstractMap; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import static io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_ALLOW_HEADERS; import static io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_EXPOSE_HEADERS; public class RouteMatcher { private final boolean debugMode; private HashMap<PatternBinding, HttpRequestHandler> routes = new HashMap(); private HttpRequestHandler noMatch = request -> request.response("404", HttpResponseStatus.NOT_FOUND).end(); static final AttributeKey<String> PATH = AttributeKey.valueOf("/path"); private List<Map.Entry<PatternBinding, HttpRequestHandler>> prefixRoutes = new LinkedList<>(); public RouteMatcher(boolean debugMode) { this.debugMode = debugMode; } public void handle(ChannelHandlerContext ctx, WebSocketFrame frame) { String path = ctx.attr(PATH).get(); final Object handler = routes.get(new PatternBinding(HttpMethod.GET, path)); if (handler != null) { if(handler instanceof WebSocketService) { ((WebSocketService) handler).handle(ctx, frame); } } else { // TODO: WHAT TO DO? ctx.close(); } } public void handle(RakamHttpRequest request) { String path = cleanPath(request.path()); int lastIndex = path.length() - 1; if(lastIndex > 0 && path.charAt(lastIndex) == '/') path = path.substring(0, lastIndex); // TODO: Make it optional if(request.getMethod() == HttpMethod.OPTIONS) { DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().set(ACCESS_CONTROL_ALLOW_HEADERS, "Origin, X-Requested-With, Content-Type, Accept, api_key"); response.headers().set(ACCESS_CONTROL_EXPOSE_HEADERS, "_auto_action"); request.response(response).end(); return; } final HttpRequestHandler handler = routes.get(new PatternBinding(request.getMethod(), path)); if (handler != null) { if(handler instanceof WebSocketService) { request.context().attr(PATH).set(path); } handler.handle(request); } else { for (Map.Entry<PatternBinding, HttpRequestHandler> prefixRoute : prefixRoutes) { if(path.startsWith(prefixRoute.getKey().pattern)) { prefixRoute.getValue().handle(request); return; } } noMatch.handle(request); } } private String cleanPath(String path) { StringBuilder builder = new StringBuilder(); boolean edge = false; int length = path.length(); for (int i = 0; i < length; i++) { char c = path.charAt(i); if (c == '/') { if(!edge) builder.append(c); edge = true; } else { builder.append(c); edge = false; } } return builder.toString(); } public void add(String path, WebSocketService handler) { PatternBinding key = new PatternBinding(HttpMethod.GET, path); routes.put(key, handler); } public void add(HttpMethod method, String path, HttpRequestHandler handler) { if(path.endsWith("*")) { String substring = path.substring(0, path.length() - 1); routes.put(new PatternBinding(method, substring), handler); prefixRoutes.add(new AbstractMap.SimpleImmutableEntry<>(new PatternBinding(method, substring), handler)); }else { routes.put(new PatternBinding(method, path), handler); } } public void noMatch(HttpRequestHandler handler) { noMatch = handler; } public static class PatternBinding { final HttpMethod method; final String pattern; private PatternBinding(HttpMethod method, String pattern) { this.method = method; this.pattern = pattern; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof PatternBinding)) return false; PatternBinding that = (PatternBinding) o; if (!method.equals(that.method)) return false; if (!pattern.equals(that.pattern)) return false; return true; } @Override public int hashCode() { int result = method.hashCode(); result = 31 * result + pattern.hashCode(); return result; } } public static class MicroRouteMatcher { private final RouteMatcher routeMatcher; private String path; public MicroRouteMatcher(RouteMatcher routeMatcher, String path) { this.routeMatcher = routeMatcher; this.path = path; } public void add(String lastPath, HttpMethod method, HttpRequestHandler handler) { Objects.requireNonNull(path, "path is not configured"); routeMatcher.add(method, path.equals("/") ? lastPath : path + lastPath, handler); } } }
package org.spongepowered.api; import com.google.common.base.Optional; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.item.Item; /** * Provides an easy way to retrieve types from a {@link Game}. */ public interface GameRegistry { /** * Gets a {@link BlockType} by its identifier. * * @param id The id to look up * @return The block or null if not found */ Optional<BlockType> getBlock(String id); /** * Gets an {@link Item} by its identifier. * * @param id The id to look up * @return The item or null if not found */ Optional<Item> getItem(String id); /** * Gets the ID registered to the object. * * @param obj The object to look up * @return The id or null if none found */ Optional<String> getId(Object obj); }
package prope.executables; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.apache.commons.io.FileUtils; import prope.metrics.adaptability.AdaptabilityAnalyzer; import prope.metrics.installability.deployability.DeploymentPackageAnalyzer; import prope.metrics.installability.server.AverageInstallationTimeCalculator; import prope.metrics.portability.PortabilityAnalyzer; import prope.reporting.Report; import prope.reporting.ReportWriter; public final class AnalysisWorkflow { private final Path root; private final DirectoryAnalyzer dirAnalyzer; private FileAnalyzer fileAnalyzer; private Report report; private long startTime; public AnalysisWorkflow(Path root, AnalysisType type) { this.root = root; if (!Files.exists(root)) { throw new IllegalArgumentException("path " + root.toString() + " does not exist"); } if (AnalysisType.DEPLOYABILITY.equals(type)) { fileAnalyzer = new DeploymentPackageAnalyzer(); } else if (AnalysisType.INSTALLABILITY.equals(type)) { fileAnalyzer = new AverageInstallationTimeCalculator(); } else if (AnalysisType.PORTABILITY.equals(type)) { fileAnalyzer = new PortabilityAnalyzer(); } else if (AnalysisType.ADAPTABILITY.equals(type)) { fileAnalyzer = new AdaptabilityAnalyzer(); } else if (AnalysisType.UNKNOWN.equals(type)) { throw new AnalysisException("no valid AnalysisType found"); } dirAnalyzer = new DirectoryAnalyzer(fileAnalyzer); } public Report start() { startWatch(); if (!Files.isDirectory(root)) { parseFile(root); } else { parseDirectory(root); } stopWatch(); writeResults(); purgeTempDir(); return report; } private void stopWatch() { long duration = System.currentTimeMillis() - startTime; System.out.println("======================================="); System.out.println("Analysis finished; Duration: " + duration + " millisec; writing results"); } private void startWatch() { startTime = System.currentTimeMillis(); } private void parseFile(Path file) { report = new Report(); fileAnalyzer.analyzeFile(file).forEach( reportEntry -> report.addEntry(reportEntry)); } private void parseDirectory(Path root) { report = dirAnalyzer.analyzeDirectory(root); } private void writeResults() { fileAnalyzer.traversalCompleted(); ReportWriter writer = new ReportWriter(report); writer.writeToExcelFile("results.csv"); } private void purgeTempDir() { try { FileUtils.deleteDirectory(new File("tmp")); } catch (IOException ignore) { // Not critical -> ignore } } }
package se.lundakarnevalen.ticket.db; import lombok.Getter; import se.lundakarnevalen.ticket.db.framework.Column; import se.lundakarnevalen.ticket.db.framework.Mapper; import se.lundakarnevalen.ticket.db.framework.Table; import java.math.BigInteger; import java.security.SecureRandom; import java.sql.*; import java.util.LinkedList; import java.util.List; @Table(name = "orders") public class Order extends Entity { @Column public final int id; @Column @Getter protected Timestamp created; @Column @Getter protected Timestamp expires; @Column @Getter protected String identifier; @Column @Getter protected int customer_id; @Column(table = "payments", column = "id") @Getter protected int payment_id; private static final String TABLE = "`orders` LEFT JOIN `payments` ON `orders`.`id`=`payments`.`order_id`"; private static final String COLS = Entity.getCols(Order.class); private static SecureRandom random = new SecureRandom(); private Order(int id) throws SQLException { this.id = id; } private static Order create(ResultSet rs) throws SQLException { Order order = new Order(rs.getInt("id")); populateColumns(order, rs); return order; } public static List<Order> getAll() throws SQLException { String query = "SELECT " + COLS + " FROM " + TABLE + " GROUP BY `orders`.`id`"; return new Mapper<Order>(getCon(), query).toEntityList(rs -> Order.create(rs)); } public static List<Order> getUnpaid() throws SQLException { String query = "SELECT " + COLS + " FROM " + TABLE + " WHERE `payments`.`id` IS NULL" + " GROUP BY `orders`.`id`"; return new Mapper<Order>(getCon(), query).toEntityList(rs -> Order.create(rs)); } public static List<Order> getPaid() throws SQLException { String query = "SELECT " + COLS + " FROM " + TABLE + " WHERE `payments`.`id` IS NOT NULL" + " GROUP BY `orders`.`id`"; return new Mapper<Order>(getCon(), query).toEntityList(rs -> Order.create(rs)); } public static Order getSingle(long id) throws SQLException { String query = "SELECT " + COLS + " FROM " + TABLE + " WHERE `orders`.`id`=?" + " GROUP BY `orders`.`id`"; PreparedStatement stmt = prepare(query); stmt.setLong(1, id); return new Mapper<Order>(stmt).toEntity(rs -> Order.create(rs)); } public static Order getByIdentifier(String id) throws SQLException { String query = "SELECT " + COLS + " FROM " + TABLE + " WHERE `orders`.`identifier`=?" + " GROUP BY `orders`.`id`"; PreparedStatement stmt = prepare(query); stmt.setString(1, id); return new Mapper<Order>(stmt).toEntity(Order::create); } public static List<Order> getByCustomer(Customer customer) throws SQLException { String query = "SELECT " + COLS + " FROM " + TABLE + " WHERE `orders`.`customer_id`=?" + " GROUP BY `orders`.`id`"; PreparedStatement stmt = prepare(query); stmt.setLong(1, customer.id); return new Mapper<Order>(stmt).toEntityList(rs -> Order.create(rs)); } public static Order create(User user) throws SQLException { Connection con = transaction(); try { String query = "INSERT INTO `orders` SET `identifier`=?, `expires`=(CURRENT_TIMESTAMP + INTERVAL 30 MINUTE)"; PreparedStatement stmt = prepare(con, query); stmt.setString(1, generateIdentifier()); int id = executeInsert(stmt); Transaction.create(con, user.id, id, 0, 0, 0, 0); commit(con); return getSingle(id); } finally { rollback(con); } } private static String generateIdentifier() { String identifier = new BigInteger(48, random).toString(32).substring(0, 8); identifier = identifier.toUpperCase(); identifier = identifier.replace('O', '0'); identifier = identifier.replace('I', '1'); return identifier; } public List<Ticket> addTickets(Performance performance, int category_id, int rate_id, int profile_id, int ticketCount, User user, Location location) throws SQLException { System.out.println("Reserving " + ticketCount + " tickets for perf=" + performance.id + ", cat=" + category_id + ", rate=" + rate_id + " and profile=" + profile_id); Connection con = getCon(); try { con.setAutoCommit(false); String query = "SELECT `id` FROM `seats` WHERE `active_ticket_id` IS NULL AND `category_id`=? AND `performance_id`=? AND `profile_id`=? LIMIT ? FOR UPDATE"; PreparedStatement stmt = con.prepareStatement(query); stmt.setInt(1, category_id); stmt.setInt(2, performance.id); stmt.setInt(3, profile_id); stmt.setInt(4, ticketCount); ResultSet rs = stmt.executeQuery(); Price price = Price.getSingle(category_id, rate_id); int transaction_id = Transaction.create(con, user.id, id, profile_id, 0, 0, location.id); List<Ticket> tickets = new LinkedList<Ticket>(); int ticketsAvailable = 0; while (rs.next()) { int seat_id = rs.getInt("id"); int ticketPrice = Math.max(0, price.price + performance.surcharge); if (price.price == 0) { // Complimentary tickets are not subject to surcharge ticketPrice = 0; } Ticket ticket = Ticket.create(con, id, seat_id, rate_id, ticketPrice); stmt = con.prepareStatement("UPDATE `seats` SET `active_ticket_id`=? WHERE `id`=?"); stmt.setInt(1, ticket.id); stmt.setInt(2, seat_id); stmt.executeUpdate(); Transaction.addTicket(con, transaction_id, ticket.id, Transaction.TICKET_ADDED); tickets.add(ticket); ticketsAvailable++; } if (ticketsAvailable < ticketCount) { con.rollback(); return null; } con.commit(); return tickets; } catch (SQLException e) { con.rollback(); throw e; } finally { con.close(); } } public void setCustomer(int new_customer, User user) throws SQLException { String query = "UPDATE `orders` SET `customer_id`=? WHERE `orders`.`id`=?"; Connection con = getCon(); try { con.setAutoCommit(false); PreparedStatement stmt = con.prepareStatement(query); stmt.setLong(2, id); setIntNullable(stmt, 1, new_customer); stmt.executeUpdate(); this.customer_id = new_customer; int transaction_id = Transaction.create(con, user.id, id, 0, new_customer, 0, 0); for (Ticket t : Ticket.getByOrder(id)) { Transaction.addTicket(con, transaction_id, t.id, Transaction.CUSTOMER_SET); } con.commit(); } catch (SQLException e) { con.rollback(); throw e; } finally { con.close(); } } public Payment pay(int user_id, int profile_id, int amount, List<Ticket> tickets, String method, String reference) throws SQLException { Connection con = getCon(); try { con.setAutoCommit(false); int transaction_id = Transaction.create(con, user_id, id, profile_id, 0, 0, 0); int payment_id = Payment.create(con, transaction_id, id, amount, method, reference); for (Ticket t : tickets) { Transaction.addTicket(con, transaction_id, t.id, Transaction.TICKET_PAID); t.setPaid(con); } con.commit(); return Payment.getSingle(payment_id); } catch (SQLException e) { con.rollback(); throw e; } finally { con.close(); } } public boolean isPaid() throws SQLException { List<Payment> payments = Payment.getByOrder(id); return !payments.isEmpty(); } public boolean hasTickets() throws SQLException { List<Ticket> tickets = Ticket.getByOrder(id); return !tickets.isEmpty(); } public static void cleanup(int profile_id) throws SQLException { System.out.println("Starting abandoned order cleanup"); Connection con = transaction(); try { String query = "SELECT `seats`.`id` as `seat_id`, `tickets`.`id` as `ticket_id`" + ", `orders`.`id` as `order_id`, `orders`.`identifier`" + ", `orders`.`customer_id`" + " FROM `seats` LEFT JOIN `tickets` ON `seats`.`active_ticket_id` = `tickets`.`id`" + " LEFT JOIN `orders` ON `tickets`.`order_id` = `orders`.`id`" + " WHERE `seats`.`profile_id`=? AND `orders`.`expires` < (NOW() - INTERVAL 10 MINUTE)" + " AND `tickets`.`paid` IS NULL AND `tickets`.`printed` IS NULL" + " AND (`orders`.`customer_id` IS NULL OR `orders`.`customer_id`" + " IN (SELECT `customer_id` FROM `customer_profiles` WHERE `profile_id`=?))"; PreparedStatement stmt = prepare(con, query); stmt.setInt(1, profile_id); stmt.setInt(2, profile_id); ResultSet rs = stmt.executeQuery(); String removeTicketQuery = "UPDATE `tickets` SET `order_id`=NULL WHERE `id`=?"; PreparedStatement removeTicket = prepare(con, removeTicketQuery); String releaseSeatQuery = "UPDATE `seats` SET `active_ticket_id` = NULL WHERE `active_ticket_id`=?"; PreparedStatement releaseSeat = prepare(con, releaseSeatQuery); while (rs.next()) { int seat_id = rs.getInt("seat_id"); int ticket_id = rs.getInt("ticket_id"); int order_id = rs.getInt("order_id"); String identifier = rs.getString("identifier"); System.out.println("Releasing seat " + seat_id + ", ticket " + ticket_id + ", order " + order_id + " " + identifier); removeTicket.setInt(1, ticket_id); removeTicket.executeUpdate(); releaseSeat.setInt(1, ticket_id); releaseSeat.executeUpdate(); int transaction_id = Transaction.create(con, 1, order_id, 1, 0, 0, 0); Transaction.addTicket(con, transaction_id, ticket_id, Transaction.TICKET_REMOVED); } commit(con); } finally { rollback(con); } } }
package seedu.emeraldo.model.task; import seedu.emeraldo.commons.exceptions.IllegalValueException; import java.time.*; import java.time.temporal.ChronoUnit; import java.util.regex.Matcher; /** * Represents a Task's date and time in Emeraldo. * Guarantees: immutable; is valid as declared in {@link #isValidDateTime(String)} */ public class DateTime { //@@author A0139749L private static final String MESSAGE_KEYWORD_FROM_CONSTRAINTS = "Invalid format! It should be " + "'from DD/MM/YYYY, HH:MM to DD/MM/YYYY, HH:MM'\n" + "Accepted date formats: 4/03/2016 | 4/03/16 | 4-03-16 | 4 March 16 | 4/03 | 4 Mar\n" + "Accepted time formats: 14:20 (time in 24 hours format)\n" + "Type 'help' to see the full list of accepted formats in the user guide"; private static final String MESSAGE_KEYWORD_BY_CONSTRAINTS = "Invalid format! It should be " + "'by DD/MM/YYYY, HH:MM'\n" + "Accepted date formats: 4/03/2016 | 4/03/16 | 4-03-16 | 4 March 16 | 4/03 | 4 Mar\n" + "Accepted time formats: 14:20 (time in 24 hours format)\n" + "Type 'help' to see the full list of accepted formats in the user guide"; private static final String MESSAGE_KEYWORD_ON_CONSTRAINTS = "Invalid format! It should be " + "'on DD/MM/YYYY'\n" + "Accepted date formats: 4/03/2016 | 4/03/16 | 4-03-16 | 4 March 16 | 4/03 | 4 Mar\n" + "Type 'help' to see the full list of accepted formats in the user guide"; public static final String MESSAGE_DATETIME_CONSTRAINTS = "Command format is invalid! " + "It must be one of the following:\n" + "Keyword 'on' : on DD/MM/YYYY\n" + "Keyword 'by' : by DD/MM/YYYY, HH:MM\n" + "Keyword 'from' and 'to' : from DD/MM/YYYY, HH:MM to DD/MM/YYYY, HH:MM"; public final String value; public final String context; public final String overdueContext; public final String eventContext; public final String valueFormatted; public final LocalDate valueDate; public final LocalTime valueTime; public final LocalDate valueDateEnd; public final LocalTime valueTimeEnd; public DateTime(String dateTime) throws IllegalValueException { assert dateTime != null; final Matcher matcher = DateTimeParser.DATETIME_VALIDATION_REGEX.matcher(dateTime); if (!dateTime.isEmpty() && !matcher.matches()) { throw new IllegalValueException(MESSAGE_DATETIME_CONSTRAINTS); } if(dateTime.isEmpty()){ this.valueDate = null; this.valueTime = null; this.valueDateEnd = null; this.valueTimeEnd = null; this.value = ""; this.valueFormatted = "Not specified"; this.context = ""; this.overdueContext = ""; this.eventContext = ""; } else { final String preKeyword = matcher.group("preKeyword").trim(); if(preKeyword.equals("on")){ if(!isValidFormatFor_GivenKeyword(dateTime, preKeyword)) throw new IllegalValueException(MESSAGE_KEYWORD_ON_CONSTRAINTS); this.valueDate = DateTimeParser.valueDateFormatter(matcher, preKeyword); this.context = setContext(valueDate, null); this.overdueContext = setOverdueContext(valueDate, null); this.eventContext = ""; this.valueFormatted = DateTimeParser.valueFormatter(matcher, preKeyword) + context; this.valueTime = null; this.valueDateEnd = null; this.valueTimeEnd = null; }else if(preKeyword.equals("by")){ if(!isValidFormatFor_GivenKeyword(dateTime, preKeyword)) throw new IllegalValueException(MESSAGE_KEYWORD_BY_CONSTRAINTS); this.valueDate = DateTimeParser.valueDateFormatter(matcher, preKeyword); this.valueTime = DateTimeParser.valueTimeFormatter(matcher, preKeyword); this.context = setContext(valueDate, valueTime); this.overdueContext = setOverdueContext(valueDate, valueTime); this.eventContext = ""; this.valueFormatted = DateTimeParser.valueFormatter(matcher, preKeyword) + context; this.valueDateEnd = null; this.valueTimeEnd = null; }else{ if(!isValidFormatFor_GivenKeyword(dateTime, preKeyword)) throw new IllegalValueException(MESSAGE_KEYWORD_FROM_CONSTRAINTS); final String aftKeyword = matcher.group("aftKeyword").trim(); this.valueDate = DateTimeParser.valueDateFormatter(matcher, preKeyword); this.valueTime = DateTimeParser.valueTimeFormatter(matcher, preKeyword); this.context = setContext(valueDate, valueTime); this.valueDateEnd = DateTimeParser.valueDateFormatter(matcher, aftKeyword); this.valueTimeEnd = DateTimeParser.valueTimeFormatter(matcher, aftKeyword); this.overdueContext = setOverdueContext(valueDateEnd, valueTimeEnd); this.eventContext = setEventContext(valueDate, valueTime, valueDateEnd, valueTimeEnd); this.valueFormatted = DateTimeParser.valueFormatter(matcher, preKeyword) + " " + DateTimeParser.valueFormatter(matcher, aftKeyword) + context + eventContext; } this.value = dateTime; } } private boolean isValidFormatFor_GivenKeyword(String dateTime, String keyword){ switch(keyword){ case "on": return dateTime.matches(DateTimeParser.ON_KEYWORD_VALIDATION_REGEX); case "by": return dateTime.matches(DateTimeParser.BY_KEYWORD_VALIDATION_REGEX); case "from": return dateTime.matches(DateTimeParser.FROM_KEYWORD_VALIDATION_REGEX); default: return false; } } //@@author A0142290 public String setContext(LocalDate valueDate, LocalTime valueTime) { String context = ""; Boolean timeIsNow = valueTime != null && valueTime.getHour() == LocalTime.now().getHour() && valueTime.getMinute() == LocalTime.now().getMinute(); Boolean dayIsToday = valueDate.isEqual(LocalDate.now()); Boolean timeIsLater = valueTime != null && valueTime.isAfter(LocalTime.now()); Boolean noTimeSpecified = valueTime == null; Boolean dayIsTomorrow = valueDate.minusDays(1).isEqual(LocalDate.now()); Boolean dayIsBeforeToday = valueDate.isBefore(LocalDate.now()); String stringHours = ""; //For tasks due today, now if (dayIsToday && timeIsNow) context = "(Today; Now)"; //For tasks that is due today, after current time else if (dayIsToday && timeIsLater){ stringHours = Long.toString(LocalTime.now().until(valueTime, ChronoUnit.HOURS)); context = " (Today; in " + stringHours + " hours) "; } //For tasks due today at unspecified times else if (dayIsToday && noTimeSpecified) context = " (Today)"; //For tasks due tomorrow else if (dayIsTomorrow) context = " (Tomorrow)"; else if (dayIsBeforeToday) context = ""; else context = ""; return context; } public String setOverdueContext(LocalDate valueDate, LocalTime valueTime) { String overdueContext = ""; Boolean dayIsBeforeToday = valueDate.isBefore(LocalDate.now()); Boolean dayIsToday = valueDate.isEqual(LocalDate.now()); Boolean dayIsAfterToday = valueDate.isEqual(LocalDate.now()); Boolean timeIsBeforeNow = valueTime != null && valueTime.isBefore(LocalTime.now()); //For tasks due before today if (dayIsBeforeToday){ int monthsDue = valueDate.until(LocalDate.now()).getMonths(); int yearsDue = valueDate.until(LocalDate.now()).getYears(); int daysDue = valueDate.until(LocalDate.now()).getDays(); String stringDaysDue = Integer.toString(daysDue); String stringMonthsDue = Integer.toString(monthsDue); String stringYearsDue = Integer.toString(yearsDue); String periodDue = ""; if (monthsDue > 0 && yearsDue > 0) periodDue = stringYearsDue + " years, " + stringMonthsDue + " months and " + stringDaysDue + " days"; else if (monthsDue > 0 && yearsDue == 0) periodDue = stringMonthsDue + " months and " + stringDaysDue + " days "; else if (monthsDue == 0 && yearsDue == 0) periodDue = valueDate.until(LocalDate.now()).getDays() + " days"; else periodDue = ""; overdueContext = "Overdue by " + periodDue; } //For tasks that is due today, at or before current time else if (dayIsToday && timeIsBeforeNow) { String stringHoursDue = Long.toString(valueTime.until(LocalTime.now(), ChronoUnit.HOURS)); String periodDue = stringHoursDue + " hours "; overdueContext = "Due just now, " + periodDue + "ago"; } else if (dayIsAfterToday) { overdueContext = ""; } return overdueContext; } public String setEventContext(LocalDate valueDate, LocalTime valueTime, LocalDate valueDateEnd, LocalTime valueTimeEnd) { String eventContext = ""; LocalDateTime valueDateTime = LocalDateTime.of(valueDate, valueTime); LocalDateTime valueDateTimeEnd = LocalDateTime.of(valueDateEnd, valueTimeEnd); Boolean duringEventTime = valueDateTime.isBefore(LocalDateTime.now()) && valueDateTimeEnd.isAfter(LocalDateTime.now()); if (duringEventTime) eventContext = " (Today; Now)"; else eventContext = ""; return eventContext; } public String getOverdueContext(){ return overdueContext; } public String getEventContext(){ return eventContext; } @Override public String toString() { return valueFormatted; } //@@author @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof DateTime // instanceof handles nulls && this.valueFormatted.equals(((DateTime) other).valueFormatted)); // state check } @Override public int hashCode() { return value.hashCode(); } }
package seedu.jimi.model.datetime; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; import java.util.Date; import java.util.Objects; import seedu.jimi.commons.core.Messages; import seedu.jimi.commons.exceptions.IllegalValueException; public class DateTime implements Comparable<DateTime> { public static final String DATE_FORMAT = "yyyy-MM-dd"; public static final String TIME_FORMAT = "HH:mm"; public static final String DATETIME_FORMAT = DATE_FORMAT + " " + TIME_FORMAT; private LocalDateTime dtInstance; public DateTime() { dtInstance = LocalDateTime.now(); } public DateTime(String dateStr) throws IllegalValueException { DateTimeFormatter dtFormatter = DateTimeFormatter.ofPattern(DATETIME_FORMAT); try { dtInstance = LocalDateTime.parse(dateStr, dtFormatter); } catch (DateTimeParseException e) { throw new IllegalValueException(Messages.MESSAGE_INVALID_DATE); } } public DateTime(Date date) { dtInstance = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); } public String getDate() { DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(DATE_FORMAT); return dtInstance.format(dateFormatter).toString(); } public String getTime() { DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(TIME_FORMAT); return dtInstance.format(timeFormatter).toString(); } private LocalDateTime getLocalDateTime() { return dtInstance; } public long getDifferenceInHours(DateTime other) { return ChronoUnit.HOURS.between(dtInstance, other.getLocalDateTime()); } public long getDifferenceInDays(DateTime other) { return ChronoUnit.DAYS.between(dtInstance, other.getLocalDateTime()); } public long getDifferenceInMonths(DateTime other) { return ChronoUnit.MONTHS.between(dtInstance, other.getLocalDateTime()); } @Override public int compareTo(DateTime dt) { return dtInstance.compareTo(dt.getLocalDateTime()); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof DateTime// instanceof handles nulls && this.dtInstance.equals(((DateTime) other).getLocalDateTime())); } @Override public int hashCode() { return Objects.hash(dtInstance); } @Override public String toString() { DateTimeFormatter dtFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); return dtInstance.format(dtFormatter); } }
package seedu.taskboss.commons.core; import java.util.Objects; import java.util.logging.Level; /** * Config values used by the app */ public class Config { public static final String DEFAULT_CONFIG_FILE = "config.json"; // Config values customizable through config file private String appTitle = "TaskBoss App"; private Level logLevel = Level.INFO; private String userPrefsFilePath = "preferences.json"; private String taskBossFilePath = "/taskboss.xml"; private String taskBossName = "MyTaskBoss"; public String getAppTitle() { return appTitle; } public void setAppTitle(String appTitle) { this.appTitle = appTitle; } public Level getLogLevel() { return logLevel; } public void setLogLevel(Level logLevel) { this.logLevel = logLevel; } public String getUserPrefsFilePath() { return userPrefsFilePath; } public void setUserPrefsFilePath(String userPrefsFilePath) { this.userPrefsFilePath = userPrefsFilePath; } public String getTaskBossFilePath() { return taskBossFilePath; } public void setTaskBossFilePath(String taskBossFilePath) { this.taskBossFilePath = taskBossFilePath; } public String getTaskBossName() { return taskBossName; } public void setTaskBossName(String taskBossName) { this.taskBossName = taskBossName; } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Config)) { //this handles null as well. return false; } Config o = (Config) other; return Objects.equals(appTitle, o.appTitle) && Objects.equals(logLevel, o.logLevel) && Objects.equals(userPrefsFilePath, o.userPrefsFilePath) && Objects.equals(taskBossFilePath, o.taskBossFilePath) && Objects.equals(taskBossName, o.taskBossName); } @Override public int hashCode() { return Objects.hash(appTitle, logLevel, userPrefsFilePath, taskBossFilePath, taskBossName); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("App title : " + appTitle); sb.append("\nCurrent log level : " + logLevel); sb.append("\nPreference file Location : " + userPrefsFilePath); sb.append("\nLocal data file location : " + taskBossFilePath); sb.append("\nTaskBoss name : " + taskBossName); return sb.toString(); } }
package taro.spreadsheet; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.usermodel.XSSFSheet; import java.util.Date; import java.util.List; import static com.google.common.collect.Lists.newArrayList; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.apache.commons.lang3.StringUtils.trim; /** * Very simple utility to help read a POI sheet within an Excel (.xlsx) file. * Does not work with .xls files. * * The getValue and getStringValue methods return the TRIMMED content of the cell, and return an empty String * if the cell doesn't exist or is empty. * * The getNumericValue method returns 0 if the cell doesn't exist or is empty. It throws an exception if the * value cannot be parsed to a number. * * The getDateValue method returns null if the cell doesn't exist or is empty, and throws an exception if the * value is not a date. */ @SuppressWarnings("UnusedDeclaration") public class SpreadsheetReader { public static int getColumnIndex(String cellId) { return new CellReference(cellId).getCol(); } public static int getRowIndex(String cellId) { return new CellReference(cellId).getRow(); } public static String getCellAddress(int col, int row) { return CellReference.convertNumToColString(col) + (row+1); } private Sheet sheet; private DataFormatter df = new DataFormatter(); public SpreadsheetReader(Sheet sheet) { this.sheet = sheet; } public Sheet getPoiSheet() { return sheet; } public int getNumRows() { return sheet.getLastRowNum()+1; } public int getNumCols(int rowNum) { return sheet.getRow(rowNum).getLastCellNum()+1; } /** * Attempts to convert all values to a string. Returns the trimmed content of the cell, or an empty String * if the cell doesn't exist or is empty. */ public String getValue(String cellId) { Cell cell = getCell(cellId); return getValue(cell); } /** * Attempts to convert all values to a string. Returns the trimmed content of the cell, or an empty String * if the cell doesn't exist or is empty. */ public String getValue(int colIndex, int rowIndex) { Cell cell = getCell(colIndex, rowIndex); return getValue(cell); } /** * Attempts to convert all values to a string. Returns the trimmed content of the cell, or an empty String * if the cell doesn't exist or is empty. */ public String getValue(Cell cell) { return trim(df.formatCellValue(cell)); } /** * Returns the trimmed content of the cell as a String, or an empty String * if the cell doesn't exist or is empty. */ public String getStringValue(String cellId) { Cell cell = getCell(cellId); return getStringValue(cell); } /** * Returns the trimmed content of the cell as a String, or an empty String * if the cell doesn't exist or is empty. */ public String getStringValue(int columnIndex, int rowIndex) { Cell cell = getCell(columnIndex, rowIndex); return getStringValue(cell); } /** * Returns the trimmed content of the cell as a String, or an empty String * if the cell doesn't exist or is empty. */ public String getStringValue(Cell cell) { if (cell == null) { return ""; } else { String value = cell.getStringCellValue(); if (value != null) { value = value.trim(); } return value; } } /** * Returns the numeric content of the cell, or 0 if the cell doesn't exist or is empty. */ public Double getNumericValue(String cellId) { Cell cell = getCell(cellId); return getNumericValue(cell); } /** * Returns the numeric content of the cell, or 0 if the cell doesn't exist or is empty. */ public Double getNumericValue(int columnIndex, int rowIndex) { Cell cell = getCell(columnIndex, rowIndex); return getNumericValue(cell); } public Double getNumericValue(Cell cell) { if (cell == null) { return 0d; } else { return cell.getNumericCellValue(); } } /** * Returns the Date content of the cell, or null if the cell doesn't exist or is empty. */ public Date getDateValue(int columnIndex, int rowIndex) { Cell cell = getCell(columnIndex, rowIndex); return getDateValue(cell); } public Date getDateValue(String cellId) { Cell cell = getCell(cellId); return getDateValue(cell); } public Date getDateValue(Cell cell) { if (cell == null) { return null; } else { return cell.getDateCellValue(); } } public Cell getCell(String cellId) { int columnIndex = getColumnIndex(cellId); int rowIndex = getRowIndex(cellId); return getCell(columnIndex, rowIndex); } public Cell getCell(int columnIndex, int rowIndex) { Row row = sheet.getRow(rowIndex); if (row == null) { return null; } else { return row.getCell(columnIndex); } } public CellType getCellType(int col, int row) { Cell cell = getCell(col, row); return cell != null ? cell.getCellType() : CellType.BLANK; } public boolean isString(int col, int row) { return getCellType(col, row) == CellType.STRING; } public boolean isNumeric(int col, int row) { return getCellType(col, row) == CellType.NUMERIC; } public List<String> readDownUntilBlank(String startingCell) { List<String> values = newArrayList(); int rowIndex = getRowIndex(startingCell); int colIndex = getColumnIndex(startingCell); String value = getValue(colIndex, rowIndex); while (isNotBlank(value)) { values.add(value); rowIndex++; value = getValue(colIndex, rowIndex); } return values; } public String[] readDown(String startingCell, int num) { String[] values = new String[num]; int rowIndex = getRowIndex(startingCell); int colIndex = getColumnIndex(startingCell); for (int i = 0; i < values.length; i++) { values[i] = getValue(colIndex, rowIndex+i); } return values; } public double[] readDownNumeric(String startingCell, int num) { double[] values = new double[num]; int rowIndex = getRowIndex(startingCell); int colIndex = getColumnIndex(startingCell); for (int i = 0; i < values.length; i++) { values[i] = getNumericValue(colIndex, rowIndex+i); } return values; } public List<String> readAcrossUntilBlank(String startingCell) { List<String> values = newArrayList(); int rowIndex = getRowIndex(startingCell); int colIndex = getColumnIndex(startingCell); String value = getValue(colIndex, rowIndex); while (isNotBlank(value)) { values.add(value); colIndex++; value = getValue(colIndex, rowIndex); } return values; } public String[] readAcross(String startingCell, int num) { String[] values = new String[num]; int rowIndex = getRowIndex(startingCell); int colIndex = getColumnIndex(startingCell); for (int i = 0; i < values.length; i++) { values[i] = getValue(colIndex+i, rowIndex); } return values; } public double[] readAcrossNumeric(String startingCell, int num) { double[] values = new double[num]; int rowIndex = getRowIndex(startingCell); int colIndex = getColumnIndex(startingCell); for (int i = 0; i < values.length; i++) { values[i] = getNumericValue(colIndex+i, rowIndex); } return values; } public String[][] readSheet() { List<List<String>> contents = newArrayList(); int maxRowNum = sheet.getLastRowNum(); int maxColNum = 0; for (int rowNum = 0; rowNum <= maxRowNum; rowNum++) { Row row = sheet.getRow(rowNum); List<String> rowContents = newArrayList(); contents.add(rowContents); if (row == null) continue; int lastCellNum = row.getLastCellNum(); for (int cellNum = 0; cellNum <= lastCellNum; cellNum++) { rowContents.add(getValue(row.getCell(cellNum))); } if (lastCellNum > maxColNum) { maxColNum = lastCellNum; } } String[][] contentsArray = new String[contents.size()][maxColNum]; for (int i = 0; i < contentsArray.length; i++) { contentsArray[i] = contents.get(i).toArray(new String[maxColNum]); } return contentsArray; } public String getSheetName() { return sheet.getSheetName(); } public boolean rowHasData(int rowIndex) { Row row = sheet.getRow(rowIndex); return row != null && row.getPhysicalNumberOfCells() > 0; } }
package properties.competition; /* * Taken from the JavaRV-MMT benchmarks - check if they have non mmt benchmarks too */ import static structure.impl.other.Quantification.FORALL; import java.awt.geom.Line2D; import properties.Property; import properties.PropertyMaker; import structure.intf.Assignment; import structure.intf.Binding; import structure.intf.Guard; import structure.intf.QEA; import creation.QEABuilder; public class JavaRV_mmt implements PropertyMaker { @Override public QEA make(Property property) { switch (property) { case JAVARV_MMT_ONE: return makeOne(); case JAVARV_MMT_TWO: return makeTwo(); case JAVARV_MMT_THREE: return makeThree(); case JAVARV_MMT_FOUR: return makeFour(); case JAVARV_MMT_FIVE: return makeFive(); default: return null; } } public QEA makeOne() { QEABuilder q = new QEABuilder("JAVARV_MMT_ONE"); final int STEP = 1; final int counterOld = 1; final int counterNew = 2; // TODO Should we add a guard here to specify that the counter must // start in 1? q.addTransition(1, STEP, new int[] { counterOld }, 2); q.startTransition(2); q.eventName(STEP); q.addVarArg(counterNew); q.addGuard(new Guard("counterNew_=_counterOld_+_1") { @Override public int[] vars() { return new int[] { counterOld, counterNew }; } @Override public boolean usesQvars() { return false; } @Override public boolean check(Binding binding, int qvar, Object firstQval) { return check(binding); } @Override public boolean check(Binding binding) { int counterOldVal = binding.getForcedAsInteger(counterOld); int counterNewVal = binding.getForcedAsInteger(counterNew); return counterNewVal == counterOldVal + 1; } }); q.addAssignment(Assignment.store(counterOld, counterNew)); q.endTransition(2); q.addFinalStates(1, 2); QEA qea = q.make(); qea.record_event_name("step", 1); return qea; } public QEA makeTwo() { QEABuilder q = new QEABuilder("JAVARV_MMT_TWO"); int REQUEST = 1; int RESPONSE = 2; int s = -1; q.addQuantification(FORALL, s); q.addTransition(1, REQUEST, new int[] { s }, 2); q.addTransition(2, REQUEST, new int[] { s }, 2); q.addTransition(2, RESPONSE, new int[] { s }, 3); q.addTransition(3, RESPONSE, new int[] { s }, 3); q.addTransition(3, REQUEST, new int[] { s }, 2); q.addFinalStates(1, 3); QEA qea = q.make(); qea.record_event_name("request", 1); qea.record_event_name("response", 2); return qea; } public QEA makeThree() { QEABuilder q = new QEABuilder("JAVARV_MMT_THREE"); int RUN = 1; int LOCK_TRUE = 2; int UNLOCK = 3; int ACTION = 4; int i = -1; int j = 1; q.addQuantification(FORALL, i); q.addTransition(1, RUN, new int[] { i }, 2); q.addTransition(1, UNLOCK, new int[] { i }, 2); q.addTransition(2, LOCK_TRUE, new int[] { i }, 3); q.addTransition(3, UNLOCK, new int[] { i }, 2); q.addTransition(3, ACTION, new int[] { i }, 3); q.addTransition(3, LOCK_TRUE, new int[] { j }, 4); q.addFinalStates(1, 2, 3); QEA qea = q.make(); qea.record_event_name("run", 1); qea.record_event_name("lock_true", 2); qea.record_event_name("unlock", 3); qea.record_event_name("action", 4); return qea; } public QEA makeFour() { QEABuilder q = new QEABuilder("JAVARV_MMT_FOUR"); final int STEP = 1; final int pos = 1; final int time = 2; final int newPos = 3; final int newTime = 4; q.addTransition(1, STEP, new int[] { pos, time }, 2); q.startTransition(2); q.eventName(STEP); q.addVarArg(newPos); q.addVarArg(newTime); q.addGuard(new Guard("velocity_<=_10") { @Override public int[] vars() { return new int[] { pos, time, newPos, newTime }; } @Override public boolean usesQvars() { return false; } @Override public boolean check(Binding binding, int qvar, Object firstQval) { return check(binding); } @Override public boolean check(Binding binding) { double posVal = (double) binding.getForced(pos); double timeVal = (double) binding.getForced(time); double newPosVal = (double) binding.getForced(newPos); double newTimeVal = (double) binding.getForced(newTime); return (newPosVal - posVal) / (newTimeVal - timeVal) <= 10; } }); q.addAssignment(new Assignment( "store(pos,newPos)_and_store(time,NewTime)") { @Override public int[] vars() { return new int[] { pos, time, newPos, newTime }; } @Override public Binding apply(Binding binding, boolean copy) { int newPosVal = binding.getForcedAsInteger(newPos); int newTimeVal = binding.getForcedAsInteger(newTime); Binding newBinding = binding; if (copy) { newBinding = binding.copy(); } newBinding.setValue(pos, newPosVal); newBinding.setValue(time, newTimeVal); return newBinding; } }); q.endTransition(2); q.addFinalStates(1, 2); QEA qea = q.make(); qea.record_event_name("step", 1); return qea; } public QEA makeFive() { QEABuilder q = new QEABuilder("JAVARV_MMT_FIVE"); int BLOCK_ROUTE = 1; int FREE_ROUTE = 2; int r1 = -1; int r2 = -2; final int r1x1 = 1; final int r1y1 = 2; final int r1x2 = 3; final int r1y2 = 4; final int r2x1 = 5; final int r2y1 = 6; final int r2x2 = 7; final int r2y2 = 8; q.addQuantification(FORALL, r1); q.addQuantification(FORALL, r2); // TODO How to express the condition r1 != r2? q.addTransition(1, BLOCK_ROUTE, new int[] { r1, r1x1, r1y1, r1x2, r1y2 }, 2); q.addTransition(2, FREE_ROUTE, new int[] { r1 }, 1); q.startTransition(2); q.eventName(BLOCK_ROUTE); q.addVarArg(r2); q.addVarArg(r2x1); q.addVarArg(r2y1); q.addVarArg(r2x2); q.addVarArg(r2y2); q.addGuard(new Guard("intersect_r1_r2") { @Override public int[] vars() { return new int[] { r1x1, r1y1, r1x2, r1y2, r2x1, r2y1, r2x2, r2y2 }; } @Override public boolean usesQvars() { return false; } @Override public boolean check(Binding binding, int qvar, Object firstQval) { return check(binding); } @Override public boolean check(Binding binding) { double r1x1Val = (double) binding.getForced(r1x1); double r1y1Val = (double) binding.getForced(r1y1); double r1x2Val = (double) binding.getForced(r1x2); double r1y2Val = (double) binding.getForced(r1y2); double r2x1Val = (double) binding.getForced(r2x1); double r2y1Val = (double) binding.getForced(r2y1); double r2x2Val = (double) binding.getForced(r2x2); double r2y2Val = (double) binding.getForced(r2y2); Line2D route1 = new Line2D.Double(r1x1Val, r1y1Val, r1x2Val, r1y2Val); Line2D route2 = new Line2D.Double(r2x1Val, r2y1Val, r2x2Val, r2y2Val); return route1.intersectsLine(route2); } }); q.endTransition(3); q.addFinalStates(1, 2); q.setSkipStates(1, 2, 3); QEA qea = q.make(); qea.record_event_name("block_route", 1); qea.record_event_name("free_route", 2); return qea; } }
package org.xbill.DNS; import java.util.*; import java.io.*; import org.xbill.DNS.utils.*; /** * A DNS Message. A message is the basic unit of communication between * the client and server of a DNS operation. A message consists of a Header * and 4 message sections. * @see Resolver * @see Header * @see Section * * @author Brian Wellington */ public class Message implements Cloneable { /** The maximum length of a message in wire format. */ public static int MAXLENGTH = 65535; private Header header; private List [] sections; private int size; private byte [] wireFormat; private TSIG tsigkey; private TSIGRecord querytsig; private byte tsigerror; int tsigstart; boolean TSIGsigned, TSIGverified; private static Record [] emptyRecordArray = new Record[0]; private static RRset [] emptyRRsetArray = new RRset[0]; private Message(Header header) { sections = new List[4]; this.header = header; wireFormat = null; } /** Creates a new Message with the specified Message ID */ public Message(int id) { this(new Header(id)); } /** Creates a new Message with a random Message ID */ public Message() { this(Header.randomID()); } /** * Creates a new Message with a random Message ID suitable for sending as a * query. * @param r A record containing the question */ public static Message newQuery(Record r) { Message m = new Message(); m.header.setOpcode(Opcode.QUERY); m.header.setFlag(Flags.RD); m.addRecord(r, Section.QUESTION); return m; } /** * Creates a new Message to contain a dynamic update. A random Message ID * and the zone are filled in. * @param zone The zone to be updated */ public static Message newUpdate(Name zone) { Message m = new Message(); m.header.setOpcode(Opcode.UPDATE); Record soa = Record.newRecord(zone, Type.SOA, DClass.IN); m.addRecord(soa, Section.QUESTION); return m; } Message(DataByteInputStream in) throws IOException { this(new Header(in)); for (int i = 0; i < 4; i++) { for (int j = 0; j < header.getCount(i); j++) { int pos = in.getPos(); Record rec = Record.fromWire(in, i); if (sections[i] == null) sections[i] = new LinkedList(); sections[i].add(rec); if (rec.getType() == Type.TSIG) tsigstart = pos; } } size = in.getPos(); } /** * Creates a new Message from its DNS wire format representation * @param b A byte array containing the DNS Message. */ public Message(byte [] b) throws IOException { this(new DataByteInputStream(b)); } /** * Replaces the Header with a new one. * @see Header */ public void setHeader(Header h) { header = h; } /** * Retrieves the Header. * @see Header */ public Header getHeader() { return header; } /** * Adds a record to a section of the Message, and adjusts the header. * @see Record * @see Section */ public void addRecord(Record r, int section) { if (sections[section] == null) sections[section] = new LinkedList(); sections[section].add(r); header.incCount(section); } /** * Removes a record from a section of the Message, and adjusts the header. * @see Record * @see Section */ public boolean removeRecord(Record r, int section) { if (sections[section] != null && sections[section].remove(r)) { header.decCount(section); return true; } else return false; } /** * Removes all records from a section of the Message, and adjusts the header. * @see Record * @see Section */ public void removeAllRecords(int section) { sections[section] = null; header.setCount(section, (short)0); } /** * Determines if the given record is already present in the given section. * @see Record * @see Section */ public boolean findRecord(Record r, int section) { return (sections[section] != null && sections[section].contains(r)); } /** * Determines if the given record is already present in any section. * @see Record * @see Section */ public boolean findRecord(Record r) { for (int i = Section.ANSWER; i <= Section.ADDITIONAL; i++) if (sections[i] != null && sections[i].contains(r)) return true; return false; } /** * Determines if an RRset with the given name and type is already * present in the given section. * @see RRset * @see Section */ public boolean findRRset(Name name, short type, int section) { if (sections[section] == null) return false; for (int i = 0; i < sections[section].size(); i++) { Record r = (Record) sections[section].get(i); if (r.getType() == type && name.equals(r.getName())) return true; } return false; } /** * Determines if an RRset with the given name and type is already * present in any section. * @see RRset * @see Section */ public boolean findRRset(Name name, short type) { return (findRRset(name, type, Section.ANSWER) || findRRset(name, type, Section.AUTHORITY) || findRRset(name, type, Section.ADDITIONAL)); } /** * Returns the first record in the QUESTION section. * @see Record * @see Section */ public Record getQuestion() { if (sections[Section.QUESTION] == null) return null; try { return (Record) sections[Section.QUESTION].get(0); } catch (NoSuchElementException e) { return null; } } /** * Returns the TSIG record from the ADDITIONAL section, if one is present. * @see TSIGRecord * @see TSIG * @see Section */ public TSIGRecord getTSIG() { int count = header.getCount(Section.ADDITIONAL); if (count == 0) return null; List l = sections[Section.ADDITIONAL]; Record rec = (Record) l.get(count - 1); if (rec.type != Type.TSIG) return null; return (TSIGRecord) rec; } /** * Was this message signed by a TSIG? * @see TSIG */ public boolean isSigned() { return TSIGsigned; } /** * If this message was signed by a TSIG, was the TSIG verified? * @see TSIG */ public boolean isVerified() { return TSIGverified; } /** * Returns the OPT record from the ADDITIONAL section, if one is present. * @see OPTRecord * @see Section */ public OPTRecord getOPT() { Record [] additional = getSectionArray(Section.ADDITIONAL); for (int i = 0; i < additional.length; i++) if (additional[i] instanceof OPTRecord) return (OPTRecord) additional[i]; return null; } /** * Returns the message's rcode (error code). This incorporates the EDNS * extended rcode. */ public short getRcode() { short rcode = header.getRcode(); OPTRecord opt = getOPT(); if (opt != null) rcode += (short)(opt.getExtendedRcode() << 4); return rcode; } /** * Returns an Enumeration listing all records in the given section. * @see Record * @see Section * @deprecated As of dnsjava 1.3.0, replaced by <code>getSectionArray()</code>. */ public Enumeration getSection(int section) { if (sections[section] != null) return Collections.enumeration(sections[section]); else return Collections.enumeration(Collections.EMPTY_LIST); } /** * Returns an array containing all records in the given section, or an * empty array if the section is empty. * @see Record * @see Section */ public Record [] getSectionArray(int section) { if (sections[section] == null) return emptyRecordArray; List l = sections[section]; return (Record []) l.toArray(new Record[l.size()]); } private static boolean sameSet(Record r1, Record r2) { return (r1.getRRsetType() == r2.getRRsetType() && r1.getDClass() == r2.getDClass() && r1.getName().equals(r2.getName())); } private static boolean sameSet(RRset set, Record rec) { return (sameSet(set.first(), rec)); } /** * Returns an array containing all records in the given section grouped into * RRsets. * @see RRset * @see Section */ public RRset [] getSectionRRsets(int section) { if (sections[section] == null) return emptyRRsetArray; List sets = new LinkedList(); Record [] recs = getSectionArray(section); Set hash = new HashSet(); for (int i = 0; i < recs.length; i++) { Name name = recs[i].getName(); boolean newset = true; if (hash.contains(name)) { for (int j = sets.size() - 1; j >= 0; j RRset set = (RRset) sets.get(j); if (set.getType() == recs[i].getRRsetType() && set.getDClass() == recs[i].getDClass() && set.getName().equals(name)) { set.addRR(recs[i]); newset = false; break; } } } if (newset) { RRset set = new RRset(); sets.add(set); set.addRR(recs[i]); hash.add(name); } } return (RRset []) sets.toArray(new RRset[sets.size()]); } void toWire(DataByteOutputStream out) { header.toWire(out); Compression c = new Compression(); for (int i = 0; i < 4; i++) { if (sections[i] == null) continue; for (int j = 0; j < sections[i].size(); j++) { Record rec = (Record)sections[i].get(j); rec.toWire(out, i, c); } } } /* Returns the number of records not successfully rendered. */ private int sectionToWire(DataByteOutputStream out, int section, Compression c, int maxLength) { int n = sections[section].size(); int pos = out.getPos(); int rendered = 0; Record lastrec = null; for (int i = 0; i < n; i++) { Record rec = (Record)sections[section].get(i); if (lastrec != null && !sameSet(rec, lastrec)) { pos = out.getPos(); rendered = i; } lastrec = rec; rec.toWire(out, section, c); if (out.getPos() > maxLength) { out.setPos(pos); return n - rendered; } } return 0; } /* Returns true if the message could be rendered. */ private boolean toWire(DataByteOutputStream out, int maxLength) { if (maxLength < Header.LENGTH) return false; Header newheader = null; int tempMaxLength = maxLength; if (tsigkey != null) tempMaxLength -= tsigkey.recordLength(); int startpos = out.getPos(); header.toWire(out); Compression c = new Compression(); for (int i = 0; i < 4; i++) { int skipped; if (sections[i] == null) continue; skipped = sectionToWire(out, i, c, tempMaxLength); if (skipped != 0) { if (i != Section.ADDITIONAL) { if (newheader == null) newheader = (Header) header.clone(); newheader.setFlag(Flags.TC); int count = newheader.getCount(i); newheader.setCount(i, count - skipped); for (int j = i + 1; j < 4; j++) newheader.setCount(j, 0); int pos = out.getPos(); out.setPos(startpos); newheader.toWire(out); out.setPos(pos); } break; } } if (tsigkey != null) { TSIGRecord tsigrec = tsigkey.generate(this, out.toByteArray(), tsigerror, querytsig); if (newheader == null) newheader = (Header) header.clone(); tsigrec.toWire(out, Section.ADDITIONAL, c); newheader.incCount(Section.ADDITIONAL); int pos = out.getPos(); out.setPos(startpos); newheader.toWire(out); out.setPos(pos); } return true; } /** * Returns an array containing the wire format representation of the Message. */ public byte [] toWire() { DataByteOutputStream out = new DataByteOutputStream(); toWire(out); size = out.getPos(); return out.toByteArray(); } /** * Returns an array containing the wire format representation of the Message * with the specified maximum length. This will generate a truncated * message (with the TC bit) if the message doesn't fit, and will also * sign the message with the TSIG key set by a call to setTSIG(). This * method may return null if the message could not be rendered at all; this * could happen if maxLength is smaller than a DNS header, for example. * @param maxLength The maximum length of the message. * @return The wire format of the message, or null if the message could not be * rendered into the specified length. * @see Flags * @see TSIG */ public byte [] toWire(int maxLength) { DataByteOutputStream out = new DataByteOutputStream(); toWire(out, maxLength); size = out.getPos(); return out.toByteArray(); } /** * Sets the TSIG key and other necessary information to sign a message. * @param key The TSIG key. * @param error The value of the TSIG error field. * @param querytsig If this is a response, the TSIG from the request. */ public void setTSIG(TSIG key, byte error, TSIGRecord querytsig) { this.tsigkey = key; this.tsigerror = error; this.querytsig = querytsig; } /** * Returns the size of the message. Only valid if the message has been * converted to or from wire format. */ public int numBytes() { return size; } /** * Converts the given section of the Message to a String. * @see Section */ public String sectionToString(int i) { if (i > 3) return null; StringBuffer sb = new StringBuffer(); Record [] records = getSectionArray(i); for (int j = 0; j < records.length; j++) { Record rec = records[j]; if (i == Section.QUESTION) { sb.append(";;\t" + rec.name); sb.append(", type = " + Type.string(rec.type)); sb.append(", class = " + DClass.string(rec.dclass)); } else sb.append(rec); sb.append("\n"); } return sb.toString(); } /** * Converts the Message to a String. */ public String toString() { StringBuffer sb = new StringBuffer(); OPTRecord opt = getOPT(); if (opt != null) sb.append(header.toStringWithRcode(getRcode()) + "\n"); else sb.append(header + "\n"); if (isSigned()) { sb.append(";; TSIG "); if (isVerified()) sb.append("ok"); else sb.append("invalid"); sb.append('\n'); } for (int i = 0; i < 4; i++) { if (header.getOpcode() != Opcode.UPDATE) sb.append(";; " + Section.longString(i) + ":\n"); else sb.append(";; " + Section.updString(i) + ":\n"); sb.append(sectionToString(i) + "\n"); } sb.append(";; done (" + numBytes() + " bytes)"); return sb.toString(); } /** * Creates a copy of this Message. This is done by the Resolver before adding * TSIG and OPT records, for example. * @see Resolver * @see TSIGRecord * @see OPTRecord */ public Object clone() { Message m = new Message(); for (int i = 0; i < sections.length; i++) { if (sections[i] != null) m.sections[i] = new LinkedList(sections[i]); } m.header = (Header) header.clone(); m.size = size; return m; } }
package org.xbill.DNS; import java.util.*; import java.io.*; import org.xbill.DNS.utils.*; /** * A DNS Message. A message is the basic unit of communication between * the client and server of a DNS operation. A message consists of a Header * and 4 message sections. * @see Resolver * @see Header * @see Section * * @author Brian Wellington */ public class Message implements Cloneable { private Header header; private List [] sections; private int size; private byte [] wireFormat; private boolean frozen; boolean TSIGsigned, TSIGverified; private static Record [] emptyRecordArray = new Record[0]; private static RRset [] emptyRRsetArray = new RRset[0]; private Message(Header header) { sections = new List[4]; this.header = header; wireFormat = null; frozen = false; } /** Creates a new Message with the specified Message ID */ public Message(int id) { this(new Header(id)); } /** Creates a new Message with a random Message ID */ public Message() { this(Header.randomID()); } /** * Creates a new Message with a random Message ID suitable for sending as a * query. * @param r A record containing the question */ public static Message newQuery(Record r) { Message m = new Message(); m.header.setOpcode(Opcode.QUERY); m.header.setFlag(Flags.RD); m.addRecord(r, Section.QUESTION); return m; } /** * Creates a new Message to contain a dynamic update. A random Message ID * and the zone are filled in. * @param zone The zone to be updated */ public static Message newUpdate(Name zone) { Message m = new Message(); m.header.setOpcode(Opcode.UPDATE); Record soa = Record.newRecord(zone, Type.SOA, DClass.IN); m.addRecord(soa, Section.QUESTION); return m; } Message(DataByteInputStream in) throws IOException { this(new Header(in)); for (int i = 0; i < 4; i++) { for (int j = 0; j < header.getCount(i); j++) { Record rec = Record.fromWire(in, i); if (sections[i] == null) sections[i] = new LinkedList(); sections[i].add(rec); } } size = in.getPos(); } /** Creates a new Message from its DNS wire format representation */ public Message(byte [] b) throws IOException { this(new DataByteInputStream(b)); } /** * Replaces the Header with a new one. * @see Header */ public void setHeader(Header h) { header = h; } /** * Retrieves the Header. * @see Header */ public Header getHeader() { return header; } /** * Adds a record to a section of the Message, and adjusts the header. * @see Record * @see Section */ public void addRecord(Record r, int section) { if (sections[section] == null) sections[section] = new LinkedList(); sections[section].add(r); header.incCount(section); } /** * Removes a record from a section of the Message, and adjusts the header. * @see Record * @see Section */ public boolean removeRecord(Record r, int section) { if (sections[section] != null && sections[section].remove(r)) { header.decCount(section); return true; } else return false; } /** * Removes all records from a section of the Message, and adjusts the header. * @see Record * @see Section */ public void removeAllRecords(int section) { sections[section] = null; header.setCount(section, (short)0); } /** * Determines if the given record is already present in the given section. * @see Record * @see Section */ public boolean findRecord(Record r, int section) { return (sections[section] != null && sections[section].contains(r)); } /** * Determines if the given record is already present in any section. * @see Record * @see Section */ public boolean findRecord(Record r) { for (int i = Section.ANSWER; i <= Section.ADDITIONAL; i++) if (sections[i] != null && sections[i].contains(r)) return true; return false; } /** * Determines if an RRset with the given name and type is already * present in the given section. * @see RRset * @see Section */ public boolean findRRset(Name name, short type, int section) { if (sections[section] == null) return false; for (int i = 0; i < sections[section].size(); i++) { Record r = (Record) sections[section].get(i); if (r.getType() == type && name.equals(r.getName())) return true; } return false; } /** * Determines if an RRset with the given name and type is already * present in any section. * @see RRset * @see Section */ public boolean findRRset(Name name, short type) { return (findRRset(name, type, Section.ANSWER) || findRRset(name, type, Section.AUTHORITY) || findRRset(name, type, Section.ADDITIONAL)); } /** * Returns the first record in the QUESTION section. * @see Record * @see Section */ public Record getQuestion() { if (sections[Section.QUESTION] == null) return null; try { return (Record) sections[Section.QUESTION].get(0); } catch (NoSuchElementException e) { return null; } } /** * Returns the TSIG record from the ADDITIONAL section, if one is present. * @see TSIGRecord * @see TSIG * @see Section */ public TSIGRecord getTSIG() { int count = header.getCount(Section.ADDITIONAL); if (count == 0) return null; List l = sections[Section.ADDITIONAL]; Record rec = (Record) l.get(count - 1); if (rec.type != Type.TSIG) return null; return (TSIGRecord) rec; } /** * Was this message signed by a TSIG? * @see TSIG */ public boolean isSigned() { return TSIGsigned; } /** * If this message was signed by a TSIG, was the TSIG verified? * @see TSIG */ public boolean isVerified() { return TSIGverified; } /** * Returns the OPT record from the ADDITIONAL section, if one is present. * @see OPTRecord * @see Section */ public OPTRecord getOPT() { Record [] additional = getSectionArray(Section.ADDITIONAL); for (int i = 0; i < additional.length; i++) if (additional[i] instanceof OPTRecord) return (OPTRecord) additional[i]; return null; } /** * Returns the message's rcode (error code). This incorporates the EDNS * extended rcode. */ public short getRcode() { short rcode = header.getRcode(); OPTRecord opt = getOPT(); if (opt != null) rcode += (short)(opt.getExtendedRcode() << 4); return rcode; } /** * Returns an Enumeration listing all records in the given section. * @see Record * @see Section * @deprecated As of dnsjava 1.3.0, replaced by <code>getSectionArray()</code>. */ public Enumeration getSection(int section) { if (sections[section] != null) return Collections.enumeration(sections[section]); else return Collections.enumeration(Collections.EMPTY_LIST); } /** * Returns an array containing all records in the given section, or an * empty array if the section is empty. * @see Record * @see Section */ public Record [] getSectionArray(int section) { if (sections[section] == null) return emptyRecordArray; List l = sections[section]; return (Record []) l.toArray(new Record[l.size()]); } /** * Returns an array containing all records in the given section grouped into * RRsets. * @see RRset * @see Section */ public RRset [] getSectionRRsets(int section) { if (sections[section] == null) return emptyRRsetArray; List sets = new LinkedList(); Record [] recs = getSectionArray(section); Arrays.sort(recs); int i = 0; while (i < recs.length) { RRset set = new RRset(); sets.add(set); do { set.addRR(recs[i]); i++; } while (i < recs.length && set.getType() == recs[i].getRRsetType() && set.getDClass() == recs[i].getDClass() && set.getName().equals(recs[i].getName())); } return (RRset []) sets.toArray(new RRset[sets.size()]); } void toWire(DataByteOutputStream out) throws IOException { header.toWire(out); Compression c = new Compression(); for (int i = 0; i < 4; i++) { if (sections[i] == null) continue; for (int j = 0; j < sections[i].size(); j++) { Record rec = (Record)sections[i].get(j); rec.toWire(out, i, c); } } } /** * Returns an array containing the wire format representation of the Message. */ public byte [] toWire() throws IOException { if (frozen && wireFormat != null) return wireFormat; DataByteOutputStream out = new DataByteOutputStream(); toWire(out); size = out.getPos(); if (frozen) { wireFormat = out.toByteArray(); return wireFormat; } else return out.toByteArray(); } /** * Indicates that a message's contents will not be changed until a thaw * operation. * @see #thaw */ public void freeze() { frozen = true; } /** * Indicates that a message's contents can now change (are no longer frozen). * @see #freeze */ public void thaw() { frozen = false; wireFormat = null; } /** * Returns the size of the message. Only valid if the message has been * converted to or from wire format. */ public int numBytes() { return size; } /** * Converts the given section of the Message to a String. * @see Section */ public String sectionToString(int i) { if (i > 3) return null; StringBuffer sb = new StringBuffer(); Record [] records = getSectionArray(i); for (int j = 0; j < records.length; j++) { Record rec = records[j]; if (i == Section.QUESTION) { sb.append(";;\t" + rec.name); sb.append(", type = " + Type.string(rec.type)); sb.append(", class = " + DClass.string(rec.dclass)); } else sb.append(rec); sb.append("\n"); } return sb.toString(); } /** * Converts the Message to a String. */ public String toString() { StringBuffer sb = new StringBuffer(); OPTRecord opt = getOPT(); if (opt != null) sb.append(header.toStringWithRcode(getRcode()) + "\n"); else sb.append(header + "\n"); if (isSigned()) { sb.append(";; TSIG "); if (isVerified()) sb.append("ok"); else sb.append("invalid"); sb.append('\n'); } for (int i = 0; i < 4; i++) { if (header.getOpcode() != Opcode.UPDATE) sb.append(";; " + Section.longString(i) + ":\n"); else sb.append(";; " + Section.updString(i) + ":\n"); sb.append(sectionToString(i) + "\n"); } sb.append(";; done (" + numBytes() + " bytes)"); return sb.toString(); } /** * Creates a copy of this Message. This is done by the Resolver before adding * TSIG and OPT records, for example. * @see Resolver * @see TSIGRecord * @see OPTRecord */ public Object clone() { Message m = new Message(); for (int i = 0; i < sections.length; i++) { if (sections[i] != null) m.sections[i] = new LinkedList(sections[i]); } m.header = (Header) header.clone(); m.size = size; return m; } }
package org.xbill.DNS; import java.util.*; import org.xbill.DNS.utils.*; /** * The shared superclass of Zone and Cache. All names are stored in a * hashtable. Each name contains a hashtable indexed on type and class. * * @author Brian Wellington */ class NameSet { private Hashtable data; /** Creates an empty NameSet */ protected NameSet() { data = new Hashtable(); } /** * Finds all matching sets. This traverses CNAMEs, and has provisions for * Type ANY. */ protected Object [] findSets(Name name, short type, short dclass) { Object [] array; Object o; Hashtable nameInfo = findName(name); if (nameInfo == null) return null; if (type == Type.ANY) { synchronized (nameInfo) { array = new Object[nameInfo.size()]; int i = 0; Enumeration e = nameInfo.elements(); while (e.hasMoreElements()) array[i++] = e.nextElement(); } return array; } o = nameInfo.get(new TypeClass(type, dclass)); if (o != null) { array = new Object[1]; array[0] = o; return array; } if (type != Type.CNAME) { o = nameInfo.get(new TypeClass(Type.CNAME, dclass)); if (o == null) return null; else { array = new Object[1]; array[0] = o; return array; } } return null; } /** * Finds all sets that exactly match. This does not traverse CNAMEs or handle * Type ANY queries. */ protected Object findExactSet(Name name, short type, short dclass) { Hashtable nameInfo = findName(name); if (nameInfo == null) return null; return nameInfo.get(new TypeClass(type, dclass)); } /** * Finds all records for a given name, if the name exists. */ protected Hashtable findName(Name name) { return (Hashtable) data.get(name); } /** * Adds a set associated with a name/type/class. The data contained in the * set is abstract. */ protected void addSet(Name name, short type, short dclass, Object set) { Hashtable nameInfo = findName(name); if (nameInfo == null) data.put(name, nameInfo = new Hashtable()); synchronized (nameInfo) { nameInfo.put(new TypeClass(type, dclass), set); } } /** * Removes the given set from the name/type/class. The data contained in the * set is abstract. */ protected void removeSet(Name name, short type, short dclass, Object set) { Hashtable nameInfo = findName(name); if (nameInfo == null) return; Object o = nameInfo.get(new TypeClass(type, dclass)); if (o != set && type != Type.CNAME) { type = Type.CNAME; o = nameInfo.get(new TypeClass(type, dclass)); } if (o == set) { synchronized (nameInfo) { nameInfo.remove(new TypeClass(type, dclass)); } if (nameInfo.isEmpty()) data.remove(name); } } /** Converts the NameSet to a String */ public String toString() { StringBuffer sb = new StringBuffer(); Enumeration e = data.elements(); while (e.hasMoreElements()) { Hashtable nameInfo = (Hashtable) e.nextElement(); Enumeration e2 = nameInfo.elements(); while (e2.hasMoreElements()) sb.append(e2.nextElement()); } return sb.toString(); } }
package com.planet_ink.coffee_mud.Abilities; import com.planet_ink.coffee_mud.interfaces.*; import com.planet_ink.coffee_mud.common.*; import com.planet_ink.coffee_mud.utils.*; import java.util.*; public class StdAbility implements Ability, Cloneable { public String ID() { return "StdAbility"; } public String Name(){return name();} public String name(){ return "an ability";} public String description(){return "&";} public String displayText(){return "What they see when affected.";} public static final String[] empty={}; public String[] triggerStrings(){return empty;} public int maxRange(){return 0;} public int minRange(){return 0;} public boolean putInCommandlist(){return true;} public boolean isAutoInvoked(){return false;} public boolean bubbleAffect(){return false;} protected int trainsRequired(){return CommonStrings.getIntVar(CommonStrings.SYSTEMI_SKILLTRAINCOST);} protected int practicesRequired(){return CommonStrings.getIntVar(CommonStrings.SYSTEMI_SKILLPRACCOST);} protected int practicesToPractice(){return 1;} public long flags(){return 0;} protected int overrideMana(){return -1;} //-1=normal, Integer.MAX_VALUE=all public int quality(){return Ability.INDIFFERENT;} protected int canAffectCode(){return Ability.CAN_AREAS| Ability.CAN_ITEMS| Ability.CAN_MOBS| Ability.CAN_ROOMS| Ability.CAN_EXITS;} protected int canTargetCode(){return Ability.CAN_AREAS| Ability.CAN_ITEMS| Ability.CAN_MOBS| Ability.CAN_ROOMS| Ability.CAN_EXITS;} protected boolean isAnAutoEffect=false; protected int profficiency=0; protected boolean borrowed=false; public String miscText=""; protected MOB invoker=null; protected Environmental affected=null; protected boolean canBeUninvoked=true; protected boolean unInvoked=false; protected int tickDown=-1; protected long lastProfHelp=0; public StdAbility() { } public Environmental newInstance() { return new StdAbility(); } public int classificationCode(){ return Ability.SKILL; } protected static final EnvStats envStats=new DefaultEnvStats(); public EnvStats envStats(){return envStats;} public EnvStats baseEnvStats(){return envStats;} public boolean isNowAnAutoEffect(){ return isAnAutoEffect; } public boolean isBorrowed(Environmental toMe){ return borrowed; } public void setBorrowed(Environmental toMe, boolean truefalse) { borrowed=truefalse; } public void setName(String newName){} public void recoverEnvStats() {} public void setBaseEnvStats(EnvStats newBaseEnvStats){} public void setDisplayText(String newDisplayText){} public void setDescription(String newDescription){} public int abilityCode(){return 0;} public void setAbilityCode(int newCode){} // ** For most abilities, the following stuff actually matters */ public void setMiscText(String newMiscText) { miscText=newMiscText;} public String text(){ return miscText;} public int profficiency(){ return profficiency;} public void setProfficiency(int newProfficiency) { profficiency=newProfficiency; if(profficiency>100) profficiency=100; } public void startTickDown(MOB invokerMOB, Environmental affected, int tickTime) { if(invokerMOB!=null) invoker=invokerMOB; borrowed=true; // makes it so that the affect does not save! if(invoker()!=null) tickTime=invoker().charStats().getCurrentClass().classDurationModifier(invoker(),this,tickTime); if(affected instanceof MOB) { if(((MOB)affected).location()==null) return; if(affected.fetchAffect(this.ID())==null) affected.addAffect(this); ((MOB)affected).location().recoverRoomStats(); if(invoker()!=affected) tickTime=((MOB)affected).charStats().getCurrentClass().classDurationModifier(((MOB)affected),this,tickTime); } else { if(affected.fetchAffect(this.ID())==null) affected.addAffect(this); if(affected instanceof Room) ((Room)affected).recoverRoomStats(); else affected.recoverEnvStats(); ExternalPlay.startTickDown(this,Host.MOB_TICK,1); } tickDown=tickTime; } public int adjustedLevel(MOB caster) { if(caster==null) return 1; int lowestQualifyingLevel=CMAble.lowestQualifyingLevel(this.ID()); int adjLevel=lowestQualifyingLevel; int qualifyingLevel=CMAble.qualifyingLevel(caster,this); if((caster.isMonster())||(qualifyingLevel>=0)) adjLevel+=(CMAble.qualifyingClassLevel(caster,this)-qualifyingLevel); else { adjLevel=caster.envStats().level()-lowestQualifyingLevel-25; if(adjLevel<lowestQualifyingLevel) adjLevel=lowestQualifyingLevel; } if(adjLevel<1) return 1; return adjLevel; } public boolean canAffect(Environmental E) { if((E==null)&&(canAffectCode()==0)) return true; if(E==null) return false; if((E instanceof MOB)&&((canAffectCode()&Ability.CAN_MOBS)>0)) return true; if((E instanceof Item)&&((canAffectCode()&Ability.CAN_ITEMS)>0)) return true; if((E instanceof Exit)&&((canAffectCode()&Ability.CAN_EXITS)>0)) return true; if((E instanceof Room)&&((canAffectCode()&Ability.CAN_ROOMS)>0)) return true; if((E instanceof Area)&&((canAffectCode()&Ability.CAN_AREAS)>0)) return true; return false; } public boolean canTarget(Environmental E) { if((E==null)&&(canTargetCode()==0)) return true; if(E==null) return false; if((E instanceof MOB)&&((canTargetCode()&Ability.CAN_MOBS)>0)) return true; if((E instanceof Item)&&((canTargetCode()&Ability.CAN_ITEMS)>0)) return true; if((E instanceof Room)&&((canTargetCode()&Ability.CAN_ROOMS)>0)) return true; if((E instanceof Area)&&((canTargetCode()&Ability.CAN_AREAS)>0)) return true; return false; } public MOB getTarget(MOB mob, Vector commands, Environmental givenTarget) { return getTarget(mob,commands,givenTarget,false); } public MOB getTarget(MOB mob, Vector commands, Environmental givenTarget, boolean quiet) { String targetName=Util.combine(commands,0); MOB target=null; if((givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; else if((targetName.length()==0)&&(mob.isInCombat())&&(quality()==Ability.MALICIOUS)&&(mob.getVictim()!=null)) target=mob.getVictim(); else if((targetName.length()==0)&&(quality()!=Ability.MALICIOUS)) target=mob; else if(targetName.length()>0) { target=mob.location().fetchInhabitant(targetName); if(target==null) { Environmental t=mob.location().fetchFromRoomFavorItems(null,targetName,Item.WORN_REQ_UNWORNONLY); if((t!=null)&&(!(t instanceof MOB))) { if(!quiet) mob.tell(mob,t,null,"You can't do that to <T-NAMESELF>."); return null; } } } if(target!=null) targetName=target.name(); if((target==null)||((!Sense.canBeSeenBy(target,mob))&&((!Sense.canBeHeardBy(target,mob))||(!target.isInCombat())))) { if(!quiet) { if(targetName.trim().length()==0) mob.tell("You don't see them here."); else mob.tell("You don't see anyone called '"+targetName+"' here."); } return null; } if((target.fetchAffect(this.ID())!=null)&&(!isAutoInvoked())) { if(!quiet) { if(target==mob) mob.tell("You are already affected by "+name()+"."); else mob.tell(target,null,null,"<S-NAME> is already affected by "+name()+"."); } return null; } return target; } public Environmental getAnyTarget(MOB mob, Vector commands, Environmental givenTarget, int wornReqCode) { String targetName=Util.combine(commands,0); Environmental target=null; if(givenTarget!=null) target=givenTarget; else if((targetName.length()==0)&&(mob.isInCombat())&&(quality()==Ability.MALICIOUS)&&(mob.getVictim()!=null)) target=mob.getVictim(); else { target=mob.location().fetchFromRoomFavorMOBs(null,targetName, wornReqCode); if(target==null) target=mob.location().fetchFromMOBRoomFavorsItems(mob,null,targetName,wornReqCode); if((target==null) &&(targetName.equalsIgnoreCase("room") ||targetName.equalsIgnoreCase("here") ||targetName.equalsIgnoreCase("place"))) target=mob.location(); } if(target!=null) targetName=target.name(); if((target==null)||((!Sense.canBeSeenBy(target,mob))&&((!Sense.canBeHeardBy(target,mob))||((target instanceof MOB)&&(!((MOB)target).isInCombat()))))) { if(targetName.trim().length()==0) mob.tell("You don't see that here."); else mob.tell("You don't see '"+targetName+"' here."); return null; } if(target.fetchAffect(this.ID())!=null) { if(target==mob) mob.tell("You are already affected by "+name()+"."); else mob.tell(mob,target,null,"<T-NAME> is already affected by "+name()+"."); return null; } return target; } protected static Item possibleContainer(MOB mob, Vector commands, boolean withStuff, int wornReqCode) { if((commands==null)||(commands.size()<2)) return null; String possibleContainerID=(String)commands.elementAt(commands.size()-1); Environmental thisThang=mob.location().fetchFromMOBRoomFavorsItems(mob,null,possibleContainerID,wornReqCode); if((thisThang!=null) &&(thisThang instanceof Item) &&(((Item)thisThang) instanceof Container) &&((!withStuff)||(((Container)thisThang).getContents().size()>0))) { commands.removeElementAt(commands.size()-1); return (Item)thisThang; } return null; } public Item getTarget(MOB mob, Room location, Environmental givenTarget, Vector commands, int wornReqCode) { return getTarget(mob,location,givenTarget,null,commands,wornReqCode);} public Item getTarget(MOB mob, Room location, Environmental givenTarget, Item container, Vector commands, int wornReqCode) { String targetName=Util.combine(commands,0); Environmental target=null; if((givenTarget!=null)&&(givenTarget instanceof Item)) target=givenTarget; if(location!=null) target=location.fetchFromRoomFavorItems(container,targetName,wornReqCode); if(target==null) { if(location!=null) target=location.fetchFromMOBRoomFavorsItems(mob,container,targetName,wornReqCode); else target=mob.fetchCarried(container,targetName); } if(target!=null) targetName=target.name(); if((target==null)||((target!=null)&&((!Sense.canBeSeenBy(target,mob))||(!(target instanceof Item))))) { if(targetName.length()==0) mob.tell("You need to be more specific."); else if((target==null)||(target instanceof Item)) { if(targetName.trim().length()==0) mob.tell("You don't see that here."); else mob.tell("You don't see anything called '"+targetName+"' here."); } else mob.tell(mob,target,null,"You can't do that to <T-NAMESELF>."); return null; } return (Item)target; } public int compareTo(Object o){ return CMClass.classID(this).compareToIgnoreCase(CMClass.classID(o));} private void cloneFix(Ability E){} public Environmental copyOf() { try { StdAbility E=(StdAbility)this.clone(); E.cloneFix(this); return E; } catch(CloneNotSupportedException e) { return this.newInstance(); } } public boolean profficiencyCheck(int adjustment, boolean auto) { if(auto) { this.isAnAutoEffect=true; this.setProfficiency(100); return true; } isAnAutoEffect=false; int pctChance=profficiency(); if(pctChance>95) pctChance=95; if(pctChance<5) pctChance=5; if(adjustment>=0) pctChance+=adjustment; else if(Dice.rollPercentage()>(100+adjustment)) return false; return (Dice.rollPercentage()<pctChance); } public Environmental affecting() { return affected; } public void setAffectedOne(Environmental being) { affected=being; } public void unInvoke() { unInvoked=true; if(affected==null) return; Environmental being=affected; if(canBeUninvoked()) { being.delAffect(this); if(being instanceof Room) ((Room)being).recoverRoomStats(); else if(being instanceof MOB) { if(((MOB)being).location()!=null) ((MOB)being).location().recoverRoomStats(); else { being.recoverEnvStats(); ((MOB)being).recoverCharStats(); ((MOB)being).recoverMaxState(); } } else being.recoverEnvStats(); } } public boolean canBeUninvoked() { return canBeUninvoked; } public void affectEnvStats(Environmental affected, EnvStats affectableStats) {} public void affectCharStats(MOB affectedMob, CharStats affectableStats) {} public void affectCharState(MOB affectedMob, CharState affectableMaxState) {} public MOB invoker() { return invoker; } public void setInvoker(MOB mob){invoker=mob;} public int manaCost(MOB mob) { if(mob==null) return overrideMana(); int diff=0; for(int c=0;c<mob.charStats().numClasses();c++) { CharClass C=mob.charStats().getMyClass(c); int qualifyingLevel=CMAble.getQualifyingLevel(C.ID(),ID()); int classLevel=mob.charStats().getClassLevel(C.ID()); if((qualifyingLevel>=0)&&(classLevel>=qualifyingLevel)) diff+=(classLevel-qualifyingLevel); } int manaConsumed=CommonStrings.getIntVar(CommonStrings.SYSTEMI_MANACOST); if(diff>0) manaConsumed=manaConsumed - (manaConsumed /10 * diff); if(manaConsumed<5) manaConsumed=5; if(overrideMana()==Integer.MAX_VALUE) manaConsumed=mob.maxState().getMana(); else if(overrideMana()>=0) manaConsumed=overrideMana(); return manaConsumed; } public void helpProfficiency(MOB mob) { Ability A=(Ability)mob.fetchAbility(ID()); if(A==null) return; if((System.currentTimeMillis() -((StdAbility)A).lastProfHelp)<60000) return; if(A.profficiency()<100) { if(((int)Math.round(Math.sqrt(new Integer(mob.charStats().getStat(CharStats.INTELLIGENCE)).doubleValue())*34.0*Math.random()))>=A.profficiency()) { // very important, since these can be autoinvoked affects (copies)! A.setProfficiency(A.profficiency()+1); if((this!=A)&&(profficiency()<100)) setProfficiency(profficiency()+1); if(Util.bset(mob.getBitmap(),MOB.ATT_AUTOIMPROVE)) mob.tell("You become better at "+A.name()+"."); ((StdAbility)A).lastProfHelp=System.currentTimeMillis(); } } else A.setProfficiency(100); } public boolean invoke(MOB mob, Environmental target, boolean auto) { Vector V=new Vector(); if(target!=null) V.addElement(target.name()); return invoke(mob,V,target,auto); } public boolean invoke(MOB mob, Vector commands, Environmental target, boolean auto) { if(!auto) { isAnAutoEffect=false; // if you can't move, you can't cast! Not even verbal! if(!Sense.aliveAwakeMobile(mob,false)) return false; int manaConsumed=manaCost(mob); if(mob.curState().getMana()<manaConsumed) { if(mob.maxState().getMana()==manaConsumed) mob.tell("You must be at full mana to do that."); else mob.tell("You don't have enough mana to do that."); return false; } mob.curState().adjMana(-manaConsumed,mob.maxState()); helpProfficiency(mob); } else isAnAutoEffect=true; return true; } public boolean maliciousAffect(MOB mob, Environmental target, int tickAdjustmentFromStandard, int additionAffectCheckCode) { boolean ok=true; if(additionAffectCheckCode>=0) { FullMsg msg=new FullMsg(mob,target,this,Affect.NO_EFFECT,additionAffectCheckCode,Affect.NO_EFFECT,null); if(mob.location().okAffect(mob,msg)) { mob.location().send(mob,msg); ok=(!msg.wasModified()); } else ok=false; } if(ok) { invoker=mob; Ability newOne=(Ability)this.copyOf(); ((StdAbility)newOne).canBeUninvoked=true; if(tickAdjustmentFromStandard<=0) { tickAdjustmentFromStandard=(adjustedLevel(mob)*4)+25; if(target!=null) tickAdjustmentFromStandard-=(target.envStats().level()*2); if(tickAdjustmentFromStandard>(Host.TICKS_PER_DAY/2)) tickAdjustmentFromStandard=(int)(Host.TICKS_PER_DAY/2); if(tickAdjustmentFromStandard<5) tickAdjustmentFromStandard=5; } newOne.startTickDown(invoker,target,tickAdjustmentFromStandard); } return ok; } public boolean beneficialWordsFizzle(MOB mob, Environmental target, String message) { // it didn't work, but tell everyone you tried. FullMsg msg=new FullMsg(mob,target,this,Affect.MSG_SPEAK,"^T"+message+"^?"); if(mob.location().okAffect(mob,msg)) mob.location().send(mob,msg); return false; } public boolean beneficialVisualFizzle(MOB mob, Environmental target, String message) { // it didn't work, but tell everyone you tried. FullMsg msg=new FullMsg(mob,target,this,Affect.MSG_OK_VISUAL,message); if(mob.location().okAffect(mob,msg)) mob.location().send(mob,msg); return false; } public boolean maliciousFizzle(MOB mob, Environmental target, String message) { // it didn't work, but tell everyone you tried. FullMsg msg=new FullMsg(mob,target,this,Affect.MSG_OK_VISUAL|Affect.MASK_MALICIOUS,message); if(mob.location().okAffect(mob,msg)) mob.location().send(mob,msg); return false; } public boolean beneficialAffect(MOB mob, Environmental target, int tickAdjustmentFromStandard) { boolean ok=true; if(ok) { invoker=mob; Ability newOne=(Ability)this.copyOf(); ((StdAbility)newOne).canBeUninvoked=true; if(tickAdjustmentFromStandard<=0) { tickAdjustmentFromStandard=(adjustedLevel(mob)*7)+60; if(tickAdjustmentFromStandard>(Host.TICKS_PER_DAY/2)) tickAdjustmentFromStandard=(int)(Host.TICKS_PER_DAY/2); if(tickAdjustmentFromStandard<5) tickAdjustmentFromStandard=5; } newOne.startTickDown(invoker,target,tickAdjustmentFromStandard); } return ok; } public boolean autoInvocation(MOB mob) { if(isAutoInvoked()) { Ability thisAbility=mob.fetchAffect(this.ID()); if(thisAbility!=null) return false; Ability thatAbility=(Ability)this.copyOf(); ((StdAbility)thatAbility).canBeUninvoked=true; thatAbility.setBorrowed(mob,true); mob.addAffect(thatAbility); return true; } return false; } public void makeNonUninvokable() { unInvoked=false; canBeUninvoked=false; borrowed=false; } public String accountForYourself(){return name();} public int getTickDownRemaining(){return tickDown;} public void setTickDownRemaining(int newTick){tickDown=newTick;} public long getTickStatus(){ return Tickable.STATUS_NOT;} public boolean canBeTaughtBy(MOB teacher, MOB student) { if(Util.bset(teacher.getBitmap(),MOB.ATT_NOTEACH)) { teacher.tell("You are refusing to teach right now."); student.tell(teacher.name()+" is refusing to teach right now."); return false; } Ability yourAbility=teacher.fetchAbility(ID()); if(yourAbility!=null) { if(yourAbility.profficiency()<25) { teacher.tell("You are not profficient enough to teach '"+name()+"'"); student.tell(teacher.name()+" is not profficient enough to teach '"+name()+"'."); return false; } return true; } teacher.tell("You don't know '"+name()+"'."); student.tell(teacher.name()+" doesn't know '"+name()+"'."); return false; } protected boolean ableOk(MOB mob, MOB target, Affect msg) { if((mob==null)||(mob.location()==null)) return false; if((target==null) ||(target.location()==null) ||(target.location()==mob.location())) return mob.location().okAffect(mob,msg); boolean ok=mob.location().okAffect(mob,msg); if(!ok) return false; return target.okAffect(mob,msg); } protected void ableSend(MOB mob, MOB target, Affect msg) { if((mob==null)||(mob.location()==null)) return; if((target==null) ||(target.location()==null) ||(target.location()==mob.location())) { mob.location().send(mob,msg); return; } mob.location().send(mob,msg); target.affect(mob,msg); } public String requirements() { String returnable=""; if(trainsRequired()==1) returnable="1 train"; else if(trainsRequired()>1) returnable=trainsRequired()+" trains"; if((returnable.length()>0)&&(practicesRequired()>0)) returnable+=", "; if(practicesRequired()==1) returnable+="1 practice"; else if(practicesRequired()>1) returnable+=practicesRequired()+" practices"; if(returnable.length()==0) return "free!"; else return returnable; } public boolean canBeLearnedBy(MOB teacher, MOB student) { if(student.getPractices()<practicesRequired()) { teacher.tell(student.name()+" does not have enough practice points to learn '"+name()+"'."); student.tell("You do not have enough practice points."); return false; } if(student.getTrains()<trainsRequired()) { teacher.tell(student.name()+" does not have enough training sessions to learn '"+name()+"'."); student.tell("You do not have enough training sessions."); return false; } if(Util.bset(student.getBitmap(),MOB.ATT_NOTEACH)) { teacher.tell(student.name()+" is refusing training at this time."); student.tell("You are refusing training at this time."); return false; } int qLevel=CMAble.qualifyingLevel(student,this); if(qLevel<0) { teacher.tell(student.name()+" is not the right class to learn '"+name()+"'."); student.tell("You are not the right class to learn '"+name()+"'."); return false; } if(!CMAble.qualifiesByLevel(student,this)) { teacher.tell(student.name()+" is not high enough level to learn '"+name()+"'."); student.tell("You are not high enough level to learn '"+name()+"'."); return false; } if(qLevel>(student.charStats().getStat(CharStats.INTELLIGENCE)+15)) { teacher.tell(student.name()+" is too stupid to learn '"+name()+"'."); student.tell("You are not of high enough intelligence to learn '"+name()+"'."); return false; } Ability yourAbility=student.fetchAbility(ID()); Ability teacherAbility=teacher.fetchAbility(ID()); if(yourAbility!=null) { teacher.tell(student.name()+" already knows '"+name()+"'."); student.tell("You already know '"+name()+"'."); return false; } if(teacherAbility!=null) { if(teacherAbility.profficiency()<25) { teacher.tell("You aren't profficient enough to teach '"+name()+"'."); student.tell(teacher.name()+" isn't profficient enough to teach you '"+name()+"'."); return false; } } else { student.tell(teacher.name()+" does not know anything about that."); teacher.tell("You don't know that."); return false; } return true; } public boolean canBePracticedBy(MOB teacher, MOB student) { if(student.getPractices()<practicesToPractice()) { teacher.tell(student.name()+" does not have enough practices to practice '"+name()+"'."); student.tell("You do not have enough practices."); return false; } if(Util.bset(teacher.getBitmap(),MOB.ATT_NOTEACH)) { teacher.tell("You are refusing to teach right now."); student.tell(teacher.name()+" is refusing to teach right now."); return false; } if(Util.bset(student.getBitmap(),MOB.ATT_NOTEACH)) { teacher.tell(student.name()+" is refusing training at this time."); student.tell("You are refusing training at this time."); return false; } Ability yourAbility=student.fetchAbility(ID()); Ability teacherAbility=teacher.fetchAbility(ID()); if(yourAbility==null) { teacher.tell(student.name()+" has not gained '"+name()+"' yet."); student.tell("You havn't gained '"+name()+"' yet."); return false; } if(teacherAbility==null) { student.tell(teacher.name()+" does not know anything about '"+name()+"'."); teacher.tell("You don't know '"+name()+"'."); return false; } if(yourAbility.profficiency()>teacherAbility.profficiency()) { teacher.tell("You aren't profficient enough to teach any more about '"+name()+"'."); student.tell(teacher.name()+" isn't profficient enough to teach any more about '"+name()+"'."); return false; } else if(yourAbility.profficiency()>74) { teacher.tell("You can't teach "+student.charStats().himher()+" any more about '"+name()+"'."); student.tell("You can't learn any more about '"+name()+"' except through dilligence."); return false; } if(teacherAbility.profficiency()<25) { teacher.tell("You aren't profficient enough to teach '"+name()+"'."); student.tell(teacher.name()+" isn't profficient enough to teach you '"+name()+"'."); return false; } return true; } public void teach(MOB teacher, MOB student) { if(student.getPractices()<practicesRequired()) return; if(student.getTrains()<trainsRequired()) return; if(student.fetchAbility(ID())==null) { student.setPractices(student.getPractices()-practicesRequired()); student.setTrains(student.getTrains()-trainsRequired()); Ability newAbility=(Ability)newInstance(); newAbility.setProfficiency((int)Math.round(Util.mul(profficiency(),((Util.div(teacher.charStats().getStat(CharStats.WISDOM)+student.charStats().getStat(CharStats.INTELLIGENCE),100.0)))))); if(newAbility.profficiency()>75) newAbility.setProfficiency(75); student.addAbility(newAbility); newAbility.autoInvocation(student); } } public void practice(MOB teacher, MOB student) { if(student.getPractices()<practicesToPractice()) return; Ability yourAbility=student.fetchAbility(ID()); if(yourAbility!=null) { if(yourAbility.profficiency()<75) { student.setPractices(student.getPractices()-practicesToPractice()); yourAbility.setProfficiency(yourAbility.profficiency()+(int)Math.round(25.0*(Util.div(teacher.charStats().getStat(CharStats.WISDOM)+student.charStats().getStat(CharStats.INTELLIGENCE),36.0)))); if(yourAbility.profficiency()>75) yourAbility.setProfficiency(75); } } } public void makeLongLasting() { tickDown=Integer.MAX_VALUE; } /** this method defines how this thing responds * to environmental changes. It may handle any * and every affect listed in the Affect class * from the given Environmental source */ public void affect(Environmental myHost, Affect affect) { return; } /** this method is used to tell the system whether * a PENDING affect may take place */ public boolean okAffect(Environmental myHost, Affect affect) { return true; } /** * this method allows any environmental object * to behave according to a timed response. by * default, it will never be called unless the * object uses the ServiceEngine to setup service. * The tickID allows granularity with the type * of service being requested. */ public boolean tick(Tickable ticking, int tickID) { if((unInvoked)&&(canBeUninvoked())) return false; if((tickID==Host.MOB_TICK) &&(tickDown!=Integer.MAX_VALUE) &&(canBeUninvoked())) { if(tickDown<0) return !unInvoked; else { tickDown-=1; if(tickDown<=0) { tickDown=-1; unInvoke(); return false; } } } return true; } public boolean appropriateToMyAlignment(int alignment){return true;} public void addAffect(Ability to){} public void addNonUninvokableAffect(Ability to){} public void delAffect(Ability to){} public int numAffects(){ return 0;} public Ability fetchAffect(int index){return null;} public Ability fetchAffect(String ID){return null;} public void addBehavior(Behavior to){} public void delBehavior(Behavior to){} public int numBehaviors(){return 0;} public Behavior fetchBehavior(int index){return null;} public Behavior fetchBehavior(String ID){return null;} public boolean isGeneric(){return false;} private static final String[] CODES={"CLASS","TEXT"}; public String[] getStatCodes(){return CODES;} private int getCodeNum(String code){ for(int i=0;i<CODES.length;i++) if(code.equalsIgnoreCase(CODES[i])) return i; return -1; } public String getStat(String code){ switch(getCodeNum(code)) { case 0: return ID(); case 1: return text(); } return ""; } public void setStat(String code, String val) { switch(getCodeNum(code)) { case 0: return; case 1: setMiscText(val); break; } } public boolean sameAs(Environmental E) { if(!(E instanceof StdAbility)) return false; for(int i=0;i<CODES.length;i++) if(!E.getStat(CODES[i]).equals(getStat(CODES[i]))) return false; return true; } }
package com.couchbase.lite.support; import com.couchbase.lite.Database; import com.couchbase.lite.LiteTestCase; import com.couchbase.lite.util.Log; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class BatcherTest extends LiteTestCase { public void testBatcherSingleBatch() throws Exception { final CountDownLatch doneSignal = new CountDownLatch(10); ScheduledExecutorService workExecutor = new ScheduledThreadPoolExecutor(1); int inboxCapacity = 10; int processorDelay = 1000; Batcher batcher = new Batcher<String>(workExecutor, inboxCapacity, processorDelay, new BatchProcessor<String>() { @Override public void process(List<String> itemsToProcess) { Log.v(Database.TAG, "process called with: " + itemsToProcess); try { Thread.sleep(100); // add this to make it a bit more realistic } catch (InterruptedException e) { e.printStackTrace(); } assertNumbersConsecutive(itemsToProcess); doneSignal.countDown(); } }); ArrayList<String> objectsToQueue = new ArrayList<String>(); for (int i=0; i<inboxCapacity * 10; i++) { objectsToQueue.add(Integer.toString(i)); } batcher.queueObjects(objectsToQueue); boolean didNotTimeOut = doneSignal.await(35, TimeUnit.SECONDS); assertTrue(didNotTimeOut); } public void testBatcherBatchSize5() throws Exception { final CountDownLatch doneSignal = new CountDownLatch(10); ScheduledExecutorService workExecutor = new ScheduledThreadPoolExecutor(1); int inboxCapacity = 10; final int processorDelay = 1000; Batcher batcher = new Batcher<String>(workExecutor, inboxCapacity, processorDelay, new BatchProcessor<String>() { @Override public void process(List<String> itemsToProcess) { Log.v(Database.TAG, "process called with: " + itemsToProcess); try { Thread.sleep(processorDelay * 2); // add this to make it a bit more realistic } catch (InterruptedException e) { e.printStackTrace(); } assertNumbersConsecutive(itemsToProcess); doneSignal.countDown(); } }); ArrayList<String> objectsToQueue = new ArrayList<String>(); for (int i=0; i<inboxCapacity * 10; i++) { objectsToQueue.add(Integer.toString(i)); if (objectsToQueue.size() == 5) { batcher.queueObjects(objectsToQueue); objectsToQueue = new ArrayList<String>(); } } boolean didNotTimeOut = doneSignal.await(35, TimeUnit.SECONDS); assertTrue(didNotTimeOut); } public void testBatcherBatchSize1() throws Exception { final CountDownLatch doneSignal = new CountDownLatch(1); ScheduledExecutorService workExecutor = new ScheduledThreadPoolExecutor(1); int inboxCapacity = 100; final int processorDelay = 1000; Batcher batcher = new Batcher<String>(workExecutor, inboxCapacity, processorDelay, new BatchProcessor<String>() { @Override public void process(List<String> itemsToProcess) { Log.v(Database.TAG, "process called with: " + itemsToProcess); try { Thread.sleep(processorDelay * 2); // add this to make it a bit more realistic } catch (InterruptedException e) { e.printStackTrace(); } assertNumbersConsecutive(itemsToProcess); doneSignal.countDown(); } }); ArrayList<String> objectsToQueue = new ArrayList<String>(); for (int i=0; i<inboxCapacity; i++) { objectsToQueue.add(Integer.toString(i)); if (objectsToQueue.size() == 5) { batcher.queueObjects(objectsToQueue); objectsToQueue = new ArrayList<String>(); } } boolean didNotTimeOut = doneSignal.await(35, TimeUnit.SECONDS); assertTrue(didNotTimeOut); } private static void assertNumbersConsecutive(List<String> itemsToProcess) { int previousItemNumber = -1; for (String itemString : itemsToProcess) { if (previousItemNumber == -1) { previousItemNumber = Integer.parseInt(itemString); } else { int curItemNumber = Integer.parseInt(itemString); assertTrue(curItemNumber == previousItemNumber + 1); previousItemNumber = curItemNumber; } } } }
package net.techcable.npclib.nms; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.UUID; import net.techcable.npclib.NPC; import net.techcable.npclib.util.ProfileUtils; import net.techcable.npclib.util.ProfileUtils.PlayerProfile; import org.apache.commons.lang.ArrayUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; import com.google.common.base.Function; import com.google.common.collect.Lists; import lombok.*; @Getter @Setter public class NMSNPC extends BukkitRunnable implements NPC, Listener { public NMSNPC(UUID uuid, EntityType type, NMSRegistry registry) { if (!type.equals(EntityType.PLAYER)) throw new UnsupportedOperationException("Can only spawn players"); this.type = type; this.UUID = uuid; this.registry = registry; runTaskTimer(getRegistry().getPlugin(), 20, 1); } @Setter(AccessLevel.NONE) @Getter(AccessLevel.NONE) private boolean protect; private final NMSRegistry registry; private Entity entity; private final UUID UUID; private final EntityType type; private String name = ""; @Override public boolean despawn() { if (!isSpawned()) return false; getEntity().remove(); setEntity(null); run(); cancel(); getRegistry().deregister(this); return true; } @Override public void faceLocation(Location toFace) { Util.look(getEntity(), toFace); } @Override public String getName() { String name = this.name; if (getEntity() == null) return name; if (getEntity() != null && getEntity() instanceof LivingEntity) { if (getEntity() instanceof HumanEntity) { name = ((HumanEntity)getEntity()).getName(); } name = ((LivingEntity)getEntity()).getCustomName(); if (name == null) return ""; this.name = name; } return name; } @Override public boolean isSpawned() { return entity != null; } @Override public void setName(String name) { if (name == null) return; this.name = name; if (isSpawned()) { if (getEntity() instanceof Player) { Location current = getEntity().getLocation(); despawn(); spawn(current); } else if (getEntity() instanceof LivingEntity) { ((LivingEntity)getEntity()).setCustomName(name); } } } @Override public boolean spawn(Location toSpawn) { if (isSpawned()) return false; Entity spawned = Util.spawn(toSpawn, getType(), getName(), this); if (spawned != null) { setEntity(spawned); update(Bukkit.getOnlinePlayers()); return true; } else return false; } @Override public void setProtected(boolean protect) { this.protect = protect; } @Override public boolean isProtected() { return protect; } private UUID skin; @Override public void setSkin(UUID skin) { if (!Util.getNMS().isSupported(OptionalFeature.SKINS)) throw new UnsupportedOperationException(); this.skin = skin; if (isSpawned()) { Location last = getEntity().getLocation(); getEntity().remove(); Util.spawn(last, EntityType.PLAYER, getName(), this); } } @Override public void setSkin(String skin) { if (skin == null) return; PlayerProfile profile = ProfileUtils.lookup(skin); if (profile == null) return; setSkin(profile.getId()); } //Update logic @EventHandler public void onJoin(PlayerJoinEvent event) { if (!isSpawned()) return; update(event.getPlayer()); } public void update(Player... players) { if (isSpawned()) { Util.getNMS().notifyOfSpawn(players, (Player)getEntity()); tryEquipmentChangeNotify(players); } else Util.getNMS().notifyOfDespawn(players, (Player)getEntity()); } @Override public void run() { if (!isSpawned()) return; tryEquipmentChangeNotify(Util.getNearbyPlayers(getRange(), getEntity().getLocation())); } private ItemStack[] lastArmor = new ItemStack[5]; public void tryEquipmentChangeNotify(Player[] toNotify) { synchronized (lastArmor) { ArrayList<Integer> toUpdate = new ArrayList<>(5); for (int i = 0; i < 5; i++) { ItemStack lastArmor = this.lastArmor[i]; ItemStack currentArmor = getEquipment(i); if (!equals(currentArmor, lastArmor)) toUpdate.add(i); } if (toUpdate.size() != 0) Util.getNMS().notifyOfEquipmentChange(toNotify, (Player)this.getEntity(), ArrayUtils.toPrimitive(((Integer[])toUpdate.toArray()))); } } public static int getRange() { return (Bukkit.getViewDistance() * 16) + 24; } public ItemStack getEquipment(int slot) { switch (slot) { case 0 : return getEquipment().getItemInHand(); case 1 : return getEquipment().getHelmet(); case 2 : return getEquipment().getChestplate(); case 3 : return getEquipment().getLeggings(); case 4 : return getEquipment().getBoots(); default : return null; } } public EntityEquipment getEquipment() { return ((LivingEntity)getEntity()).getEquipment(); } public static boolean equals(ItemStack first, ItemStack second) { if (first == null) return second == null; return first.equals(second); } }
package com.lzy.okgo.adapter; import android.graphics.Bitmap; import com.lzy.okgo.OkGo; import com.lzy.okgo.cache.CacheEntity; import com.lzy.okgo.cache.CacheManager; import com.lzy.okgo.cache.CacheMode; import com.lzy.okgo.callback.AbsCallback; import com.lzy.okgo.callback.AbsCallbackWrapper; import com.lzy.okgo.exception.OkGoException; import com.lzy.okgo.model.HttpHeaders; import com.lzy.okgo.model.Response; import com.lzy.okgo.request.BaseRequest; import com.lzy.okgo.utils.HeaderParser; import com.lzy.okgo.utils.HttpUtils; import java.io.IOException; import okhttp3.Headers; import okhttp3.Request; import okhttp3.RequestBody; public class CacheCall<T> implements Call<T> { private volatile boolean canceled; private boolean executed; private BaseRequest baseRequest; private okhttp3.Call rawCall; private CacheEntity<T> cacheEntity; private AbsCallback<T> mCallback; public CacheCall(BaseRequest baseRequest) { this.baseRequest = baseRequest; } @Override public void execute(AbsCallback<T> callback) { synchronized (this) { if (executed) throw new IllegalStateException("Already executed."); executed = true; } mCallback = callback; if (mCallback == null) mCallback = new AbsCallbackWrapper<>(); mCallback.onBefore(baseRequest); if (baseRequest.getCacheKey() == null) baseRequest.setCacheKey(HttpUtils.createUrlFromParams(baseRequest.getBaseUrl(), baseRequest.getParams().urlParamsMap)); if (baseRequest.getCacheMode() == null) baseRequest.setCacheMode(CacheMode.NO_CACHE); final CacheMode cacheMode = baseRequest.getCacheMode(); if (cacheMode != CacheMode.NO_CACHE) { //noinspection unchecked cacheEntity = (CacheEntity<T>) CacheManager.INSTANCE.get(baseRequest.getCacheKey()); if (cacheEntity != null && cacheEntity.checkExpire(cacheMode, baseRequest.getCacheTime(), System.currentTimeMillis())) { cacheEntity.setExpire(true); } HeaderParser.addCacheHeaders(baseRequest, cacheEntity, cacheMode); } RequestBody requestBody = baseRequest.generateRequestBody(); Request request = baseRequest.generateRequest(baseRequest.wrapRequestBody(requestBody)); rawCall = baseRequest.generateCall(request); if (cacheMode == CacheMode.IF_NONE_CACHE_REQUEST) { if (cacheEntity != null && !cacheEntity.isExpire()) { T data = cacheEntity.getData(); HttpHeaders headers = cacheEntity.getResponseHeaders(); if (data == null || headers == null) { sendFailResultCallback(true, rawCall, null, OkGoException.INSTANCE(",!")); } else { sendSuccessResultCallback(true, data, rawCall, null); return; } } else { sendFailResultCallback(true, rawCall, null, OkGoException.INSTANCE(",!")); } } else if (cacheMode == CacheMode.FIRST_CACHE_THEN_REQUEST) { if (cacheEntity != null && !cacheEntity.isExpire()) { T data = cacheEntity.getData(); HttpHeaders headers = cacheEntity.getResponseHeaders(); if (data == null || headers == null) { sendFailResultCallback(true, rawCall, null, OkGoException.INSTANCE(",!")); } else { sendSuccessResultCallback(true, data, rawCall, null); } } else { sendFailResultCallback(true, rawCall, null, OkGoException.INSTANCE(",!")); } } if (canceled) { rawCall.cancel(); } rawCall.enqueue(new okhttp3.Callback() { @Override public void onFailure(okhttp3.Call call, IOException e) { mCallback.parseError(call, e); //url, if (!call.isCanceled()) { sendFailResultCallback(false, call, null, e); } } @Override public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException { int responseCode = response.code(); //304 if (responseCode == 304 && cacheMode == CacheMode.DEFAULT) { if (cacheEntity == null) { sendFailResultCallback(true, call, response, OkGoException.INSTANCE("304")); } else { T data = cacheEntity.getData(); HttpHeaders headers = cacheEntity.getResponseHeaders(); if (data == null || headers == null) { sendFailResultCallback(true, call, response, OkGoException.INSTANCE(",!")); } else { sendSuccessResultCallback(true, data, call, response); } } return; } if (responseCode == 404 || responseCode >= 500) { sendFailResultCallback(false, call, response, OkGoException.INSTANCE("!")); return; } try { Response<T> parseResponse = parseResponse(response); T data = parseResponse.body(); handleCache(response.headers(), data); sendSuccessResultCallback(false, data, call, response); } catch (Exception e) { sendFailResultCallback(false, call, response, e); } } }); } /** * * * @param headers * @param data */ @SuppressWarnings("unchecked") private void handleCache(Headers headers, T data) { if (baseRequest.getCacheMode() == CacheMode.NO_CACHE) return; if (data instanceof Bitmap) return; //BitmapSerializable, CacheEntity<T> cache = HeaderParser.createCacheEntity(headers, data, baseRequest.getCacheMode(), baseRequest.getCacheKey()); if (cache == null) { CacheManager.INSTANCE.remove(baseRequest.getCacheKey()); } else { CacheManager.INSTANCE.replace(baseRequest.getCacheKey(), (CacheEntity<Object>) cache); } } @SuppressWarnings("unchecked") private void sendFailResultCallback(final boolean isFromCache, final okhttp3.Call call, final okhttp3.Response response, final Exception e) { final CacheMode cacheMode = baseRequest.getCacheMode(); OkGo.getInstance().getDelivery().post(new Runnable() { @Override public void run() { if (isFromCache) { mCallback.onCacheError(call, e); if (cacheMode == CacheMode.DEFAULT || cacheMode == CacheMode.REQUEST_FAILED_READ_CACHE) { mCallback.onAfter(null, e); } } else { mCallback.onError(call, response, e); if (cacheMode != CacheMode.REQUEST_FAILED_READ_CACHE) { mCallback.onAfter(null, e); } } } }); if (!isFromCache && cacheMode == CacheMode.REQUEST_FAILED_READ_CACHE) { if (cacheEntity != null && !cacheEntity.isExpire()) { T data = cacheEntity.getData(); HttpHeaders headers = cacheEntity.getResponseHeaders(); if (data == null || headers == null) { sendFailResultCallback(true, call, response, OkGoException.INSTANCE(",!")); } else { sendSuccessResultCallback(true, data, call, response); } } else { sendFailResultCallback(true, call, response, OkGoException.INSTANCE(",!")); } } } private void sendSuccessResultCallback(final boolean isFromCache, final T t, final okhttp3.Call call, final okhttp3.Response response) { final CacheMode cacheMode = baseRequest.getCacheMode(); OkGo.getInstance().getDelivery().post(new Runnable() { @Override public void run() { if (isFromCache) { mCallback.onCacheSuccess(t, call); if (cacheMode == CacheMode.DEFAULT || cacheMode == CacheMode.REQUEST_FAILED_READ_CACHE || cacheMode == CacheMode.IF_NONE_CACHE_REQUEST) { mCallback.onAfter(t, null); } } else { mCallback.onSuccess(t, call, response); mCallback.onAfter(t, null); } } }); } @Override public Response<T> execute() throws Exception { synchronized (this) { if (executed) throw new IllegalStateException("Already executed."); executed = true; } okhttp3.Call call = baseRequest.getCall(); if (canceled) { call.cancel(); } return parseResponse(call.execute()); } private Response<T> parseResponse(okhttp3.Response rawResponse) throws Exception { //noinspection unchecked T body = (T) baseRequest.getConverter().convertSuccess(rawResponse); return Response.success(body, rawResponse); } @Override public boolean isExecuted() { return executed; } @Override public void cancel() { canceled = true; if (rawCall != null) { rawCall.cancel(); } } @Override public boolean isCanceled() { return canceled; } @Override public Call<T> clone() { return new CacheCall<>(baseRequest); } @Override public BaseRequest getBaseRequest() { return baseRequest; } }
package com.intellij.util.xml.ui; import com.intellij.util.xml.DomElement; import javax.swing.*; /** * @author peter * * @see DomUIFactory */ public interface DomUIControl extends CommittablePanel { DomElement getDomElement(); void bind(JComponent component); void addCommitListener(CommitListener listener); void removeCommitListener(CommitListener listener); boolean canNavigate(DomElement element); void navigate(DomElement element); }
package ch.unizh.ini.caviar.hardwareinterface.usb; import ch.unizh.ini.caviar.aemapper.*; import ch.unizh.ini.caviar.aesequencer.*; import ch.unizh.ini.caviar.aemonitor.*; import ch.unizh.ini.caviar.hardwareinterface.*; import de.thesycon.usbio.*; import de.thesycon.usbio.structs.*; import java.util.*; import java.util.concurrent.*; import java.util.logging.*; /** * Daniel Fasnacht's AEX board which monitors and sequences * @author tobi * Sim: This class may be used if a direct USB connection to this device is desired, * otherwise The AEX class will be used, which connects to the netdemon for this device. */ public class CypressFX2AEX extends CypressFX2MonitorSequencer { /** Creates a new instance of CypressFX2AEX */ public CypressFX2AEX(int devNumber) { super(devNumber); TICK_US_BOARD=1; this.EEPROM_SIZE=0x4000; } }
package ch.unizh.ini.jaer.chip.multicamera; /** * * @author Gemma * * MultiDAVISCameraChip.java * */ import eu.seebetter.ini.chips.DavisChip; import eu.seebetter.ini.chips.davis.Davis240Config; import java.util.ArrayList; import java.util.TreeMap; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.aemonitor.AEMonitorInterface; import net.sf.jaer.hardwareinterface.HardwareInterface; import net.sf.jaer.hardwareinterface.HardwareInterfaceFactory; import net.sf.jaer.hardwareinterface.usb.USBInterface; import net.sf.jaer.stereopsis.MultiCameraBiasgenHardwareInterface; import net.sf.jaer.stereopsis.MultiCameraHardwareInterface; import net.sf.jaer.biasgen.BiasgenHardwareInterface; import net.sf.jaer.stereopsis.MultiCameraInterface; import net.sf.jaer.aemonitor.AEPacketRaw; import net.sf.jaer.aemonitor.EventRaw; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.OutputEventIterator; import net.sf.jaer.event.MultiCameraApsDvsEvent; import net.sf.jaer.event.ApsDvsEvent; import eu.seebetter.ini.chips.davis.DavisBaseCamera; import eu.seebetter.ini.chips.davis.DavisConfig; import eu.seebetter.ini.chips.davis.DavisTowerBaseConfig; import eu.seebetter.ini.chips.davis.imu.IMUSample; import net.sf.jaer.JAERViewer; import net.sf.jaer.graphics.AEViewer; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Frame; import java.awt.event.ActionEvent; import javax.swing.Action; import javax.swing.KeyStroke; import java.awt.event.KeyEvent; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JSeparator; import net.sf.jaer.graphics.ImageDisplay; import net.sf.jaer.graphics.TwoCamera3DDisplayMethod; import java.util.Iterator; import net.sf.jaer.chip.Chip; import net.sf.jaer.event.ApsDvsEvent.ReadoutType; import net.sf.jaer.graphics.AEViewer.PlayMode; import net.sf.jaer.graphics.DisplayMethod3DSpace; //import net.sf.jaer.graphics.MultiViewerFromMultiCamera; @Description("A multi Davis retina each on it's own USB interface with merged and presumably aligned fields of view") @DevelopmentStatus(DevelopmentStatus.Status.InDevelopment) abstract public class MultiDavisCameraChip extends DavisBaseCamera implements MultiCameraInterface { public int NUM_CAMERAS=4; //MultiCameraHardwareInterface.NUM_CAMERAS; public int NUM_VIEWERS; private AEChip chip= new AEChip(); private AEChip mainChip= new AEChip(); public AEChip[] cameras= new AEChip[NUM_CAMERAS]; public JAERViewer JAERV; public AEViewer mainAEV; public AEViewer[] camerasAEVs= new AEViewer[NUM_CAMERAS]; private JFrame apsFrame = null; public ImageDisplay[] apsDisplay= new ImageDisplay[NUM_CAMERAS]; private ImageDisplay.Legend apsDisplayLegend; int displaycamera; private float[][] displayFrame; private boolean displayAPSEnable=false; public ArrayList<HardwareInterface> hws = new ArrayList(); private int sx; private int sy; private int ADCMax; private float[][] resetBuffer, signalBuffer; private float[][] displayBuffer; private float[][] apsDisplayPixmapBuffer; int count0=0; int count1=0; private JMenu multiCameraMenu = null; // public MulticameraDavisRenderer MultiDavisRenderer; /** Creates a new instance of */ public MultiDavisCameraChip() { super(); // LogManager.getLogManager().reset(); setName("MultiDavisCameraChip"); setEventClass(MultiCameraApsDvsEvent.class); setEventExtractor(new Extractor(this)); getCanvas().addDisplayMethod(new TwoCamera3DDisplayMethod(getCanvas())); getCanvas().addDisplayMethod(new DisplayMethod3DSpace(getCanvas())); // getCanvas().addDisplayMethod(new Triangulation3DViewer (getCanvas())); } @Override public void onDeregistration() { super.onDeregistration(); if (getAeViewer() == null) { return; } if (multiCameraMenu != null) { getAeViewer().removeMenu(multiCameraMenu); multiCameraMenu = null; } if (camerasAEVs != null) { for (int i=0; i<camerasAEVs.length; i++){ if(camerasAEVs[i]!=null){ camerasAEVs[i].setVisible(false); } } } } @Override public void onRegistration() { super.onRegistration(); if (getAeViewer() == null) { return; } multiCameraMenu = new JMenu("MultiCameraMenu"); multiCameraMenu.add(new JMenuItem(new SelectCamera())); multiCameraMenu.add(new JSeparator()); multiCameraMenu.add(new JMenuItem(new ApsDisplay())); // multiCameraMenu.appendCopy(new JMenuItem(new createMultipleAEViewer())); getAeViewer().addMenu(multiCameraMenu); } public void setBiasgenCameraViewers (AEChip chip){ String biasName=chip.getBiasgen().getName(); if (biasName=="DavisConfig") { DavisConfig davisconfig= (DavisConfig) chip.getBiasgen(); davisconfig.setDisplayFrames(false); davisconfig.setDisplayImu(false); chip.setBiasgen(davisconfig); } if (biasName=="Davis240Config"){ Davis240Config davisconfig= (Davis240Config) chip.getBiasgen(); davisconfig.setDisplayFrames(false); davisconfig.setDisplayImu(false); chip.setBiasgen(davisconfig); } if (biasName=="DavisTowerBaseConfig"){ DavisTowerBaseConfig davisconfig= (DavisTowerBaseConfig) chip.getBiasgen(); davisconfig.setDisplayFrames(false); davisconfig.setDisplayImu(false); chip.setBiasgen(davisconfig); } } final public class ApsDisplay extends DavisMenuAction { public ApsDisplay() { super("ApsDisplay", "Display APS", "Display the sorted event in frames"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_E, java.awt.event.InputEvent.SHIFT_MASK)); } @Override public void actionPerformed(ActionEvent e) { displayAPSEnable=true; resetBuffer = new float[sx * sy][NUM_CAMERAS]; signalBuffer = new float[sx * sy][NUM_CAMERAS]; displayFrame = new float[sx * sy][NUM_CAMERAS]; displayBuffer = new float[sx * sy][NUM_CAMERAS]; apsDisplayPixmapBuffer = new float[3 * sx * sy][NUM_CAMERAS]; for (int c=0; c< NUM_CAMERAS; c++){ apsDisplay[c] = ImageDisplay.createOpenGLCanvas(); apsFrame = new JFrame("APS Camera " + c); apsFrame.setPreferredSize(new Dimension(400, 400)); apsFrame.getContentPane().add(apsDisplay[c], BorderLayout.CENTER); apsFrame.setVisible(true); apsFrame.pack(); apsDisplay[c].setImageSize(sx, sy); } } } final public class SelectCamera extends DavisMenuAction { public SelectCamera() { super("SelectCamera", "Select which camera display", "SelectCamera"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_E, java.awt.event.InputEvent.SHIFT_MASK)); } @Override public void actionPerformed(ActionEvent e) { Object[] possibilities = new Object[NUM_CAMERAS+1]; for (int i=0; i<NUM_CAMERAS; i++){ possibilities[i]=i; } possibilities[NUM_CAMERAS]="All"; Frame frame=new Frame(); try{ displaycamera = (int)JOptionPane.showInputDialog(frame,"Select camera to display:","Choose Camera",JOptionPane.QUESTION_MESSAGE,null,possibilities,possibilities[NUM_CAMERAS]); } catch(Exception ex){ displaycamera=NUM_CAMERAS; } } } public void findMaxNumCameras(MultiCameraApsDvsEvent e){ if (e.camera>NUM_CAMERAS){ NUM_CAMERAS=e.camera+1; } } public void setCameraChip(AEChip chip){ for (int i=0; i<NUM_CAMERAS; i++) { cameras[i] = chip; } // AEViewer.DEFAULT_CHIP_CLASS=chip.getName(); this.chip=chip; sx=chip.getSizeX(); setSizeX(sx); sy=chip.getSizeY(); setSizeY(sy); } public void setADCMax(int ADCmaxValue){ ADCMax=ADCmaxValue; } public AEChip getChipType(){ return this.chip; } public AEChip getMultiChip(){ mainChip=this; return mainChip; } @Override public int getNumCellTypes() { return NUM_CAMERAS*2; } @Override public int getNumCameras() { return NUM_CAMERAS; } public void setNumCameras(int n) { NUM_CAMERAS=n; } @Override public void setCamera(int i, AEChip chip) { cameras[i] = chip; } @Override public AEChip getCamera(int i) { return cameras[i]; } /** Changes order of cameras according to list in permutation (which is not checked for uniqueness or bounds). * * @param permutation list of destination indices for elements of cameras. */ @Override public void permuteCameras(int[] permutation) { AEChip[] tmp = new AEChip[permutation.length]; System.arraycopy(cameras, 0, tmp, 0, permutation.length); for (int i = 0; i < permutation.length; i++) { cameras[i] = tmp[permutation[i]]; } } /** the event extractor for the multi chip. * It extracts from each event the x,y,type of the event and in addition, * it adds getNumCellTypes to each type to signal * a right event (as opposed to a left event) */ public class Extractor extends DavisBaseCamera.DavisEventExtractor { public Extractor(MultiDavisCameraChip chip) { super(chip); // they are the same type } /** extracts the meaning of the raw events and returns EventPacket containing BinocularEvent. *@param in the raw events, can be null *@return out the processed events. these are partially processed in-place. empty packet is returned if null is supplied as in. */ @Override synchronized public ApsDvsEventPacket extractPacket(AEPacketRaw in) { if (!(getChip() instanceof MultiDavisCameraChip)) { return null; } final int sx = getChipType().getSizeX()-1; final int sy = getChipType().getSizeY()-1; if (out == null) { out = new ApsDvsEventPacket(MultiCameraApsDvsEvent.class); }else { out.clear(); } out.setRawPacket(in); if (in == null) { return (ApsDvsEventPacket) out; } OutputEventIterator outItr = out.outputIterator(); EventPacket davisExtractedPacket = new DavisEventExtractor((DavisBaseCamera) chip).extractPacket(in); int n =in.getNumEvents();//davisExtractedPacket.getSize(); int[] a = in.getAddresses(); for (int i = 0; i < n; i++) { ApsDvsEvent davisExtractedEvent= (ApsDvsEvent) davisExtractedPacket.getEvent(i); MultiCameraApsDvsEvent e= (MultiCameraApsDvsEvent) outItr.nextOutput(); e.copyFrom(davisExtractedEvent); int address=e.address; if (NUM_CAMERAS==0){ findMaxNumCameras(e); } e.NUM_CAMERAS=NUM_CAMERAS; //if DVS if (e.isDVSEvent() ){ e.camera = MultiCameraApsDvsEvent.getCameraFromRawAddressDVS(address); }else if (e.isApsData()& !e.isImuSample()){ e.camera = MultiCameraApsDvsEvent.getCameraFromRawAddressAPS(address, NUM_CAMERAS); // System.out.println(" camera: " +e.camera+" x: "+ e.x+" y: "+e.y); } if (NUM_CAMERAS==0){ findMaxNumCameras(e); } e.NUM_CAMERAS=NUM_CAMERAS; if(displaycamera<NUM_CAMERAS){ int chosencamera=displaycamera; if(e.camera!=chosencamera){ e.setFilteredOut(true); } } } return (ApsDvsEventPacket) out; } /** Reconstructs the raw packet after event filtering to include the binocular information @param packet the filtered packet @return the reconstructed packet */ @Override public AEPacketRaw reconstructRawPacket(EventPacket oldPacket) { AEPacketRaw newPacket = super.reconstructRawPacket(oldPacket); int n=oldPacket.getSize(); // we also need to appendCopy camera info to raw events for (int i = 0; i < n; i++) { MultiCameraApsDvsEvent mce = (MultiCameraApsDvsEvent) oldPacket.getEvent(i); EventRaw event = newPacket.getEvent(i); int eventAddress=event.address; int eventCamera=mce.camera; if (mce.isDVSEvent()){ event.address=MultiCameraApsDvsEvent.setCameraNumberToRawAddressDVS(eventCamera, eventAddress); } if (mce.isApsData()){ event.address=MultiCameraApsDvsEvent.setCameraNumberToRawAddressAPS(mce.camera, event.address); } } return newPacket; } }// extractor for @Override public void setHardwareInterface(HardwareInterface hw) { if (hw != null) { log.warning("trying to set hardware interface to " + hw + " but hardware interface should have been constructed as a MultiCameraHardwareInterface by this MultiDAVIS240CCameraChip"); } if (hw != null && hw.isOpen()) { log.info("closing hw interface"); hw.close(); } super.setHardwareInterface(hw); } boolean deviceMissingWarningLogged = false; /**Builds and returns a hardware interface for this multi camera device. * Unlike other chip objects, this one actually invokes the HardwareInterfaceFactory to * construct the interfaces and opens them, because this device depends on a particular set of interfaces. * <p> * The hardware serial number IDs are used to assign cameras. * @return the hardware interface for this device */ @Override public HardwareInterface getHardwareInterface() { if (hardwareInterface != null) { return hardwareInterface; } int n = HardwareInterfaceFactory.instance().getNumInterfacesAvailable(); log.info(n + " interfaces found!"); if (n <1) { log.warning( " couldn't build MultiCameraHardwareInterface hardware interface because only " + n + " camera is available and at least 2 cameras are needed"); hardwareInterface= HardwareInterfaceFactory.instance().getInterface(n); try{ if(getAeViewer().getPlayMode()==PlayMode.PLAYBACK){ log.info("playback mode"); } } catch(Exception e){ log.warning("display a logged file or connect interfaces"); } return hardwareInterface; } for (int i = 0; i < n; i++) { HardwareInterface hw = HardwareInterfaceFactory.instance().getInterface(i); if (hw instanceof AEMonitorInterface && hw instanceof BiasgenHardwareInterface) { log.info("found AEMonitorInterface && BiasgenHardwareInterface " + hw); hws.add(hw); } } // TODO fix assignment of cameras according to serial number order // make treemap (sorted map) of string serial numbers of cameras mapped to interfaces TreeMap<String, AEMonitorInterface> map = new TreeMap(); for (HardwareInterface hw : hws) { try { hw.open(); USBInterface usb0 = (USBInterface) hw; String[] sa = usb0.getStringDescriptors(); if (sa.length < 3) { log.warning("interface " + hw.toString() + " has no serial number, cannot guarentee assignment of cameras"); } else { map.put(sa[2], (AEMonitorInterface) hw); } } catch (Exception ex) { log.warning("enumerating multiple cameras: " + ex.toString()); } } try { Object[] oa=map.values().toArray(); AEMonitorInterface[] aemons=new AEMonitorInterface[oa.length]; int ind=0; for(Object o:oa){ aemons[ind++]=(AEMonitorInterface)o; } hardwareInterface = new MultiCameraBiasgenHardwareInterface(aemons); ((MultiCameraBiasgenHardwareInterface) hardwareInterface).setChip(this); hardwareInterface.close(); // will be opened later on by user } catch (Exception e) { log.warning("couldn't build correct multi camera hardware interface: " + e.getMessage()); return null; } deviceMissingWarningLogged = false; return hardwareInterface; } /**Separation of the MultiPacket in SinglePacket. * Unlike other chip objects, this one create a mixed packet containing all the events * from the different plugged cameras. This function separate the mixed Packet in single Packets * one for each camera. The single Packets are saved in an array of EventPacket[]. * <p> * @return EventPacket[NUM_CAMERAS] */ public EventPacket[] separatedCameraPackets(EventPacket in){ int n = in.getSize(); int numCameras=NUM_CAMERAS; EventPacket[] camerasPacket=new EventPacket[numCameras]; int[] freePositionPacket= new int[numCameras]; Iterator evItr = in.iterator(); for(int i=0; i<n; i++) { Object e = evItr.next(); if ( e == null ){ log.warning("null event, skipping"); } MultiCameraApsDvsEvent ev = (MultiCameraApsDvsEvent) e; if (ev.isSpecial()) { continue; } int camera= ev.camera; //Inizialization of the cameraPackets depending on how many cameras are connected //CameraPackets is an array of the EventPackets sorted by camera for(int c=0; c<numCameras; c++) { camerasPacket[c]=new EventPacket(); camerasPacket[c].allocate(n); camerasPacket[c].clear(); } //Allocation of each event in the new sorted Packet freePositionPacket[camera]=camerasPacket[camera].getSize(); camerasPacket[camera].elementData[freePositionPacket[camera]]=ev; camerasPacket[camera].size=camerasPacket[camera].size+1; } return camerasPacket; } public void setDisplayCamera(int n){ displaycamera=n; } }