answer
stringlengths
17
10.2M
package org.fiteagle.north.sfa; import info.openmultinet.ontology.vocabulary.Omn_resource; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.ejb.Timeout; import javax.ejb.Timer; import javax.ejb.TimerConfig; import javax.ejb.TimerService; import org.apache.jena.atlas.web.HttpException; import org.fiteagle.api.tripletStoreAccessor.TripletStoreAccessor; import org.fiteagle.api.tripletStoreAccessor.TripletStoreAccessor.ResourceRepositoryException; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Resource; @Startup @Singleton public class StartUp { private static final Logger LOGGER = Logger.getLogger(StartUp.class .getName()); @javax.annotation.Resource private TimerService timerService; Model defaultModel; private int failureCounter = 0; private static String resourceUri = "http://localhost/resource/SFA"; @PostConstruct public void addSfaApi() { setDefaultModel(); timerService.createIntervalTimer(0, 5000, new TimerConfig()); } @PreDestroy public void deleteSfaApi() { } @Timeout public void timerMethod(Timer timer) { if(failureCounter < 10){ try { if (defaultModel == null) { TripletStoreAccessor.addResource(setDefaultModel().getResource( resourceUri)); timer.cancel(); } else { TripletStoreAccessor.addResource(defaultModel .getResource(resourceUri)); timer.cancel(); } } catch (ResourceRepositoryException e) { LOGGER.log(Level.INFO, "Errored while adding something to Database - will try again"); failureCounter++; } catch (HttpException e) { LOGGER.log(Level.INFO, "Couldn't find RDF Database - will try again"); failureCounter++; } }else{ LOGGER.log(Level.SEVERE, "Tried to add something to Database several times, but failed. Please check the OpenRDF-Database"); } } private Model setDefaultModel() { Model model = ModelFactory.createDefaultModel(); Resource resource = model .createResource(resourceUri); resource.addProperty(Omn_resource.hasInterface, "/sfa/api/am/v3"); resource.addProperty(Omn_resource.hasInterface, "/sfa/api/sa/v1"); defaultModel = model; return model; } }
package org.galibier.packet; import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import java.util.Arrays; import java.util.List; public class MACAddress { public static final int MAC_ADDRESS_LENGTH = 6; private byte[] address = new byte[MAC_ADDRESS_LENGTH]; // preventing to create a instance private MACAddress() {} public static MACAddress valueOf(String address) { String[] elements = address.split(":"); Preconditions.checkArgument(elements.length == MAC_ADDRESS_LENGTH); MACAddress instance = new MACAddress(); for (int i = 0; i < MAC_ADDRESS_LENGTH; i++) { String element = elements[i]; instance.address[i] = (byte)Integer.parseInt(element, 16); } return instance; } public static MACAddress valueOf(byte[] address) { Preconditions.checkArgument(address.length == MAC_ADDRESS_LENGTH); MACAddress instance = new MACAddress(); instance.address = Arrays.copyOf(address, MAC_ADDRESS_LENGTH); return instance; } public byte[] toBytes() { return Arrays.copyOf(address, address.length); } @Override public boolean equals(Object o) { if (o instanceof MACAddress) { MACAddress other = (MACAddress)o; return Arrays.equals(this.address, other.address); } return false; } @Override public int hashCode() { return Arrays.hashCode(this.address); } @Override public String toString() { List<String> elements = Lists.newArrayList(); for (byte b: address) { elements.add(String.format("%02X", b & 0xFF)); } return Joiner.on(":").join(elements); } }
package org.jassetmanager; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class AssetServlet extends HttpServlet { private static final Log LOG = LogFactory.getLog(AssetServlet.class); private final AssetRegistry registry; private static final String USER_AGENT_HEADER = "User-Agent"; private static final String IF_MODIFIED_SINCE_HEADER = "If-Modified-Since"; protected static final String ASSET_ROOT_PATH = "/"; private boolean debug; public AssetServlet() { this.registry = new AssetRegistry(); this.debug = false; } public void setDebug(boolean debug) { this.debug = debug; } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userAgent = request.getHeader(USER_AGENT_HEADER); if (userAgent == null) { userAgent = ""; } String uri = request.getRequestURI(); AssetRegistry.RegistryEntry registryEntry = this.registry.get(uri, userAgent); if (registryEntry == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } else { AssetBundle bundle = registryEntry.getBundle(); try { rebuildBundleIfNeeded(bundle, uri, userAgent); } catch (AssetException e) { handleException(uri, userAgent, response, e); } if (!(isBundleModified(bundle, request))) { LOG.debug("Bundle for '" + uri + "' and User-Agent '" + userAgent + "' not modified."); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { LOG.debug("Serving bundle for '" + uri + "' and User-Agent '" + userAgent + "'"); response.setStatus(HttpServletResponse.SC_OK); response.setContentType(registryEntry.getServeAsMimeType()); response.setContentLength(bundle.getContent().length); response.getOutputStream().write(bundle.getContent()); } } } protected void handleException(String uri, String userAgent, HttpServletResponse response, AssetException e) throws IOException { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); if (this.debug) { response.setContentType("text/plain"); e.printStackTrace(response.getWriter()); } LOG.error("Failed to serve asset bundle for '" + uri + "' and UserAgent '" + userAgent + "'", e); } protected void rebuildBundleIfNeeded(AssetBundle bundle, String uri, String userAgent) throws AssetException { Assets assets = new Assets(this.getServletContext(), bundle.getConfiguration().getContextRootPath()); if (bundle.getConfiguration().getBuildStrategy().isRebuildNeeded(bundle, assets)) { LOG.info("Building bundle for '" + uri + "' and User-Agent '" + userAgent + "'"); bundle.build(assets.listAssets()); } } protected boolean isBundleModified(AssetBundle bundle, HttpServletRequest request) { long ifModifiedSince = request.getDateHeader(IF_MODIFIED_SINCE_HEADER); if (ifModifiedSince > 0) { return bundle.getBuiltAt() > ifModifiedSince; } return true; } protected void configureBundle(String requestPath, String serveAsMimeType, UserAgentMatcher userAgentMatcher, AssetBundleConfiguration config) { this.registry.register(requestPath, serveAsMimeType, userAgentMatcher, new AssetBundle(config, this.getServletContext())); } }
package org.myrobotlab.service; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.commons.io.FilenameUtils; import org.myrobotlab.codec.CodecUtils; import org.myrobotlab.framework.Platform; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.framework.Status; import org.myrobotlab.framework.interfaces.Attachable; import org.myrobotlab.inmoov.Utils; import org.myrobotlab.inmoov.Vision; import org.myrobotlab.io.FileIO; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.opencv.OpenCVData; import org.myrobotlab.service.abstracts.AbstractSpeechSynthesis.Voice; import org.myrobotlab.service.data.JoystickData; import org.myrobotlab.service.data.Locale; import org.myrobotlab.service.interfaces.JoystickListener; import org.myrobotlab.service.interfaces.LocaleProvider; import org.myrobotlab.service.interfaces.ServoControl; import org.myrobotlab.service.interfaces.Simulator; import org.myrobotlab.service.interfaces.SpeechRecognizer; import org.myrobotlab.service.interfaces.SpeechSynthesis; import org.myrobotlab.service.interfaces.TextListener; import org.myrobotlab.service.interfaces.TextPublisher; import org.slf4j.Logger; public class InMoov2 extends Service implements TextListener, TextPublisher, JoystickListener, LocaleProvider { public final static Logger log = LoggerFactory.getLogger(InMoov2.class); public static LinkedHashMap<String, String> lpVars = new LinkedHashMap<String, String>(); // FIXME - why static boolean RobotCanMoveRandom = true; private static final long serialVersionUID = 1L; static String speechRecognizer = "WebkitSpeechRecognition"; /** * This static method returns all the details of the class without it having to * be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(InMoov2.class); meta.addDescription("InMoov2 Service"); meta.addCategory("robot"); meta.sharePeer("mouthControl.mouth", "mouth", "MarySpeech", "shared Speech"); meta.addPeer("eye", "OpenCV", "eye"); meta.addPeer("servomixer", "ServoMixer", "for making gestures"); // the two legacy controllers .. :( meta.addPeer("left", "Arduino", "legacy controller"); meta.addPeer("right", "Arduino", "legacy controller"); meta.addPeer("htmlFilter", "HtmlFilter", "filter speaking html"); meta.addPeer("brain", "ProgramAB", "brain"); meta.addPeer("simulator", "JMonkeyEngine", "simulator"); meta.addPeer("head", "InMoov2Head", "head"); meta.addPeer("torso", "InMoov2Torso", "torso"); // meta.addPeer("eyelids", "InMoovEyelids", "eyelids"); meta.addPeer("leftArm", "InMoov2Arm", "left arm"); meta.addPeer("leftHand", "InMoov2Hand", "left hand"); meta.addPeer("rightArm", "InMoov2Arm", "right arm"); meta.addPeer("rightHand", "InMoov2Hand", "right hand"); meta.addPeer("mouthControl", "MouthControl", "MouthControl"); // meta.addPeer("imageDisplay", "ImageDisplay", "image display service"); meta.addPeer("mouth", "MarySpeech", "InMoov speech service"); meta.addPeer("ear", speechRecognizer, "InMoov webkit speech recognition service"); meta.addPeer("headTracking", "Tracking", "Head tracking system"); meta.sharePeer("headTracking.opencv", "eye", "OpenCV", "shared head OpenCV"); // meta.sharePeer("headTracking.controller", "left", "Arduino", "shared head // Arduino"); NO !!!! meta.sharePeer("headTracking.x", "head.rothead", "Servo", "shared servo"); meta.sharePeer("headTracking.y", "head.neck", "Servo", "shared servo"); // Global - undecorated by self name meta.addRootPeer("python", "Python", "shared Python service"); // latest - not ready until repo is ready meta.addDependency("fr.inmoov", "inmoov2", null, "zip"); return meta; } /** * This method will load a python file into the python interpreter. */ public static boolean loadFile(String file) { File f = new File(file); Python p = (Python) Runtime.getService("python"); log.info("Loading Python file {}", f.getAbsolutePath()); if (p == null) { log.error("Python instance not found"); return false; } String script = null; try { script = FileIO.toString(f.getAbsolutePath()); } catch (IOException e) { log.error("IO Error loading file : ", e); return false; } // evaluate the scripts in a blocking way. boolean result = p.exec(script, true); if (!result) { log.error("Error while loading file {}", f.getAbsolutePath()); return false; } else { log.debug("Successfully loaded {}", f.getAbsolutePath()); } return true; } public static void main(String[] args) { try { LoggingFactory.init(Level.INFO); Platform.setVirtual(true); // Runtime.main(new String[] { "--install", "InMoov2" }); // Runtime.main(new String[] { "--interactive", "--id", "inmoov", // "--install-dependency","fr.inmoov", "inmoov2", "latest", "zip"}); Runtime.main(new String[] { "--resource-override", "InMoov2=/lhome/grperry/github/mrl.develop/myrobotlab/src/main/resources/resource/InMoov2/resource/InMoov2", "WebGui=/lhome/grperry/github/mrl.develop/myrobotlab/src/main/resources/resource/InMoov2/resource/WebGui", "ProgramAB=/lhome/grperry/github/mrl.develop/myrobotlab/src/main/resources/resource/InMoov2/resource/ProgramAB", "--interactive", "--id", "inmoov" }); String[] langs = java.util.Locale.getISOLanguages(); java.util.Locale[] locales = java.util.Locale.getAvailableLocales(); log.info("{}", locales.length); for (java.util.Locale l : locales) { log.info(" log.info(CodecUtils.toJson(l)); log.info(l.getDisplayLanguage()); log.info(l.getLanguage()); log.info(l.getCountry()); log.info(l.getDisplayCountry()); log.info(CodecUtils.toJson(new Locale(l))); if (l.getLanguage().equals("en")) { log.info("here"); } } InMoov2 i01 = (InMoov2) Runtime.start("i01", "InMoov2"); WebGui webgui = (WebGui) Runtime.create("webgui", "WebGui"); webgui.autoStartBrowser(false); webgui.startService(); boolean done = true; if (done) { return; } i01.startBrain(); i01.startAll("COM3", "COM4"); Runtime.start("python", "Python"); // Runtime.start("log", "Log"); /* * OpenCV cv = (OpenCV) Runtime.start("cv", "OpenCV"); cv.setCameraIndex(2); */ // i01.startSimulator(); /* * Arduino mega = (Arduino) Runtime.start("mega", "Arduino"); * mega.connect("/dev/ttyACM0"); */ } catch (Exception e) { log.error("main threw", e); } } boolean autoStartBrowser = false; transient ProgramAB brain; Set<String> configs = null; String currentConfigurationName = "default"; transient SpeechRecognizer ear; transient OpenCV eye; transient Tracking eyesTracking; // waiting controable threaded gestures we warn user boolean gestureAlreadyStarted = false; // FIXME - what the hell is this for ? Set<String> gestures = new TreeSet<String>(); transient InMoov2Head head; transient Tracking headTracking; transient HtmlFilter htmlFilter; // transient ImageDisplay imageDisplay; /** * simple booleans to determine peer state of existence FIXME - should be an * auto-peer variable */ boolean isBrainActivated = false; boolean isEarActivated = false; boolean isEyeActivated = false; boolean isEyeLidsActivated = false; boolean isHeadActivated = false; boolean isLeftArmActivated = false; boolean isLeftHandActivated = false; boolean isMouthActivated = false; boolean isRightArmActivated = false; boolean isRightHandActivated = false; boolean isSimulatorActivated = false; boolean isTorsoActivated = false; boolean isNeopixelActivated = false; boolean isPirActivated = false; boolean isUltraSonicSensorActivated = false; boolean isServoMixerActivated = false; // TODO - refactor into a Simulator interface when more simulators are borgd transient JMonkeyEngine jme; String lastGestureExecuted; Long lastPirActivityTime; transient InMoov2Arm leftArm; // transient LanguagePack languagePack = new LanguagePack(); // transient InMoovEyelids eyelids; eyelids are in the head transient InMoov2Hand leftHand; Locale locale; /** * supported locales */ Map<String, Locale> locales = null; int maxInactivityTimeSeconds = 120; transient SpeechSynthesis mouth; // FIXME ugh - new MouthControl service that uses AudioFile output transient public MouthControl mouthControl; boolean mute = false; transient NeoPixel neopixel; transient ServoMixer servomixer; transient Python python; transient InMoov2Arm rightArm; transient InMoov2Hand rightHand; /** * used to remember/serialize configuration the user's desired speech type */ String speechService = "MarySpeech"; transient InMoov2Torso torso; @Deprecated public Vision vision; // FIXME - remove all direct references // transient private HashMap<String, InMoov2Arm> arms = new HashMap<>(); protected List<Voice> voices = null; protected String voiceSelected; transient WebGui webgui; public InMoov2(String n, String id) { super(n, id); // by default all servos will auto-disable Servo.setAutoDisableDefault(true); locales = Locale.getLocaleMap("en-US", "fr-FR", "es-ES", "de-DE", "nl-NL", "ru-RU", "hi-IN", "it-IT", "fi-FI", "pt-PT"); locale = Runtime.getInstance().getLocale(); python = (Python) startPeer("python"); load(locale.getTag()); // get events of new services and shutdown Runtime r = Runtime.getInstance(); subscribe(r.getName(), "shutdown"); listConfigFiles(); // FIXME - Framework should auto-magically auto-start peers AFTER // construction - unless explicitly told not to // peers to start on construction // imageDisplay = (ImageDisplay) startPeer("imageDisplay"); } @Override /* local strong type - is to be avoided - use name string */ public void addTextListener(TextListener service) { // CORRECT WAY ! - no direct reference - just use the name in a subscription addListener("publishText", service.getName()); } @Override public void attachTextListener(TextListener service) { addListener("publishText", service.getName()); } public void attachTextPublisher(String name) { subscribe(name, "publishText"); } @Override public void attachTextPublisher(TextPublisher service) { subscribe(service.getName(), "publishText"); } public void beginCheckingOnInactivity() { beginCheckingOnInactivity(maxInactivityTimeSeconds); } public void beginCheckingOnInactivity(int maxInactivityTimeSeconds) { this.maxInactivityTimeSeconds = maxInactivityTimeSeconds; // speakBlocking("power down after %s seconds inactivity is on", // this.maxInactivityTimeSeconds); log.info("power down after %s seconds inactivity is on", this.maxInactivityTimeSeconds); addTask("checkInactivity", 5 * 1000, 0, "checkInactivity"); } public long checkInactivity() { // speakBlocking("checking"); long lastActivityTime = getLastActivityTime(); long now = System.currentTimeMillis(); long inactivitySeconds = (now - lastActivityTime) / 1000; if (inactivitySeconds > maxInactivityTimeSeconds) { // speakBlocking("%d seconds have passed without activity", // inactivitySeconds); powerDown(); } else { // speakBlocking("%d seconds have passed without activity", // inactivitySeconds); info("checking checkInactivity - %d seconds have passed without activity", inactivitySeconds); } return lastActivityTime; } public void closeAllImages() { // imageDisplay.closeAll(); log.error("implement webgui.closeAllImages"); } public void cycleGestures() { // if not loaded load - // FIXME - this needs alot of "help" :P // WHY IS THIS DONE ? if (gestures.size() == 0) { loadGestures(); } for (String gesture : gestures) { try { String methodName = gesture.substring(0, gesture.length() - 3); speakBlocking(methodName); log.info("executing gesture {}", methodName); python.eval(methodName + "()"); // wait for finish - or timeout ? } catch (Exception e) { error(e); } } } public void disable() { if (head != null) { head.disable(); } if (rightHand != null) { rightHand.disable(); } if (leftHand != null) { leftHand.disable(); } if (rightArm != null) { rightArm.disable(); } if (leftArm != null) { leftArm.disable(); } if (torso != null) { torso.disable(); } } public void displayFullScreen(String src) { try { // imageDisplay.displayFullScreen(src); log.error("implement webgui.displayFullScreen"); } catch (Exception e) { error("could not display picture %s", src); } } public void enable() { if (head != null) { head.enable(); } if (rightHand != null) { rightHand.enable(); } if (leftHand != null) { leftHand.enable(); } if (rightArm != null) { rightArm.enable(); } if (leftArm != null) { leftArm.enable(); } if (torso != null) { torso.enable(); } } /** * This method will try to launch a python command with error handling */ public String execGesture(String gesture) { lastGestureExecuted = gesture; if (python == null) { log.warn("execGesture : No jython engine..."); return null; } subscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus"); startedGesture(lastGestureExecuted); return python.evalAndWait(gesture); } public void finishedGesture() { finishedGesture("unknown"); } public void finishedGesture(String nameOfGesture) { if (gestureAlreadyStarted) { waitTargetPos(); RobotCanMoveRandom = true; gestureAlreadyStarted = false; log.info("gesture : {} finished...", nameOfGesture); } } public void fullSpeed() { if (head != null) { head.fullSpeed(); } if (rightHand != null) { rightHand.fullSpeed(); } if (leftHand != null) { leftHand.fullSpeed(); } if (rightArm != null) { rightArm.fullSpeed(); } if (leftArm != null) { leftArm.fullSpeed(); } if (torso != null) { torso.fullSpeed(); } } public String get(String param) { if (lpVars.containsKey(param.toUpperCase())) { return lpVars.get(param.toUpperCase()); } return "not yet translated"; } public InMoov2Arm getArm(String side) { if ("left".equals(side)) { return leftArm; } else if ("right".equals(side)) { return rightArm; } else { log.error("can not get arm {}", side); } return null; } public InMoov2Hand getHand(String side) { if ("left".equals(side)) { return leftHand; } else if ("right".equals(side)) { return rightHand; } else { log.error("can not get arm {}", side); } return null; } public InMoov2Head getHead() { return head; } /** * get current language */ public String getLanguage() { return locale.getLanguage(); } /** * finds most recent activity * * @return the timestamp of the last activity time. */ public long getLastActivityTime() { long lastActivityTime = 0; if (leftHand != null) { lastActivityTime = Math.max(lastActivityTime, leftHand.getLastActivityTime()); } if (leftArm != null) { lastActivityTime = Math.max(lastActivityTime, leftArm.getLastActivityTime()); } if (rightHand != null) { lastActivityTime = Math.max(lastActivityTime, rightHand.getLastActivityTime()); } if (rightArm != null) { lastActivityTime = Math.max(lastActivityTime, rightArm.getLastActivityTime()); } if (head != null) { lastActivityTime = Math.max(lastActivityTime, head.getLastActivityTime()); } if (torso != null) { lastActivityTime = Math.max(lastActivityTime, torso.getLastActivityTime()); } if (lastPirActivityTime != null) { lastActivityTime = Math.max(lastActivityTime, lastPirActivityTime); } if (lastActivityTime == 0) { error("invalid activity time - anything connected?"); lastActivityTime = System.currentTimeMillis(); } return lastActivityTime; } public InMoov2Arm getLeftArm() { return leftArm; } public InMoov2Hand getLeftHand() { return leftHand; } @Override public Locale getLocale() { return locale; } @Override public Map<String, Locale> getLocales() { return locales; } public InMoov2Arm getRightArm() { return rightArm; } public InMoov2Hand getRightHand() { return rightHand; } public Simulator getSimulator() { return jme; } public InMoov2Torso getTorso() { return torso; } public void halfSpeed() { if (head != null) { head.setSpeed(25.0, 25.0, 25.0, 25.0, -1.0, 25.0); } if (rightHand != null) { rightHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0); } if (leftHand != null) { leftHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0); } if (rightArm != null) { rightArm.setSpeed(25.0, 25.0, 25.0, 25.0); } if (leftArm != null) { leftArm.setSpeed(25.0, 25.0, 25.0, 25.0); } if (torso != null) { torso.setSpeed(20.0, 20.0, 20.0); } } public boolean isCameraOn() { if (eye != null) { if (eye.isCapturing()) { return true; } } return false; } public boolean isEyeLidsActivated() { return isEyeLidsActivated; } public boolean isHeadActivated() { return isHeadActivated; } public boolean isLeftArmActivated() { return isLeftArmActivated; } public boolean isLeftHandActivated() { return isLeftHandActivated; } public boolean isMute() { return mute; } public boolean isNeopixelActivated() { return isNeopixelActivated; } public boolean isRightArmActivated() { return isRightArmActivated; } public boolean isRightHandActivated() { return isRightHandActivated; } public boolean isTorsoActivated() { return isTorsoActivated; } public boolean isPirActivated() { return isPirActivated; } public boolean isUltraSonicSensorActivated() { return isUltraSonicSensorActivated; } public boolean isServoMixerActivated() { return isServoMixerActivated; } public Set<String> listConfigFiles() { configs = new HashSet<>(); // data list String configDir = getResourceDir() + fs + "config"; File f = new File(configDir); if (!f.exists()) { f.mkdirs(); } String[] files = f.list(); for (String config : files) { configs.add(config); } // data list configDir = getDataDir() + fs + "config"; f = new File(configDir); if (!f.exists()) { f.mkdirs(); } files = f.list(); for (String config : files) { configs.add(config); } return configs; } /* * iterate over each txt files in the directory */ public void load(String locale) { String extension = "lang"; File dir = Utils.makeDirectory(getResourceDir() + File.separator + "system" + File.separator + "languagePack" + File.separator + locale); if (dir.exists()) { lpVars.clear(); for (File f : dir.listFiles()) { if (f.isDirectory()) { continue; } if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) { log.info("Inmoov languagePack load : {}", f.getName()); try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8")); for (String line = br.readLine(); line != null; line = br.readLine()) { String[] parts = line.split("::"); if (parts.length > 1) { lpVars.put(parts[0].toUpperCase(), parts[1]); } } } catch (IOException e) { log.error("LanguagePack : {}", e); } } else { log.warn("{} is not a {} file", f.getAbsolutePath(), extension); } } } } // FIXME - what is this for ??? public void loadGestures() { loadGestures(getResourceDir() + fs + "gestures"); } /** * This blocking method will look at all of the .py files in a directory. One by * one it will load the files into the python interpreter. A gesture python file * should contain 1 method definition that is the same as the filename. * * @param directory - the directory that contains the gesture python files. */ public boolean loadGestures(String directory) { speakBlocking("loading gestures"); // FIXME - make polyglot // iterate over each of the python files in the directory // and load them into the python interpreter. String extension = "py"; Integer totalLoaded = 0; Integer totalError = 0; File dir = new File(directory); dir.mkdirs(); if (dir.exists()) { for (File f : dir.listFiles()) { if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) { if (loadFile(f.getAbsolutePath()) == true) { totalLoaded += 1; String methodName = f.getName().substring(0, f.getName().length() - 3) + "()"; gestures.add(methodName); } else { error("could not load %s", f.getName()); totalError += 1; } } else { log.info("{} is not a {} file", f.getAbsolutePath(), extension); } } } info("%s Gestures loaded, %s Gestures with error", totalLoaded, totalError); broadcastState(); if (totalError > 0) { speakAlert(get("GESTURE_ERROR")); return false; } return true; } public void moveArm(String which, double bicep, double rotate, double shoulder, double omoplate) { InMoov2Arm arm = getArm(which); if (arm == null) { info("%s arm not started", which); return; } arm.moveTo(bicep, rotate, shoulder, omoplate); } public void moveEyelids(double eyelidleftPos, double eyelidrightPos) { if (head != null) { head.moveEyelidsTo(eyelidleftPos, eyelidrightPos); } else { log.warn("moveEyelids - I have a null head"); } } public void moveEyes(double eyeX, double eyeY) { if (head != null) { head.moveTo(null, null, eyeX, eyeY, null, null); } else { log.warn("moveEyes - I have a null head"); } } public void moveHand(String which, double thumb, double index, double majeure, double ringFinger, double pinky) { moveHand(which, thumb, index, majeure, ringFinger, pinky, null); } public void moveHand(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) { InMoov2Hand hand = getHand(which); if (hand == null) { log.warn("{} hand does not exist"); return; } hand.moveTo(thumb, index, majeure, ringFinger, pinky, wrist); } public void moveHead(double neck, double rothead) { moveHead(neck, rothead, null); } public void moveHead(double neck, double rothead, double eyeX, double eyeY, double jaw) { moveHead(neck, rothead, eyeX, eyeY, jaw, null); } public void moveHead(Double neck, Double rothead, Double rollNeck) { moveHead(neck, rothead, null, null, null, rollNeck); } public void moveHead(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) { if (head != null) { head.moveTo(neck, rothead, eyeX, eyeY, jaw, rollNeck); } else { log.error("I have a null head"); } } public void moveHeadBlocking(double neck, double rothead) { moveHeadBlocking(neck, rothead, null); } public void moveHeadBlocking(double neck, double rothead, Double rollNeck) { moveHeadBlocking(neck, rothead, null, null, null, rollNeck); } public void moveHeadBlocking(double neck, double rothead, Double eyeX, Double eyeY, Double jaw) { moveHeadBlocking(neck, rothead, eyeX, eyeY, jaw, null); } public void moveHeadBlocking(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) { if (head != null) { head.moveToBlocking(neck, rothead, eyeX, eyeY, jaw, rollNeck); } else { log.error("I have a null head"); } } public void moveTorso(double topStom, double midStom, double lowStom) { if (torso != null) { torso.moveTo(topStom, midStom, lowStom); } else { log.error("moveTorso - I have a null torso"); } } public void moveTorsoBlocking(double topStom, double midStom, double lowStom) { if (torso != null) { torso.moveToBlocking(topStom, midStom, lowStom); } else { log.error("moveTorsoBlocking - I have a null torso"); } } public void onGestureStatus(Status status) { if (!status.equals(Status.success()) && !status.equals(Status.warn("Python process killed !"))) { error("I cannot execute %s, please check logs", lastGestureExecuted); } finishedGesture(lastGestureExecuted); unsubscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus"); } @Override public void onJoystickInput(JoystickData input) throws Exception { // TODO Auto-generated method stub } public OpenCVData onOpenCVData(OpenCVData data) { return data; } @Override public void onText(String text) { // FIXME - we should be able to "re"-publish text but text is coming from // different sources // some might be coming from the ear - some from the mouth ... - there has // to be a distinction log.info("onText - {}", text); invoke("publishText", text); } // TODO FIX/CHECK this, migrate from python land public void powerDown() { rest(); purgeTasks(); disable(); if (ear != null) { ear.lockOutAllGrammarExcept("power up"); } python.execMethod("power_down"); } // TODO FIX/CHECK this, migrate from python land public void powerUp() { enable(); rest(); if (ear != null) { ear.clearLock(); } beginCheckingOnInactivity(); python.execMethod("power_up"); } /** * all published text from InMoov2 - including ProgramAB */ @Override public String publishText(String text) { return text; } public void releaseService() { try { disable(); releasePeers(); super.releaseService(); } catch (Exception e) { error(e); } } // FIXME NO DIRECT REFERENCES - publishRest --> (onRest) --> rest public void rest() { log.info("InMoov2.rest()"); if (head != null) { head.rest(); } if (rightHand != null) { rightHand.rest(); } if (leftHand != null) { leftHand.rest(); } if (rightArm != null) { rightArm.rest(); } if (leftArm != null) { leftArm.rest(); } if (torso != null) { torso.rest(); } } @Deprecated public void setArmVelocity(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) { InMoov2Arm arm = getArm(which); if (arm == null) { warn("%s hand not started", which); return; } arm.setSpeed(bicep, rotate, shoulder, omoplate); } public void setAutoDisable(Boolean param) { if (head != null) { head.setAutoDisable(param); } if (rightArm != null) { rightArm.setAutoDisable(param); } if (leftArm != null) { leftArm.setAutoDisable(param); } if (leftHand != null) { leftHand.setAutoDisable(param); } if (rightHand != null) { leftHand.setAutoDisable(param); } if (torso != null) { torso.setAutoDisable(param); } /* * if (eyelids != null) { eyelids.setAutoDisable(param); } */ } public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) { setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null); } public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) { InMoov2Hand hand = getHand(which); if (hand == null) { warn("%s hand not started", which); return; } hand.setSpeed(thumb, index, majeure, ringFinger, pinky, wrist); } @Deprecated public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) { setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null); } @Deprecated public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) { setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, wrist); } public void setHeadSpeed(Double rothead, Double neck) { setHeadSpeed(rothead, neck, null, null, null); } public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) { setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null); } public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) { if (head == null) { warn("setHeadSpeed - head not started"); return; } head.setSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed); } @Deprecated public void setHeadVelocity(Double rothead, Double neck) { setHeadSpeed(rothead, neck, null, null, null, null); } @Deprecated public void setHeadVelocity(Double rothead, Double neck, Double rollNeck) { setHeadSpeed(rothead, neck, null, null, null, rollNeck); } @Deprecated public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) { setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null); } @Deprecated public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) { setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed); } /** * TODO : use system locale set language for InMoov service used by chatbot + * * @param code * @return */ @Deprecated /* use setLocale */ public String setLanguage(String code) { setLocale(code); return code; } @Override public void setLocale(String code) { if (code == null) { log.warn("setLocale null"); return; } // filter of the set of supported locales if (!locales.containsKey(code)) { error("InMooov does not support %s only %s", code, locales.keySet()); return; } locale = new Locale(code); speakBlocking("setting language to %s", locale.getDisplayLanguage()); // attempt to set all other language providers to the same language as me List<String> providers = Runtime.getServiceNamesFromInterface(LocaleProvider.class); for (String provider : providers) { if (!provider.equals(getName())) { log.info("{} setting locale to %s", provider, code); send(provider, "setLocale", code); send(provider, "broadcastState"); } } load(locale.getTag()); } public void setMute(boolean mute) { info("Set mute to %s", mute); this.mute = mute; sendToPeer("mouth", "setMute", mute); broadcastState(); } public void setNeopixelAnimation(String animation, Integer red, Integer green, Integer blue, Integer speed) { if (neopixel != null /* && neopixelArduino != null */) { neopixel.setAnimation(animation, red, green, blue, speed); } else { warn("No Neopixel attached"); } } public String setSpeechType(String speechType) { speechService = speechType; setPeer("mouth", speechType); return speechType; } public void setTorsoSpeed(Double topStom, Double midStom, Double lowStom) { if (torso != null) { torso.setSpeed(topStom, midStom, lowStom); } else { log.warn("setTorsoSpeed - I have no torso"); } } @Deprecated public void setTorsoVelocity(Double topStom, Double midStom, Double lowStom) { if (torso != null) { torso.setVelocity(topStom, midStom, lowStom); } else { log.warn("setTorsoVelocity - I have no torso"); } } /** * overridden setVirtual for InMoov sets "all" services to virtual */ public boolean setVirtual(boolean virtual) { super.setVirtual(virtual); Platform.setVirtual(virtual); return virtual; } public void setVoice(String name) { if (mouth != null) { mouth.setVoice(name); voiceSelected = name; speakBlocking("setting voice to %s", name); } } public void speak(String toSpeak) { sendToPeer("mouth", "speak", toSpeak); } public void speakAlert(String toSpeak) { speakBlocking(get("ALERT")); speakBlocking(toSpeak); } public void speakBlocking(String speak) { speakBlocking(speak, null); } // FIXME - publish text regardless if mouth exists ... public void speakBlocking(String format, Object... args) { if (format == null) { return; } String toSpeak = format; if (args != null) { toSpeak = String.format(format, args); } // FIXME - publish onText when listening invoke("publishText", toSpeak); if (!mute) { // sendToPeer("mouth", "speakBlocking", toSpeak); invokePeer("mouth", "speakBlocking", toSpeak); } } public void startAll() throws Exception { startAll(null, null); } public void startAll(String leftPort, String rightPort) throws Exception { startMouth(); startBrain(); startHeadTracking(); // startEyesTracking(); // startOpenCV(); startEar(); startServos(leftPort, rightPort); // startMouthControl(head.jaw, mouth); speakBlocking("startup sequence completed"); } public ProgramAB startBrain() { try { brain = (ProgramAB) startPeer("brain"); isBrainActivated = true; speakBlocking(get("CHATBOTACTIVATED")); // GOOD EXAMPLE ! - no type, uses name - does a set of subscriptions ! // attachTextPublisher(brain.getName()); /* * not necessary - ear needs to be attached to mouth not brain if (ear != null) * { ear.attachTextListener(brain); } */ brain.attachTextPublisher(ear); // this.attach(brain); FIXME - attach as a TextPublisher - then re-publish // FIXME - deal with language // speakBlocking(get("CHATBOTACTIVATED")); brain.repetitionCount(10); brain.setPath(getResourceDir() + fs + "chatbot"); brain.startSession("default", locale.getTag()); // reset some parameters to default... brain.setPredicate("topic", "default"); brain.setPredicate("questionfirstinit", ""); brain.setPredicate("tmpname", ""); brain.setPredicate("null", ""); // load last user session if (!brain.getPredicate("name").isEmpty()) { if (brain.getPredicate("lastUsername").isEmpty() || brain.getPredicate("lastUsername").equals("unknown")) { brain.setPredicate("lastUsername", brain.getPredicate("name")); } } brain.setPredicate("parameterHowDoYouDo", ""); try { brain.savePredicates(); } catch (IOException e) { log.error("saving predicates threw", e); } // start session based on last recognized person if (!brain.getPredicate("default", "lastUsername").isEmpty() && !brain.getPredicate("default", "lastUsername").equals("unknown")) { brain.startSession(brain.getPredicate("lastUsername")); } htmlFilter = (HtmlFilter) startPeer("htmlFilter");// Runtime.start("htmlFilter", // "HtmlFilter"); brain.attachTextListener(htmlFilter); htmlFilter.attachTextListener((TextListener) getPeer("mouth")); brain.attachTextListener(this); } catch (Exception e) { speak("could not load brain"); error(e.getMessage()); speak(e.getMessage()); } broadcastState(); return brain; } public SpeechRecognizer startEar() { ear = (SpeechRecognizer) startPeer("ear"); isEarActivated = true; ear.attachSpeechSynthesis((SpeechSynthesis) getPeer("mouth")); ear.attachTextListener(brain); speakBlocking(get("STARTINGEAR")); broadcastState(); return ear; } public void startedGesture() { startedGesture("unknown"); } public void startedGesture(String nameOfGesture) { if (gestureAlreadyStarted) { warn("Warning 1 gesture already running, this can break spacetime and lot of things"); } else { log.info("Starting gesture : {}", nameOfGesture); gestureAlreadyStarted = true; RobotCanMoveRandom = false; } } // FIXME - universal (good) way of handling all exceptions - ie - reporting // back to the user the problem in a short concise way but have // expandable detail in appropriate places public OpenCV startEye() throws Exception { speakBlocking(get("STARTINGOPENCV")); eye = (OpenCV) startPeer("eye", "OpenCV"); subscribeTo(eye.getName(), "publishOpenCVData"); isEyeActivated = true; return eye; } public Tracking startEyesTracking() throws Exception { if (head == null) { startHead(); } return startHeadTracking(head.eyeX, head.eyeY); } public Tracking startEyesTracking(ServoControl eyeX, ServoControl eyeY) throws Exception { if (eye == null) { startEye(); } speakBlocking(get("TRACKINGSTARTED")); eyesTracking = (Tracking) this.startPeer("eyesTracking"); eyesTracking.connect(eye, head.eyeX, head.eyeY); return eyesTracking; } public InMoov2Head startHead() throws Exception { return startHead(null, null, null, null, null, null, null, null); } public InMoov2Head startHead(String port) throws Exception { return startHead(port, null, null, null, null, null, null, null); } // legacy inmoov head exposed pins public InMoov2Head startHead(String port, String type, Integer headYPin, Integer headXPin, Integer eyeXPin, Integer eyeYPin, Integer jawPin, Integer rollNeckPin) { // log.warn(InMoov.buildDNA(myKey, serviceClass)) // speakBlocking(get("STARTINGHEAD") + " " + port); // ??? SHOULD THERE BE REFERENCES AT ALL ??? ... probably not speakBlocking(get("STARTINGHEAD")); head = (InMoov2Head) startPeer("head"); isHeadActivated = true; if (headYPin != null) { head.setPins(headYPin, headXPin, eyeXPin, eyeYPin, jawPin, rollNeckPin); } // lame assumption - port is specified - it must be an Arduino :( if (port != null) { try { speakBlocking(get(port)); Arduino arduino = (Arduino) startPeer("left", "Arduino"); arduino.connect(port); arduino.attach(head.neck); arduino.attach(head.rothead); arduino.attach(head.eyeX); arduino.attach(head.eyeY); arduino.attach(head.jaw); arduino.attach(head.rollNeck); } catch (Exception e) { error(e); } } speakBlocking(get("STARTINGMOUTHCONTROL")); mouthControl = (MouthControl) startPeer("mouthControl"); mouthControl.attach(head.jaw); mouthControl.attach((Attachable) getPeer("mouth")); mouthControl.setmouth(10, 50);// <-- FIXME - not the right place for // config !!! return head; } public void startHeadTracking() throws Exception { if (eye == null) { startEye(); } if (head == null) { startHead(); } if (headTracking == null) { speakBlocking(get("TRACKINGSTARTED")); headTracking = (Tracking) this.startPeer("headTracking"); headTracking.connect(this.eye, head.rothead, head.neck); } } public Tracking startHeadTracking(ServoControl rothead, ServoControl neck) throws Exception { if (eye == null) { startEye(); } if (headTracking == null) { speakBlocking(get("TRACKINGSTARTED")); headTracking = (Tracking) this.startPeer("headTracking"); headTracking.connect(this.eye, rothead, neck); } return headTracking; } public InMoov2Arm startLeftArm() { return startLeftArm(null); } public InMoov2Arm startLeftArm(String port) { // log.warn(InMoov.buildDNA(myKey, serviceClass)) // speakBlocking(get("STARTINGHEAD") + " " + port); // ??? SHOULD THERE BE REFERENCES AT ALL ??? ... probably not speakBlocking(get("STARTINGLEFTARM")); leftArm = (InMoov2Arm) startPeer("leftArm"); isLeftArmActivated = true; if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("left", "Arduino"); arduino.connect(port); arduino.attach(leftArm.bicep); arduino.attach(leftArm.omoplate); arduino.attach(leftArm.rotate); arduino.attach(leftArm.shoulder); } catch (Exception e) { error(e); } } return leftArm; } public InMoov2Hand startLeftHand() { return startLeftHand(null); } public InMoov2Hand startLeftHand(String port) { speakBlocking(get("STARTINGLEFTHAND")); leftHand = (InMoov2Hand) startPeer("leftHand"); isLeftHandActivated = true; if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("left", "Arduino"); arduino.connect(port); arduino.attach(leftHand.thumb); arduino.attach(leftHand.index); arduino.attach(leftHand.majeure); arduino.attach(leftHand.ringFinger); arduino.attach(leftHand.pinky); arduino.attach(leftHand.wrist); } catch (Exception e) { error(e); } } return leftHand; } // TODO - general objective "might" be to reduce peers down to something // that does not need a reference - where type can be switched before creation // and the onnly thing needed is pubs/subs that are not handled in abstracts public SpeechSynthesis startMouth() { mouth = (SpeechSynthesis) startPeer("mouth"); voices = mouth.getVoices(); Voice voice = mouth.getVoice(); if (voice != null) { voiceSelected = voice.getName(); } isMouthActivated = true; if (mute) { mouth.setMute(true); } mouth.attachSpeechRecognizer(ear); // mouth.attach(htmlFilter); // same as brain not needed // this.attach((Attachable) mouth); // if (ear != null) .... broadcastState(); speakBlocking(get("STARTINGMOUTH")); if (Platform.isVirtual()) { speakBlocking("in virtual hardware mode"); } speakBlocking(get("WHATISTHISLANGUAGE")); return mouth; } @Deprecated /* use start eye */ public void startOpenCV() throws Exception { startEye(); } public InMoov2Arm startRightArm() { return startRightArm(null); } public InMoov2Arm startRightArm(String port) { speakBlocking(get("STARTINGRIGHTARM")); rightArm = (InMoov2Arm) startPeer("rightArm"); isRightArmActivated = true; if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("right", "Arduino"); arduino.connect(port); arduino.attach(rightArm.bicep); arduino.attach(rightArm.omoplate); arduino.attach(rightArm.rotate); arduino.attach(rightArm.shoulder); } catch (Exception e) { error(e); } } return rightArm; } public InMoov2Hand startRightHand() { return startRightHand(null); } public InMoov2Hand startRightHand(String port) { speakBlocking(get("STARTINGRIGHTHAND")); rightHand = (InMoov2Hand) startPeer("rightHand"); isRightHandActivated = true; if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("right", "Arduino"); arduino.connect(port); arduino.attach(rightHand.thumb); arduino.attach(rightHand.index); arduino.attach(rightHand.majeure); arduino.attach(rightHand.ringFinger); arduino.attach(rightHand.pinky); arduino.attach(rightHand.wrist); } catch (Exception e) { error(e); } } return rightHand; } public void startServos(String leftPort, String rightPort) throws Exception { startHead(leftPort); startLeftArm(leftPort); startLeftHand(leftPort); startRightArm(rightPort); startRightHand(rightPort); startTorso(leftPort); } // FIXME .. externalize in a json file included in InMoov2 public Simulator startSimulator() throws Exception { speakBlocking(get("STARTINGVIRTUAL")); if (jme != null) { log.info("start called twice - starting simulator is reentrant"); return jme; } jme = (JMonkeyEngine) startPeer("simulator"); isSimulatorActivated = true; // adding InMoov2 asset path to the jonkey simulator String assetPath = getResourceDir() + fs + JMonkeyEngine.class.getSimpleName(); File check = new File(assetPath); log.info("loading assets from {}", assetPath); if (!check.exists()) { log.warn("%s does not exist"); } // disable the frustrating servo events ... // Servo.eventsEnabledDefault(false); // jme.loadModels(assetPath); not needed - as InMoov2 unzips the model into // /resource/JMonkeyEngine/assets jme.setRotation(getName() + ".head.jaw", "x"); jme.setRotation(getName() + ".head.neck", "x"); jme.setRotation(getName() + ".head.rothead", "y"); jme.setRotation(getName() + ".head.rollNeck", "z"); jme.setRotation(getName() + ".head.eyeY", "x"); jme.setRotation(getName() + ".head.eyeX", "y"); jme.setRotation(getName() + ".torso.topStom", "z"); jme.setRotation(getName() + ".torso.midStom", "y"); jme.setRotation(getName() + ".torso.lowStom", "x"); jme.setRotation(getName() + ".rightArm.bicep", "x"); jme.setRotation(getName() + ".leftArm.bicep", "x"); jme.setRotation(getName() + ".rightArm.shoulder", "x"); jme.setRotation(getName() + ".leftArm.shoulder", "x"); jme.setRotation(getName() + ".rightArm.rotate", "y"); jme.setRotation(getName() + ".leftArm.rotate", "y"); jme.setRotation(getName() + ".rightArm.omoplate", "z"); jme.setRotation(getName() + ".leftArm.omoplate", "z"); jme.setRotation(getName() + ".rightHand.wrist", "y"); jme.setRotation(getName() + ".leftHand.wrist", "y"); jme.setMapper(getName() + ".head.jaw", 0, 180, -5, 80); jme.setMapper(getName() + ".head.neck", 0, 180, 20, -20); jme.setMapper(getName() + ".head.rollNeck", 0, 180, 30, -30); jme.setMapper(getName() + ".head.eyeY", 0, 180, 40, 140); jme.setMapper(getName() + ".head.eyeX", 0, 180, -10, 70); // HERE there need // to be // two eyeX (left and // right?) jme.setMapper(getName() + ".rightArm.bicep", 0, 180, 0, -150); jme.setMapper(getName() + ".leftArm.bicep", 0, 180, 0, -150); jme.setMapper(getName() + ".rightArm.shoulder", 0, 180, 30, -150); jme.setMapper(getName() + ".leftArm.shoulder", 0, 180, 30, -150); jme.setMapper(getName() + ".rightArm.rotate", 0, 180, 80, -80); jme.setMapper(getName() + ".leftArm.rotate", 0, 180, -80, 80); jme.setMapper(getName() + ".rightArm.omoplate", 0, 180, 10, -180); jme.setMapper(getName() + ".leftArm.omoplate", 0, 180, -10, 180); jme.setMapper(getName() + ".rightHand.wrist", 0, 180, -20, 60); jme.setMapper(getName() + ".leftHand.wrist", 0, 180, 20, -60); jme.setMapper(getName() + ".torso.topStom", 0, 180, -30, 30); jme.setMapper(getName() + ".torso.midStom", 0, 180, 50, 130); jme.setMapper(getName() + ".torso.lowStom", 0, 180, -30, 30); jme.attach(getName() + ".leftHand.thumb", getName() + ".leftHand.thumb1", getName() + ".leftHand.thumb2", getName() + ".leftHand.thumb3"); jme.setRotation(getName() + ".leftHand.thumb1", "y"); jme.setRotation(getName() + ".leftHand.thumb2", "x"); jme.setRotation(getName() + ".leftHand.thumb3", "x"); jme.attach(getName() + ".leftHand.index", getName() + ".leftHand.index", getName() + ".leftHand.index2", getName() + ".leftHand.index3"); jme.setRotation(getName() + ".leftHand.index", "x"); jme.setRotation(getName() + ".leftHand.index2", "x"); jme.setRotation(getName() + ".leftHand.index3", "x"); jme.attach(getName() + ".leftHand.majeure", getName() + ".leftHand.majeure", getName() + ".leftHand.majeure2", getName() + ".leftHand.majeure3"); jme.setRotation(getName() + ".leftHand.majeure", "x"); jme.setRotation(getName() + ".leftHand.majeure2", "x"); jme.setRotation(getName() + ".leftHand.majeure3", "x"); jme.attach(getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger2", getName() + ".leftHand.ringFinger3"); jme.setRotation(getName() + ".leftHand.ringFinger", "x"); jme.setRotation(getName() + ".leftHand.ringFinger2", "x"); jme.setRotation(getName() + ".leftHand.ringFinger3", "x"); jme.attach(getName() + ".leftHand.pinky", getName() + ".leftHand.pinky", getName() + ".leftHand.pinky2", getName() + ".leftHand.pinky3"); jme.setRotation(getName() + ".leftHand.pinky", "x"); jme.setRotation(getName() + ".leftHand.pinky2", "x"); jme.setRotation(getName() + ".leftHand.pinky3", "x"); // left hand mapping complexities of the fingers jme.setMapper(getName() + ".leftHand.index", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.index2", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.index3", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.majeure", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.majeure2", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.majeure3", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.ringFinger", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.ringFinger2", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.ringFinger3", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.pinky", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.pinky2", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.pinky3", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.thumb1", 0, 180, -30, -100); jme.setMapper(getName() + ".leftHand.thumb2", 0, 180, 80, 20); jme.setMapper(getName() + ".leftHand.thumb3", 0, 180, 80, 20); // right hand jme.attach(getName() + ".rightHand.thumb", getName() + ".rightHand.thumb1", getName() + ".rightHand.thumb2", getName() + ".rightHand.thumb3"); jme.setRotation(getName() + ".rightHand.thumb1", "y"); jme.setRotation(getName() + ".rightHand.thumb2", "x"); jme.setRotation(getName() + ".rightHand.thumb3", "x"); jme.attach(getName() + ".rightHand.index", getName() + ".rightHand.index", getName() + ".rightHand.index2", getName() + ".rightHand.index3"); jme.setRotation(getName() + ".rightHand.index", "x"); jme.setRotation(getName() + ".rightHand.index2", "x"); jme.setRotation(getName() + ".rightHand.index3", "x"); jme.attach(getName() + ".rightHand.majeure", getName() + ".rightHand.majeure", getName() + ".rightHand.majeure2", getName() + ".rightHand.majeure3"); jme.setRotation(getName() + ".rightHand.majeure", "x"); jme.setRotation(getName() + ".rightHand.majeure2", "x"); jme.setRotation(getName() + ".rightHand.majeure3", "x"); jme.attach(getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger2", getName() + ".rightHand.ringFinger3"); jme.setRotation(getName() + ".rightHand.ringFinger", "x"); jme.setRotation(getName() + ".rightHand.ringFinger2", "x"); jme.setRotation(getName() + ".rightHand.ringFinger3", "x"); jme.attach(getName() + ".rightHand.pinky", getName() + ".rightHand.pinky", getName() + ".rightHand.pinky2", getName() + ".rightHand.pinky3"); jme.setRotation(getName() + ".rightHand.pinky", "x"); jme.setRotation(getName() + ".rightHand.pinky2", "x"); jme.setRotation(getName() + ".rightHand.pinky3", "x"); jme.setMapper(getName() + ".rightHand.index", 0, 180, 65, -10); jme.setMapper(getName() + ".rightHand.index2", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.index3", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.majeure", 0, 180, 65, -10); jme.setMapper(getName() + ".rightHand.majeure2", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.majeure3", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.ringFinger", 0, 180, 65, -10); jme.setMapper(getName() + ".rightHand.ringFinger2", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.ringFinger3", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.pinky", 0, 180, 65, -10); jme.setMapper(getName() + ".rightHand.pinky2", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.pinky3", 0, 180, 60, -10); jme.setMapper(getName() + ".rightHand.thumb1", 0, 180, 30, 110); jme.setMapper(getName() + ".rightHand.thumb2", 0, 180, -100, -150); jme.setMapper(getName() + ".rightHand.thumb3", 0, 180, -100, -160); // additional experimental mappings /* * simulator.attach(getName() + ".leftHand.pinky", getName() + * ".leftHand.index2"); simulator.attach(getName() + ".leftHand.thumb", * getName() + ".leftHand.index3"); simulator.setRotation(getName() + * ".leftHand.index2", "x"); simulator.setRotation(getName() + * ".leftHand.index3", "x"); simulator.setMapper(getName() + ".leftHand.index", * 0, 180, -90, -270); simulator.setMapper(getName() + ".leftHand.index2", 0, * 180, -90, -270); simulator.setMapper(getName() + ".leftHand.index3", 0, 180, * -90, -270); */ return jme; } public InMoov2Torso startTorso() { return startTorso(null); } public InMoov2Torso startTorso(String port) { if (torso == null) { speakBlocking(get("STARTINGTORSO")); isTorsoActivated = true; torso = (InMoov2Torso) startPeer("torso"); if (port != null) { try { speakBlocking(port); Arduino left = (Arduino) startPeer("left"); left.connect(port); left.attach(torso.lowStom); left.attach(torso.midStom); left.attach(torso.topStom); } catch (Exception e) { error(e); } } } return torso; } public ServoMixer startServoMixer() { servomixer = (ServoMixer) startPeer("servomixer"); isServoMixerActivated = true; speakBlocking(get("STARTINGSERVOMIXER")); broadcastState(); return servomixer; } public void stop() { if (head != null) { head.stop(); } if (rightHand != null) { rightHand.stop(); } if (leftHand != null) { leftHand.stop(); } if (rightArm != null) { rightArm.stop(); } if (leftArm != null) { leftArm.stop(); } if (torso != null) { torso.stop(); } } public void stopBrain() { speakBlocking(get("STOPCHATBOT")); releasePeer("brain"); isBrainActivated = false; } public void stopEar() { speakBlocking(get("STOPEAR")); releasePeer("ear"); isEarActivated = false; broadcastState(); } public void stopEye() { speakBlocking(get("STOPOPENCV")); isEyeActivated = false; releasePeer("eye"); } public void stopGesture() { Python p = (Python) Runtime.getService("python"); p.stop(); } public void stopLeftArm() { speakBlocking(get("STOPLEFTARM")); releasePeer("leftArm"); isLeftArmActivated = false; } public void stopLeftHand() { speakBlocking(get("STOPLEFTHAND")); releasePeer("leftHand"); isLeftHandActivated = false; } public void stopMouth() { speakBlocking(get("STOPMOUTH")); releasePeer("mouth"); // TODO - potentially you could set the field to null in releasePeer mouth = null; isMouthActivated = false; } public void stopRightArm() { speakBlocking(get("STOPRIGHTARM")); releasePeer("rightArm"); isRightArmActivated = false; } public void stopRightHand() { speakBlocking(get("STOPRIGHTHAND")); releasePeer("rightHand"); isRightHandActivated = false; } public void stopTorso() { speakBlocking(get("STOPTORSO")); releasePeer("torso"); isTorsoActivated = false; } public void stopSimulator() { speakBlocking(get("STOPVIRTUAL")); releasePeer("simulator"); jme = null; isSimulatorActivated = false; } public void stopPir() { speakBlocking(get("STOPPIR")); releasePeer("pir"); isPirActivated = false; } public void stopUltraSonicSensor() { speakBlocking(get("STOPULTRASONIC")); releasePeer("ultraSonicSensor"); isPirActivated = false; } public void stopServoMixer() { speakBlocking(get("STOPSERVOMIXER")); releasePeer("ServoMixer"); isServoMixerActivated = false; } public void waitTargetPos() { if (head != null) { head.waitTargetPos(); } if (leftArm != null) { leftArm.waitTargetPos(); } if (rightArm != null) { rightArm.waitTargetPos(); } if (leftHand != null) { leftHand.waitTargetPos(); } if (rightHand != null) { rightHand.waitTargetPos(); } if (torso != null) { torso.waitTargetPos(); } } }
package org.pfaa.geologica; import java.util.ArrayList; import java.util.List; import net.minecraft.block.material.Material; import org.pfaa.chemica.model.Compound.Compounds; import org.pfaa.chemica.model.Condition; import org.pfaa.chemica.model.ConditionProperties; import org.pfaa.chemica.model.IndustrialMaterial; import org.pfaa.chemica.model.Mixture; import org.pfaa.chemica.model.MixtureComponent; import org.pfaa.geologica.processing.Aggregate.Aggregates; import org.pfaa.geologica.processing.Crude.Crudes; import org.pfaa.geologica.processing.IndustrialMineral; import org.pfaa.geologica.processing.IndustrialMineral.IndustrialMinerals; import org.pfaa.geologica.processing.OreMineral; import org.pfaa.geologica.processing.OreMineral.Ores; import org.pfaa.geologica.processing.SimpleCrude; import org.pfaa.geologica.processing.SimpleOre; import com.google.common.base.CaseFormat; public enum GeoMaterial implements Mixture { BRECCIA(Aggregates.GRAVEL, Strength.WEAK), CARBONATITE(Aggregates.STONE.mix(Ores.CALCITE, 0.5).mix(Ores.PYROCHLORE, 0.02).mix(Ores.MICROLITE, 0.005), Strength.WEAK), CLAYSTONE(Aggregates.STONE, Strength.WEAK), CONGLOMERATE(Aggregates.SAND.mix(Aggregates.GRAVEL, 1.0), Strength.WEAK), MUDSTONE(Aggregates.STONE, Strength.WEAK), LIMESTONE(Aggregates.STONE.mix(Ores.CALCITE, 0.5), Strength.MEDIUM), SCHIST(Aggregates.STONE, Strength.MEDIUM), SERPENTINITE(Aggregates.STONE.mix(IndustrialMinerals.CHRYSOTILE, 0.05) .mix(IndustrialMinerals.TALC, 0.05).mix(IndustrialMinerals.OLIVINE, 0.05), Strength.MEDIUM), SLATE(Aggregates.STONE, Strength.MEDIUM), SKARN(Aggregates.STONE, Strength.MEDIUM), ANDESITE(Aggregates.STONE, Strength.STRONG), BASALT(Aggregates.STONE, Strength.STRONG), GNEISS(Aggregates.STONE, Strength.STRONG), GRANITE(Aggregates.STONE, Strength.STRONG), GREENSCHIST(Aggregates.STONE, Strength.STRONG), MARBLE(Aggregates.STONE.mix(Ores.CALCITE, 1.0), Strength.STRONG), PEGMATITE(Aggregates.STONE.mix(IndustrialMinerals.FELDSPAR, 0.5) .mix(IndustrialMinerals.QUARTZ, 0.2).mix(IndustrialMinerals.MICA, 0.2), Strength.STRONG), RHYOLITE(Aggregates.STONE, Strength.STRONG), DIORITE(Aggregates.STONE, Strength.VERY_STRONG), GABBRO(Aggregates.STONE, Strength.VERY_STRONG), HORNFELS(Aggregates.STONE, Strength.VERY_STRONG), PERIDOTITE(Aggregates.STONE.mix(IndustrialMinerals.OLIVINE, 0.5), Strength.VERY_STRONG), QUARTZITE(Aggregates.SAND, Strength.VERY_STRONG), BASALTIC_MINERAL_SAND(Ores.MAGNETITE.mix(Aggregates.SAND, 0.4).mix(IndustrialMinerals.GARNET, 1.4) .mix(Ores.CHROMITE, 0.2).mix(Ores.ILMENITE, 0.6).mix(Ores.RUTILE, 0.2).mix(Ores.ZIRCON, 0.2), Strength.WEAK, Material.sand), CASSITERITE_SAND(Ores.CASSITERITE, Strength.WEAK, Material.sand), GARNET_SAND(IndustrialMinerals.GARNET, Strength.WEAK, Material.sand), GRANITIC_MINERAL_SAND(Ores.MAGNETITE.mix(Aggregates.SAND, 1.4).mix(IndustrialMinerals.KYANITE, 0.2) .mix(Ores.ILMENITE, 0.4).mix(Ores.RUTILE, 0.6).mix(Ores.ZIRCON, 0.4).mix(Ores.MONAZITE, 0.4), Strength.WEAK, Material.sand), QUARTZ_SAND(IndustrialMinerals.QUARTZ, Strength.WEAK, Material.sand), VOLCANIC_ASH(IndustrialMinerals.VOLCANIC_ASH, Strength.WEAK, Material.sand), LATERITE(Aggregates.CLAY, Strength.WEAK, Material.clay), // FIXME: add niter (KNO3)? BAUXITE(Ores.GIBBSITE.mix(Ores.HEMATITE, 0.45).mix(Ores.CALCITE, 0.10) .mix(IndustrialMinerals.KAOLINITE, 0.10).mix(IndustrialMinerals.QUARTZ, 0.05).mix(Ores.ANATASE, 0.05), Strength.WEAK, Material.clay), BENTONITE(IndustrialMinerals.BENTONITE, Strength.WEAK, Material.clay), FULLERS_EARTH(IndustrialMinerals.FULLERS_EARTH, Strength.WEAK, Material.clay), KAOLINITE(IndustrialMinerals.KAOLINITE, Strength.WEAK, Material.clay), BROWN_LIMONITE(Ores.LEPIDOCROCITE.mix(Aggregates.CLAY, 1.0), Strength.WEAK, Material.clay), YELLOW_LIMONITE(Ores.GOETHITE.mix(Aggregates.CLAY, 1.0), Strength.WEAK, Material.clay), VERMICULITE(IndustrialMinerals.VERMICULITE, Strength.WEAK, Material.clay), // FIXME: should we add stone to all of the stone ores? // maybe this should just be the "host rock" once we add that concept? BORAX(Ores.BORAX, Strength.WEAK), CINNABAR(Ores.CINNABAR.mix(Ores.PYRITE, 0.05).mix(Ores.REALGAR, 0.04).mix(Ores.STIBNITE, 0.02).mix(Ores.BARITE, 0.02), Strength.WEAK), GALENA(Ores.GALENA.mix(Ores.SPHALERITE, 0.2).mix(Ores.ACANTHITE, 0.05).mix(Ores.FLUORITE, 0.05).mix(Ores.BISMUTHINITE, 0.05) .mix(Ores.REALGAR, 0.04).mix(Ores.STIBNITE, 0.02).mix(Ores.GREENOCKITE, 0.01).mix(Ores.VANADINITE, 0.01), Strength.WEAK), MOLYBDENITE(Ores.MOLYBDENITE.mix(Ores.PYRITE, 0.05).mix(Ores.CHALCOPYRITE, 0.05) .mix(Ores.FLUORITE, 0.02), Strength.WEAK), PYROLUSITE(Ores.PYROLUSITE.mix(Ores.GOETHITE, 0.1), Strength.WEAK), ROCK_SALT(Ores.HALITE.mix(Ores.SYLVITE, 0.5).mix(Ores.CARNALLITE, 0.1).mix(Ores.GYPSUM, 0.05), Strength.WEAK), STIBNITE(Ores.STIBNITE.mix(Ores.PYRITE, 0.05).mix(Ores.GALENA, 0.05).mix(Ores.REALGAR, 0.04).mix(Ores.CINNABAR, 0.02), Strength.WEAK), BARITE(Ores.BARITE, Strength.MEDIUM), BASTNASITE(Ores.BASTNASITE, Strength.MEDIUM), CHALCOPYRITE(Ores.CHALCOPYRITE.mix(Ores.PYRITE, 0.10).mix(Ores.MOLYBDENITE, 0.05) .mix(Ores.COBALTITE, 0.01), Strength.MEDIUM), GARNIERITE(Ores.NEPOUITE.mix(SERPENTINITE, 1.0), Strength.MEDIUM), LEPIDOLITE(Ores.LEPIDOLITE.mix(PEGMATITE, 1.0).mix(Ores.SPODUMENE, 0.2), Strength.MEDIUM), MAGNESITE(Ores.MAGNESITE.mix(IndustrialMinerals.TALC, 0.2), Strength.MEDIUM), PENTLANDITE(Ores.PENTLANDITE.mix(Ores.PYRITE, 0.1), Strength.MEDIUM), SCHEELITE(Ores.SCHEELITE.mix(Ores.CASSITERITE, 0.2).mix(Ores.WOLFRAMITE, 0.2), Strength.MEDIUM), SPHALERITE(Ores.SPHALERITE.mix(Ores.GALENA, 0.2).mix(Ores.PYRITE, 0.1), Strength.MEDIUM), WOLFRAMITE(Ores.WOLFRAMITE.mix(Ores.CASSITERITE, 0.2).mix(Ores.SCHEELITE, 0.2), Strength.MEDIUM), BANDED_IRON(Ores.HEMATITE.mix(Ores.MAGNETITE, 0.5), Strength.STRONG), BERYL(Ores.BERYL.mix(PEGMATITE, 1.0), Strength.STRONG), CASSITERITE(Ores.CASSITERITE.mix(Ores.FLUORITE, 0.1).mix(Ores.WOLFRAMITE, 0.1) .mix(IndustrialMinerals.APATITE, 0.05).mix(Ores.MOLYBDENITE, 0.05), Strength.STRONG), CHROMITE(Ores.CHROMITE.mix(SERPENTINITE, 0.5).mix(Ores.MAGNETITE, 0.1), Strength.STRONG), ILMENITE(Ores.ILMENITE.mix(Ores.RUTILE, 0.2).mix(Ores.MAGNETITE, 0.1), Strength.STRONG), MAGNETITE(Ores.MAGNETITE, Strength.STRONG), POLLUCITE(Ores.POLLUCITE.mix(PEGMATITE, 1.0).mix(Ores.SPODUMENE, 0.1), Strength.STRONG), SPODUMENE(Ores.SPODUMENE.mix(PEGMATITE, 1.0).mix(Ores.LEPIDOLITE, 0.1), Strength.STRONG), TANTALITE(Ores.TANTALITE.mix(Ores.COLUMBITE, 2.0), Strength.STRONG), PITCHBLENDE(Ores.URANINITE.mix(Ores.CARNOTITE, 0.05), Strength.STRONG), VANADIUM_MAGNETITE(Ores.TITANO_MAGNETITE, Strength.STRONG), CHRYSOTILE(IndustrialMinerals.CHRYSOTILE.mix(SERPENTINITE, 0.5), Strength.WEAK), DIATOMITE(IndustrialMinerals.DIATOMITE, Strength.WEAK), GLAUCONITE(IndustrialMinerals.GLAUCONITE.mix(Aggregates.SAND, 1.0), Strength.WEAK), GRAPHITE(IndustrialMinerals.GRAPHITE.mix(IndustrialMinerals.COAL, 0.5), Strength.WEAK), GYPSUM(IndustrialMinerals.GYPSUM.mix(Ores.HALITE, 0.05), Strength.WEAK), MIRABILITE(IndustrialMinerals.MIRABILITE .mix(IndustrialMinerals.GYPSUM, 0.2).mix(Ores.HALITE, 0.05), Strength.WEAK), MICA(IndustrialMinerals.MICA.mix(PEGMATITE, 0.5), Strength.WEAK), SOAPSTONE(IndustrialMinerals.TALC.mix(SERPENTINITE, 0.5), Strength.WEAK), TRONA(IndustrialMinerals.TRONA .mix(IndustrialMinerals.GYPSUM, 0.2).mix(Ores.HALITE, 0.05), Strength.WEAK), ALUNITE(IndustrialMinerals.ALUNITE.mix(IndustrialMinerals.BENTONITE, 0.1), Strength.MEDIUM), CELESTINE(Ores.CELESTINE.mix(IndustrialMinerals.GYPSUM, 0.2).mix(Ores.HALITE, 0.05), Strength.MEDIUM), DOLOMITE(IndustrialMinerals.DOLOMITE.mix(Ores.MAGNESITE, 0.05), Strength.MEDIUM), FLUORITE(Ores.FLUORITE.mix(Ores.SPHALERITE, 0.06).mix(Ores.GALENA, 0.02), Strength.MEDIUM), WOLLASTONITE(IndustrialMinerals.WOLLASTONITE.mix(Ores.CALCITE, 0.1), Strength.MEDIUM), ZEOLITE(IndustrialMinerals.ZEOLITE, Strength.MEDIUM), APATITE(IndustrialMinerals.APATITE, Strength.STRONG), KYANITE(IndustrialMinerals.KYANITE.mix(PEGMATITE, 0.5), Strength.STRONG), PERLITE(IndustrialMinerals.PERLITE.mix(IndustrialMinerals.OBSIDIAN, 0.1), Strength.STRONG), PUMICE(IndustrialMinerals.PUMICE, Strength.STRONG), LIGHT_OIL(new SimpleCrude(Crudes.FUEL_GAS, 0.1).mix(Crudes.LIGHT_NAPHTHA, 0.35).mix(Crudes.HEAVY_NAPHTHA, 0.25). mix(Crudes.KEROSENE, 0.1).mix(Crudes.LIGHT_GAS_OIL, 0.05).mix(Crudes.HEAVY_GAS_OIL, 0.05). mix(Crudes.BITUMEN, 0.10), Strength.WEAK, Material.water), MEDIUM_OIL(new SimpleCrude(Crudes.FUEL_GAS, 0.05).mix(Crudes.LIGHT_NAPHTHA, 0.15).mix(Crudes.HEAVY_NAPHTHA, 0.30). mix(Crudes.KEROSENE, 0.15).mix(Crudes.LIGHT_GAS_OIL, 0.1).mix(Crudes.HEAVY_GAS_OIL, 0.05). mix(Crudes.BITUMEN, 0.2), Strength.MEDIUM, Material.water), HEAVY_OIL(new SimpleCrude(Crudes.LIGHT_NAPHTHA, 0.05).mix(Crudes.HEAVY_NAPHTHA, 0.10). mix(Crudes.KEROSENE, 0.20).mix(Crudes.LIGHT_GAS_OIL, 0.25).mix(Crudes.HEAVY_GAS_OIL, 0.1). mix(Crudes.BITUMEN, 0.3), Strength.STRONG, Material.water), EXTRA_HEAVY_OIL(new SimpleCrude(Crudes.HEAVY_NAPHTHA, 0.05). mix(Crudes.KEROSENE, 0.05).mix(Crudes.LIGHT_GAS_OIL, 0.10).mix(Crudes.HEAVY_GAS_OIL, 0.2). mix(Crudes.BITUMEN, 0.6), Strength.STRONG, Material.water), OIL_SAND(EXTRA_HEAVY_OIL.mix(Aggregates.SAND, 2.0), Strength.WEAK, Material.sand), NATURAL_GAS(Compounds.METHANE.mix(Compounds.ETHANE, 0.05).mix(Compounds.PROPANE, 0.002). mix(Compounds.N_BUTANE, 0.0003).mix(Compounds.ISO_BUTANE, 0.0003), Strength.WEAK, Material.air), OIL_SHALE(new SimpleCrude(Crudes.KEROGEN, 0.15).mix(MUDSTONE, 1.0).mix(Crudes.BITUMEN, 0.05), Strength.WEAK) ; public enum Strength { WEAK, MEDIUM, STRONG, VERY_STRONG; public String getCamelName() { if (this == VERY_STRONG) return "veryStrong"; else return name().toLowerCase(); } } private Strength strength; private Material blockMaterial; private Mixture composition; GeoMaterial(Mixture composition, Strength strength, Material blockMaterial) { this.strength = strength; this.blockMaterial = blockMaterial; this.composition = composition; } GeoMaterial(Mixture composition, Strength strength) { this(composition, strength, Material.rock); } GeoMaterial(OreMineral composition, Strength strength, Material blockMaterial) { this(new SimpleOre(composition), strength, blockMaterial); } GeoMaterial(OreMineral composition, Strength strength) { this(composition, strength, Material.rock); } GeoMaterial(IndustrialMineral composition, Strength strength, Material blockMaterial) { this(new SimpleOre(composition), strength, blockMaterial); } GeoMaterial(IndustrialMineral composition, Strength strength) { this(composition, strength, Material.rock); } public int getId() { return ordinal(); } public Strength getStrength() { return strength; } public Material getBlockMaterial() { return blockMaterial; } public String getLowerName() { return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name()); } public String getOreDictKey() { return composition.getOreDictKey(); } public static GeoMaterial getForId(int id) { return values()[id]; } public IndustrialMaterial getComposition() { return this.composition; } public static List<GeoMaterial> lookup(Strength strength, Class<? extends IndustrialMaterial> compositionType, Material blockMaterial) { List<GeoMaterial> materialsToReturn = new ArrayList<GeoMaterial>(); for (GeoMaterial material : values()) { if (material.blockMaterial == blockMaterial && material.strength == strength && compositionType.isAssignableFrom(material.composition.getClass())) materialsToReturn.add(material); } return materialsToReturn; } @Override public ConditionProperties getProperties(Condition condition) { return composition.getProperties(condition); } @Override public List<MixtureComponent> getComponents() { return composition.getComponents(); } @Override public Mixture mix(IndustrialMaterial material, double weight) { return composition.mix(material, weight); } }
package org.rakam.server.http; import com.google.common.collect.Lists; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.cookie.Cookie; import io.netty.handler.codec.http.cookie.DefaultCookie; import java.util.List; public class Response<T> { private final T data; private final HttpResponseStatus status; private List<Cookie> cookies; private Response(T data, HttpResponseStatus status) { this.data = data; this.status = status; } public Response addCookie(DefaultCookie cookie) { if(cookies == null) { cookies = Lists.newArrayList(); } cookies.add(cookie); return this; } public Response addCookie(String name, String value, String domain, Boolean isHttpOnly, Long maxAge, String path, Boolean isSecured) { if(cookies == null) { cookies = Lists.newArrayList(); } final DefaultCookie defaultCookie = new DefaultCookie(name, value); if(domain != null) { defaultCookie.setDomain(domain); } if(isHttpOnly != null) { defaultCookie.setHttpOnly(isHttpOnly); } if(maxAge != null) { defaultCookie.setMaxAge(maxAge); } if(path != null) { defaultCookie.setPath(path); } if(isSecured != null) { defaultCookie.setSecure(isSecured); } cookies.add(defaultCookie); return this; } public Response addCookie(String name, String value) { if(cookies == null) { cookies = Lists.newArrayList(); } cookies.add(new DefaultCookie(name, value)); return this; } public T getData() { return data; } public List<Cookie> getCookies() { return cookies; } public static <T> Response<T> ok(T elem) { return new Response<>(elem, HttpResponseStatus.OK); } public static Response value(Object value, HttpResponseStatus status) { return new Response(value, status); } }
package org.usfirst.frc.team4828; import com.kauailabs.navx.frc.AHRS; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.SPI; import edu.wpi.first.wpilibj.Timer; public class Robot extends IterativeRobot { private Joystick driveStick; private DriveTrain drive; private AHRS navx; private DigitalInput ir; private UltraThread us; @Override public void robotInit() { super.robotInit(); System.out.println("THE ROBOT TURNED ON"); driveStick = new Joystick(0); drive = new DriveTrain(1, 2, 3, 4); navx = new AHRS(SPI.Port.kMXP); ir = new DigitalInput(2); us = new UltraThread(0); } @Override public void autonomousInit() { super.autonomousInit(); System.out.println("Entering auton..."); } @Override public void autonomousPeriodic() { super.autonomousPeriodic(); } @Override public void teleopInit() { super.teleopInit(); System.out.println("Entering teleop..."); } @Override public void teleopPeriodic() { super.teleopPeriodic(); drive.mecanumDrive(driveStick.getX(), driveStick.getY(), driveStick.getTwist(), navx.getAngle()); if (driveStick.getRawButton(11)) { navx.reset(); } //System.out.println("Angle: " + navx.getAngle()); //System.out.println("IR Status: " + ir.get()); } @Override public void testInit() { super.testInit(); System.out.println("Entering test..."); us.start(); } @Override public void testPeriodic() { System.out.println("Ultrasonic Dist: " + us.distIn + " inches"); Timer.delay(0.1); } @Override public void disabledInit() { us.terminate(); System.out.println("Stopping thread"); } }
package romelo333.rflux.blocks; 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.tileentity.TileEntity; public class LightTE extends TileEntity { @Override public boolean shouldRenderInPass(int pass) { return pass == 1; } @Override public boolean canUpdate() { return false; } @Override public Packet getDescriptionPacket() { NBTTagCompound nbtTag = new NBTTagCompound(); this.writeToNBT(nbtTag); return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, 1, nbtTag); } @Override public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity packet) { readFromNBT(packet.func_148857_g()); } }
package sds.decompile; import sds.assemble.BaseContent; import sds.assemble.LineInstructions; import sds.assemble.MethodContent; import sds.assemble.controlflow.CFNode; import sds.classfile.bytecode.CpRefOpcode; import sds.classfile.bytecode.Iinc; import sds.classfile.bytecode.IndexOpcode; import sds.classfile.bytecode.MultiANewArray; import sds.classfile.bytecode.NewArray; import sds.classfile.bytecode.OpcodeInfo; import sds.classfile.bytecode.PushOpcode; import static sds.assemble.controlflow.CFNodeType.LoopEntry; import static sds.classfile.bytecode.MnemonicTable.*; /** * This class is for decompiling contents of method. * @author inagaki */ public class MethodDecompiler extends AbstractDecompiler { private OperandStack opStack; private LocalStack local; private String caller; /** * constructor. * @param result decompiled source * @param caller caller class has this method */ public MethodDecompiler(DecompiledResult result, String caller) { super(result); this.caller = caller; } @Override public void decompile(BaseContent content) { MethodContent method = (MethodContent)content; this.opStack = new OperandStack(); this.local = new LocalStack(); addAnnotation(method.getAnnotation()); addDeclaration(method); result.changeIndent(DecompiledResult.INCREMENT); result.writeEndScope(); } @Override void addDeclaration(BaseContent content) { MethodContent method = (MethodContent)content; StringBuilder methodDeclaration = new StringBuilder(); methodDeclaration.append(method.getAccessFlag()); String desc = method.getDescriptor(); String returnType = desc.substring(desc.indexOf(")") + 1, desc.length()); methodDeclaration.append(returnType).append(" ") .append(method.getName().replace("<init>", caller)).append("("); // args String[][] args = method.getArgs(); if(args.length > 0) { for(int i = 0; i < args.length - 1 ; i++) { methodDeclaration.append(args[i][0]).append(" ").append(args[i][1]).append(", "); } methodDeclaration.append(args[args.length - 1][0]).append(" ") .append(args[args.length - 1][1]); } methodDeclaration.append(")"); // has throws statement if(method.getExceptions().length > 0) { methodDeclaration.append(" throws "); String[] exceptions = method.getExceptions(); for(int i = 0; i < exceptions.length - 1; i++) { methodDeclaration.append(exceptions[i]).append(", "); } methodDeclaration.append(exceptions[exceptions.length - 1]); } // abstract or other method if(method.getAccessFlag().contains("abstract")) { methodDeclaration.append(";"); } else { methodDeclaration.append(" {"); } result.write(methodDeclaration.toString()); // method body result.changeIndent(DecompiledResult.INCREMENT); buildMethodBody(method.getInst(), method.getNodes()); result.changeIndent(DecompiledResult.DECREMENT); } private void buildMethodBody(LineInstructions[] insts, CFNode[] nodes) { for(int i = 0; i < insts.length; i++) { CFNode node = nodes[i]; LineInstructions inst = insts[i]; StringBuilder line = new StringBuilder(); for(OpcodeInfo opcode : inst.getOpcodes().getAll()) { System.out.println(opcode + ", current: " + opStack.getCurrentStackSize()); System.out.println("local: " + local); System.out.println("stack: " + opStack); switch(opcode.getOpcodeType()) { case nop: break; case aconst_null: opStack.push("null"); break; case iconst_m1: opStack.push(-1); break; case iconst_0: opStack.push(0); break; case iconst_1: opStack.push(1); break; case iconst_2: opStack.push(2); break; case iconst_3: opStack.push(3); break; case iconst_4: opStack.push(4); break; case iconst_5: opStack.push(5); break; case lconst_0: opStack.push(0L); break; case lconst_1: opStack.push(1L); break; case fconst_0: opStack.push(0.0f); break; case fconst_1: opStack.push(1.0f); break; case fconst_2: opStack.push(2.0f); break; case dconst_0: opStack.push(0.0d); break; case dconst_1: opStack.push(1.0d); break; case bipush: case sipush: opStack.push(((PushOpcode)opcode).getValue()); break; case ldc: case ldc_w: case ldc2_w: opStack.push(((CpRefOpcode)opcode).getOperand()); break; case iload: case lload: case fload: case dload: case aload: String loaded = local.load(((IndexOpcode)opcode).getIndex()); opStack.push(loaded); break; case iload_0: opStack.push(local.load(0)); break; case iload_1: opStack.push(local.load(1)); break; case iload_2: opStack.push(local.load(2)); break; case iload_3: opStack.push(local.load(3)); break; case lload_0: opStack.push(local.load(0)); break; case lload_1: opStack.push(local.load(1)); break; case lload_2: opStack.push(local.load(2)); break; case lload_3: opStack.push(local.load(3)); break; case fload_0: opStack.push(local.load(0)); break; case fload_1: opStack.push(local.load(1)); break; case fload_2: opStack.push(local.load(2)); break; case fload_3: opStack.push(local.load(3)); break; case dload_0: opStack.push(local.load(0)); break; case dload_1: opStack.push(local.load(1)); break; case dload_2: opStack.push(local.load(2)); break; case dload_3: opStack.push(local.load(3)); break; case aload_0: if(local.getCurrentStackSize() == 0) { local.push("this"); } opStack.push(local.load(0)); break; case aload_1: opStack.push(local.load(1)); break; case aload_2: opStack.push(local.load(2)); break; case aload_3: opStack.push(local.load(3)); break; case iaload: case laload: case faload: case daload: case aaload: case baload: case caload: case saload: String arrayIndex = opStack.pop(); String refedArray = opStack.pop(); opStack.push(refedArray + "[" + arrayIndex + "]"); break; case istore: case fstore: case astore: IndexOpcode inOp = (IndexOpcode)opcode; line.append(local.load(inOp.getIndex())).append(" = ").append(opStack.pop()); break; case lstore: case dstore: IndexOpcode inOpDL = (IndexOpcode)opcode; line.append(local.load(inOpDL.getIndex(), true)).append(" = ").append(opStack.pop()); break; case istore_0: line.append(local.load(0)).append(" = ").append(opStack.pop()); break; case istore_1: line.append(local.load(1)).append(" = ").append(opStack.pop()); break; case istore_2: line.append(local.load(2)).append(" = ").append(opStack.pop()); break; case istore_3: line.append(local.load(3)).append(" = ").append(opStack.pop()); break; case fstore_0: line.append(local.load(0)).append(" = ").append(opStack.pop()); break; case fstore_1: line.append(local.load(1)).append(" = ").append(opStack.pop()); break; case fstore_2: line.append(local.load(2)).append(" = ").append(opStack.pop()); break; case fstore_3: line.append(local.load(3)).append(" = ").append(opStack.pop()); break; case astore_0: line.append(local.load(0)).append(" = ").append(opStack.pop()); break; case astore_1: line.append(local.load(1)).append(" = ").append(opStack.pop()); break; case astore_2: line.append(local.load(2)).append(" = ").append(opStack.pop()); break; case astore_3: line.append(local.load(3)).append(" = ").append(opStack.pop()); break; case lstore_0: line.append(local.load(0, true)).append(" = ").append(opStack.pop()); break; case lstore_1: line.append(local.load(1, true)).append(" = ").append(opStack.pop()); break; case lstore_2: line.append(local.load(2, true)).append(" = ").append(opStack.pop()); break; case lstore_3: line.append(local.load(3, true)).append(" = ").append(opStack.pop()); break; case dstore_0: line.append(local.load(0, true)).append(" = ").append(opStack.pop()); break; case dstore_1: line.append(local.load(1, true)).append(" = ").append(opStack.pop()); break; case dstore_2: line.append(local.load(2, true)).append(" = ").append(opStack.pop()); break; case dstore_3: line.append(local.load(3, true)).append(" = ").append(opStack.pop()); break; case iastore: case lastore: case fastore: case dastore: case aastore: case bastore: case castore: case sastore: String arrayRef = opStack.pop(); int index = Integer.parseInt(opStack.pop()); String storingValue = opStack.pop(); line.append(arrayRef).append("[").append(index).append("]") .append(" = ").append(storingValue); break; case pop: opStack.pop(); break; case pop2: opStack.pop(); opStack.pop(); break; case dup: String dup = opStack.pop(); opStack.push(dup); opStack.push(dup); break; case dup_x1: String dup_x1_2 = opStack.pop(); String dup_x1_1 = opStack.pop(); opStack.push(dup_x1_1); opStack.push(dup_x1_2); opStack.push(dup_x1_1); break; case dup_x2: String dup_x2_3 = opStack.pop(); String dup_x2_2 = opStack.pop(); String dup_x2_1 = opStack.pop(); opStack.push(dup_x2_1); opStack.push(dup_x2_2); opStack.push(dup_x2_3); opStack.push(dup_x2_1); break; case dup2: String dup2_1 = opStack.pop(); String dup2_2 = opStack.pop(); opStack.push(dup2_2); opStack.push(dup2_1); opStack.push(dup2_2); opStack.push(dup2_1); break; case dup2_x1: String dup2_x1_3 = opStack.pop(); String dup2_x1_2 = opStack.pop(); String dup2_x1_1 = opStack.pop(); opStack.push(dup2_x1_1); opStack.push(dup2_x1_2); opStack.push(dup2_x1_3); opStack.push(dup2_x1_1); opStack.push(dup2_x1_2); break; case dup2_x2: String dup2_x2_4 = opStack.pop(); String dup2_x2_3 = opStack.pop(); String dup2_x2_2 = opStack.pop(); String dup2_x2_1 = opStack.pop(); opStack.push(dup2_x2_1); opStack.push(dup2_x2_2); opStack.push(dup2_x2_3); opStack.push(dup2_x2_4); opStack.push(dup2_x2_1); opStack.push(dup2_x2_2); break; case swap: String two = opStack.pop(); String one = opStack.pop(); opStack.push(two); opStack.push(one); break; case iadd: case ladd: case fadd: case dadd: String sum = "(" + opStack.pop() + " + " + opStack.pop() + ")"; opStack.push(sum); break; case isub: case lsub: case fsub: case dsub: String sub = "(" + opStack.pop() + " - " + opStack.pop() + ")"; opStack.push(sub); break; case imul: case lmul: case fmul: case dmul: String product = "(" + opStack.pop() + " * " + opStack.pop() + ")"; opStack.push(product); break; case idiv: case ldiv: case fdiv: case ddiv: String quotient = "(" + opStack.pop() + " / " + opStack.pop() + ")"; opStack.push(quotient); break; case irem: case lrem: case frem: case drem: String remainder = "(" + opStack.pop() + " % " + opStack.pop() + ")"; opStack.push(remainder); break; case ineg: case lneg: case fneg: case dneg: String minus = "-(" + opStack.pop() + ")"; opStack.push(minus); break; case ishl: case lshl: String right_1 = opStack.pop(); String left_1 = opStack.pop(); opStack.push("(" + left_1 + " << " + right_1 + ")"); break; case ishr: case lshr: String right_2 = opStack.pop(); String left_2 = opStack.pop(); opStack.push("(" + left_2 + " >> " + right_2 + ")"); break; case iushr: case lushr: String right_3 = opStack.pop(); String left_3 = opStack.pop(); opStack.push("(" + left_3 + " >>> " + right_3 + ")"); break; case iand: case land: String and = "(" + opStack.pop() + " & " + opStack.pop() + ")"; opStack.push(and); break; case ior: case lor: String or = "(" + opStack.pop() + " | " + opStack.pop() + ")"; opStack.push(or); break; case ixor: case lxor: String xor = "(" + opStack.pop() + " ^ " + opStack.pop() + ")"; opStack.push(xor); break; case iinc: Iinc inc = (Iinc)opcode; line.append(local.load(inc.getIndex())); int _const = inc.getConst(); if(_const == 1) { line.append("++"); } else if(_const == -1) { line.append(" } else if(_const > 1) { line.append(" += ").append(_const); } else if(_const < -1) { line.append(" -= ").append(_const); } // in case of "_const == 0", ignoring break; case i2l: castPrimitive("long"); break; case i2f: castPrimitive("float"); break; case i2d: castPrimitive("double"); break; case l2i: castPrimitive("int"); break; case l2f: castPrimitive("float"); break; case l2d: castPrimitive("double"); break; case f2i: castPrimitive("int"); break; case f2l: castPrimitive("long"); break; case f2d: castPrimitive("double"); break; case d2i: castPrimitive("int"); break; case d2l: castPrimitive("long"); break; case d2f: castPrimitive("float"); break; case i2b: castPrimitive("byte"); break; case i2c: castPrimitive("char"); break; case i2s: castPrimitive("short"); break; case lcmp: case fcmpl: case fcmpg: case dcmpl: case dcmpg: String cmpNum_2 = opStack.pop(); String cmpNum_1 = opStack.pop(); opStack.push("(" + cmpNum_1 + "OPERATOR" + cmpNum_2 + ")"); break; case ifeq: // if(node.getType() == LoopEntry) { // } else { // String eq = opStack.pop().replace("OPERATOR", " != "); break; case ifne: // if(node.getType() == LoopEntry) { // } else { // String ne = opStack.pop().replace("OPERATOR", " == "); break; case iflt: // if(node.getType() == LoopEntry) { // } else { // String lt = opStack.pop().replace("OPERATOR", " >= "); break; case ifge: // if(node.getType() == LoopEntry) { // } else { // String ge = opStack.pop().replace("OPERATOR", " < "); break; case ifgt: // if(node.getType() == LoopEntry) { // } else { // String gt = opStack.pop().replace("OPERATOR", " <= "); break; case ifle: // if(node.getType() == LoopEntry) { // } else { // String le = opStack.pop().replace("OPERATOR", " > "); break; case if_icmpeq: String ieq_2 = opStack.pop(); String ieq_1 = opStack.pop(); line.append("if(").append(ieq_1).append(" == ").append(ieq_2).append(")"); break; case if_icmpne: String ine_2 = opStack.pop(); String ine_1 = opStack.pop(); line.append("if(").append(ine_1).append(" != ").append(ine_2).append(")"); break; case if_icmplt: String ilt_2 = opStack.pop(); String ilt_1 = opStack.pop(); line.append("if(").append(ilt_1).append(" < ").append(ilt_2).append(")"); break; case if_icmpge: String ige_2 = opStack.pop(); String ige_1 = opStack.pop(); line.append("if(").append(ige_1).append(" >= ").append(ige_2).append(")"); break; case if_icmpgt: String igt_2 = opStack.pop(); String igt_1 = opStack.pop(); line.append("if(").append(igt_1).append(" > ").append(igt_2).append(")"); break; case if_icmple: String ile_2 = opStack.pop(); String ile_1 = opStack.pop(); line.append("if(").append(ile_1).append(" <= ").append(ile_2).append(")"); break; case if_acmpeq: String aeq_2 = opStack.pop(); String aeq_1 = opStack.pop(); line.append("if(").append(aeq_1).append(" == ").append(aeq_2).append(")"); break; case if_acmpne: String ane_2 = opStack.pop(); String ane_1 = opStack.pop(); line.append("if(").append(ane_1).append(" != ").append(ane_2).append(")"); break; case _goto: break; case jsr: break; case ret: break; case tableswitch: break; case lookupswitch: break; case ireturn: case lreturn: case freturn: case dreturn: case areturn: line.append("return ").append(opStack.pop()); break; case _return: if(i != nodes.length - 1) { // in case of this return instruction is not end of opcode, // specifies "return;". line.append("return"); } break; case getstatic: CpRefOpcode getSta = (CpRefOpcode)opcode; String getStaticField = getSta.getOperand().split("\\|")[0]; opStack.push(getStaticField); break; case putstatic: CpRefOpcode putSta = (CpRefOpcode)opcode; String putStaticField = putSta.getOperand().split("\\|")[0]; line.append(putStaticField).append(" = ").append(opStack.pop()); break; case getfield: CpRefOpcode getField = (CpRefOpcode)opcode; String get = getField.getOperand().split("\\|")[0]; String getDeclaration = opStack.pop() + "."; String[] getNames = get.split("\\."); opStack.push(getDeclaration + getNames[getNames.length - 1]); break; case putfield: CpRefOpcode putField = (CpRefOpcode)opcode; String put = putField.getOperand().split("\\|")[0]; String[] putNames = put.split("\\."); String value = opStack.pop(); String putCaller = opStack.pop(); line.append(putCaller).append(".").append(putNames[putNames.length - 1]) .append(" = ").append(value); break; case invokevirtual: CpRefOpcode virOpcode = (CpRefOpcode)opcode; // 0: xxx.yyy.zzz.method // 1: (args_1,args_2,...)returnType String[] virOperand = virOpcode.getOperand().split("\\|"); if(! virOperand[1].endsWith(")void")) { String[] virArgs = new String[virOperand[1].split(",").length + 1]; for(int j = 0; j < virArgs.length; j++) { virArgs[j] = opStack.pop(); } // xxx.yyy.zzz.method String[] virMethod = virOperand[0].split("\\."); StringBuilder virtual = new StringBuilder(); // caller.method( virtual.append(opStack.pop()).append(".") .append(virMethod[virMethod.length - 1]).append("("); for(int j = virArgs.length - 1; j > 0; j virtual.append(virArgs[j]).append(","); } // caller.method(args1,args2,...) virtual.append(virArgs[0]).append(")"); opStack.push(virtual.toString()); } break; case invokespecial: break; case invokestatic: break; case invokeinterface: break; case inovokedynamic: break; case _new: String newClass = ((CpRefOpcode)opcode).getOperand(); opStack.push(newClass.replace("/", ".")); break; case newarray: String type = ((NewArray)opcode).getType(); String primLen = opStack.pop(); opStack.push("new " + type + "[" + primLen + "]"); break; case anewarray: String objType = ((CpRefOpcode)opcode).getOperand(); String objLen = opStack.pop(); opStack.push("new " + objType.replace("/", ".") + "[" + objLen + "]"); break; case arraylength: opStack.push(opStack.pop() + ".length"); break; case athrow: break; case checkcast: String casted = ((CpRefOpcode)opcode).getOperand().replace("/", "."); opStack.push("((" + casted + ")" + opStack.pop() + ")"); break; case _instanceof: String instanceType = ((CpRefOpcode)opcode).getOperand().replace("/", "."); opStack.push("(" + opStack.pop() + " instanceof " + instanceType + ")"); break; case monitorenter: break; case monitorexit: break; case wide: break; case multianewarray: MultiANewArray mana = (MultiANewArray)opcode; String[] dimArray = new String[mana.getDemensions()]; for(int j = 0; j < dimArray.length; j++) { dimArray[j] = opStack.pop(); } StringBuilder manArray = new StringBuilder(); manArray.append("new ").append(mana.getOperand().replace("/", ".")); for(int j = 0; j < dimArray.length - 1; j++) { manArray.append("[").append(dimArray[j]).append("]"); } manArray.append("[").append(dimArray[dimArray.length - 1]).append("]"); opStack.push(manArray.toString()); break; case ifnull: if(node.getType() == LoopEntry) { } else { String ifn = "if(" + opStack.pop() + " == null) {"; } break; case ifnonnull: if(node.getType() == LoopEntry) { } else { String ifnonn = "if(" + opStack.pop() + " != null) {"; } break; case goto_w: break; case jsr_w: break; case breakpoint: break; case impdep1: break; case impdep2: break; default: break; } System.out.println(opcode + ", current: " + opStack.getCurrentStackSize()); System.out.println("local: " + local); System.out.println("stack: " + opStack + "\n"); } // When the node is not start or end of a statement, (ex. "if(...) {", "}") // add semicolon and write in the line context. if(true) { line.append(";"); result.write(line.toString()); } } } private void castPrimitive(String type) { String casted = "((" + type + ")" + opStack.pop() + ")"; opStack.push(casted); } }
package seedu.typed.model; import java.util.ArrayList; import java.util.Set; import java.util.logging.Logger; import javafx.collections.transformation.FilteredList; import seedu.typed.commons.core.ComponentManager; import seedu.typed.commons.core.LogsCenter; import seedu.typed.commons.core.UnmodifiableObservableList; import seedu.typed.commons.events.model.TaskManagerChangedEvent; import seedu.typed.commons.exceptions.IllegalValueException; import seedu.typed.commons.util.CollectionUtil; import seedu.typed.commons.util.Pair; import seedu.typed.commons.util.StringUtil; import seedu.typed.logic.commands.util.Type; import seedu.typed.model.task.ReadOnlyTask; import seedu.typed.model.task.Task; import seedu.typed.model.task.UniqueTaskList.DuplicateTaskException; import seedu.typed.model.task.UniqueTaskList.TaskNotFoundException; /** * Represents the in-memory model of the task manager data. All changes to any * model should be synchronized. */ public class ModelManager extends ComponentManager implements Model { private static final Logger logger = LogsCenter.getLogger(ModelManager.class); private TaskManager taskManager; private final FilteredList<ReadOnlyTask> filteredTasks; // private Expression currentExpression; private Expression defaultExpression = new Negation(new CompletedQualifer()); // private Expression doneExpression = new PredicateExpression(new CompletedQualifer()); public ModelManager(ReadOnlyTaskManager taskManager, UserPrefs userPrefs) throws IllegalValueException { super(); assert !CollectionUtil.isAnyNull(taskManager, userPrefs); logger.fine("Initializing with task manager: " + taskManager + " and user prefs " + userPrefs); this.taskManager = new TaskManager(taskManager); filteredTasks = new FilteredList<>(this.taskManager.getTaskList()); updateFilteredListToShowDefault(); //this.currentExpression = defaultExpression; } public ModelManager() throws IllegalValueException { this(new TaskManager(), new UserPrefs()); updateFilteredListToShowDefault(); } //Test @Override public ReadOnlyTaskManager getTaskManager() { return taskManager; } @Override public int getNumberCompletedTasks() { return taskManager.getNumberCompletedTasks(); } @Override public int getNumberUncompletedTasks() { return taskManager.getNumberUncompletedTasks(); } @Override public int getTotalTasks() { return getNumberCompletedTasks() + getNumberUncompletedTasks(); } @Override public int getNumberEvents() { return taskManager.getNumberEvents(); } @Override public int getNumberDeadlines() { return taskManager.getNumberDeadlines(); } @Override public int getNumberFloatingTasks() { return taskManager.getNumberFloatingTasks(); } @Override public int getNumberUncompletedEvents() { return taskManager.getNumberUncompletedEvents(); } @Override public int getNumberUncompletedDeadlines() { return taskManager.getNumberUncompletedDeadlines(); } @Override public int getNumberUncompletedFloatingTasks() { return taskManager.getNumberUncompletedFloatingTasks(); } //@@author A0143853A @Override public int getNumberOverdue() { return taskManager.getNumberOverdue(); } @Override public int getIndexOfTask(Task task) throws TaskNotFoundException { return taskManager.getIndexOf(task); } //@@author //@@author A0143853A @Override public Task getTaskAt(int index) { return taskManager.getTaskAt(index); } //@@author @Override public synchronized void addTask(Task task) throws DuplicateTaskException { taskManager.addTask(task); updateFilteredListToShowDefault(); indicateTaskManagerChanged(); } //@@author A0143853A @Override public synchronized void addTask(int index, Task task) throws DuplicateTaskException { taskManager.addTask(index, task); indicateTaskManagerChanged(); } //@@author @Override public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException { taskManager.removeTask(target); updateFilteredListToShowDefault(); indicateTaskManagerChanged(); } //@@author A0143853A @Override public synchronized void deleteTaskAt(int index) { taskManager.removeTaskAt(index); indicateTaskManagerChanged(); } //@@author //@@author A0143853A @Override public synchronized void deleteTasks(int startIndex, int endIndex) throws TaskNotFoundException, IllegalValueException { int num = endIndex - startIndex + 1; if (num == 1) { int taskManagerIndex = filteredTasks.getSourceIndex(startIndex); taskManager.removeTaskAt(taskManagerIndex); } else { int[] listOfIndices = new int[num]; for (int i = 0; i < num; i++) { int taskManagerIndex = filteredTasks.getSourceIndex(startIndex + i); listOfIndices[i] = taskManagerIndex; } TaskManager newTaskManager = new TaskManager(); newTaskManager.copyDataExcludingIndices(taskManager, listOfIndices); taskManager.resetData(newTaskManager); } indicateTaskManagerChanged(); } @Override public synchronized void deleteTasksForRedo(ArrayList<Pair<Integer, Task>> list) throws DuplicateTaskException { for (int curr = 0; curr < list.size(); curr++) { Pair<Integer, Task> indexAndTask = list.get(curr); int index = indexAndTask.getFirst(); taskManager.removeTaskAt(index); } updateFilteredListToShowDefault(); indicateTaskManagerChanged(); } //@@author //@@author A0139379M @Override public synchronized void completeTaskAt(int filteredTaskListIndex) throws DuplicateTaskException, IllegalValueException { int taskManagerIndex = filteredTasks.getSourceIndex(filteredTaskListIndex); taskManager.completeTaskAt(taskManagerIndex); updateFilteredListToShowDefault(); indicateTaskManagerChanged(); } //@@author //@@author A0143853A @Override public synchronized void completeTasks(int startIndex, int endIndex) throws DuplicateTaskException, IllegalValueException { for (int curr = startIndex; curr <= endIndex; curr++) { int taskManagerIndex = filteredTasks.getSourceIndex(curr); taskManager.completeTaskAt(taskManagerIndex); } updateFilteredListToShowDefault(); indicateTaskManagerChanged(); } @Override public synchronized void completeTasksAndStoreIndices(int startIndex, int endIndex, ArrayList<Integer> list) throws DuplicateTaskException, IllegalValueException { for (int curr = startIndex; curr <= endIndex; curr++) { int taskManagerIndex = filteredTasks.getSourceIndex(curr); addTaskIndexToListIfUncompleted(taskManagerIndex, list); taskManager.completeTaskAt(taskManagerIndex); } updateFilteredListToShowDefault(); indicateTaskManagerChanged(); } private void addTaskIndexToListIfUncompleted(int taskIndex, ArrayList<Integer> list) { if (!taskManager.getTaskAt(taskIndex).getIsCompleted()) { list.add(taskIndex); } } @Override public synchronized void uncompleteTaskAtForUndo(int taskManagerIndex) throws DuplicateTaskException { taskManager.uncompleteTaskAt(taskManagerIndex); updateFilteredListToShowDefault(); indicateTaskManagerChanged(); } @Override public synchronized void uncompleteTasksAtForUndo(ArrayList<Integer> list) throws DuplicateTaskException { for (int curr = 0; curr < list.size(); curr++) { taskManager.uncompleteTaskAt(list.get(curr)); } updateFilteredListToShowDefault(); indicateTaskManagerChanged(); } @Override public synchronized void completeTasksAtForRedo(ArrayList<Integer> list) throws DuplicateTaskException, IllegalValueException { for (int curr = 0; curr < list.size(); curr++) { taskManager.completeTaskAt(list.get(curr)); } updateFilteredListToShowDefault(); indicateTaskManagerChanged(); } @Override public synchronized void completeTaskAtForRedo(int taskManagerIndex) throws DuplicateTaskException, IllegalValueException { taskManager.completeTaskAt(taskManagerIndex); updateFilteredListToShowDefault(); indicateTaskManagerChanged(); } //@@author //@@author A0143853A @Override public void updateTaskForUndoRedo(int index, ReadOnlyTask editedTask) throws DuplicateTaskException, IllegalValueException { assert editedTask != null; taskManager.updateTask(index, editedTask); taskManager.sort(); indicateTaskManagerChanged(); } //@@author @Override public void updateTask(int filteredTaskListIndex, ReadOnlyTask editedTask) throws DuplicateTaskException, IllegalValueException { assert editedTask != null; int taskManagerIndex = filteredTasks.getSourceIndex(filteredTaskListIndex); taskManager.updateTask(taskManagerIndex, editedTask); // updateFilteredListToShowDefault(); taskManager.sort(); indicateTaskManagerChanged(); } @Override public void resetData(ReadOnlyTaskManager newData) throws IllegalValueException { taskManager.resetData(newData); // updateFilteredListToShowDefault(); indicateTaskManagerChanged(); } //@@author A0143853A @Override public void copyData(ReadOnlyTaskManager newData) throws IllegalValueException { taskManager.copyData(newData); // updateFilteredListToShowDefault(); indicateTaskManagerChanged(); } //@@author /** Raises an event to indicate the model has changed */ private void indicateTaskManagerChanged() { raise(new TaskManagerChangedEvent(this.taskManager)); } @Override public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() { return new UnmodifiableObservableList<>(filteredTasks); } @Override public void updateFilteredListToShowAll() { filteredTasks.setPredicate(null); } @Override public void updateFilteredListToShowDefault() { updateFilteredTaskList(defaultExpression); } //@@author A0141094M @Override public void updateFilteredTaskList(Set<String> keywords, Set<String> tagKeywords) { updateFilteredTaskList(new PredicateExpression(new NameQualifier(keywords)), new PredicateExpression(new TagQualifier(tagKeywords))); } private void updateFilteredTaskList(Expression expression, Expression tagExpression) { filteredTasks.setPredicate(p -> (expression.satisfies(p) || tagExpression.satisfies(p))); } //@@author @Override public void updateFilteredTaskList(Set<String> keywords) { updateFilteredTaskList(new PredicateExpression(new NameQualifier(keywords))); } private void updateFilteredTaskList(Expression expression) { taskManager.sort(); filteredTasks.setPredicate(expression::satisfies); } @Override public void updateFilteredTaskList(String type) { switch (type) { case "deadline": updateFilteredListToShowDeadline(); break; case "duration": updateFilteredListToShowDuration(); break; case "done": updateFilteredListToShowDone(); break; case "undone": updateFilteredListToShowUndone(); break; case "untimed": updateFilteredListToShowUntimed(); break; case "all": updateFilteredListToShowAll(); break; default: updateFilteredListToShowDefault(); } } @Override public void updateFilteredTaskList(Type type) { switch (type) { // NOT DONE case DEADLINE: updateFilteredListToShowDeadline(); break; // NOT DONE case DURATION: updateFilteredListToShowDuration(); break; case DONE: updateFilteredListToShowDone(); break; case UNDONE: updateFilteredListToShowUndone(); break; // NOT DONE case UNTIMED: updateFilteredListToShowUntimed(); break; case ALL: updateFilteredListToShowAll(); break; default: updateFilteredListToShowDefault(); } } //@@author A0141094M @Override public void updateFilteredListToShowDeadline() { // todo filteredTasks.setPredicate(null); } @Override public void updateFilteredListToShowDuration() { // todo this.taskManager.printData(); } @Override public void updateFilteredListToShowDone() { updateFilteredTaskList(new PredicateExpression(new CompletedQualifer())); } @Override public void updateFilteredListToShowUndone() { updateFilteredTaskList(new Negation(new CompletedQualifer())); } @Override public void updateFilteredListToShowUntimed() { //todo //filteredTasks.setPredicate(null); //System.out.println("mmm"); //FXCollections.sort(filteredTasks, DateTimeComparator); this.taskManager.sort(); } //@@author interface Expression { boolean satisfies(ReadOnlyTask task); @Override String toString(); } private class PredicateExpression implements Expression { private final Qualifier qualifier; PredicateExpression(Qualifier qualifier) { this.qualifier = qualifier; } @Override public boolean satisfies(ReadOnlyTask task) { return qualifier.run(task); } @Override public String toString() { return qualifier.toString(); } } //@@author A0139379M private class Negation implements Expression { private final Qualifier qualifier; Negation(Qualifier qualifier) { this.qualifier = qualifier; } @Override public boolean satisfies(ReadOnlyTask task) { return !qualifier.run(task); } } //@@author interface Qualifier { boolean run(ReadOnlyTask task); @Override String toString(); } private class NameQualifier implements Qualifier { private Set<String> nameKeyWords; NameQualifier(Set<String> nameKeyWords) { this.nameKeyWords = nameKeyWords; } @Override public boolean run(ReadOnlyTask task) { return nameKeyWords.stream() .filter(keyword -> StringUtil .isFuzzyKeywordSearchIgnoreCase(task.getName().getValue(), keyword)) .findAny().isPresent(); } @Override public String toString() { return "name=" + String.join(", ", nameKeyWords); } } //@@author A0141094M private class TagQualifier implements Qualifier { private Set<String> tagKeyWords; TagQualifier(Set<String> tagKeyWords) { this.tagKeyWords = tagKeyWords; } @Override public boolean run(ReadOnlyTask task) { return tagKeyWords.stream().filter(keyword -> StringUtil .isFuzzyKeywordSearchIgnoreCase(task.getTags(), keyword)).findAny().isPresent(); } @Override public String toString() { return "tag=" + String.join(", ", tagKeyWords); } } //@@author //@@author A0139379M /** * Returns true for tasks that are completed * @author YIM CHIA HUI * */ private class CompletedQualifer implements Qualifier { @Override public boolean run(ReadOnlyTask task) { return task.getIsCompleted(); } } }
package soot.dexpler; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import soot.Body; import soot.Local; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.jimple.AssignStmt; import soot.jimple.DefinitionStmt; import soot.toolkits.scalar.LocalDefs; /** * Simplistic caching, flow-insensitive def/use analysis * * @author Steven Arzt * */ public class DexDefUseAnalysis implements LocalDefs { private final Body body; private Map<Local, Set<Unit>> localToUses = new HashMap<Local, Set<Unit>>(); private Map<Local, Set<Unit>> localToDefs = new HashMap<Local, Set<Unit>>(); private Map<Local, Set<Unit>> localToDefsWithAliases = new HashMap<Local, Set<Unit>>(); protected BitSet[] localToDefsBits; protected BitSet[] localToUsesBits; protected Map<Local, Integer> localToNumber = new HashMap<>(); protected List<Unit> unitList; public DexDefUseAnalysis(Body body) { this.body = body; initialize(); } protected void initialize() { int lastLocalNumber = 0; for (Local l : body.getLocals()) { localToNumber.put(l, lastLocalNumber++); } localToDefsBits = new BitSet[body.getLocalCount()]; localToUsesBits = new BitSet[body.getLocalCount()]; unitList = new ArrayList<>(body.getUnits()); for (int i = 0; i < unitList.size(); i++) { Unit u = unitList.get(i); // Record the definitions if (u instanceof DefinitionStmt) { Value val = ((DefinitionStmt) u).getLeftOp(); if (val instanceof Local) { final int localIdx = localToNumber.get(val); BitSet bs = localToDefsBits[localIdx]; if (bs == null) { bs = new BitSet(); localToDefsBits[localIdx] = bs; } bs.set(i); } } // Record the uses for (ValueBox vb : u.getUseBoxes()) { Value val = vb.getValue(); if (val instanceof Local) { final int localIdx = localToNumber.get(val); BitSet bs = localToUsesBits[localIdx]; if (bs == null) { bs = new BitSet(); localToUsesBits[localIdx] = bs; } bs.set(i); } } } } public Set<Unit> getUsesOf(Local l) { Set<Unit> uses = localToUses.get(l); if (uses == null) { uses = new HashSet<>(); BitSet bs = localToUsesBits[localToNumber.get(l)]; if (bs != null) { for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) { uses.add(unitList.get(i)); } } localToUses.put(l, uses); } return uses; } /** * Collect definitions of l in body including the definitions of aliases of * l. This analysis exploits that the problem is flow-insensitive anyway. * * In this context an alias is a local that propagates its value to l. * * @param l * the local whose definitions are to collect */ protected Set<Unit> collectDefinitionsWithAliases(Local l) { Set<Unit> defs = localToDefsWithAliases.get(l); if (defs == null) { Set<Local> seenLocals = new HashSet<Local>(); defs = new HashSet<Unit>(); List<Local> newLocals = new ArrayList<Local>(); newLocals.add(l); while (!newLocals.isEmpty()) { Local curLocal = newLocals.remove(0); // Definition of l? BitSet bsDefs = localToDefsBits[localToNumber.get(curLocal)]; if (bsDefs != null) { for (int i = bsDefs.nextSetBit(0); i >= 0; i = bsDefs.nextSetBit(i + 1)) { Unit u = unitList.get(i); defs.add(u); DefinitionStmt defStmt = (DefinitionStmt) u; if (defStmt.getRightOp() instanceof Local && seenLocals.add((Local) defStmt.getRightOp())) newLocals.add((Local) defStmt.getRightOp()); } } // Use of l? BitSet bsUses = localToUsesBits[localToNumber.get(curLocal)]; if (bsUses != null) { for (int i = bsUses.nextSetBit(0); i >= 0; i = bsUses.nextSetBit(i + 1)) { Unit use = unitList.get(i); if (use instanceof AssignStmt) { AssignStmt assignUse = (AssignStmt) use; if (assignUse.getRightOp() == curLocal && assignUse.getLeftOp() instanceof Local && seenLocals.add((Local) assignUse.getLeftOp())) newLocals.add((Local) assignUse.getLeftOp()); } } } } localToDefsWithAliases.put(l, defs); } return defs; } @Override public List<Unit> getDefsOfAt(Local l, Unit s) { return getDefsOf(l); } @Override public List<Unit> getDefsOf(Local l) { Set<Unit> defs = localToDefs.get(l); if (defs == null) { defs = new HashSet<>(); BitSet bs = localToDefsBits[localToNumber.get(l)]; if (bs != null) { for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) { Unit u = unitList.get(i); if (u instanceof DefinitionStmt) if (((DefinitionStmt) u).getLeftOp() == l) defs.add(u); } } localToDefs.put(l, defs); } return new ArrayList<>(defs); } }
package techreborn.init; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityType; import net.minecraft.util.ResourceLocation; import reborncore.common.tile.TileMachineBase; import techreborn.TechReborn; import techreborn.tiles.*; import techreborn.tiles.cable.TileCable; import techreborn.tiles.fusionReactor.TileFusionControlComputer; import techreborn.tiles.generator.TileLightningRod; import techreborn.tiles.generator.TilePlasmaGenerator; import techreborn.tiles.generator.TileSolarPanel; import techreborn.tiles.generator.advanced.*; import techreborn.tiles.generator.basic.TileSolidFuelGenerator; import techreborn.tiles.generator.basic.TileWaterMill; import techreborn.tiles.generator.basic.TileWindMill; import techreborn.tiles.lighting.TileLamp; import techreborn.tiles.machine.iron.TileIronAlloyFurnace; import techreborn.tiles.machine.iron.TileIronFurnace; import techreborn.tiles.machine.multiblock.*; import techreborn.tiles.machine.tier1.*; import techreborn.tiles.storage.TileAdjustableSU; import techreborn.tiles.storage.TileHighVoltageSU; import techreborn.tiles.storage.TileLowVoltageSU; import techreborn.tiles.storage.TileMediumVoltageSU; import techreborn.tiles.storage.idsu.TileInterdimensionalSU; import techreborn.tiles.storage.lesu.TileLSUStorage; import techreborn.tiles.storage.lesu.TileLapotronicSU; import techreborn.tiles.transformers.TileHVTransformer; import techreborn.tiles.transformers.TileLVTransformer; import techreborn.tiles.transformers.TileMVTransformer; import java.util.ArrayList; import java.util.List; public class TRTileEntities { public static final TileEntityType<TileThermalGenerator> THERMAL_GEN = register(TileThermalGenerator.class, "thermal_generator"); public static final TileEntityType<TileQuantumTank> QUANTUM_TANK = register(TileQuantumTank.class, "quantum_tank"); public static final TileEntityType<TileQuantumChest> QUANTUM_CHEST = register(TileQuantumChest.class, "quantum_chest"); public static final TileEntityType<TileDigitalChest> DIGITAL_CHEST = register(TileDigitalChest.class, "digital_chest"); public static final TileEntityType<TileIndustrialCentrifuge> INDUSTRIAL_CENTRIFUGE = register(TileIndustrialCentrifuge.class, "industrial_centrifuge"); public static final TileEntityType<TileRollingMachine> ROLLING_MACHINE = register(TileRollingMachine.class, "rolling_machine"); public static final TileEntityType<TileIndustrialBlastFurnace> INDUSTRIAL_BLAST_FURNACE = register(TileIndustrialBlastFurnace.class, "industrial_blast_furnace"); public static final TileEntityType<TileAlloySmelter> ALLOY_SMELTER = register(TileAlloySmelter.class, "alloy_smelter"); public static final TileEntityType<TileIndustrialGrinder> INDUSTRIAL_GRINDER = register(TileIndustrialGrinder.class, "industrial_grinder"); public static final TileEntityType<TileImplosionCompressor> IMPLOSION_COMPRESSOR = register(TileImplosionCompressor.class, "implosion_compressor"); public static final TileEntityType<TileMatterFabricator> MATTER_FABRICATOR = register(TileMatterFabricator.class, "matter_fabricator"); public static final TileEntityType<TileChunkLoader> CHUNK_LOADER = register(TileChunkLoader.class, "chunk_loader"); public static final TileEntityType<TileChargeOMat> CHARGE_O_MAT = register(TileChargeOMat.class, "charge_o_mat"); public static final TileEntityType<TilePlayerDectector> PLAYER_DETECTOR = register(TilePlayerDectector.class, "player_detector"); public static final TileEntityType<TileCable> CABLE = register(TileCable.class, "cable"); public static final TileEntityType<TileMachineCasing> MACHINE_CASINGS = register(TileMachineCasing.class, "machine_casing"); public static final TileEntityType<TileDragonEggSyphon> DRAGON_EGG_SYPHON = register(TileDragonEggSyphon.class, "dragon_egg_syphon"); public static final TileEntityType<TileAssemblingMachine> ASSEMBLY_MACHINE = register(TileAssemblingMachine.class, "assembly_machine"); public static final TileEntityType<TileDieselGenerator> DIESEL_GENERATOR = register(TileDieselGenerator.class, "diesel_generator"); public static final TileEntityType<TileIndustrialElectrolyzer> INDUSTRIAL_ELECTROLYZER = register(TileIndustrialElectrolyzer.class, "industrial_electrolyzer"); public static final TileEntityType<TileSemiFluidGenerator> SEMI_FLUID_GENERATOR = register(TileSemiFluidGenerator.class, "semi_fluid_generator"); public static final TileEntityType<TileGasTurbine> GAS_TURBINE = register(TileGasTurbine.class, "gas_turbine"); public static final TileEntityType<TileIronAlloyFurnace> IRON_ALLOY_FURNACE = register(TileIronAlloyFurnace.class, "iron_alloy_furnace"); public static final TileEntityType<TileChemicalReactor> CHEMICAL_REACTOR = register(TileChemicalReactor.class, "chemical_reactor"); public static final TileEntityType<TileInterdimensionalSU> INTERDIMENSIONAL_SU = register(TileInterdimensionalSU.class, "interdimensional_su"); public static final TileEntityType<TileAdjustableSU> ADJUSTABLE_SU = register(TileAdjustableSU.class, "adjustable_su"); public static final TileEntityType<TileLapotronicSU> LAPOTRONIC_SU = register(TileLapotronicSU.class, "lapotronic_su"); public static final TileEntityType<TileLSUStorage> LSU_STORAGE = register(TileLSUStorage.class, "lsu_storage"); public static final TileEntityType<TileDistillationTower> DISTILLATION_TOWER = register(TileDistillationTower.class, "distillation_tower"); public static final TileEntityType<TileVacuumFreezer> VACUUM_FREEZER = register(TileVacuumFreezer.class, "vacuum_freezer"); public static final TileEntityType<TileFusionControlComputer> FUSION_CONTROL_COMPUTER = register(TileFusionControlComputer.class, "fusion_control_computer"); public static final TileEntityType<TileLightningRod> LIGHTNING_ROD = register(TileLightningRod.class, "lightning_rod"); public static final TileEntityType<TileIndustrialSawmill> INDUSTRIAL_SAWMILL = register(TileIndustrialSawmill.class, "industrial_sawmill"); public static final TileEntityType<TileGrinder> GRINDER = register(TileGrinder.class, "grinder"); public static final TileEntityType<TileSolidFuelGenerator> SOLID_FUEL_GENEREATOR = register(TileSolidFuelGenerator.class, "solid_fuel_generator"); public static final TileEntityType<TileExtractor> EXTRACTOR = register(TileExtractor.class, "extractor"); public static final TileEntityType<TileCompressor> COMPRESSOR = register(TileCompressor.class, "compressor"); public static final TileEntityType<TileElectricFurnace> ELECTRIC_FURNACE = register(TileElectricFurnace.class, "electric_furnace"); public static final TileEntityType<TileSolarPanel> SOLAR_PANEL = register(TileSolarPanel.class, "solar_panel"); public static final TileEntityType<TileCreativeQuantumTank> CREATIVE_QUANTUM_TANK = register(TileCreativeQuantumTank.class, "creative_quantum_tank"); public static final TileEntityType<TileCreativeQuantumChest> CREATIVE_QUANTUM_CHEST = register(TileCreativeQuantumChest.class, "creative_quantum_chest"); public static final TileEntityType<TileWaterMill> WATER_MILL = register(TileWaterMill.class, "water_mill"); public static final TileEntityType<TileWindMill> WIND_MILL = register(TileWindMill.class, "wind_mill"); public static final TileEntityType<TileMachineBase> MACHINE_BASE = register(TileMachineBase.class, "machine_base"); public static final TileEntityType<TileRecycler> RECYCLER = register(TileRecycler.class, "recycler"); public static final TileEntityType<TileLowVoltageSU> LOW_VOLTAGE_SU = register(TileLowVoltageSU.class, "low_voltage_su"); public static final TileEntityType<TileMediumVoltageSU> MEDIUM_VOLTAGE_SU = register(TileMediumVoltageSU.class, "medium_voltage_su"); public static final TileEntityType<TileHighVoltageSU> HIGH_VOLTAGE_SU = register(TileHighVoltageSU.class, "high_voltage_su"); public static final TileEntityType<TileLVTransformer> LV_TRANSFORMER = register(TileLVTransformer.class, "lv_transformer"); public static final TileEntityType<TileMVTransformer> MV_TRANSFORMER = register(TileMVTransformer.class, "mv_transformer"); public static final TileEntityType<TileHVTransformer> HV_TRANSFORMER = register(TileHVTransformer.class, "hv_transformer"); public static final TileEntityType<TileAutoCraftingTable> AUTO_CRAFTING_TABLE = register(TileAutoCraftingTable.class, "auto_crafting_table"); public static final TileEntityType<TileIronFurnace> IRON_FURNACE = register(TileIronFurnace.class, "iron_furnace"); public static final TileEntityType<TileScrapboxinator> SCRAPBOXINATOR = register(TileScrapboxinator.class, "scrapboxinator"); public static final TileEntityType<TilePlasmaGenerator> PLASMA_GENERATOR = register(TilePlasmaGenerator.class, "plasma_generator"); public static final TileEntityType<TileLamp> LAMP = register(TileLamp.class, "lamp"); public static final TileEntityType<TileAlarm> ALARM = register(TileAlarm.class, "alarm"); public static final TileEntityType<TileFluidReplicator> FLUID_REPLICATOR = register(TileFluidReplicator.class, "fluid_replicator"); public static List<TileEntityType<?>> TYPES = new ArrayList<>(); public static <T extends TileEntity> TileEntityType<T> register(Class<T> tClass, String name) { return register(new ResourceLocation(TechReborn.MOD_ID, name).toString(), TileEntityType.Builder.create(() -> { //TODO clean this up try { return tClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException("Failed to create tile", e); } })); } public static <T extends TileEntity> TileEntityType<T> register(String id, TileEntityType.Builder<T> builder) { TileEntityType<T> tileEntityType = builder.build(null); tileEntityType.setRegistryName(new ResourceLocation(id)); return tileEntityType; } }
package org.dbflute.erflute.editor.controller.command.diagram_contents.element.node; import org.dbflute.erflute.editor.controller.command.AbstractCommand; import org.dbflute.erflute.editor.model.ERDiagram; import org.dbflute.erflute.editor.model.ERModelUtil; import org.dbflute.erflute.editor.model.diagram_contents.element.node.DiagramWalker; public class DeleteElementCommand extends AbstractCommand { private final ERDiagram diagram; private final DiagramWalker element; public DeleteElementCommand(ERDiagram diagram, DiagramWalker element) { this.diagram = diagram; this.element = element; } @Override protected void doExecute() { diagram.removeContent(element); ERModelUtil.refreshDiagram(diagram, element); } @Override protected void doUndo() { diagram.addWalkerPlainly(element); } }
package vizceral.hystrix; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.Unpooled; import io.netty.handler.codec.PrematureChannelClosureException; import io.netty.handler.codec.base64.Base64; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; import io.netty.handler.ssl.util.InsecureTrustManagerFactory; import io.reactivex.netty.RxNetty; import io.reactivex.netty.pipeline.PipelineConfigurators; import io.reactivex.netty.pipeline.ssl.DefaultFactories; import io.reactivex.netty.pipeline.ssl.SSLEngineFactory; import io.reactivex.netty.protocol.http.client.HttpClient; import io.reactivex.netty.protocol.http.client.HttpClientBuilder; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import javax.net.ssl.SSLEngine; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.concurrent.TimeUnit; /** * Reads a hystrix event stream (typically from turbine) and emits events when items are received in the SSE stream. */ public class HystrixReader { private static final Logger logger = LoggerFactory.getLogger(HystrixReader.class); private static final ObjectMapper objectMapper = new ObjectMapper(); private final HttpClient<ByteBuf, ServerSentEvent> rxNetty; private final Configuration configuration; private final String cluster; /** * Creates a new hystrix reader. * * @param configuration The configuration to use. * @param cluster The cluster to read from. */ public HystrixReader(Configuration configuration, String cluster) { this.configuration = configuration; this.cluster = cluster; HttpClientBuilder<ByteBuf, ServerSentEvent> builder = RxNetty.newHttpClientBuilder(configuration.getTurbineHost(), configuration.getTurbinePort()); builder.pipelineConfigurator(PipelineConfigurators.clientSseConfigurator()); if (configuration.isSecure()) { builder.withSslEngineFactory(new HystrixSSLEngineFactory(configuration.getTurbineHost(), configuration.getHttpPort())); } rxNetty = builder.build(); } /** * Starts reading Sever Sent Events from hystrix and emits one item to the observable per HystrixCommand type event. * * @return Observable that can be subscribed to receive events from hystrix. */ public Observable<HystrixEvent> read() { String path = configuration.getTurbinePath(cluster); logger.info("Starting to read from path {}", path); final HttpClientRequest<ByteBuf> request = HttpClientRequest.create(HttpMethod.GET, path); if (configuration.authEnabled()) { String authHeader = "Basic " + Base64.encode(Unpooled.copiedBuffer(configuration.getUsername() + ":" + configuration.getPassword(), StandardCharsets.UTF_8)).toString(StandardCharsets.UTF_8).replace("\n", ""); request.getHeaders().add("Authorization", authHeader); } return rxNetty.submit(request) .flatMap(c -> { logger.info("Http code {} for path {} in region {}", c.getStatus().code(), path, configuration.getRegionName()); if (c.getStatus().code() == 404) { return Observable.error(new UnknownClusterException("Turbine does not recognize cluster " + cluster)); } else if (c.getStatus().code() != 200) { return Observable.error(new IllegalStateException("Got " + c.getStatus().code() + " from turbine")); } else { return c.getContent(); } }) .map(sse -> { try { JsonNode objectNode = objectMapper.readTree(sse.contentAsString()); if (!"HystrixCommand".equals(objectNode.get("type").asText())) { return null; } String commandName = objectNode.get("name").asText(); String group = configuration.getEffectiveGroup(objectNode.get("group").asText()); if (group.isEmpty()) { logger.warn("Invalid hystrix event with an empty group for command {}", commandName); return null; } return HystrixEvent .newBuilder() .rejectedCount((sumFields(objectNode, "rollingCountSemaphoreRejected", "rollingCountThreadPoolRejected")) / 10) .timeoutCount(objectNode.get("rollingCountTimeout").asInt() / 10) .errorCount((sumFields(objectNode, "rollingCountFailure", "rollingCountSemaphoreRejected", "rollingCountShortCircuited") / 10)) .requestCount(objectNode.get("rollingCountSuccess").asInt() / 10) .totalRequestCount(objectNode.get("requestCount").asInt() / 10) .group(group) .name(commandName) .isCircuitBreakerOpen(objectNode.get("isCircuitBreakerOpen").asBoolean()) .build(); } catch (IOException e) { logger.error("Could not parse json", e); return null; } }) .filter(Objects::nonNull) .onErrorResumeNext(ex -> { if (ex instanceof UnknownClusterException) { logger.warn("UnknownClusterException returned"); return Observable.error(ex); } if (ex instanceof IllegalStateException) { logger.warn("IllegalStateException returned"); return Observable.error(ex); } logger.error("Exception from hystrix event for cluster " + cluster + " for region " + configuration.getRegionName() + ". Will retry in 10s", ex); return Observable.timer(10, TimeUnit.SECONDS).flatMap(ignore -> read()); }) .doOnCompleted(() -> logger.info("Cluster {} got on completed", cluster)) .repeatWhen(observable -> observable.flatMap(ignore -> read())); } private static int sumFields(JsonNode objectNode, String... keys) { int sum = 0; for (String key : keys) { if (objectNode.has(key)) { sum += objectNode.get(key).asInt(); } } return sum; } private static class HystrixSSLEngineFactory implements SSLEngineFactory { private final SslContext sslCtx; private final String host; private final int port; private HystrixSSLEngineFactory(String host, int port) { this.host = host; this.port = port; try { sslCtx = SslContextBuilder .forClient() .sslProvider(SslProvider.JDK) .trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); } catch (Exception e) { throw new IllegalStateException("Failed to create default SSL context", e); } } @Override public SSLEngine createSSLEngine(ByteBufAllocator allocator) { return sslCtx.newEngine(allocator, host, port); } } }
package org.smartrfactory.contest.app.matchinggui.gui; import org.ogema.core.application.ApplicationManager; import org.ogema.model.metering.ElectricityMeter; import org.smartrfactory.contest.app.powerbizbase.config.PowervizPlant; import org.smartrplace.util.directresourcegui.TableReceiverTemplate; import org.smartrplace.util.directresourcegui.ValueReceiverHelper; import de.iwes.widgets.api.widgets.WidgetPage; import de.iwes.widgets.api.widgets.sessionmanagement.OgemaHttpRequest; import de.iwes.widgets.html.complextable.RowTemplate; import de.iwes.widgets.html.form.label.Header; import de.iwes.widgets.html.form.label.HeaderData; import de.iwes.widgets.resource.widget.table.ResourceTable; /** * An HTML page, generated from the Java code. */ public class MainPage { public final long UPDATE_RATE = 5*1000; private final WidgetPage<?> page; ResourceTable<ElectricityMeter> meterTable; public MainPage(final WidgetPage<?> page, final ApplicationManager appMan) { this.page = page; Header header = new Header(page, "header", "Connected Meters"); header.addDefaultStyle(HeaderData.CENTERED); RowTemplate<ElectricityMeter> rowTemplate = new TableReceiverTemplate<ElectricityMeter>( new TableReceiverTemplate.TableProvider<ElectricityMeter>() { @Override public ResourceTable<ElectricityMeter> getTable(OgemaHttpRequest req) { return meterTable; } }, ElectricityMeter.class, appMan) { @Override protected Row addRow(ElectricityMeter meter, ValueReceiverHelper<ElectricityMeter> vh, String id, OgemaHttpRequest req) { Row row = new Row(); vh.stringLabel("Name", id, meter.getLocation(), row); String text; PowervizPlant device = meter.getSubResource("device", PowervizPlant.class); if(device.exists()) { text = device.getLocation(); } else { text = "n/a"; } vh.stringLabel("Device", id, text, row); vh.floatLabel("Power_W", id, meter.connection().powerSensor().reading(), row, null); //vh.linkingButton("match", id, meter, row, "Start Matching", "/org/smartrfactory/app/identificiation&meterId="+meter.getLocation()); return row; } }; meterTable = new ResourceTable<ElectricityMeter>( page, "meterTable", false, rowTemplate, ElectricityMeter.class, appMan); //init all widgets page.append(header); page.append(meterTable); /*StaticTable table1 = new StaticTable(1, 2); page.append(table1); table1.setContent(0, 0, roomName); table1.setContent(0, 1, "Measurement value :");*/ } public WidgetPage<?> getPage() { return page; } }
package com.thinkaurelius.titan.graphdb.database.serialize; import com.google.common.base.Preconditions; import com.thinkaurelius.titan.core.Parameter; import com.thinkaurelius.titan.core.attribute.FullDouble; import com.thinkaurelius.titan.core.attribute.FullFloat; import com.thinkaurelius.titan.core.attribute.Geoshape; import com.thinkaurelius.titan.graphdb.database.serialize.attribute.*; import com.thinkaurelius.titan.graphdb.types.*; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; public class SerializerInitialization { private static final int KRYO_OFFSET = 40; public static final int RESERVED_ID_OFFSET = 256; public static final void initialize(Serializer serializer) { serializer.registerClass(String[].class, KRYO_OFFSET + 1); serializer.registerClass(TypeAttributeType.class, KRYO_OFFSET + 2); serializer.registerClass(TypeAttribute.class, KRYO_OFFSET + 3); serializer.registerClass(String.class, new StringSerializer(), KRYO_OFFSET + 4); serializer.registerClass(Date.class, new DateSerializer(), KRYO_OFFSET + 6); serializer.registerClass(ArrayList.class, KRYO_OFFSET + 7); serializer.registerClass(HashMap.class, KRYO_OFFSET + 8); serializer.registerClass(int[].class, KRYO_OFFSET + 9); serializer.registerClass(double[].class, KRYO_OFFSET + 10); serializer.registerClass(long[].class, KRYO_OFFSET + 11); serializer.registerClass(byte[].class, new ByteArrayHandler(), KRYO_OFFSET + 12); serializer.registerClass(boolean[].class, KRYO_OFFSET + 13); serializer.registerClass(IndexType.class, KRYO_OFFSET + 14); //duplicate of 20 TODO: remove one! serializer.registerClass(TitanTypeClass.class, KRYO_OFFSET + 15); serializer.registerClass(Integer.class, new IntegerSerializer(), KRYO_OFFSET + 16); serializer.registerClass(Double.class, new DoubleSerializer(), KRYO_OFFSET + 17); serializer.registerClass(Float.class, new FloatSerializer(), KRYO_OFFSET + 18); serializer.registerClass(Long.class, new LongSerializer(), KRYO_OFFSET + 19); serializer.registerClass(IndexType.class, KRYO_OFFSET + 20); serializer.registerClass(IndexType[].class, KRYO_OFFSET + 21); serializer.registerClass(Geoshape.class, new GeoshapeHandler(), KRYO_OFFSET + 22); serializer.registerClass(Byte.class, new ByteSerializer(), KRYO_OFFSET + 23); serializer.registerClass(Short.class, new ShortSerializer(), KRYO_OFFSET + 24); serializer.registerClass(Character.class, new CharacterSerializer(), KRYO_OFFSET + 25); serializer.registerClass(Boolean.class, new BooleanSerializer(), KRYO_OFFSET + 26); serializer.registerClass(Object.class, KRYO_OFFSET + 27); serializer.registerClass(FullFloat.class, new FullFloatHandler(), KRYO_OFFSET + 28); serializer.registerClass(FullDouble.class, new FullDoubleHandler(), KRYO_OFFSET + 29); serializer.registerClass(char[].class, KRYO_OFFSET + 30); serializer.registerClass(short[].class, KRYO_OFFSET + 31); serializer.registerClass(float[].class, KRYO_OFFSET + 32); serializer.registerClass(Parameter.class,KRYO_OFFSET + 33); serializer.registerClass(Parameter[].class,KRYO_OFFSET + 34); serializer.registerClass(IndexParameters.class,KRYO_OFFSET + 35); serializer.registerClass(IndexParameters[].class,KRYO_OFFSET + 36); Preconditions.checkArgument(KRYO_OFFSET + 50 < RESERVED_ID_OFFSET, "ID allocation overflow!"); } }
package org.mwc.debrief.core.editors.painters.snail; import java.awt.*; import java.util.*; import org.mwc.debrief.core.editors.painters.SnailHighlighter; import Debrief.Tools.Tote.Watchable; import Debrief.Wrappers.*; import MWC.GUI.CanvasType; import MWC.GenericData.*; /** class to draw a 'back-track' of points backwards from the current * datapoint for the indicated period. * * Internally, the class retrieves the list of included points from the * track itself and stores them in the HashTable indexed by the current fix. * So, when we are asked to plot a point, we look in the HashTable first -- * if we have a vector of points for this fix we re-plot these and then * remove them from the hashtable. * If we don't find a vector of points for this Fix then we retrieve * the list from the track and then insert the list into our HashTable * Ta-Da! * */ final class SnailDrawSWTTrack { /** the size of points to draw */ private int _pointSize; /** the length of trail to draw (microseconds) */ private long _trailLength; /** whether to join fixes */ private boolean _joinPoints; /** our list of Vectors of points */ private final java.util.Hashtable _fixLists; /** whether to fade out the track and symbols */ private boolean _fadePoints; // constructor public SnailDrawSWTTrack() { setJoinPositions(true); setFadePoints(true); setTrailLength(new Long(15 * 1000 * 1000* 60 )); // 15 minutes setPointSize(5); _fixLists = new java.util.Hashtable(); } // member functions public final java.awt.Rectangle drawMe(MWC.Algorithms.PlainProjection proj, CanvasType dest, Watchable watch, SnailHighlighter parent, HiResDate dtg, Color backColor) { // set the width // if(dest instanceof CanvasType) // CanvasType ct = (CanvasType)dest; // ct.setLineWidth(_pointSize / 3); // if(dest instanceof Graphics2D) // Graphics2D g2 = (Graphics2D)dest; // BasicStroke bs = new BasicStroke(_pointSize/3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL); // g2.setStroke(bs); // represent this area as a rectangle java.awt.Rectangle thisR = null; // get the fix and the track final FixWrapper theFix = (FixWrapper)watch; TrackWrapper trk = theFix.getTrackWrapper(); // declare the Vector of track points we are using final Collection dotPoints; // do we have these points already? Object myList = _fixLists.get(theFix); // did we find it? if(myList != null) { // cast it back to the vector dotPoints = (Collection)myList; } else { // retrieve the points in range dotPoints = trk.getUnfilteredItems(new HiResDate(0, dtg.getMicros() - _trailLength), new HiResDate(0, dtg.getMicros()+2)); // add the target fix aswell. We are showing the symbol nearest to the current DTG - // which may be ahead of the current DTG. We were drawing lines connecting points // from the current DTG back through the indicated time period. This may // result in there being a gap between the current symbol and the snail trail. Therefore, // add the current fix to the list of points if we don't already contain it. //if(!dotPoints.contains(theFix)) dotPoints.add(theFix); // check that we found some points for this track if(dotPoints != null) { // and put them into the list _fixLists.put(theFix, dotPoints); } } // see if there are any points if(dotPoints != null) { if(dotPoints.size()>0) { // get the colour of the track /** NOTE that we are working in floats for all of the color * stuff - if we were to work in ints, then when we * want more than 255 shades, the deltas become zero * and the track dissappears. By working in floats we * can provide very fine deltas, allowing very large numbers * of points to be tidily plotted in the track */ float red, green, blue; final Color mainCol = trk.getColor(); red = mainCol.getRed(); green = mainCol.getGreen(); blue = mainCol.getBlue(); // sort out the r,g,b components of the background colour float backR, backG, backB; backR = backColor.getRed(); backG = backColor.getGreen(); backB = backColor.getBlue(); // now switch r,g,b to their deltas from the back ground colour red -= backR; green -= backG; blue -= backB; // how many shades to we need? final float numShades = (float)dotPoints.size()+1; // what are the deltas? float dRed, dGreen, dBlue; dRed = red / numShades; dGreen = green / numShades; dBlue = blue / numShades; // give our shades valid start values red = backR; green = backG; blue = backB; // remember the last location Point lastLoc=null; Iterator iter = dotPoints.iterator(); while(iter.hasNext()) { final Color newCol; // see if we are fading to black if(_fadePoints) { // produce the next colour red += dRed; green += dGreen; blue += dBlue; newCol = new Color((int)red, (int)green, (int) blue); } else { // just use the normal track colour newCol = trk.getColor(); } // update the colour for this segment dest.setColor(newCol); // get this fix FixWrapper gw = (FixWrapper)iter.next(); // get the location WorldLocation loc = gw.getLocation(); // get the screen location Point screenP = new Point(proj.toScreen(loc)); // initialise the area, if we have to if(thisR == null) thisR = new Rectangle(screenP); // see if this fix is visible if(gw.getSymbolShowing()) { // and draw the dot drawDot(screenP, dest, _pointSize, thisR); } // see if we are joining them if(lastLoc == null) { lastLoc = screenP; } else { // see if we are joining the points if(_joinPoints) { dest.drawLine(lastLoc.x, lastLoc.y, screenP.x, screenP.y); } lastLoc = screenP; } // see if we are plotting the DTG if(gw.getLabelShowing()) { // // set the font to the current font for the fix (so that we get the metrics right) // dest.setFont(gw.getFont()); // get the text itself, again for the metrics String msg = gw.getName(); // and get the label to paint itself gw.paintLabel(dest); // somehow we need to include this extended area int sWid = dest.getStringWidth(gw.getFont(), msg); // shift from the start of the string (using a copy of the point) Point newP = new Point(screenP); newP.translate(sWid, 0); // and add to the limits rectangle thisR.add(newP); } } } } return thisR; } private static void drawDot(final Point loc, final CanvasType dest, final int size, final Rectangle area) { final int wid = size / 2; dest.fillOval(loc.x - wid, loc.y - wid, size, size); area.add(loc.x - size - 2, loc.y - size - 2); area.add(loc.x + size + 2, loc.y + size + 2); } // public boolean canPlot(Watchable wt) // boolean res = false; // if((wt instanceof Debrief.Wrappers.TrackWrapper)||(wt instanceof Debrief.Wrappers.BuoyPatternWrapper)) // res = true; // return res; public final void setJoinPositions(final boolean val) { _joinPoints = val; } public final boolean getJoinPositions() { return _joinPoints; } public final void setFadePoints(final boolean val) { _fadePoints = val; } public final boolean getFadePoints() { return _fadePoints; } /** point size of symbols (pixels) */ public final int getPointSize() { return _pointSize; } /** length of trail to plot (micros) */ public final Long getTrailLength() { return new Long(_trailLength); } /** size of points to draw (pixels) */ public final void setPointSize(final int val) { _pointSize = val; } /** length of trail to draw (micros) */ public final void setTrailLength(final Long len) { _trailLength = len.longValue(); // and clear the lists of fixes we are using, so that they are re-calculated if(_fixLists != null) _fixLists.clear(); } }
package uk.ac.bolton.archimate.editor.diagram.policies; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.emf.ecore.EClass; import org.eclipse.gef.EditPart; import org.eclipse.gef.EditPolicy; import org.eclipse.gef.commands.Command; import org.eclipse.gef.editpolicies.NonResizableEditPolicy; import org.eclipse.gef.editpolicies.ResizableEditPolicy; import org.eclipse.gef.editpolicies.XYLayoutEditPolicy; import org.eclipse.gef.requests.CreateRequest; import uk.ac.bolton.archimate.editor.diagram.commands.CreateDiagramArchimateObjectCommand; import uk.ac.bolton.archimate.editor.diagram.commands.CreateDiagramObjectCommand; import uk.ac.bolton.archimate.editor.diagram.commands.SetConstraintObjectCommand; import uk.ac.bolton.archimate.editor.diagram.editparts.INonResizableEditPart; import uk.ac.bolton.archimate.model.IArchimatePackage; import uk.ac.bolton.archimate.model.IDiagramModelContainer; import uk.ac.bolton.archimate.model.IDiagramModelObject; /** * Policy for General Diagram * * @author Phillip Beauvoir */ public class DiagramLayoutPolicy extends XYLayoutEditPolicy { @Override protected Command getCreateCommand(CreateRequest request) { Rectangle bounds = getConstraintFor(request); if(request.getNewObjectType() instanceof EClass) { EClass eClass = (EClass)request.getNewObjectType(); // Archimate type object if(IArchimatePackage.eINSTANCE.getArchimateElement().isSuperTypeOf(eClass)) { return new CreateDiagramArchimateObjectCommand((IDiagramModelContainer)getHost().getModel(), request, bounds); } // Other non-Archimate object (note, group, sticky) else { return new CreateDiagramObjectCommand((IDiagramModelContainer)getHost().getModel(), request, bounds); } } return null; } /* * Over-ride this to get any extra constraints for an object */ @Override protected Rectangle getConstraintFor(CreateRequest request) { Rectangle bounds = (Rectangle)super.getConstraintFor(request); if(request.getNewObjectType() instanceof EClass) { Dimension d = getMaximumSizeFor((EClass)request.getNewObjectType()); bounds.width = Math.min(d.width, bounds.width); bounds.height = Math.min(d.height, bounds.height); } return bounds; } /** * @param eClass * @return The Maximum size constraint for an object */ protected Dimension getMaximumSizeFor(EClass eClass) { // Junctions should not be bigger than default size if(IArchimatePackage.eINSTANCE.getJunctionElement().isSuperTypeOf(eClass)) { return new Dimension(-1, -1); } return IFigure.MAX_DIMENSION; } @Override protected EditPolicy createChildEditPolicy(EditPart child) { return (child instanceof INonResizableEditPart) ? new NonResizableEditPolicy() : new ResizableEditPolicy(); } @Override protected Command createChangeConstraintCommand(EditPart child, Object constraint) { // Return a command that can move and/or resize a Shape if(constraint instanceof Rectangle) { return new SetConstraintObjectCommand((IDiagramModelObject)child.getModel(), (Rectangle)constraint); } return null; } /* * This allows us to drag parts from a parent container to another. * This is the "add" counterpart to the "remove" Command created in GroupContainerEditPolicy.getOrphanChildrenCommand(GroupRequest); * * If you don't want a part to be added, return null here. */ @Override protected Command createAddCommand(EditPart childEditPart, Object constraint) { IDiagramModelContainer parent = (IDiagramModelContainer)getHost().getModel(); IDiagramModelObject child = (IDiagramModelObject)childEditPart.getModel(); // Keep within box Rectangle bounds = (Rectangle)constraint; if(bounds.x < 0) { bounds.x = 0; } if(bounds.y < 0) { bounds.y = 0; } return new AddObjectCommand(parent, child, bounds); } /** * AddObjectCommand */ static class AddObjectCommand extends Command { IDiagramModelContainer fParent; IDiagramModelObject fChild; Rectangle fBounds; public AddObjectCommand(IDiagramModelContainer parent, IDiagramModelObject child, Rectangle bounds) { fParent = parent; fChild = child; fBounds = bounds.getCopy(); } @Override public void execute() { fChild.setBounds(fBounds.x, fBounds.y, fBounds.width, fBounds.height); fParent.getChildren().add(fChild); } @Override public void undo() { fParent.getChildren().remove(fChild); } @Override public void dispose() { fParent = null; fChild = null; } } }
package edu.northwestern.bioinformatics.studycalendar.restlets; import edu.northwestern.bioinformatics.studycalendar.dao.SiteDao; import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao; import edu.northwestern.bioinformatics.studycalendar.domain.Site; import edu.northwestern.bioinformatics.studycalendar.domain.Study; import edu.northwestern.bioinformatics.studycalendar.domain.StudySite; import static edu.northwestern.bioinformatics.studycalendar.restlets.UriTemplateParameters.*; import edu.northwestern.bioinformatics.studycalendar.xml.StudyCalendarXmlCollectionSerializer; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Status; import org.restlet.data.Reference; import org.restlet.resource.Representation; import org.restlet.resource.ResourceException; import org.restlet.resource.Variant; import org.springframework.beans.factory.annotation.Required; import java.io.IOException; /** * @author Rhett Sutphin */ public abstract class StudySiteCollectionResource<V> extends AbstractPscResource { private SiteDao siteDao; private StudyDao studyDao; protected StudyCalendarXmlCollectionSerializer<V> xmlSerializer; private Study study; private Site site; private StudySite studySite; @Override public void init(Context context, Request request, Response response) { super.init(context, request, response); setReadable(true); study = studyDao.getByAssignedIdentifier(STUDY_IDENTIFIER.extractFrom(request)); log.debug("Resolved study from {} as {}", STUDY_IDENTIFIER.extractFrom(request), study); site = siteDao.getByAssignedIdentifier(SITE_IDENTIFIER.extractFrom(request)); log.debug("Resolved site from {} as {}", SITE_IDENTIFIER.extractFrom(request), site); if (study != null && site != null) { studySite = study.getStudySite(site); } setAvailable(studySite != null); log.debug("Site {} participating in study", isAvailable() ? "is" : "is not"); getVariants().add(new Variant(MediaType.TEXT_XML)); } @Override public boolean allowPost() { return true; } protected StudySite getStudySite() { return studySite; } protected Study getStudy() { return study; } protected Site getSite() { return site; } private void verifyStudySiteExists() throws ResourceException { if (study == null) { throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No study matching " + STUDY_IDENTIFIER.extractFrom(getRequest())); } else if (site == null) { throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No site matching " + SITE_IDENTIFIER.extractFrom(getRequest())); } else if (studySite == null) { throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "Site " + SITE_IDENTIFIER.extractFrom(getRequest()) + " is not participating in " + STUDY_IDENTIFIER.extractFrom(getRequest()) ); } } protected abstract Representation createXmlRepresentation(StudySite target) throws ResourceException; @Override public Representation represent(Variant variant) throws ResourceException { verifyStudySiteExists(); if (variant.getMediaType().equals(MediaType.TEXT_XML)) { return createXmlRepresentation(studySite); } else { return null; } } protected abstract String acceptValue(V value) throws ResourceException; @Override public void acceptRepresentation(Representation entity) throws ResourceException { verifyStudySiteExists(); if (entity.getMediaType().equals(MediaType.TEXT_XML)) { V value; try { value = xmlSerializer.readDocument(entity.getStream()); } catch (IOException e) { log.warn("PUT failed with IOException"); throw new ResourceException(e); } if (value == null) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Could not parse request"); } else { String target = acceptValue(value); getResponse().setStatus(Status.SUCCESS_CREATED); getResponse().setLocationRef(new Reference(getRequest().getRootRef() + "/" + target)); } } else { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Unsupported content type"); } } ////// CONFIGURATION @Required public void setSiteDao(SiteDao siteDao) { this.siteDao = siteDao; } @Required public void setStudyDao(StudyDao studyDao) { this.studyDao = studyDao; } @Required public void setXmlSerializer(StudyCalendarXmlCollectionSerializer<V> xmlSerializer) { this.xmlSerializer = xmlSerializer; } }
package com.wix.restaurants.authentication.model; public class Namespaces { private Namespaces() {} /** Facebook users, id is the Facebook user id. */ public static final String facebook = "com.facebook"; /** Wix users, id is the Wix user id. */ public static final String wix = "com.wix"; /** Wix websites, id is the Wix site id. */ public static final String wixSites = "com.wix.sites"; /** Wix app instances, id is the Wix instance id. */ public static final String wixInstances = "com.wix.instances"; /** Owner (customer) of a Wix Restaurants order, id is the order id. */ public static final String wixRestaurantsOrdersOwners = "com.wix.restaurants.orders.owners"; /** Recipient of Wix Restaurants order share, id is the order id. */ public static final String wixRestaurantsOrdersShares = "com.wix.restaurants.orders.shares"; /** Owner (customer) of a Wix Restaurants reservation, id is the reservation id. */ public static final String wixRestaurantsReservationsOwners = "com.wix.restaurants.reservations.owners"; /** Recipient of Wix Restaurants reservation share, id is the reservation id. */ public static final String wixRestaurantsReservationsShares = "com.wix.restaurants.reservations.shares"; /** OpenRest users, id is the user's email. */ public static final String openrest = "com.openrest"; /** Google OpenID Connect, id is the user's email. */ public static final String google = "com.google"; public static final String phone = "tel"; /** Email address owner, id is the email address in lowercase. */ public static final String email = "email"; }
package org.opendaylight.yangtools.yang.parser.spi.meta; import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement; import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement; import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition; import org.opendaylight.yangtools.yang.parser.spi.source.SourceException; /** * * Support for processing concrete YANG statement. * * This interface is intended to be implemented by developers, which want to * introduce support of statement to parser. Consider subclassing * {@link AbstractStatementSupport} for easier implementation of this interface. * * @param <A> * Argument type * @param <D> * Declared Statement representation * @param <E> * Effective Statement representation */ public interface StatementSupport<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> extends StatementDefinition, StatementFactory<A, D, E> { /** * Returns public statement definition, which will be present in built * statements. * * Public statement definition may be used to provide different * implementation of statement definition, which will not retain any build * specific data or context. * * @return public statement definition, which will be present in built * statements. */ StatementDefinition getPublicView(); /** * * Parses textual representation of argument in object representation. * * @param ctx * Context, which may be used to access source-specific * namespaces required for parsing. * @param value * String representation of value, as was present in text source. * @return Parsed value */ A parseArgumentValue(StmtContext<?, ?, ?> ctx, String value) throws SourceException; /** * Invoked when a statement supported by this instance is added to build context. This allows implementations * of this interface to start tracking the statement and perform any modifications to the build context hierarchy, * accessible via {@link StmtContext#getParentContext()}. One such use is populating the parent's namespaces to * allow it to locate this child statement. * * @param stmt * Context of added statement. No substatements are available. */ void onStatementAdded(StmtContext.Mutable<A, D, E> stmt); /** * Invoked when statement is closed during * {@link ModelProcessingPhase#SOURCE_PRE_LINKAGE} phase, only substatements * from this and previous phase are available. * * Implementation may use method to perform actions on this event or * register modification action using * {@link StmtContext.Mutable#newInferenceAction(ModelProcessingPhase)}. * * @param stmt * Context of added statement. */ void onPreLinkageDeclared(StmtContext.Mutable<A, D, E> stmt); /** * Invoked when statement is closed during * {@link ModelProcessingPhase#SOURCE_LINKAGE} phase, only substatements * from this and previous phase are available. * * Implementation may use method to perform actions on this event or * register modification action using * {@link StmtContext.Mutable#newInferenceAction(ModelProcessingPhase)}. * * @param stmt * Context of added statement. */ void onLinkageDeclared(StmtContext.Mutable<A, D, E> stmt) throws SourceException; /** * Invoked when statement is closed during * {@link ModelProcessingPhase#STATEMENT_DEFINITION} phase, only * substatements from this phase are available. * * Implementation may use method to perform actions on this event or * register modification action using * {@link StmtContext.Mutable#newInferenceAction(ModelProcessingPhase)}. * * @param stmt * Context of added statement. Argument and statement parent is * accessible. */ void onStatementDefinitionDeclared(StmtContext.Mutable<A, D, E> stmt) throws SourceException; /** * Invoked when statement is closed during * {@link ModelProcessingPhase#FULL_DECLARATION} phase. * * Invoked when statement is closed during * {@link ModelProcessingPhase#FULL_DECLARATION} phase, only substatements * from this phase are available. * * Implementation may use method to perform actions on this event or * register modification action using * {@link StmtContext.Mutable#newInferenceAction(ModelProcessingPhase)}. * * * @param stmt * Context of added statement. Argument and statement parent is * accessible. */ void onFullDefinitionDeclared(StmtContext.Mutable<A, D, E> stmt) throws SourceException; }
package com.udacity.gamedev.sierpinskitriangle; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.viewport.FitViewport; /** * TODO: Start here * * Your challenge, should you choose to accept it, is to draw a Serpinski Triangle. I offer no hints * beyond the fact that ShapeRenderer has a very convenient triangle() function, and that using a * FitViewport can simplify matters considerably. Good luck! */ public class SierpinskiTriangle extends ApplicationAdapter { static final float SIZE = 10; private static final int RECURSIONS = 7; ShapeRenderer renderer; FitViewport viewport; @Override public void create() { renderer = new ShapeRenderer(); viewport = new FitViewport(SIZE, SIZE); } @Override public void dispose() { renderer.dispose(); } @Override public void resize(int width, int height) { viewport.update(width, height, true); } @Override public void render() { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); viewport.apply(); renderer.setProjectionMatrix(viewport.getCamera().combined); renderer.begin(ShapeType.Filled); inscribeSierpinskiTriangle(renderer, SIZE, RECURSIONS); renderer.end(); } private void inscribeSierpinskiTriangle(ShapeRenderer shapeRenderer, float size, int recursions) { Vector2 corner1 = new Vector2(0, 0); Vector2 corner2 = new Vector2(size, 0); Vector2 corner3 = new Vector2(size / 2, size * MathUtils.sin(MathUtils.PI/3f)); drawSierpinskiTriangle(shapeRenderer, corner1, corner2, corner3, recursions); } private void drawSierpinskiTriangle(ShapeRenderer shapeRenderer, Vector2 corner1, Vector2 corner2, Vector2 corner3, int recursions) { Vector2 midpoint12 = new Vector2((corner1.x + corner2.x) / 2, (corner1.y + corner2.y) / 2); Vector2 midpoint23 = new Vector2((corner2.x + corner3.x) / 2, (corner2.y + corner3.y) / 2); Vector2 midpoint31 = new Vector2((corner3.x + corner1.x) / 2, (corner3.y + corner1.y) / 2); if (recursions == 1) { shapeRenderer.triangle(corner1.x, corner1.y, midpoint12.x, midpoint12.y, midpoint31.x, midpoint31.y); shapeRenderer.triangle(corner2.x, corner2.y, midpoint23.x, midpoint23.y, midpoint12.x, midpoint12.y); shapeRenderer.triangle(corner3.x, corner3.y, midpoint31.x, midpoint31.y, midpoint23.x, midpoint23.y); } else { drawSierpinskiTriangle(shapeRenderer, corner1, midpoint12, midpoint31, recursions - 1); drawSierpinskiTriangle(shapeRenderer, corner2, midpoint23, midpoint12, recursions - 1); drawSierpinskiTriangle(shapeRenderer, corner3, midpoint31, midpoint23, recursions - 1); } } }
package com.hubspot.baragon.service.edgecache.cloudflare.client; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Optional; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import com.hubspot.baragon.service.BaragonServiceModule; import com.hubspot.baragon.service.config.EdgeCacheConfiguration; import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareDnsRecord; import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareListDnsRecordsResponse; import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareListZonesResponse; import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflarePurgeCacheResponse; import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflarePurgeRequest; import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareResponse; import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareResultInfo; import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareZone; import com.hubspot.horizon.HttpRequest.Method; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder; import com.ning.http.client.Response; @Singleton public class CloudflareClient { private static final Logger LOG = LoggerFactory.getLogger(CloudflareClient.class); private static final int MAX_ZONES_PER_PAGE = 50; private static final int MAX_DNS_RECORDS_PER_PAGE = 100; private final AsyncHttpClient httpClient; private final ObjectMapper objectMapper; private final String apiBase; private final String apiEmail; private final String apiKey; // <ZoneId, CloudflareZone> private final Supplier<Map<String, List<CloudflareZone>>> zoneCache; // <ZoneId, <DnsName, CloudflareDnsRecord>> private final LoadingCache<String, Map<String, CloudflareDnsRecord>> dnsRecordCache; @Inject public CloudflareClient(EdgeCacheConfiguration edgeCacheConfiguration, @Named(BaragonServiceModule.BARAGON_SERVICE_HTTP_CLIENT) AsyncHttpClient httpClient, ObjectMapper objectMapper) { this.httpClient = httpClient; this.objectMapper = objectMapper; Map<String, String> integrationSettings = edgeCacheConfiguration.getIntegrationSettings(); this.apiBase = integrationSettings.get("apiBase"); this.apiEmail = integrationSettings.get("apiEmail"); this.apiKey = integrationSettings.get("apiKey"); this.zoneCache = Suppliers.memoizeWithExpiration(() -> { try { return retrieveAllZones().stream().collect(Collectors.groupingBy(CloudflareZone::getName)); } catch (CloudflareClientException e) { LOG.error("Unable to refresh Cloudflare zone cache", e); return new ConcurrentHashMap<>(); } }, 10, TimeUnit.MINUTES); this.dnsRecordCache = CacheBuilder.newBuilder() .maximumSize(10_000) .expireAfterWrite(10, TimeUnit.MINUTES) .build(new CacheLoader<String, Map<String, CloudflareDnsRecord>>() { @Override public Map<String, CloudflareDnsRecord> load(String zoneId) throws Exception { return retrieveDnsRecords(zoneId).stream().collect(Collectors.toConcurrentMap( CloudflareDnsRecord::getName, Function.identity(), (name1, name2) -> { LOG.debug("Duplicate name found", name1); return name1; } )); } }); } public boolean purgeEdgeCache(String zoneId, List<String> cacheTags) throws CloudflareClientException { CloudflarePurgeRequest purgeRequest = new CloudflarePurgeRequest(Collections.emptyList(), cacheTags); Response response = requestWith(Method.DELETE, String.format("zones/%s/purge_cache", zoneId), purgeRequest); try { LOG.trace("Sending purge request to Cloudflare: {}", objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(purgeRequest)); } catch (JsonProcessingException e) { // no-op } boolean success = isSuccess(response); try { if (!success && response.getResponseBody() != null) { CloudflarePurgeCacheResponse parsedResponse = objectMapper.readValue(response.getResponseBody(), CloudflarePurgeCacheResponse.class); LOG.error("Failed to purge Cloudflare edge cache for cache tag(s) {}. Errors were: {}", cacheTags, parsedResponse.getErrors()); } } catch (IOException e) { LOG.warn("Failed to read response from Cloudflare while trying to inspect unsuccessful cache purge response."); } return success; } private Response requestWith(Method method, String path, Object body) throws CloudflareClientException { return request(method, path, Optional.of(body), Optional.absent(), Optional.absent(), Optional.absent(), Optional.absent()); } private Response request(Method method, String path, Optional<Object> body, Optional<Integer> page, Optional<Integer> perPage, Optional<String> order, Optional<String> direction) throws CloudflareClientException { BoundRequestBuilder builder; switch (method) { case DELETE: builder = httpClient.prepareDelete(apiBase + path); break; case GET: default: builder = httpClient.prepareGet(apiBase + path); } builder .addHeader("X-Auth-Email", apiEmail) .addHeader("X-Auth-Key", apiKey); if (body.isPresent()) { try { builder.setBody(objectMapper.writeValueAsString(body.get())); } catch (JsonProcessingException e) { throw new CloudflareClientException("Unable to serialize body while preparing to send API request", e); } } page.asSet().forEach(p -> builder.addQueryParameter("page", page.get().toString())); perPage.asSet().forEach(p -> builder.addQueryParameter("per_page", perPage.get().toString())); order.asSet().forEach(o -> builder.addQueryParameter("order", order.get())); direction.asSet().forEach(d -> builder.addQueryParameter("direction", direction.get())); try { return builder.execute().get(); } catch (Exception e) { throw new CloudflareClientException("Unexpected error during Cloudflare API call", e); } } private boolean isSuccess(Response response) { return response.getStatusCode() >= 200 && response.getStatusCode() < 300; } public List<CloudflareZone> getZone(String name) throws CloudflareClientException { return zoneCache.get().get(name); } public List<CloudflareZone> retrieveAllZones() throws CloudflareClientException { CloudflareListZonesResponse cloudflareResponse = listZonesPaged(1); List<CloudflareZone> zones = new ArrayList<>(); zones.addAll(cloudflareResponse.getResult()); CloudflareResultInfo paginationInfo = cloudflareResponse.getResultInfo(); for (int i = 2; i <= paginationInfo.getTotalPages(); i++) { CloudflareListZonesResponse cloudflarePageResponse = listZonesPaged(i); zones.addAll(cloudflarePageResponse.getResult()); } return zones; } private CloudflareListZonesResponse listZonesPaged(Integer page) throws CloudflareClientException { Response response = pagedRequest(Method.GET, "zones", page, MAX_ZONES_PER_PAGE); if (!isSuccess(response)) { try { CloudflareResponse parsedResponse = objectMapper.readValue(response.getResponseBody(), CloudflareListZonesResponse.class); throw new CloudflareClientException("Failed to get zones, " + parsedResponse); } catch (IOException e) { throw new CloudflareClientException("Failed to get zones; unable to parse error response"); } } try { return objectMapper.readValue(response.getResponseBody(), CloudflareListZonesResponse.class); } catch (IOException e) { throw new CloudflareClientException("Unable to parse Cloudflare List Zones response", e); } } public CloudflareDnsRecord getDnsRecord(String zoneId, String name) throws CloudflareClientException { try { return dnsRecordCache.get(zoneId).get(name); } catch (ExecutionException e) { throw new CloudflareClientException(e.getMessage(), e.getCause()); } } public Set<CloudflareDnsRecord> retrieveDnsRecords(String zoneId) throws CloudflareClientException { CloudflareListDnsRecordsResponse cloudflareResponse = listDnsRecordsPaged(zoneId, 1); Set<CloudflareDnsRecord> dnsRecords = cloudflareResponse.getResult(); CloudflareResultInfo paginationInfo = cloudflareResponse.getResultInfo(); for (int i = 2; i <= paginationInfo.getTotalPages(); i++) { CloudflareListDnsRecordsResponse cloudflarePageResponse = listDnsRecordsPaged(zoneId, i); dnsRecords.addAll(cloudflarePageResponse.getResult()); } return dnsRecords; } private CloudflareListDnsRecordsResponse listDnsRecordsPaged(String zoneId, Integer page) throws CloudflareClientException { Response response = pagedRequest(Method.GET, String.format("zones/%s/dns_records", zoneId), page, MAX_DNS_RECORDS_PER_PAGE); if (!isSuccess(response)) { try { CloudflareResponse parsedResponse = objectMapper.readValue(response.getResponseBody(), CloudflareListDnsRecordsResponse.class); throw new CloudflareClientException("Failed to get DNS records, " + parsedResponse); } catch (IOException e) { throw new CloudflareClientException("Failed to get DNS records; unable to parse error response"); } } try { return objectMapper.readValue(response.getResponseBody(), CloudflareListDnsRecordsResponse.class); } catch (IOException e) { throw new CloudflareClientException("Unable to parse Cloudflare List DNS Records response", e); } } private Response pagedRequest(Method method, String path, Integer page, Integer perPage) throws CloudflareClientException { return request(method, path, Optional.absent(), Optional.of(page), Optional.of(perPage), Optional.absent(), Optional.absent()); } }
package org.loverde.jquery.restrictedtextfield.selenium; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.loverde.jquery.restrictedtextfield.selenium.driver.DriverFactory; import org.loverde.jquery.restrictedtextfield.selenium.util.StringUtil; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class SeleniumJUnitClient { private static Properties props; private static final String PROPERTIES_FILENAME = "application.properties"; public static final String APP_PROP_KEY_IE_DRIVER_PATH = "ieDriverPath", APP_PROP_KEY_URL = "url", SYSTEM_PROP_KEY_IE_DRIVER_PATH = "webdriver.ie.driver"; private static WebDriver driver; private WebElement field; @BeforeClass public static void init() { final File exe; props = new Properties(); try { props.load( new FileInputStream(PROPERTIES_FILENAME) ); } catch( final IOException e ) { e.printStackTrace(); System.exit( -1 ); } exe = new File( props.getProperty(APP_PROP_KEY_IE_DRIVER_PATH) ); System.setProperty( SYSTEM_PROP_KEY_IE_DRIVER_PATH, exe.getAbsolutePath() ); driver = DriverFactory.newIeDriver(); driver.get( props.getProperty(APP_PROP_KEY_URL) ); } @Before public void setUp() { ((JavascriptExecutor) driver).executeScript( "setUp();" ); field = driver.findElement( By.id("field") ); } @After public void tearDown() { ((JavascriptExecutor) driver).executeScript( "tearDown();" ); } @Test public void alpha_ignoreInvalid_success() { final String val = "C"; initField( FieldType.ALPHA, true ); keypress( val ); assertEquals( val, getFieldValue() ); assertFalse( inputIgnoredEventFired() ); assertFalse( validationFailedEventFired() ); assertTrue( validationSuccessEventFired() ); } private void keypress( final String s ) { if( StringUtil.isNothing(s) ) throw new IllegalArgumentException( "keypress has no value" ); field.sendKeys( s ); } private void initField( final FieldType fieldType, final boolean ignoreInvalidInput ) { if( fieldType == null ) throw new IllegalArgumentException( "fieldType is null" ); final String command = String.format( "initField(\"%s\", %b);", fieldType.toString(), ignoreInvalidInput ); ((JavascriptExecutor) driver).executeScript( command ); } private String getFieldValue() { return field.getAttribute( "value" ); } private boolean inputIgnoredEventFired() { return (Boolean) ((JavascriptExecutor) driver).executeScript( "return didInputIgnoredEventFire();" ); } private boolean validationFailedEventFired() { return (Boolean) ((JavascriptExecutor) driver).executeScript( "return didValidationFailedEventFire();" ); } private boolean validationSuccessEventFired() { return (Boolean) ((JavascriptExecutor) driver).executeScript( "return didValidationSuccessEventFire();" ); } }
package fr.synchrotron.soleil.ica.ci.service.dormproxy; import io.netty.handler.codec.http.HttpResponseStatus; import org.vertx.java.core.*; import org.vertx.java.core.buffer.Buffer; import org.vertx.java.core.eventbus.Message; import org.vertx.java.core.http.HttpServerRequest; /** * @author Gregory Boissinot */ public class PUTPOMHandler implements Handler<HttpServerRequest> { private Vertx vertx; public PUTPOMHandler(Vertx vertx) { this.vertx = vertx; } @Override public void handle(final HttpServerRequest request) { String path = request.path(); System.out.println("PUT " + path); final Buffer body = new Buffer(); request.dataHandler(new Handler<Buffer>() { @Override public void handle(Buffer data) { body.appendBuffer(data); } }); request.exceptionHandler(new Handler<Throwable>() { @Override public void handle(Throwable throwable) { request.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); request.response().end(); } }); request.endHandler(new VoidHandler() { @Override protected void handle() { vertx.eventBus().sendWithTimeout( ServiceAddressRegistry.EB_ADDRESS_POMIMPORT_SERVICE, body.toString(), Integer.MAX_VALUE, new AsyncResultHandler<Message<Boolean>>() { @Override public void handle(AsyncResult<Message<Boolean>> asyncResult) { if (asyncResult.succeeded()) { request.response().setStatusCode(HttpResponseStatus.NO_CONTENT.code()); request.response().end(); } else { request.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); request.response().setStatusMessage(asyncResult.cause().getMessage()); request.response().end(); } } } ); } }); } }
package org.eclipse.birt.report.designer.data.ui.util; import java.io.File; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.report.designer.data.ui.dataset.DataSetUIUtil; import org.eclipse.birt.report.designer.data.ui.dataset.PromptParameterDialog; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.ReportPlugin; import org.eclipse.birt.report.designer.ui.preferences.DateSetPreferencePage; import org.eclipse.birt.report.model.adapter.oda.IAmbiguousOption; import org.eclipse.birt.report.model.adapter.oda.ModelOdaAdapter; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.OdaDataSetHandle; import org.eclipse.birt.report.model.api.OdaDataSourceHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.elements.structures.OdaDataSetParameter; import org.eclipse.datatools.connectivity.oda.OdaException; import org.eclipse.datatools.connectivity.oda.design.DataSetDesign; import org.eclipse.datatools.connectivity.oda.design.DataSourceDesign; import org.eclipse.datatools.connectivity.oda.design.DesignFactory; import org.eclipse.datatools.connectivity.oda.design.DesignSessionRequest; import org.eclipse.datatools.connectivity.oda.design.DesignSessionResponse; import org.eclipse.datatools.connectivity.oda.design.DesignerState; import org.eclipse.datatools.connectivity.oda.design.OdaDesignSession; import org.eclipse.datatools.connectivity.oda.design.SessionStatus; import org.eclipse.datatools.connectivity.oda.design.ui.designsession.DesignSessionUtil; import org.eclipse.datatools.connectivity.oda.util.ResourceIdentifiers; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.jface.dialogs.Dialog; /** * A Utility Class to handle procedures needed to be done <br> * before <code>edit</code> or after <code>finish</code> */ public class DTPUtil { private static DTPUtil instance = null; private SessionStatus sessionStatus = null; private DesignerState designerState = null; private ModelOdaAdapter modelOdaAdapter = new ModelOdaAdapter( ); private static final String SAMPELDB_DATA_SOURCE_ID = "org.eclipse.birt.report.data.oda.sampledb"; //$NON-NLS-1$ private static final String JDBC_DATA_SOURCE_ID = "org.eclipse.birt.report.data.oda.jdbc"; //$NON-NLS-1$ private static Logger logger = Logger.getLogger( DTPUtil.class.getName( ) ); private DTPUtil( ) { } public static synchronized DTPUtil getInstance( ) { if ( instance == null ) instance = new DTPUtil( ); return instance; } /** * update DataSourceHandle * * @param response * @param dataSourceHandle */ public void updateDataSourceHandle( DesignSessionResponse response, DataSourceDesign requestDesign, OdaDataSourceHandle dataSourceHandle ) { initDesignSessionFields( response ); if ( isSessionOk( ) ) { if ( new EcoreUtil.EqualityHelper( ).equals( requestDesign, response.getDataSourceDesign( ) ) ) return; try { updateROMDesignerState( dataSourceHandle ); modelOdaAdapter.updateDataSourceHandle( response.getDataSourceDesign( ), dataSourceHandle ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); } } } /** * update DataSetHandle * * @param response * @param dataSetHandle * @param isSourceChanged */ public void updateDataSetHandle( OdaDesignSession designSession, OdaDataSetHandle dataSetHandle ) { DataSetDesign requestDesign = designSession.getRequestDataSetDesign( ); DesignSessionResponse response = designSession.getResponse( ); initDesignSessionFields( response ); if ( isSessionOk( ) ) { if ( new EcoreUtil.EqualityHelper( ).equals( requestDesign, response.getDataSetDesign( ) ) ) return; try { modelOdaAdapter.updateDataSetHandle( dataSetHandle, designSession ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); } } } /** * update DataSetHandle * * @param response * @param dataSetHandle * @param isSourceChanged */ public void updateDataSetHandle( DesignSessionResponse response, DataSetDesign requestDesign, OdaDataSetHandle dataSetHandle, boolean isSourceChanged ) { initDesignSessionFields( response ); if ( isSessionOk( ) ) { EcoreUtil.EqualityHelper equalityHelper = new EcoreUtil.EqualityHelper( ); if ( equalityHelper.equals( response.getDataSetDesign( ), requestDesign ) && equalityHelper.equals( response.getDesignerState( ), this.designerState ) ) return; try { DataSetDesign design = response.getDataSetDesign( ); if ( ReportPlugin.getDefault( ) .getPluginPreferences( ) .getBoolean( DateSetPreferencePage.PROMPT_ENABLE ) == true ) { IAmbiguousOption ambiguousOption = modelOdaAdapter.getAmbiguousOption( design, dataSetHandle ); if ( ambiguousOption != null && !ambiguousOption.getAmbiguousParameters( ) .isEmpty( ) ) { PromptParameterDialog dialog = new PromptParameterDialog( Messages.getString( "PromptParameterDialog.title" ) ); dialog.setInput( ambiguousOption ); if ( dialog.open( ) == Dialog.OK ) { Object result = dialog.getResult( ); if ( result instanceof List ) { List<OdaDataSetParameter> selectedParameters = (List) result; updateROMDesignerState( dataSetHandle ); modelOdaAdapter.updateDataSetHandle( design, dataSetHandle, selectedParameters, null, isSourceChanged ); DataSetUIUtil.updateColumnCacheAfterCleanRs( dataSetHandle ); return; } } else { updateROMDesignerState( dataSetHandle ); modelOdaAdapter.updateDataSetHandle( design, dataSetHandle, isSourceChanged ); DataSetUIUtil.updateColumnCacheAfterCleanRs( dataSetHandle ); return; } } } updateROMDesignerState( dataSetHandle ); modelOdaAdapter.updateDataSetHandle( design, dataSetHandle, isSourceChanged ); DataSetUIUtil.updateColumnCacheAfterCleanRs( dataSetHandle ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); } } return; } /** * create OdaDataSourceHandle * * @param response * @param parentHandle * @return * @throws SemanticException */ public OdaDataSourceHandle createOdaDataSourceHandle( DesignSessionResponse response, ModuleHandle parentHandle ) throws SemanticException { initDesignSessionFields( response ); OdaDataSourceHandle dataSourceHandle = null; if ( isSessionOk( ) ) { DataSourceDesign dataSourceDesign = response.getDataSourceDesign( ); if ( dataSourceDesign.getOdaExtensionId( ) .equals( SAMPELDB_DATA_SOURCE_ID ) ) { dataSourceDesign.setOdaExtensionId( JDBC_DATA_SOURCE_ID ); } try { dataSourceHandle = modelOdaAdapter.createDataSourceHandle( dataSourceDesign, parentHandle ); updateROMDesignerState( dataSourceHandle ); } catch ( SemanticException e ) { throw e; } } return dataSourceHandle; } /** * create OdaDataSetHandle * * @param response * @param parentHandle * @return * @throws OdaException * @throws SemanticException */ public OdaDataSetHandle createOdaDataSetHandle( DesignSessionResponse response, ModuleHandle parentHandle ) throws SemanticException { initDesignSessionFields( response ); OdaDataSetHandle dataSetHandle = null; if ( isSessionOk( ) ) { try { dataSetHandle = modelOdaAdapter.createDataSetHandle( response.getDataSetDesign( ), parentHandle ); updateROMDesignerState( dataSetHandle ); } catch ( SemanticException e ) { throw e; } } return dataSetHandle; } /** * create DesignSessionRequest * * @param dataSourceHandle * @return * @throws URISyntaxException */ public DesignSessionRequest createDesignSessionRequest( OdaDataSourceHandle dataSourceHandle ) throws URISyntaxException { DataSourceDesign dataSourceDesign = modelOdaAdapter.createDataSourceDesign( dataSourceHandle ); DesignSessionUtil.setDataSourceResourceIdentifiers( dataSourceDesign, getBIRTResourcePath( ), getReportDesignPath( ) ); DesignSessionRequest designSessionRequest = DesignFactory.eINSTANCE.createDesignSessionRequest( dataSourceDesign ); designerState = modelOdaAdapter.newOdaDesignerState( dataSourceHandle ); if ( designerState != null ) designSessionRequest.setDesignerState( designerState ); return designSessionRequest; } /** * Applies the ResourceIdentifiers instance to the specified DataSourceDesign * * @param dataSourceDesign * @throws URISyntaxException * @throws MalformedURLException */ public void applyResourceIdentifiers( DataSourceDesign dataSourceDesign ) throws URISyntaxException { if ( Utility.getReportModuleHandle( ) == null ) { return; } DesignSessionUtil.setDataSourceResourceIdentifiers( dataSourceDesign, getBIRTResourcePath( ), getReportDesignPath( ) ); } /** * Gets the BIRT resource path * * @return * @throws URISyntaxException */ public URI getReportDesignPath( ) { if ( Utility.getReportModuleHandle( ) == null || Utility.getReportModuleHandle( ).getSystemId( ) == null ) { return null; } try { return new URI( Utility.getReportModuleHandle( ) .getSystemId( ) .getPath( ) ); } catch ( URISyntaxException e ) { return null; } } /** * Gets the report design file path * * @return */ public URI getBIRTResourcePath( ) { try { return new URI( encode( ReportPlugin.getDefault( ) .getResourceFolder( UIUtil.getCurrentProject( ), (ModuleHandle) null ) ) ); } catch ( URISyntaxException e ) { return null; } } private String encode( String location ) { try { return new File( location ).toURI( ) .toASCIIString( ) .replace( new File( "" ).toURI( ).toASCIIString( ), "" ); //$NON-NLS-1$//$NON-NLS-2$ } catch ( Exception e ) { return location; } } /** * Create a DesignSessionRequest with the specified dataSetHandle * * @param dataSetHandle * @return */ public DesignSessionRequest createDesignSessionRequest( OdaDataSetHandle dataSetHandle ) { return modelOdaAdapter.createOdaDesignSession( dataSetHandle ) .getRequest( ); } /** * Create a DesignSessionRequest with the specified dataSetDesign and * designerState. * * @param dataSetDesign * @param designerState * @return */ public DesignSessionRequest createDesignSessionRequest( DataSetDesign requestDataSetDesign, DesignerState requestDesignerState ) { DesignSessionRequest newRequest = DesignFactory.eINSTANCE.createDesignSessionRequest( requestDataSetDesign ); designerState = requestDesignerState; newRequest.setDesignerState( requestDesignerState ); return newRequest; } /** * * @param dataSetDesign * @param handle */ public void updateDataSetDesign( DesignSessionResponse response, DataSetHandle handle, String propName ) { initDesignSessionFields( response ); if ( isSessionOk( ) ) { modelOdaAdapter.updateDataSetDesign( (OdaDataSetHandle) handle, response.getDataSetDesign( ), propName ); } } /** * assign values to the fields of current session * * @param response * @throws OdaException */ private void initDesignSessionFields( DesignSessionResponse response ) { sessionStatus = response.getSessionStatus( ); designerState = response.getDesignerState( ); } /** * check the status of current session * * @throws OdaException */ private boolean isSessionOk( ) { assert sessionStatus != null; if ( sessionStatus.getValue( ) != SessionStatus.OK ) { logger.log( Level.WARNING, Messages.getFormattedString( "dataset.warning.invalidReponseStatus", new Object[]{ sessionStatus.toString( ) } ) ); return false; } return true; } /** * update ROMDesignerState * * @param obj * @throws SemanticException */ private void updateROMDesignerState( Object obj ) throws SemanticException { if ( designerState == null || obj == null ) return; if ( obj instanceof OdaDataSourceHandle ) modelOdaAdapter.updateROMDesignerState( designerState, (OdaDataSourceHandle) obj ); else if ( obj instanceof OdaDataSetHandle ) modelOdaAdapter.updateROMDesignerState( designerState, (OdaDataSetHandle) obj ); } public IAmbiguousOption getAmbiguousOption( DataSetDesign design, OdaDataSetHandle handle ) { return modelOdaAdapter.getAmbiguousOption( design, handle ); } public ResourceIdentifiers createResourceIdentifiers( ) { ResourceIdentifiers ri = new ResourceIdentifiers( ); ri.setDesignResourceBaseURI( getReportDesignPath() ); ri.setApplResourceBaseURI( getBIRTResourcePath() ); return ri; } }
package im.actor.core.modules.messaging.actions; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import im.actor.core.api.ApiDocumentExAnimation; import im.actor.core.api.ApiDocumentExVoice; import im.actor.core.api.ApiFastThumb; import im.actor.core.api.ApiJsonMessage; import im.actor.core.api.ApiMessage; import im.actor.core.api.ApiPeer; import im.actor.core.api.ApiDocumentEx; import im.actor.core.api.ApiDocumentExPhoto; import im.actor.core.api.ApiDocumentExVideo; import im.actor.core.api.ApiDocumentMessage; import im.actor.core.api.ApiOutPeer; import im.actor.core.api.ApiTextMessage; import im.actor.core.api.base.SeqUpdate; import im.actor.core.api.rpc.RequestSendMessage; import im.actor.core.api.rpc.ResponseSeqDate; import im.actor.core.api.updates.UpdateMessageSent; import im.actor.core.entity.FileReference; import im.actor.core.entity.Group; import im.actor.core.entity.GroupMember; import im.actor.core.entity.Message; import im.actor.core.entity.MessageState; import im.actor.core.entity.Peer; import im.actor.core.entity.PeerType; import im.actor.core.entity.User; import im.actor.core.entity.content.AbsContent; import im.actor.core.entity.content.AnimationContent; import im.actor.core.entity.content.ContactContent; import im.actor.core.entity.content.DocumentContent; import im.actor.core.entity.content.FastThumb; import im.actor.core.entity.content.FileLocalSource; import im.actor.core.entity.content.FileRemoteSource; import im.actor.core.entity.content.JsonContent; import im.actor.core.entity.content.LocationContent; import im.actor.core.entity.content.PhotoContent; import im.actor.core.entity.content.StickerContent; import im.actor.core.entity.content.TextContent; import im.actor.core.entity.content.VideoContent; import im.actor.core.entity.content.VoiceContent; import im.actor.core.entity.Sticker; import im.actor.core.entity.content.internal.ContentRemoteContainer; import im.actor.core.modules.ModuleContext; import im.actor.core.modules.file.UploadManager; import im.actor.core.modules.messaging.actions.entity.PendingMessage; import im.actor.core.modules.messaging.actions.entity.PendingMessagesStorage; import im.actor.core.modules.ModuleActor; import im.actor.core.util.RandomUtils; import im.actor.core.network.RpcCallback; import im.actor.core.network.RpcException; import im.actor.runtime.*; import im.actor.runtime.Runtime; import im.actor.runtime.power.WakeLock; /*-[ #pragma clang diagnostic ignored "-Wnullability-completeness" ]-*/ public class SenderActor extends ModuleActor { private static final String PREFERENCES = "sender_pending"; private PendingMessagesStorage pendingMessages; private long lastSendDate = 0; private HashMap<Long, WakeLock> fileUplaodingWakeLocks = new HashMap<>(); public SenderActor(ModuleContext context) { super(context); } @Override public void preStart() { pendingMessages = new PendingMessagesStorage(); byte[] p = preferences().getBytes(PREFERENCES); if (p != null) { try { pendingMessages = PendingMessagesStorage.fromBytes(p); } catch (IOException e) { e.printStackTrace(); } } boolean isChanged = false; ArrayList<PendingMessage> messages = pendingMessages.getPendingMessages(); for (PendingMessage pending : messages.toArray(new PendingMessage[messages.size()])) { if (pending.getContent() instanceof TextContent) { performSendContent(pending.getPeer(), pending.getRid(), pending.getContent()); } else if (pending.getContent() instanceof DocumentContent) { DocumentContent documentContent = (DocumentContent) pending.getContent(); if (documentContent.getSource() instanceof FileLocalSource) { if (Storage.isFsPersistent()) { performUploadFile(pending.getRid(), ((FileLocalSource) documentContent.getSource()).getFileDescriptor(), ((FileLocalSource) documentContent.getSource()).getFileName()); } else { List<Long> rids = new ArrayList<>(); rids.add(pending.getRid()); context().getMessagesModule().getRouter().onMessagesDeleted(pending.getPeer(), rids); pendingMessages.getPendingMessages().remove(pending); isChanged = true; } } else { performSendContent(pending.getPeer(), pending.getRid(), pending.getContent()); } } } if (isChanged) { savePending(); } } private long createPendingDate() { long res = im.actor.runtime.Runtime.getCurrentSyncedTime(); if (lastSendDate >= res) { res = lastSendDate + 1; } lastSendDate = res; return res; } // Sending text public void doSendText(@NotNull Peer peer, @NotNull String text, @Nullable ArrayList<Integer> mentions, /*Ignored*/ @Nullable String markDownText, boolean autoDetect) { text = text.trim(); long rid = RandomUtils.nextRid(); long date = createPendingDate(); long sortDate = date + 365 * 24 * 60 * 60 * 1000L; if (autoDetect) { mentions = new ArrayList<>(); if (peer.getPeerType() == PeerType.GROUP) { Group group = getGroup(peer.getPeerId()); String lowText = text.toLowerCase(); for (GroupMember member : group.getMembers()) { User user = getUser(member.getUid()); if (user.getNick() != null) { String nick = "@" + user.getNick().toLowerCase(); // TODO: Better filtering if (lowText.contains(nick + ":") || lowText.contains(nick + " ") || lowText.contains(" " + nick) || lowText.endsWith(nick) || lowText.equals(nick)) { mentions.add(user.getUid()); } } } } } TextContent content = TextContent.create(text, null, mentions); Message message = new Message(rid, sortDate, date, myUid(), MessageState.PENDING, content); context().getMessagesModule().getRouter().onOutgoingMessage(peer, message); pendingMessages.getPendingMessages().add(new PendingMessage(peer, rid, content)); savePending(); performSendContent(peer, rid, content); } public void doSendJson(Peer peer, JsonContent content) { long rid = RandomUtils.nextRid(); long date = createPendingDate(); long sortDate = date + 365 * 24 * 60 * 60 * 1000L; Message message = new Message(rid, sortDate, date, myUid(), MessageState.PENDING, content); context().getMessagesModule().getRouter().onOutgoingMessage(peer, message); pendingMessages.getPendingMessages().add(new PendingMessage(peer, rid, content)); savePending(); performSendContent(peer, rid, content); } // Sending sticker public void doSendSticker(@NotNull Peer peer, @NotNull Sticker sticker) { long rid = RandomUtils.nextRid(); long date = createPendingDate(); long sortDate = date + 365 * 24 * 60 * 60 * 1000L; StickerContent content = StickerContent.create(sticker); Message message = new Message(rid, sortDate, date, myUid(), MessageState.PENDING, content); context().getMessagesModule().getRouter().onOutgoingMessage(peer, message); pendingMessages.getPendingMessages().add(new PendingMessage(peer, rid, content)); savePending(); performSendContent(peer, rid, content); } public void doSendContact(@NotNull Peer peer, @NotNull ArrayList<String> emails, @NotNull ArrayList<String> phones, @Nullable String name, @Nullable String base64photo) { long rid = RandomUtils.nextRid(); long date = createPendingDate(); long sortDate = date + 365 * 24 * 60 * 60 * 1000L; ContactContent content = ContactContent.create(name, phones, emails, base64photo); Message message = new Message(rid, sortDate, date, myUid(), MessageState.PENDING, content); context().getMessagesModule().getRouter().onOutgoingMessage(peer, message); pendingMessages.getPendingMessages().add(new PendingMessage(peer, rid, content)); savePending(); performSendContent(peer, rid, content); } public void doSendLocation(@NotNull Peer peer, @NotNull Double longitude, @NotNull Double latitude, @Nullable String street, @Nullable String place) { long rid = RandomUtils.nextRid(); long date = createPendingDate(); long sortDate = date + 365 * 24 * 60 * 60 * 1000L; LocationContent content = LocationContent.create(longitude, latitude, street, place); Message message = new Message(rid, sortDate, date, myUid(), MessageState.PENDING, content); context().getMessagesModule().getRouter().onOutgoingMessage(peer, message); pendingMessages.getPendingMessages().add(new PendingMessage(peer, rid, content)); savePending(); performSendContent(peer, rid, content); } public void doForwardContent(Peer peer, AbsContent content) { long rid = RandomUtils.nextRid(); long date = createPendingDate(); long sortDate = date + 365 * 24 * 60 * 60 * 1000L; Message message = new Message(rid, sortDate, date, myUid(), MessageState.PENDING, content); context().getMessagesModule().getRouter().onOutgoingMessage(peer, message); pendingMessages.getPendingMessages().add(new PendingMessage(peer, rid, content)); savePending(); performSendContent(peer, rid, content); } // Sending documents public void doSendDocument(Peer peer, String fileName, String mimeType, int fileSize, FastThumb fastThumb, String descriptor) { long rid = RandomUtils.nextRid(); long date = createPendingDate(); long sortDate = date + 365 * 24 * 60 * 60 * 1000L; DocumentContent documentContent = DocumentContent.createLocal(fileName, fileSize, descriptor, mimeType, fastThumb); Message message = new Message(rid, sortDate, date, myUid(), MessageState.PENDING, documentContent); context().getMessagesModule().getRouter().onOutgoingMessage(peer, message); pendingMessages.getPendingMessages().add(new PendingMessage(peer, rid, documentContent)); savePending(); performUploadFile(rid, descriptor, fileName); } public void doSendPhoto(Peer peer, FastThumb fastThumb, String descriptor, String fileName, int fileSize, int w, int h) { long rid = RandomUtils.nextRid(); long date = createPendingDate(); long sortDate = date + 365 * 24 * 60 * 60 * 1000L; PhotoContent photoContent = PhotoContent.createLocalPhoto(descriptor, fileName, fileSize, w, h, fastThumb); Message message = new Message(rid, sortDate, date, myUid(), MessageState.PENDING, photoContent); context().getMessagesModule().getRouter().onOutgoingMessage(peer, message); pendingMessages.getPendingMessages().add(new PendingMessage(peer, rid, photoContent)); savePending(); performUploadFile(rid, descriptor, fileName); } public void doSendAudio(Peer peer, String descriptor, String fileName, int fileSize, int duration) { long rid = RandomUtils.nextRid(); long date = createPendingDate(); long sortDate = date + 365 * 24 * 60 * 60 * 1000L; VoiceContent audioContent = VoiceContent.createLocalAudio(descriptor, fileName, fileSize, duration); Message message = new Message(rid, sortDate, date, myUid(), MessageState.PENDING, audioContent); context().getMessagesModule().getRouter().onOutgoingMessage(peer, message); pendingMessages.getPendingMessages().add(new PendingMessage(peer, rid, audioContent)); savePending(); performUploadFile(rid, descriptor, fileName); } public void doSendVideo(Peer peer, String fileName, int w, int h, int duration, FastThumb fastThumb, String descriptor, int fileSize) { long rid = RandomUtils.nextRid(); long date = createPendingDate(); long sortDate = date + 365 * 24 * 60 * 60 * 1000L; VideoContent videoContent = VideoContent.createLocalVideo(descriptor, fileName, fileSize, w, h, duration, fastThumb); Message message = new Message(rid, sortDate, date, myUid(), MessageState.PENDING, videoContent); context().getMessagesModule().getRouter().onOutgoingMessage(peer, message); pendingMessages.getPendingMessages().add(new PendingMessage(peer, rid, videoContent)); savePending(); performUploadFile(rid, descriptor, fileName); } public void doSendAnimation(Peer peer, String fileName, int w, int h, FastThumb fastThumb, String descriptor, int fileSize) { long rid = RandomUtils.nextRid(); long date = createPendingDate(); long sortDate = date + 365 * 24 * 60 * 60 * 1000L; AnimationContent animationContent = AnimationContent.createLocalAnimation(descriptor, fileName, fileSize, w, h, fastThumb); Message message = new Message(rid, sortDate, date, myUid(), MessageState.PENDING, animationContent); context().getMessagesModule().getRouter().onOutgoingMessage(peer, message); pendingMessages.getPendingMessages().add(new PendingMessage(peer, rid, animationContent)); savePending(); performUploadFile(rid, descriptor, fileName); } private void performUploadFile(long rid, String descriptor, String fileName) { fileUplaodingWakeLocks.put(rid, Runtime.makeWakeLock()); context().getFilesModule().requestUpload(rid, descriptor, fileName, self()); } private void onFileUploaded(long rid, FileReference fileReference) { PendingMessage msg = findPending(rid); if (msg == null) { return; } pendingMessages.getPendingMessages().remove(msg); AbsContent nContent; if (msg.getContent() instanceof PhotoContent) { PhotoContent basePhotoContent = (PhotoContent) msg.getContent(); nContent = PhotoContent.createRemotePhoto(fileReference, basePhotoContent.getW(), basePhotoContent.getH(), basePhotoContent.getFastThumb()); } else if (msg.getContent() instanceof VideoContent) { VideoContent baseVideoContent = (VideoContent) msg.getContent(); nContent = VideoContent.createRemoteVideo(fileReference, baseVideoContent.getW(), baseVideoContent.getH(), baseVideoContent.getDuration(), baseVideoContent.getFastThumb()); } else if (msg.getContent() instanceof VoiceContent) { VoiceContent baseVoiceContent = (VoiceContent) msg.getContent(); nContent = VoiceContent.createRemoteAudio(fileReference, baseVoiceContent.getDuration()); } else if (msg.getContent() instanceof AnimationContent) { AnimationContent baseAnimcationContent = (AnimationContent) msg.getContent(); nContent = AnimationContent.createRemoteAnimation(fileReference, baseAnimcationContent.getW(), baseAnimcationContent.getH(), baseAnimcationContent.getFastThumb()); } else if (msg.getContent() instanceof DocumentContent) { DocumentContent baseDocContent = (DocumentContent) msg.getContent(); nContent = DocumentContent.createRemoteDocument(fileReference, baseDocContent.getFastThumb()); } else { return; } pendingMessages.getPendingMessages().add(new PendingMessage(msg.getPeer(), msg.getRid(), nContent)); context().getMessagesModule().getRouter().onContentChanged(msg.getPeer(), msg.getRid(), nContent); performSendContent(msg.getPeer(), rid, nContent); fileUplaodingWakeLocks.remove(rid).releaseLock(); } private void onFileUploadError(long rid) { PendingMessage msg = findPending(rid); if (msg == null) { return; } self().send(new MessageError(msg.getPeer(), msg.getRid())); fileUplaodingWakeLocks.remove(rid).releaseLock(); } // Sending content private void performSendContent(final Peer peer, final long rid, AbsContent content) { WakeLock wakeLock = im.actor.runtime.Runtime.makeWakeLock(); ApiMessage message; if (content instanceof TextContent) { message = new ApiTextMessage(((TextContent) content).getText(), ((TextContent) content).getMentions(), ((TextContent) content).getTextMessageEx()); } else if (content instanceof DocumentContent) { DocumentContent documentContent = (DocumentContent) content; FileRemoteSource source = (FileRemoteSource) documentContent.getSource(); ApiDocumentEx documentEx = null; if (content instanceof PhotoContent) { PhotoContent photoContent = (PhotoContent) content; documentEx = new ApiDocumentExPhoto(photoContent.getW(), photoContent.getH()); } else if (content instanceof VideoContent) { VideoContent videoContent = (VideoContent) content; documentEx = new ApiDocumentExVideo(videoContent.getW(), videoContent.getH(), videoContent.getDuration()); } else if (content instanceof AnimationContent) { AnimationContent animationContent = (AnimationContent) content; documentEx = new ApiDocumentExAnimation(animationContent.getW(), animationContent.getH()); } else if (content instanceof VoiceContent) { VoiceContent voiceContent = (VoiceContent) content; documentEx = new ApiDocumentExVoice(voiceContent.getDuration()); } ApiFastThumb fastThumb = null; if (documentContent.getFastThumb() != null) { fastThumb = new ApiFastThumb( documentContent.getFastThumb().getW(), documentContent.getFastThumb().getH(), documentContent.getFastThumb().getImage()); } message = new ApiDocumentMessage(source.getFileReference().getFileId(), source.getFileReference().getAccessHash(), source.getFileReference().getFileSize(), source.getFileReference().getFileName(), documentContent.getMimeType(), fastThumb, documentEx); } else if (content instanceof LocationContent) { message = new ApiJsonMessage(((LocationContent) content).getRawJson()); } else if (content instanceof ContactContent) { message = new ApiJsonMessage(((ContactContent) content).getRawJson()); } else if (content instanceof JsonContent) { message = new ApiJsonMessage(((JsonContent) content).getRawJson()); } else if (content instanceof StickerContent) { message = ((ContentRemoteContainer) content.getContentContainer()).getMessage(); } else { return; } performSendApiContent(peer, rid, message, wakeLock); } private void performSendApiContent(final Peer peer, final long rid, ApiMessage message, final WakeLock wakeLock) { final ApiOutPeer outPeer = buidOutPeer(peer); final ApiPeer apiPeer = buildApiPeer(peer); if (outPeer == null || apiPeer == null) { return; } request(new RequestSendMessage(outPeer, rid, message, null, null), new RpcCallback<ResponseSeqDate>() { @Override public void onResult(ResponseSeqDate response) { self().send(new MessageSent(peer, rid)); updates().onUpdateReceived(new SeqUpdate(response.getSeq(), response.getState(), UpdateMessageSent.HEADER, new UpdateMessageSent(apiPeer, rid, response.getDate()).toByteArray())); wakeLock.releaseLock(); } @Override public void onError(RpcException e) { self().send(new MessageError(peer, rid)); wakeLock.releaseLock(); } }); } private void onSent(Peer peer, long rid) { for (PendingMessage pending : pendingMessages.getPendingMessages()) { if (pending.getRid() == rid && pending.getPeer().equals(peer)) { pendingMessages.getPendingMessages().remove(pending); break; } } savePending(); } private void onError(Peer peer, long rid) { for (PendingMessage pending : pendingMessages.getPendingMessages()) { if (pending.getRid() == rid && pending.getPeer().equals(peer)) { pendingMessages.getPendingMessages().remove(pending); break; } } savePending(); context().getMessagesModule().getRouter().onOutgoingError(peer, rid); } private void savePending() { preferences().putBytes(PREFERENCES, pendingMessages.toByteArray()); } private PendingMessage findPending(long rid) { for (PendingMessage message : pendingMessages.getPendingMessages()) { if (message.getRid() == rid) { return message; } } return null; } //region Messages @Override public void onReceive(Object message) { if (message instanceof SendText) { SendText sendText = (SendText) message; doSendText(sendText.getPeer(), sendText.getText(), sendText.getMentions(), sendText.getMarkDownText(), sendText.isAutoDetect()); } else if (message instanceof MessageSent) { MessageSent messageSent = (MessageSent) message; onSent(messageSent.getPeer(), messageSent.getRid()); } else if (message instanceof MessageError) { MessageError messageError = (MessageError) message; onError(messageError.getPeer(), messageError.getRid()); } else if (message instanceof SendDocument) { SendDocument sendDocument = (SendDocument) message; doSendDocument(sendDocument.getPeer(), sendDocument.getFileName(), sendDocument.getMimeType(), sendDocument.getFileSize(), sendDocument.getFastThumb(), sendDocument.getDescriptor()); } else if (message instanceof UploadManager.UploadCompleted) { UploadManager.UploadCompleted uploadCompleted = (UploadManager.UploadCompleted) message; onFileUploaded(uploadCompleted.getRid(), uploadCompleted.getFileReference()); } else if (message instanceof UploadManager.UploadError) { UploadManager.UploadError uploadError = (UploadManager.UploadError) message; onFileUploadError(uploadError.getRid()); } else if (message instanceof SendPhoto) { SendPhoto sendPhoto = (SendPhoto) message; doSendPhoto(sendPhoto.getPeer(), sendPhoto.getFastThumb(), sendPhoto.getDescriptor(), sendPhoto.getFileName(), sendPhoto.getFileSize(), sendPhoto.getW(), sendPhoto.getH()); } else if (message instanceof SendVideo) { SendVideo sendVideo = (SendVideo) message; doSendVideo(sendVideo.getPeer(), sendVideo.getFileName(), sendVideo.getW(), sendVideo.getH(), sendVideo.getDuration(), sendVideo.getFastThumb(), sendVideo.getDescriptor(), sendVideo.getFileSize()); } else if (message instanceof SendAudio) { SendAudio sendAudio = (SendAudio) message; doSendAudio(sendAudio.getPeer(), sendAudio.getDescriptor(), sendAudio.getFileName(), sendAudio.getFileSize(), sendAudio.getDuration()); } else if (message instanceof SendContact) { SendContact sendContact = (SendContact) message; doSendContact(sendContact.getPeer(), sendContact.getEmails(), sendContact.getPhones(), sendContact.getName(), sendContact.getBase64photo()); } else if (message instanceof SendLocation) { SendLocation sendLocation = (SendLocation) message; doSendLocation(sendLocation.getPeer(), sendLocation.getLongitude(), sendLocation.getLatitude(), sendLocation.getStreet(), sendLocation.getPlace()); } else if (message instanceof SendSticker) { SendSticker sendSticker = (SendSticker) message; doSendSticker(sendSticker.getPeer(), sendSticker.getSticker()); } else if (message instanceof SendJson) { SendJson sendJson = (SendJson) message; doSendJson(sendJson.getPeer(), sendJson.getJson()); } else if (message instanceof ForwardContent) { ForwardContent forwardContent = (ForwardContent) message; doForwardContent(forwardContent.getPeer(), forwardContent.getContent()); } else if (message instanceof SendAnimation) { SendAnimation animation = (SendAnimation) message; doSendAnimation(animation.getPeer(), animation.getFileName(), animation.getW(), animation.getH(), animation.getFastThumb(), animation.getDescriptor(), animation.getFileSize()); } else { super.onReceive(message); } } public static class SendDocument { private Peer peer; private FastThumb fastThumb; private String descriptor; private String fileName; private String mimeType; private int fileSize; public SendDocument(Peer peer, String fileName, String mimeType, int fileSize, String descriptor, FastThumb fastThumb) { this.peer = peer; this.fastThumb = fastThumb; this.descriptor = descriptor; this.fileName = fileName; this.mimeType = mimeType; this.fileSize = fileSize; } public FastThumb getFastThumb() { return fastThumb; } public int getFileSize() { return fileSize; } public String getFileName() { return fileName; } public String getMimeType() { return mimeType; } public Peer getPeer() { return peer; } public String getDescriptor() { return descriptor; } } public static class ForwardContent { private Peer peer; private AbsContent content; public ForwardContent(Peer peer, AbsContent remoteContent) { this.peer = peer; this.content = remoteContent; } public Peer getPeer() { return peer; } public AbsContent getContent() { return content; } } public static class SendPhoto { private Peer peer; private FastThumb fastThumb; private String descriptor; private String fileName; private int fileSize; private int w; private int h; public SendPhoto(Peer peer, FastThumb fastThumb, String descriptor, String fileName, int fileSize, int w, int h) { this.peer = peer; this.fastThumb = fastThumb; this.descriptor = descriptor; this.fileName = fileName; this.fileSize = fileSize; this.w = w; this.h = h; } public Peer getPeer() { return peer; } public FastThumb getFastThumb() { return fastThumb; } public String getDescriptor() { return descriptor; } public String getFileName() { return fileName; } public int getFileSize() { return fileSize; } public int getW() { return w; } public int getH() { return h; } } public static class SendAnimation { private Peer peer; private FastThumb fastThumb; private String descriptor; private String fileName; private int fileSize; private int w; private int h; public SendAnimation(Peer peer, FastThumb fastThumb, String descriptor, String fileName, int fileSize, int w, int h) { this.peer = peer; this.fastThumb = fastThumb; this.descriptor = descriptor; this.fileName = fileName; this.fileSize = fileSize; this.w = w; this.h = h; } public Peer getPeer() { return peer; } public FastThumb getFastThumb() { return fastThumb; } public String getDescriptor() { return descriptor; } public String getFileName() { return fileName; } public int getFileSize() { return fileSize; } public int getW() { return w; } public int getH() { return h; } } public static class SendVideo { private Peer peer; private String fileName; private int w; private int h; private int duration; private FastThumb fastThumb; private String descriptor; private int fileSize; public SendVideo(Peer peer, String fileName, int w, int h, int duration, FastThumb fastThumb, String descriptor, int fileSize) { this.peer = peer; this.fileName = fileName; this.w = w; this.h = h; this.duration = duration; this.fastThumb = fastThumb; this.descriptor = descriptor; this.fileSize = fileSize; } public Peer getPeer() { return peer; } public String getFileName() { return fileName; } public int getW() { return w; } public int getH() { return h; } public int getDuration() { return duration; } public FastThumb getFastThumb() { return fastThumb; } public String getDescriptor() { return descriptor; } public int getFileSize() { return fileSize; } } public static class SendAudio { private Peer peer; private String descriptor; private String fileName; private int fileSize; private int duration; public SendAudio(Peer peer, String descriptor, String fileName, int fileSize, int duration) { this.peer = peer; this.descriptor = descriptor; this.fileName = fileName; this.fileSize = fileSize; this.duration = duration; } public Peer getPeer() { return peer; } public int getDuration() { return duration; } public String getDescriptor() { return descriptor; } public String getFileName() { return fileName; } public int getFileSize() { return fileSize; } } public static class SendText { private Peer peer; private String text; private String markDownText; private ArrayList<Integer> mentions; private boolean autoDetect; public SendText(@NotNull Peer peer, @NotNull String text, @Nullable String markDownText, @Nullable ArrayList<Integer> mentions, boolean autoDetect) { this.peer = peer; this.text = text; this.markDownText = markDownText; this.mentions = mentions; this.autoDetect = autoDetect; } public Peer getPeer() { return peer; } public String getText() { return text; } public String getMarkDownText() { return markDownText; } public ArrayList<Integer> getMentions() { return mentions; } public boolean isAutoDetect() { return autoDetect; } } public static class SendContact { private Peer peer; private ArrayList<String> phones; private ArrayList<String> emails; private String name; private String base64photo; public SendContact(Peer peer, ArrayList<String> phones, ArrayList<String> emails, String name, String base64photo) { this.peer = peer; this.phones = phones; this.emails = emails; this.name = name; this.base64photo = base64photo; } public Peer getPeer() { return peer; } public ArrayList<String> getPhones() { return phones; } public ArrayList<String> getEmails() { return emails; } public String getName() { return name; } public String getBase64photo() { return base64photo; } } public static class MessageSent { private Peer peer; private long rid; public MessageSent(Peer peer, long rid) { this.peer = peer; this.rid = rid; } public Peer getPeer() { return peer; } public long getRid() { return rid; } } public static class MessageError { private Peer peer; private long rid; public MessageError(Peer peer, long rid) { this.peer = peer; this.rid = rid; } public Peer getPeer() { return peer; } public long getRid() { return rid; } } public static class SendLocation { private Peer peer; private Double longitude; private Double latitude; private String street; private String place; public SendLocation(@NotNull Peer peer, @NotNull Double longitude, @NotNull Double latitude, @Nullable String street, @Nullable String place) { this.peer = peer; this.longitude = longitude; this.latitude = latitude; this.place = place; this.street = street; } public Peer getPeer() { return peer; } public Double getLongitude() { return longitude; } public Double getLatitude() { return latitude; } public String getStreet() { return street; } public String getPlace() { return place; } } public static class SendSticker { private Peer peer; private Sticker sticker; public SendSticker(@NotNull Peer peer, @NotNull Sticker sticker) { this.peer = peer; this.sticker = sticker; } public Peer getPeer() { return peer; } public Sticker getSticker() { return sticker; } } public static class SendJson { private Peer peer; private JsonContent json; public SendJson(Peer peer, JsonContent json) { this.json = json; this.peer = peer; } public JsonContent getJson() { return json; } public Peer getPeer() { return peer; } } //endregion }
package nodomain.freeyourgadget.gadgetbridge.activities.charts; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import androidx.fragment.app.FragmentManager; import com.github.mikephil.charting.charts.Chart; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Calendar; import java.util.Date; import java.util.List; import nodomain.freeyourgadget.gadgetbridge.GBApplication; import nodomain.freeyourgadget.gadgetbridge.R; import nodomain.freeyourgadget.gadgetbridge.database.DBHandler; import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice; import nodomain.freeyourgadget.gadgetbridge.model.ActivitySample; import nodomain.freeyourgadget.gadgetbridge.model.ActivitySession; import nodomain.freeyourgadget.gadgetbridge.util.DateTimeUtils; public class ActivityListingChartFragment extends AbstractChartFragment { protected static final Logger LOG = LoggerFactory.getLogger(ActivityListingChartFragment.class); int tsDateTo; private View rootView; private ActivityListingAdapter stepListAdapter; private TextView stepsDateView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_steps_list, container, false); getChartsHost().enableSwipeRefresh(false); ListView stepsList = rootView.findViewById(R.id.itemListView); stepListAdapter = new ActivityListingAdapter(getContext()); stepsList.setAdapter(stepListAdapter); stepsList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { ActivitySession item = stepListAdapter.getItem(i); if (item.getSessionType() != ActivitySession.SESSION_SUMMARY) { int tsFrom = (int) (item.getStartTime().getTime() / 1000); int tsTo = (int) (item.getEndTime().getTime() / 1000); showDetail(tsFrom, tsTo, item, getChartsHost().getDevice()); } } }); stepsDateView = rootView.findViewById(R.id.stepsDateView); FloatingActionButton fab; fab = rootView.findViewById(R.id.fab); fab.setVisibility(View.VISIBLE); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDashboard(tsDateTo, getChartsHost().getDevice()); } }); refresh(); return rootView; } @Override public String getTitle() { return "Steps list"; } @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ChartsHost.REFRESH)) { // TODO: use LimitLines to visualize smart alarms? refresh(); } else { super.onReceive(context, intent); } } @Override protected ChartsData refreshInBackground(ChartsHost chartsHost, DBHandler db, GBDevice device) { List<? extends ActivitySample> activitySamples; activitySamples = getSamples(db, device); List<ActivitySession> stepSessions = null; ActivitySession ongoingSession = null; StepAnalysis stepAnalysis = new StepAnalysis(); boolean isEmptySummary = false; if (activitySamples != null) { stepSessions = stepAnalysis.calculateStepSessions(activitySamples); if (stepSessions.toArray().length == 0) { isEmptySummary = true; } ActivitySession stepSessionsSummary = stepAnalysis.calculateSummary(stepSessions, isEmptySummary); stepSessions.add(0, stepSessionsSummary); ActivitySession emptySession = new ActivitySession(); emptySession.setSessionType(ActivitySession.SESSION_EMPTY); stepSessions.add(emptySession); //this is to have an empty item at the end to be able to use FAB without it blocking anything ongoingSession = stepAnalysis.getOngoingSessions(stepSessions); } return new MyChartsData(stepSessions, ongoingSession); } @Override protected void updateChartsnUIThread(ChartsData chartsData) { MyChartsData mcd = (MyChartsData) chartsData; if (mcd == null) { return; } if (mcd.getStepSessions() == null) { return; } if (mcd.getStepSessions().toArray().length == 0) { getChartsHost().enableSwipeRefresh(true); //enable pull to refresh, might be needed } else { getChartsHost().enableSwipeRefresh(false); //disable pull to refresh as it collides with swipable view } stepsDateView.setText(DateTimeUtils.formatDate(new Date(tsDateTo * 1000L))); if (GBApplication.getPrefs().getBoolean("charts_show_ongoing_activity", true)) { if (mcd.getOngoingSession() != null) { showOngoingActivitySnackbar(mcd.getOngoingSession()); } } stepListAdapter.setItems(mcd.getStepSessions(), true); } @Override protected void renderCharts() { } @Override protected void setupLegend(Chart chart) { } @Override protected List<? extends ActivitySample> getSamples(DBHandler db, GBDevice device, int tsFrom, int tsTo) { Calendar day = Calendar.getInstance(); day.setTimeInMillis(tsTo * 1000L); //we need today initially, which is the end of the time range day.set(Calendar.HOUR_OF_DAY, 0); //and we set time for the start and end of the same day day.set(Calendar.MINUTE, 0); day.set(Calendar.SECOND, 0); tsFrom = (int) (day.getTimeInMillis() / 1000); tsTo = tsFrom + 24 * 60 * 60 - 1; tsDateTo = tsTo; return getAllSamples(db, device, tsFrom, tsTo); } private void showOngoingActivitySnackbar(ActivitySession ongoingSession) { String distanceLabel = stepListAdapter.getDistanceLabel(ongoingSession); String stepLabel = stepListAdapter.getStepLabel(ongoingSession); String durationLabel = stepListAdapter.getDurationLabel(ongoingSession); String hrLabel = stepListAdapter.getHrLabel(ongoingSession); String activityName = stepListAdapter.getActivityName(ongoingSession); int icon = stepListAdapter.getIcon(ongoingSession); String text = String.format("%s:\u00A0%s, %s:\u00A0%s, %s:\u00A0%s, %s:\u00A0%s", activityName, durationLabel, getString(R.string.heart_rate), hrLabel, getString(R.string.steps), stepLabel, getString(R.string.distance), distanceLabel); final Snackbar snackbar = Snackbar.make(rootView, text, 1000 * 8); View snackbarView = snackbar.getView(); snackbarView.setBackgroundColor(getContext().getResources().getColor(R.color.accent)); snackbar.setActionTextColor(Color.WHITE); snackbar.setAction(getString(R.string.dialog_hide).toUpperCase(), new View.OnClickListener() { @Override public void onClick(View view) { snackbar.dismiss(); } } ); snackbar.show(); } private void showDashboard(int date, GBDevice device) { FragmentManager fm = getActivity().getSupportFragmentManager(); ActivityListingDashboard listingDashboardFragment = ActivityListingDashboard.newInstance(date, device); listingDashboardFragment.show(fm, "activity_list_total_dashboard"); } private void showDetail(int tsFrom, int tsTo, ActivitySession item, GBDevice device) { FragmentManager fm = getActivity().getSupportFragmentManager(); ActivityListingDetail listingDetailFragment = ActivityListingDetail.newInstance(tsFrom, tsTo, item, device); listingDetailFragment.show(fm, "activity_list_detail"); } private static class MyChartsData extends ChartsData { private final List<ActivitySession> stepSessions; private final ActivitySession ongoingSession; MyChartsData(List<ActivitySession> stepSessions, ActivitySession ongoingSession) { this.stepSessions = stepSessions; this.ongoingSession = ongoingSession; } public List<ActivitySession> getStepSessions() { return stepSessions; } public ActivitySession getOngoingSession() { return this.ongoingSession; } } }
package nodomain.freeyourgadget.gadgetbridge.service.devices.pebble; import android.util.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Date; import java.util.SimpleTimeZone; import java.util.UUID; import nodomain.freeyourgadget.gadgetbridge.GBApplication; import nodomain.freeyourgadget.gadgetbridge.GBException; import nodomain.freeyourgadget.gadgetbridge.database.DBHandler; import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEvent; import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventSendBytes; import nodomain.freeyourgadget.gadgetbridge.devices.SampleProvider; import nodomain.freeyourgadget.gadgetbridge.devices.pebble.MisfitSampleProvider; import nodomain.freeyourgadget.gadgetbridge.impl.GBActivitySample; import nodomain.freeyourgadget.gadgetbridge.model.ActivityKind; import nodomain.freeyourgadget.gadgetbridge.util.Prefs; public class AppMessageHandlerMisfit extends AppMessageHandler { public static final int KEY_SLEEPGOAL = 1; public static final int KEY_STEP_ROGRESS = 2; public static final int KEY_SLEEP_PROGRESS = 3; public static final int KEY_VERSION = 4; public static final int KEY_SYNC = 5; public static final int KEY_INCOMING_DATA_BEGIN = 6; public static final int KEY_INCOMING_DATA = 7; public static final int KEY_INCOMING_DATA_END = 8; public static final int KEY_SYNC_RESULT = 9; private static final Logger LOG = LoggerFactory.getLogger(AppMessageHandlerMisfit.class); public AppMessageHandlerMisfit(UUID uuid, PebbleProtocol pebbleProtocol) { super(uuid, pebbleProtocol); } private final MisfitSampleProvider sampleProvider = new MisfitSampleProvider(); private boolean isMisfitEnabled() { Prefs prefs = GBApplication.getPrefs(); int activityTracker = prefs.getInt("pebble_activitytracker", SampleProvider.PROVIDER_PEBBLE_HEALTH); return (activityTracker == SampleProvider.PROVIDER_PEBBLE_MISFIT); } @Override public GBDeviceEvent[] handleMessage(ArrayList<Pair<Integer, Object>> pairs) { if (!isMisfitEnabled()) { return new GBDeviceEvent[] {null}; } for (Pair<Integer, Object> pair : pairs) { switch (pair.first) { case KEY_INCOMING_DATA_BEGIN: LOG.info("incoming data start"); break; case KEY_INCOMING_DATA_END: LOG.info("incoming data end"); break; case KEY_INCOMING_DATA: byte[] data = (byte[]) pair.second; ByteBuffer buf = ByteBuffer.wrap(data); buf.order(ByteOrder.LITTLE_ENDIAN); int timestamp = buf.getInt(); int key = buf.getInt(); int samples = (data.length - 8) / 2; if (samples <= 0) { break; } if (!mPebbleProtocol.isFw3x) { timestamp -= SimpleTimeZone.getDefault().getOffset(timestamp * 1000L) / 1000; } Date startDate = new Date((long) timestamp * 1000L); Date endDate = new Date((long) (timestamp + samples * 60) * 1000L); LOG.info("got data from " + startDate + " to " + endDate); int totalSteps = 0; GBActivitySample[] activitySamples = new GBActivitySample[samples]; for (int i = 0; i < samples; i++) { short sample = buf.getShort(); int steps = 0; int intensity = 0; int activityKind = ActivityKind.TYPE_UNKNOWN; if (((sample & 0x83ff) == 0x0001) && ((sample & 0xff00) <= 0x4800)) { // sleep seems to be from 0x2401 to 0x4801 (0b0IIIII0000000001) where I = intensity ? intensity = (sample & 0x7c00) >>> 10; // 9-18 decimal after shift if (intensity <= 13) { activityKind = ActivityKind.TYPE_DEEP_SLEEP; } else { // FIXME: this leads to too much false positives, ignore for now //activityKind = ActivityKind.TYPE_LIGHT_SLEEP; //intensity *= 2; // better visual distinction } } else { if ((sample & 0x0001) == 0) { // 16-??? steps encoded in bits 1-7 steps = (sample & 0x00fe); } else { // 0-14 steps encoded in bits 1-3, most of the time fc71 bits are set in that case steps = (sample & 0x000e); } intensity = steps; activityKind = ActivityKind.TYPE_ACTIVITY; } totalSteps += steps; LOG.info("got steps for sample " + i + " : " + steps + "(" + Integer.toHexString(sample & 0xffff) + ")"); activitySamples[i] = new GBActivitySample(sampleProvider, timestamp + i * 60, intensity, steps, activityKind); } LOG.info("total steps for above period: " + totalSteps); DBHandler db = null; try { db = GBApplication.acquireDB(); db.addGBActivitySamples(activitySamples); } catch (GBException e) { LOG.error("Error acquiring database", e); return null; } finally { if (db != null) { db.release(); } } break; default: LOG.info("unhandled key: " + pair.first); break; } } // always ack GBDeviceEventSendBytes sendBytesAck = new GBDeviceEventSendBytes(); sendBytesAck.encodedBytes = mPebbleProtocol.encodeApplicationMessageAck(mUUID, mPebbleProtocol.last_id); return new GBDeviceEvent[]{sendBytesAck}; } }
package com.axelor.apps.business.project.service; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.axelor.apps.account.db.Invoice; import com.axelor.apps.account.db.InvoiceLine; import com.axelor.apps.account.db.repo.InvoiceRepository; import com.axelor.apps.account.service.invoice.generator.InvoiceGenerator; import com.axelor.apps.account.service.invoice.generator.InvoiceLineGenerator; import com.axelor.apps.account.util.InvoiceLineComparator; import com.axelor.apps.base.db.Company; import com.axelor.apps.base.db.IPriceListLine; import com.axelor.apps.base.db.Partner; import com.axelor.apps.base.db.Product; import com.axelor.apps.base.service.administration.GeneralService; import com.axelor.apps.business.project.exception.IExceptionMessage; import com.axelor.apps.businessproject.db.ElementsToInvoice; import com.axelor.apps.businessproject.db.InvoicingFolder; import com.axelor.apps.businessproject.db.repo.ElementsToInvoiceRepository; import com.axelor.apps.businessproject.db.repo.InvoicingFolderRepository; import com.axelor.apps.hr.db.ExpenseLine; import com.axelor.apps.hr.db.TimesheetLine; import com.axelor.apps.hr.db.repo.ExpenseLineRepository; import com.axelor.apps.hr.db.repo.TimesheetLineRepository; import com.axelor.apps.hr.service.expense.ExpenseService; import com.axelor.apps.hr.service.timesheet.TimesheetServiceImp; import com.axelor.apps.project.db.ProjectTask; import com.axelor.apps.project.db.repo.ProjectTaskRepository; import com.axelor.apps.purchase.db.PurchaseOrderLine; import com.axelor.apps.purchase.db.repo.PurchaseOrderLineRepository; import com.axelor.apps.sale.db.SaleOrderLine; import com.axelor.apps.sale.db.repo.SaleOrderLineRepository; import com.axelor.apps.supplychain.service.PurchaseOrderInvoiceServiceImpl; import com.axelor.apps.supplychain.service.SaleOrderInvoiceServiceImpl; import com.axelor.apps.supplychain.service.invoice.generator.InvoiceLineGeneratorSupplyChain; import com.axelor.auth.db.User; import com.axelor.exception.AxelorException; import com.axelor.exception.db.IException; import com.axelor.i18n.I18n; import com.axelor.inject.Beans; import com.google.inject.Inject; import com.google.inject.persist.Transactional; public class InvoicingFolderService extends InvoicingFolderRepository{ @Inject protected SaleOrderInvoiceServiceImpl saleOrderInvoiceServiceImpl; @Inject protected PurchaseOrderInvoiceServiceImpl purchaseOrderInvoiceServiceImpl; @Inject protected TimesheetServiceImp timesheetServiceImp; @Inject protected ExpenseService expenseService; @Inject protected ElementsToInvoiceService elementsToInvoiceService; @Inject protected GeneralService generalService; protected int MAX_LEVEL_OF_PROJECT = 10; protected int sequence = 10; @Transactional public Invoice generateInvoice(InvoicingFolder folder) throws AxelorException{ ProjectTask projectTask = folder.getProjectTask(); Partner customer = projectTask.getClientPartner(); Company company = this.getRootCompany(projectTask); if(company == null){ throw new AxelorException(String.format(I18n.get(IExceptionMessage.INVOICING_FOLDER_PROJECT_TASK_COMPANY)), IException.CONFIGURATION_ERROR); } User user = projectTask.getAssignedTo(); InvoiceGenerator invoiceGenerator = new InvoiceGenerator(InvoiceRepository.OPERATION_TYPE_CLIENT_SALE, company, customer.getPaymentCondition(), customer.getPaymentMode(), customer.getMainInvoicingAddress(), customer, null, customer.getCurrency(), customer.getSalePriceList(), null, null){ @Override public Invoice generate() throws AxelorException { return super.createInvoiceHeader(); } }; Invoice invoice = invoiceGenerator.generate(); invoice.setInAti(user.getActiveCompany().getAccountConfig().getInvoiceInAti()); invoiceGenerator.populate(invoice,this.populate(invoice,folder)); Beans.get(InvoiceRepository.class).save(invoice); this.setInvoiced(folder); folder.setInvoice(invoice); save(folder); return invoice; } public List<InvoiceLine> populate(Invoice invoice,InvoicingFolder folder) throws AxelorException{ List<SaleOrderLine> saleOrderLineList = new ArrayList<SaleOrderLine>(folder.getSaleOrderLineSet()); List<PurchaseOrderLine> purchaseOrderLineList = new ArrayList<PurchaseOrderLine>(folder.getPurchaseOrderLineSet()); List<TimesheetLine> timesheetLineList = new ArrayList<TimesheetLine>(folder.getLogTimesSet()); List<ExpenseLine> expenseLineList = new ArrayList<ExpenseLine>(folder.getExpenseLineSet()); List<ElementsToInvoice> elementsToInvoiceList = new ArrayList<ElementsToInvoice>(folder.getElementsToInvoiceSet()); List<ProjectTask> projectTaskList = new ArrayList<ProjectTask>(folder.getProjectTaskSet()); List<InvoiceLine> invoiceLineList = new ArrayList<InvoiceLine>(); invoiceLineList.addAll( this.createSaleOrderInvoiceLines(invoice, saleOrderLineList,folder.getSaleOrderLineSetPrioritySelect())); invoiceLineList.addAll(this.customerChargeBackPurchases(this.createPurchaseOrderInvoiceLines(invoice, purchaseOrderLineList,folder.getPurchaseOrderLineSetPrioritySelect()),folder)); invoiceLineList.addAll(timesheetServiceImp.createInvoiceLines(invoice, timesheetLineList,folder.getLogTimesSetPrioritySelect())); invoiceLineList.addAll(expenseService.createInvoiceLines(invoice, expenseLineList,folder.getExpenseLineSetPrioritySelect())); invoiceLineList.addAll(elementsToInvoiceService.createInvoiceLines(invoice, elementsToInvoiceList, folder.getElementsToInvoiceSetPrioritySelect())); invoiceLineList.addAll(this.createInvoiceLines(invoice, projectTaskList,folder.getProjectTaskSetPrioritySelect())); Collections.sort(invoiceLineList, new InvoiceLineComparator()); for (InvoiceLine invoiceLine : invoiceLineList) { invoiceLine.setSequence(sequence); sequence+=10; invoiceLine.setSaleOrder(invoiceLine.getInvoice().getSaleOrder()); } return invoiceLineList; } public List<InvoiceLine> createSaleOrderInvoiceLines(Invoice invoice, List<SaleOrderLine> saleOrderLineList, int priority) throws AxelorException { List<InvoiceLine> invoiceLineList = new ArrayList<InvoiceLine>(); int count = 0; for(SaleOrderLine saleOrderLine : saleOrderLineList) { invoiceLineList.addAll(this.createInvoiceLine(invoice, saleOrderLine,priority*100+count)); count++; saleOrderLine.setInvoiced(true); } return invoiceLineList; } public List<InvoiceLine> createInvoiceLine(Invoice invoice, SaleOrderLine saleOrderLine, int priority) throws AxelorException { Product product = saleOrderLine.getProduct(); InvoiceLineGenerator invoiceLineGenerator = new InvoiceLineGeneratorSupplyChain(invoice, product, saleOrderLine.getProductName(), saleOrderLine.getDescription(), saleOrderLine.getQty(), saleOrderLine.getUnit(), priority, false, saleOrderLine, null, null) { @Override public List<InvoiceLine> creates() throws AxelorException { InvoiceLine invoiceLine = this.createInvoiceLine(); List<InvoiceLine> invoiceLines = new ArrayList<InvoiceLine>(); invoiceLines.add(invoiceLine); return invoiceLines; } }; return invoiceLineGenerator.creates(); } public List<InvoiceLine> createPurchaseOrderInvoiceLines(Invoice invoice, List<PurchaseOrderLine> purchaseOrderLineList, int priority) throws AxelorException { List<InvoiceLine> invoiceLineList = new ArrayList<InvoiceLine>(); int count = 0; for(PurchaseOrderLine purchaseOrderLine : purchaseOrderLineList) { invoiceLineList.addAll(this.createInvoiceLine(invoice, purchaseOrderLine, priority*100+count)); count++; purchaseOrderLine.setInvoiced(true); } return invoiceLineList; } public List<InvoiceLine> createInvoiceLine(Invoice invoice, PurchaseOrderLine purchaseOrderLine, int priority) throws AxelorException { Product product = purchaseOrderLine.getProduct(); InvoiceLineGeneratorSupplyChain invoiceLineGenerator = new InvoiceLineGeneratorSupplyChain(invoice, product, purchaseOrderLine.getProductName(), purchaseOrderLine.getDescription(), purchaseOrderLine.getQty(), purchaseOrderLine.getUnit(), priority, false, null, purchaseOrderLine, null) { @Override public List<InvoiceLine> creates() throws AxelorException { InvoiceLine invoiceLine = this.createInvoiceLine(); List<InvoiceLine> invoiceLines = new ArrayList<InvoiceLine>(); invoiceLines.add(invoiceLine); return invoiceLines; } }; return invoiceLineGenerator.creates(); } public List<InvoiceLine> createInvoiceLines(Invoice invoice, List<ProjectTask> projectTaskList, int priority) throws AxelorException { List<InvoiceLine> invoiceLineList = new ArrayList<InvoiceLine>(); int count = 0; for(ProjectTask projectTask : projectTaskList) { invoiceLineList.addAll(this.createInvoiceLine(invoice, projectTask, priority*100+count)); count++; projectTask.setInvoiced(true); invoiceLineList.get(invoiceLineList.size()-1).setProject(projectTask); } return invoiceLineList; } public List<InvoiceLine> createInvoiceLine(Invoice invoice, ProjectTask projectTask, int priority) throws AxelorException { Product product = projectTask.getProduct(); if(product == null){ throw new AxelorException(String.format(I18n.get(IExceptionMessage.INVOICING_FOLDER_PROJECT_TASK_PRODUCT),projectTask.getFullName()), IException.CONFIGURATION_ERROR); } InvoiceLineGenerator invoiceLineGenerator = new InvoiceLineGenerator(invoice, product, projectTask.getName(), projectTask.getPrice(), null,projectTask.getQty(),projectTask.getUnit(),priority,BigDecimal.ZERO,IPriceListLine.AMOUNT_TYPE_NONE, projectTask.getPrice().multiply(projectTask.getQty()),null,false) { @Override public List<InvoiceLine> creates() throws AxelorException { InvoiceLine invoiceLine = this.createInvoiceLine(); List<InvoiceLine> invoiceLines = new ArrayList<InvoiceLine>(); invoiceLines.add(invoiceLine); return invoiceLines; } }; return invoiceLineGenerator.creates(); } public void setInvoiced(InvoicingFolder folder){ for (SaleOrderLine saleOrderLine : folder.getSaleOrderLineSet()) { saleOrderLine.setInvoiced(true); } for (PurchaseOrderLine purchaseOrderLine : folder.getPurchaseOrderLineSet()) { purchaseOrderLine.setInvoiced(true); } for (TimesheetLine timesheetLine : folder.getLogTimesSet()) { timesheetLine.setInvoiced(true); } for (ExpenseLine expenseLine : folder.getExpenseLineSet()) { expenseLine.setInvoiced(true); } for (ElementsToInvoice elementsToInvoice : folder.getElementsToInvoiceSet()) { elementsToInvoice.setInvoiced(true); } for (ProjectTask projectTask : folder.getProjectTaskSet()) { projectTask.setInvoiced(true); } } public List<InvoiceLine> customerChargeBackPurchases(List<InvoiceLine> invoiceLineList,InvoicingFolder folder){ Partner customer = folder.getProjectTask().getClientPartner(); if(!customer.getFlatFeePurchase()){ for (InvoiceLine invoiceLine : invoiceLineList) { invoiceLine.setPrice(invoiceLine.getPrice().multiply(customer.getChargeBackPurchase().divide(new BigDecimal(100), generalService.getNbDecimalDigitForUnitPrice(), BigDecimal.ROUND_HALF_UP)).setScale(generalService.getNbDecimalDigitForUnitPrice(), BigDecimal.ROUND_HALF_UP)); invoiceLine.setExTaxTotal(invoiceLine.getPrice().multiply(invoiceLine.getQty()).setScale(2, BigDecimal.ROUND_HALF_UP)); } } return invoiceLineList; } public void getLines(ProjectTask projectTask, List<SaleOrderLine> saleOrderLineList, List<PurchaseOrderLine> purchaseOrderLineList, List<TimesheetLine> timesheetLineList, List<ExpenseLine> expenseLineList, List<ElementsToInvoice> elementsToInvoiceList, List<ProjectTask> projectTaskList, int counter){ if(counter > MAX_LEVEL_OF_PROJECT) { return; } counter++; if(projectTask.getInvoicingTypeSelect() == ProjectTaskRepository.INVOICING_TYPE_FLAT_RATE || projectTask.getInvoicingTypeSelect() == ProjectTaskRepository.INVOICING_TYPE_TIME_BASED) { saleOrderLineList.addAll(Beans.get(SaleOrderLineRepository.class) .all().filter("self.saleOrder.project = ?1 AND self.toInvoice = true AND self.invoiced = false", projectTask).fetch()); purchaseOrderLineList.addAll(Beans.get(PurchaseOrderLineRepository.class) .all().filter("self.projectTask = ?1 AND self.toInvoice = true AND self.invoiced = false", projectTask).fetch()); timesheetLineList.addAll(Beans.get(TimesheetLineRepository.class) .all().filter("self.affectedToTimeSheet.statusSelect = 3 AND self.projectTask = ?1 AND self.toInvoice = true AND self.invoiced = false", projectTask).fetch()); expenseLineList.addAll(Beans.get(ExpenseLineRepository.class) .all().filter("self.projectTask = ?1 AND self.toInvoice = true AND self.invoiced = false", projectTask).fetch()); elementsToInvoiceList.addAll(Beans.get(ElementsToInvoiceRepository.class) .all().filter("self.project = ?1 AND self.toInvoice = true AND self.invoiced = false", projectTask).fetch()); if(projectTask.getInvoicingTypeSelect() == ProjectTaskRepository.INVOICING_TYPE_FLAT_RATE && !projectTask.getInvoiced()) { projectTaskList.add(projectTask); } } List<ProjectTask> projectTaskChildrenList = Beans.get(ProjectTaskRepository.class).all().filter("self.project = ?1", projectTask).fetch(); for (ProjectTask projectTaskChild : projectTaskChildrenList) { this.getLines(projectTaskChild, saleOrderLineList, purchaseOrderLineList, timesheetLineList, expenseLineList, elementsToInvoiceList, projectTaskList, counter); } return; } public Company getRootCompany(ProjectTask projectTask){ if(projectTask.getProject() == null){ return projectTask.getCompany(); } else{ return getRootCompany(projectTask.getProject()); } } }
package com.codenvy.factory; import com.codenvy.api.factory.FactoryStore; import com.codenvy.commons.json.JsonHelper; import com.codenvy.commons.json.JsonParseException; import com.codenvy.factory.storage.InMemoryFactoryStore; import com.codenvy.factory.storage.mongo.MongoDBFactoryStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** * Listener that choose backend for {@link FactoryStore}. * If MongoDb configuration exist and it's correct {@link MongoDBFactoryStore} is used. {@link InMemoryFactoryStore} is used otherwise. */ public class FactoryFallBackServletContextListener implements ServletContextListener { private static final Logger LOG = LoggerFactory.getLogger(FactoryFallBackServletContextListener.class); @Override public void contextInitialized(ServletContextEvent sce) { ServletContext sctx = sce.getServletContext(); sctx.setAttribute(FactoryStore.class.getName(), getFactoryStore()); } @Override public void contextDestroyed(ServletContextEvent sce) { ServletContext sctx = sce.getServletContext(); sctx.removeAttribute(FactoryStore.class.getName()); } private FactoryStore getFactoryStore() { if (System.getProperty("codenvy.local.conf.dir") != null) { File dbSettings = new File(System.getProperty("codenvy.local.conf.dir"), "factory-storage-configuration.json"); if (dbSettings.exists() && !dbSettings.isDirectory()) { try (InputStream is = new FileInputStream(dbSettings)) { MongoDbConfiguration mConf = JsonHelper.fromJson(is, MongoDbConfiguration.class, null); return new MongoDBFactoryStore(mConf); } catch (IOException | JsonParseException e) { LOG.error(e.getLocalizedMessage(), e); throw new RuntimeException( "Invalid mongo database configuration : " + dbSettings.getAbsolutePath()); } } } LOG.warn("Persistent storage configuration not found, inmemory impl will be used."); return new InMemoryFactoryStore(); } }
package org.hisp.dhis.android.core.program; import android.content.ContentValues; import android.database.Cursor; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.hisp.dhis.android.core.category.CategoryComboTableInfo; import org.hisp.dhis.android.core.category.CreateCategoryComboUtils; import org.hisp.dhis.android.core.common.BaseIdentifiableObject; import org.hisp.dhis.android.core.common.BaseIdentifiableObjectModel; import org.hisp.dhis.android.core.common.BaseNameableObjectModel; import org.hisp.dhis.android.core.legendset.LegendSetTableInfo; import org.hisp.dhis.android.core.legendset.LegendTableInfo; import org.hisp.dhis.android.core.relationship.RelationshipTypeTableInfo; import org.hisp.dhis.android.core.trackedentity.CreateTrackedEntityUtils; import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeFields; import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeTableInfo; import org.hisp.dhis.android.core.trackedentity.TrackedEntityTypeTableInfo; import org.hisp.dhis.android.core.utils.integration.BaseIntegrationTestEmptyEnqueable; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import java.util.List; import java.util.concurrent.Callable; import androidx.test.runner.AndroidJUnit4; import static org.hisp.dhis.android.core.common.BaseIdentifiableObjectModel.Columns.UID; import static org.hisp.dhis.android.core.data.database.CursorAssert.assertThatCursor; @RunWith(AndroidJUnit4.class) public class ProgramEndpointCallMockIntegrationShould extends BaseIntegrationTestEmptyEnqueable { private static String ACCESS_DATA_WRITE = "accessDataWrite"; private static String[] PROGRAM_PROJECTION = { UID, BaseIdentifiableObjectModel.Columns.CODE, BaseIdentifiableObjectModel.Columns.NAME, BaseIdentifiableObjectModel.Columns.DISPLAY_NAME, BaseIdentifiableObjectModel.Columns.CREATED, BaseIdentifiableObjectModel.Columns.LAST_UPDATED, BaseNameableObjectModel.Columns.SHORT_NAME, BaseNameableObjectModel.Columns.DISPLAY_SHORT_NAME, BaseNameableObjectModel.Columns.DESCRIPTION, BaseNameableObjectModel.Columns.DISPLAY_DESCRIPTION, ProgramFields.VERSION, ProgramFields.ONLY_ENROLL_ONCE, ProgramFields.ENROLLMENT_DATE_LABEL, ProgramFields.DISPLAY_INCIDENT_DATE, ProgramFields.INCIDENT_DATE_LABEL, ProgramFields.REGISTRATION, ProgramFields.SELECT_ENROLLMENT_DATES_IN_FUTURE, ProgramFields.DATA_ENTRY_METHOD, ProgramFields.IGNORE_OVERDUE_EVENTS, ProgramFields.RELATIONSHIP_FROM_A, ProgramFields.SELECT_INCIDENT_DATES_IN_FUTURE, ProgramFields.CAPTURE_COORDINATES, ProgramFields.USE_FIRST_STAGE_DURING_REGISTRATION, ProgramFields.DISPLAY_FRONT_PAGE_LIST, ProgramFields.PROGRAM_TYPE, ProgramFields.RELATIONSHIP_TYPE, ProgramFields.RELATIONSHIP_TEXT, ProgramFields.RELATED_PROGRAM, ProgramFields.TRACKED_ENTITY_TYPE, ProgramFields.CATEGORY_COMBO, ACCESS_DATA_WRITE }; private static Callable<List<Program>> programEndpointCall; @BeforeClass public static void setUpClass() throws Exception { BaseIntegrationTestEmptyEnqueable.setUpClass(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setDateFormat(BaseIdentifiableObject.DATE_FORMAT.raw()); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); ContentValues categoryCombo = CreateCategoryComboUtils.create(1L, "nM3u9s5a52V"); database.insert(CategoryComboTableInfo.TABLE_INFO.name(), null, categoryCombo); ContentValues categoryCombo2 = CreateCategoryComboUtils.create(2L, "x31y45jvIQL"); database.insert(CategoryComboTableInfo.TABLE_INFO.name(), null, categoryCombo2); // inserting tracked entity ContentValues trackedEntityType = CreateTrackedEntityUtils.create(1L, "nEenWmSyUEp"); database.insert(TrackedEntityTypeTableInfo.TABLE_INFO.name(), null, trackedEntityType); programEndpointCall = objects.d2DIComponent.programCallFactory().create(); } @Before public void setUp() throws IOException { dhis2MockServer.enqueueMockResponse("program/programs_complete.json"); } @Test public void persist_program_when_call() throws Exception { // Fake call to api programEndpointCall.call(); Cursor programCursor = database.query(ProgramTableInfo.TABLE_INFO.name(), PROGRAM_PROJECTION, null, null, null, null, null); assertThatCursor(programCursor).hasRow( "IpHINAT79UW", null, "Child Programme", "Child Programme", "2013-03-04T11:41:07.494", "2017-01-26T19:39:33.356", "Child Programme", "Child Programme", null, null, 5, 1, // true "Date of enrollment", 1, // true "Date of birth", 1, // true 0, // false 0, // false 0, // false 0, // false 0, // false 1, // true 1, // true 0, // false "WITH_REGISTRATION", null, null, null, "nEenWmSyUEp", "nM3u9s5a52V", 0 ).isExhausted(); } @Test public void persist_program_rule_variables_on_call() throws Exception { programEndpointCall.call(); String[] projection = { UID, BaseIdentifiableObjectModel.Columns.CODE, BaseIdentifiableObjectModel.Columns.NAME, BaseIdentifiableObjectModel.Columns.DISPLAY_NAME, BaseIdentifiableObjectModel.Columns.CREATED, BaseIdentifiableObjectModel.Columns.LAST_UPDATED, ProgramRuleVariableFields.USE_CODE_FOR_OPTION_SET, ProgramRuleVariableFields.PROGRAM, ProgramRuleVariableFields.PROGRAM_STAGE, ProgramRuleVariableFields.DATA_ELEMENT, ProgramRuleVariableFields.TRACKED_ENTITY_ATTRIBUTE, ProgramRuleVariableFields.PROGRAM_RULE_VARIABLE_SOURCE_TYPE }; Cursor programRuleVariableCursor = database.query(ProgramRuleVariableTableInfo.TABLE_INFO.name(), projection, UID + "=?", new String[]{"g2GooOydipB"}, null, null, null); assertThatCursor(programRuleVariableCursor).hasRow( "g2GooOydipB", null, "apgarscore", "apgarscore", "2015-08-07T18:41:55.152", "2015-08-07T18:41:55.153", null, "IpHINAT79UW", null, null, null, "DATAELEMENT_NEWEST_EVENT_PROGRAM" ).isExhausted(); } @Test public void persist_program_tracker_entity_attributes_when_call() throws Exception { programEndpointCall.call(); String[] projection = { UID, BaseIdentifiableObjectModel.Columns.CODE, BaseIdentifiableObjectModel.Columns.NAME, BaseIdentifiableObjectModel.Columns.DISPLAY_NAME, BaseIdentifiableObjectModel.Columns.CREATED, BaseIdentifiableObjectModel.Columns.LAST_UPDATED, BaseNameableObjectModel.Columns.SHORT_NAME, BaseNameableObjectModel.Columns.DISPLAY_SHORT_NAME, BaseNameableObjectModel.Columns.DESCRIPTION, BaseNameableObjectModel.Columns.DISPLAY_DESCRIPTION, ProgramTrackedEntityAttributeFields.MANDATORY, ProgramTrackedEntityAttributeFields.TRACKED_ENTITY_ATTRIBUTE, ProgramTrackedEntityAttributeFields.ALLOW_FUTURE_DATE, ProgramTrackedEntityAttributeFields.DISPLAY_IN_LIST, ProgramTrackedEntityAttributeFields.PROGRAM, ProgramTrackedEntityAttributeFields.SORT_ORDER }; Cursor programTrackedEntityAttributeCursor = database.query( ProgramTrackedEntityAttributeTableInfo.TABLE_INFO.name(), projection, UID + "=?", new String[]{"l2T72XzBCLd"}, null, null, null); assertThatCursor(programTrackedEntityAttributeCursor).hasRow( "l2T72XzBCLd", null, "Child Programme First name", "Child Programme First name", "2017-01-26T19:39:33.347", "2017-01-26T19:39:33.347", "Child Programme First name", "Child Programme First name", null, null, 0, // false "w75KJ2mc4zz", 0, // false 1, // true "IpHINAT79UW", 99 ).isExhausted(); } @Test public void persist_tracked_entity_attribute_when_call() throws Exception { programEndpointCall.call(); String[] projection = { UID, BaseIdentifiableObjectModel.Columns.CODE, BaseIdentifiableObjectModel.Columns.NAME, BaseIdentifiableObjectModel.Columns.DISPLAY_NAME, BaseIdentifiableObjectModel.Columns.CREATED, BaseIdentifiableObjectModel.Columns.LAST_UPDATED, BaseNameableObjectModel.Columns.SHORT_NAME, BaseNameableObjectModel.Columns.DISPLAY_SHORT_NAME, BaseNameableObjectModel.Columns.DESCRIPTION, BaseNameableObjectModel.Columns.DISPLAY_DESCRIPTION, TrackedEntityAttributeFields.PATTERN, TrackedEntityAttributeFields.SORT_ORDER_IN_LIST_NO_PROGRAM, TrackedEntityAttributeFields.OPTION_SET, TrackedEntityAttributeFields.VALUE_TYPE, TrackedEntityAttributeFields.EXPRESSION, TrackedEntityAttributeFields.PROGRAM_SCOPE, TrackedEntityAttributeFields.DISPLAY_IN_LIST_NO_PROGRAM, TrackedEntityAttributeFields.GENERATED, TrackedEntityAttributeFields.DISPLAY_ON_VISIT_SCHEDULE, TrackedEntityAttributeFields.ORG_UNIT_SCOPE, TrackedEntityAttributeTableInfo.Columns.UNIQUE, TrackedEntityAttributeFields.INHERIT }; Cursor trackedEntityAttributeCursor = database.query(TrackedEntityAttributeTableInfo.TABLE_INFO.name(), projection, UID + "=?", new String[]{"w75KJ2mc4zz"}, null, null, null); assertThatCursor(trackedEntityAttributeCursor).hasRow( "w75KJ2mc4zz", "MMD_PER_NAM", "First name", "First name", "2014-06-06T20:41:25.233", "2015-10-20T13:57:00.939", "First name", "First name", "First name", "First name", "", 1, null, "TEXT", null, 0, // false 1, // true 0, // false 0, // false 0, // false 0, // false 0 // false ).isExhausted(); } @Test public void persist_program_indicators_when_call() throws Exception { programEndpointCall.call(); Cursor programIndicatorCursor = database.query( ProgramIndicatorTableInfo.TABLE_INFO.name(), ProgramIndicatorTableInfo.TABLE_INFO.columns().all(), UID + "=?", new String[]{"rXoaHGAXWy9"}, null, null, null); assertThatCursor(programIndicatorCursor).hasRow( "rXoaHGAXWy9", null, "Health immunization score", "Health immunization score", "2015-10-20T11:26:19.631", "2015-10-20T11:26:19.631", "Health immunization score", "Health immunization score", "Sum of BCG doses, measles doses and yellow fever doses." + " If Apgar score over or equal to 2, multiply by 2.", "Sum of BCG doses, measles doses and yellow fever doses." + " If Apgar score over or equal to 2, multiply by 2.", 0, // false "(#{A03MvHHogjR.bx6fsa0t90x} + #{A03MvHHogjR.FqlgKAG8HOu} + #{A03MvHHogjR.rxBfISxXS2U}) " + "* d2:condition('#{A03MvHHogjR.a3kGcGDCuk6} >= 2',1,2)", "rXoaHGAXWy9", null, 2, "SUM", "IpHINAT79UW" ).isExhausted(); } @Test public void persist_legend_sets_when_call() throws Exception { programEndpointCall.call(); Cursor programIndicatorCursor = database.query( LegendSetTableInfo.TABLE_INFO.name(), LegendSetTableInfo.TABLE_INFO.columns().all(), UID + "=?", new String[]{"TiOkbpGEud4"}, null, null, null); assertThatCursor(programIndicatorCursor).hasRow( "TiOkbpGEud4", "AGE15YINT", "Age 15y interval", "Age 15y interval", "2017-06-02T11:40:33.452", "2017-06-02T11:41:01.999", "color" ).isExhausted(); } @Test public void persist_legends_when_call() throws Exception { programEndpointCall.call(); Cursor programIndicatorCursor = database.query( LegendTableInfo.TABLE_INFO.name(), LegendTableInfo.TABLE_INFO.columns().all(), UID + "=?", new String[]{"ZUUGJnvX40X"}, null, null, null); assertThatCursor(programIndicatorCursor).hasRow( "ZUUGJnvX40X", null, "30 - 40", "30 - 40", "2017-06-02T11:40:44.279", "2017-06-02T11:40:44.279", 30.5, 40, "#d9f0a3", "TiOkbpGEud4" ).isExhausted(); } @Test public void persist_program_rules_when_call() throws Exception { programEndpointCall.call(); String[] projection = { UID, BaseIdentifiableObjectModel.Columns.CODE, BaseIdentifiableObjectModel.Columns.NAME, BaseIdentifiableObjectModel.Columns.DISPLAY_NAME, BaseIdentifiableObjectModel.Columns.CREATED, BaseIdentifiableObjectModel.Columns.LAST_UPDATED, ProgramRuleFields.PRIORITY, ProgramRuleFields.CONDITION, ProgramRuleFields.PROGRAM, ProgramRuleFields.PROGRAM_STAGE }; Cursor programRuleCursor = database.query(ProgramRuleTableInfo.TABLE_INFO.name(), projection, UID + "=?", new String[]{"NAgjOfWMXg6"}, null, null, null); assertThatCursor(programRuleCursor).hasRow( "NAgjOfWMXg6", null, "Ask for comment for low apgar", "Ask for comment for low apgar", "2015-09-14T21:17:40.841", "2015-09-14T22:22:15.383", null, "#{apgarscore} >= 0 && #{apgarscore} < 4 && #{apgarcomment} == ''", "IpHINAT79UW", null ).isExhausted(); } @Test public void persist_program_rule_actions_when_call() throws Exception { programEndpointCall.call(); String[] projection = { UID, ProgramRuleActionTableInfo.Columns.CODE, ProgramRuleActionTableInfo.Columns.NAME, ProgramRuleActionTableInfo.Columns.DISPLAY_NAME, ProgramRuleActionTableInfo.Columns.CREATED, ProgramRuleActionTableInfo.Columns.LAST_UPDATED, ProgramRuleActionFields.DATA, ProgramRuleActionFields.CONTENT, ProgramRuleActionFields.LOCATION, ProgramRuleActionFields.TRACKED_ENTITY_ATTRIBUTE, ProgramRuleActionFields.PROGRAM_INDICATOR, ProgramRuleActionFields.PROGRAM_STAGE_SECTION, ProgramRuleActionFields.PROGRAM_RULE_ACTION_TYPE, ProgramRuleActionFields.PROGRAM_STAGE, ProgramRuleActionFields.DATA_ELEMENT, ProgramRuleActionFields.PROGRAM_RULE }; Cursor programRuleActionCursor = database.query(ProgramRuleActionTableInfo.TABLE_INFO.name(), projection, UID + "=?", new String[]{"v434s5YPDcP"}, null, null, null); assertThatCursor(programRuleActionCursor).hasRow( "v434s5YPDcP", null, null, null, "2015-09-14T21:17:41.033", "2015-09-14T22:22:15.458", null, "It is suggested that an explanation is provided when the Apgar score is below 4", null, null, null, null, "SHOWWARNING", null, null, "NAgjOfWMXg6" ).isExhausted(); } /** * Relationship type doesn't exist for the program in the payload. Therefore we'll need to check that it doesn't * exist in the database * * @throws Exception */ @Test public void not_persist_relationship_type_when_call() throws Exception { programEndpointCall.call(); Cursor relationshipTypeCursor = database.query(RelationshipTypeTableInfo.TABLE_INFO.name(), RelationshipTypeTableInfo.TABLE_INFO.columns().all(), null, null, null, null, null); assertThatCursor(relationshipTypeCursor).isExhausted(); } }
package org.deviceconnect.android.manager.util; import android.Manifest; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.drawable.Drawable; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Bundle; import org.deviceconnect.android.manager.DConnectSettings; import org.deviceconnect.android.manager.profile.DConnectFilesProfile; import org.deviceconnect.message.DConnectMessage; import org.deviceconnect.message.intent.message.IntentDConnectMessage; import org.deviceconnect.utils.JSONUtils; import org.deviceconnect.utils.URIBuilder; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Iterator; import java.util.Random; import java.util.UUID; /** * . * @author NTT DOCOMO, INC. */ public final class DConnectUtil { private static final int MAX_NUM = 10000; private static final int DIGIT = 4; private static final int DECIMAL = 10; public static final String[] PERMISSIONS = new String[] { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }; /** * . * private */ private DConnectUtil() { } /** * . * * @return */ public static String createKeyword() { StringBuilder builder = new StringBuilder(); builder.append("DCONNECT-"); int rand = Math.abs(new Random().nextInt() % MAX_NUM); for (int i = 0; i < DIGIT; i++) { int r = rand % DECIMAL; builder.append(r); rand /= DECIMAL; } return builder.toString(); } public static String createName() { StringBuilder builder = new StringBuilder(); builder.append("Manager-"); int rand = Math.abs(new Random().nextInt() % MAX_NUM); for (int i = 0; i < DIGIT; i++) { int r = rand % DECIMAL; builder.append(r); rand /= DECIMAL; } return builder.toString(); } public static String createUuid() { return UUID.randomUUID().toString(); } /** * HttpDConnect. * @param method Http * @return DConnect */ public static String convertHttpMethod2DConnectMethod(final String method) { if (DConnectMessage.METHOD_GET.equalsIgnoreCase(method)) { return IntentDConnectMessage.ACTION_GET; } else if (DConnectMessage.METHOD_POST.equalsIgnoreCase(method)) { return IntentDConnectMessage.ACTION_POST; } else if (DConnectMessage.METHOD_PUT.equalsIgnoreCase(method)) { return IntentDConnectMessage.ACTION_PUT; } else if (DConnectMessage.METHOD_DELETE.equalsIgnoreCase(method)) { return IntentDConnectMessage.ACTION_DELETE; } return null; } /** * URI. * @param uri ContentUri * @return URI */ private static String createUri(final String uri) { DConnectSettings settings = DConnectSettings.getInstance(); URIBuilder builder = new URIBuilder(); if (settings.isSSL()) { builder.setScheme("https"); } else { builder.setScheme("http"); } builder.setHost(settings.getHost()); builder.setPort(settings.getPort()); builder.setProfile(DConnectFilesProfile.PROFILE_NAME); builder.addParameter("uri", uri); return builder.toString(); } /** * JSONuri. * * <p> * uricontent://uri<br/> * uri * </p> * * @param root JSONObject * @throws JSONException JSON */ private static void convertUri(final JSONObject root) throws JSONException { @SuppressWarnings("unchecked") // Using legacy API Iterator<String> it = root.keys(); while (it.hasNext()) { String key = it.next(); Object value = root.opt(key); if (value instanceof String) { if ("uri".equals(key) && startWithContent((String) value)) { String u = createUri((String) value); root.put(key, u); } } else if (value instanceof JSONObject) { convertUri((JSONObject) value); } } } /** * uricontent://. * @param uri uri * @return content://truefalse */ private static boolean startWithContent(final String uri) { return uri != null && (uri.startsWith("content: } /** * BundleJSONObject. * @param root JSONObject * @param b Bundle * @throws JSONException JSON */ public static void convertBundleToJSON( final JSONObject root, final Bundle b) throws JSONException { JSONUtils.convertBundleToJSON(root, b); convertUri(root); } /** * AndroidManifest.xmlversionName. * * @param context Context * @return versionName */ public static String getVersionName(final Context context) { PackageManager packageManager = context.getPackageManager(); try { PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES); return packageInfo.versionName; } catch (NameNotFoundException e) { return "Unknown"; } } /** * Gets the ip address. * @param context Context of application * @return Returns ip address */ public static String getIPAddress(final Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); int ipAddress = wifiManager.getConnectionInfo().getIpAddress(); return String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff)); } public static boolean isPermission(final Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true; } else { boolean result = true; for (int i = 0; i < PERMISSIONS.length; i++) { if (context.checkSelfPermission(PERMISSIONS[i]) != PackageManager.PERMISSION_GRANTED) { result = false; } } return result; } } public static Drawable convertToGrayScale(final Drawable drawable) { Drawable clone = drawable.getConstantState().newDrawable().mutate(); ColorMatrix matrix = new ColorMatrix(); matrix.setSaturation(0.2f); ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix); clone.setColorFilter(filter); return clone; } private static final int MASK = 0xFF; /** * 16. * @param buf * @return */ private static String hexToString(final byte[] buf) { StringBuilder hexString = new StringBuilder(); for (int i = 0; i < buf.length; i++) { hexString.append(Integer.toHexString(MASK & buf[i])); } return hexString.toString(); } /** * MD5. * MD5null * @param s MD5 * @return MD5 * @throws UnsupportedEncodingException * @throws NoSuchAlgorithmException MD5 */ public static String toMD5(final String s) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes("ASCII")); return hexToString(digest.digest()); } }
package org.datadryad.journalstatistics.extractor; import java.sql.SQLException; import org.datadryad.api.DryadDataPackage; import org.dspace.authorize.AuthorizeException; import org.dspace.content.WorkspaceItem; import org.dspace.core.Context; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Dan Leehr <dan.leehr@nescent.org> */ public class DataPackageCountTest { private Context context; public DataPackageCountTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { try { this.context = new Context(); } catch (SQLException ex) { fail("Unable to instantiate Context " + ex); } } @After public void tearDown() { } /** * Test of extract method, of class DataPackageCount. * Data packages are items in collection identified by 'stats.datapkgs.coll' * having prism.publicationName as provided */ @Test public void testExtract() throws SQLException { // There should be one package in the database with journal name "Test Journal" // Create a data package DryadDataPackage dataPackage = DryadDataPackage.create(context); // set its journal String journalName = "Test Journal"; dataPackage.setPublicationName(journalName); DataPackageCount instance = new DataPackageCount(this.context); Integer expResult = 1; Integer result = instance.extract(journalName); assertEquals(expResult, result); } }
import java.util.*; /** * Given a binary tree, determine if it is a valid binary search tree (BST). * Assume a BST is defined as follows: * * The left subtree of a node contains only nodes with keys less than the * node's key. * The right subtree of a node contains only nodes with keys greater than the * node's key. * Both the left and right subtrees must also be binary search trees. * * Tags: Tree, DFS */ class ValidateBST { public static void main(String[] args) { TreeNode r = new TreeNode(Integer.MAX_VALUE); ValidateBST v = new ValidateBST(); System.out.println(v.isValidBST(r)); } Integer pred = null; /** * Recursive * Check current node * Check left subtree * Compare with current node and set predecessor * Check right subtree * If it's a BST, the result of inorder traversal should be in acsending order. */ public boolean isValidBST(TreeNode root) { if (root == null) return true; if (!isValidBST(root.left)) return false; // visit if (pred != null && root.val <= pred) return false; pred = root.val; // set if (!isValidBST(root.right)) return false; return true; } /** * Failed if input include Integer MAX and Integer MIN */ public boolean isValidBSTB(TreeNode root) { return isValidBSTB(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } // add range of current value and do recursive check public boolean isValidBSTB(TreeNode root, int min, int max) { return root == null || root.val > min && root.val < max && isValidBSTB(root.left, min, root.val) && isValidBSTB(root.right, root.val, max); } /** * Inorder traversal, generate a list, should be increasing order */ public boolean isValidBSTC(TreeNode root) { if (root == null) return true; List<Integer> result = new ArrayList<Integer>(); inOrderList(root, result); for (int i = 0; i < result.size() - 1; i++) { if (result.get(i) >= result.get(i + 1)) { return false; } } return true; } public void inOrderList(TreeNode root, List<Integer> res) { if (root == null) return; inOrderList(root.left, res); res.add(root.val); inOrderList(root.right, res); } /** * Preorder * Check if root.val is bigger than value of rightmost node in left subtree * and smaller than value of leftmost node in right subtree. */ public boolean isValidBSTD(TreeNode root) { if (root == null) return true; TreeNode temp = null; if (root.left != null) { temp = root.left; while (temp.right != null) { // move to right most temp = temp.right; } if (temp.val >= root.val) return false; } if (root.right != null) { temp = root.right; while (temp.left != null) { // move to left most temp = temp.left; } if (temp.val <= root.val) return false; } return isValidBST(root.left) && isValidBST(root.right); } // inorder, public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } }
package markehme.factionsplus; import java.net.URL; import java.net.URLConnection; import java.util.Scanner; import markehme.factionsplus.config.Config; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitScheduler; @SuppressWarnings( "unused" ) public class FactionsPlusUpdate implements Runnable { private static final long DELAY = 5*20;//5 sec delay on startup before checking for updates private static final long PERIOD = 4*60*60*20;//20 ticks per sec, check every 24 hours private static FactionsPlusUpdate once = null; // TODO: fix when no-internet access allowed and does 'reload' two times, the second waits 10 sec for the first run of // thread to timeout on reading due to unknown host (after 10 sec) private static volatile int taskId=Integer.MIN_VALUE; // if modified in two threads static { if ( PERIOD < 60 * 20){ // FactionsPlus.instance.disableSelf(); throw FactionsPlus.bailOut("Please set the repeating delay to at least every 60 seconds though it should be much more"); //yeah this will still not stop it } } static public void checkUpdates( FactionsPlus instance ) { synchronized ( FactionsPlusUpdate.class ) { if ( null == once ) { once = new FactionsPlusUpdate(); } taskId = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(instance, once, DELAY, PERIOD); //taskId = Bukkit.getServer().getScheduler().scheduleAsyncRepeatingTask( instance, once, DELAY, PERIOD ); if ( taskId < 0 ) {// not possible FactionsPlus.warn( "Failed to start the check-for-updates thread!" ); } } } public static boolean isRunning() { synchronized ( FactionsPlusUpdate.class ) { return (taskId >= 0) && (once != null); } } public static void ensureNotRunning() { synchronized ( FactionsPlusUpdate.class ) { if ( taskId >= 0 ) { BukkitScheduler sched = Bukkit.getServer().getScheduler(); //this is nolonger relevant, since we're checking for updates every x hours, it will always be detected //as still running here (except when never started) // if ( sched.isCurrentlyRunning( taskId ) ) {// not possible due to lock // FactionsPlus.warn( "The check-for-updates thread was still running" ); sched.cancelTask( taskId );// yeah it's doing the same thing as I did // thread still runs even though plugin restarted, and now runs twice taskId = Integer.MIN_VALUE; if ( sched.isCurrentlyRunning( taskId ) ) {// not reached! FactionsPlus.warn( "Stopped the check-for-updates thread" ); } } once=null; } } public static void enableOrDisableCheckingForUpdates() { synchronized ( FactionsPlusUpdate.class ) { if ( Config._extras.disableUpdateCheck._ ) { FactionsPlusUpdate.ensureNotRunning(); FactionsPlus.info("Never checking for updates"); } else { // enable if ( !isRunning() ) { FactionsPlus.info("Will now check for updates every "+(PERIOD/20/60/60)+" hours (and on startup)"); FactionsPlusUpdate.checkUpdates( FactionsPlus.instance ); }else{ //still running FactionsPlus.info("Still checking for updates every "+(PERIOD/20/60/60)+" hours (and on startup)"); // next check is in " // Bukkit.getServer().getScheduler().); } } } } @Override public void run() { synchronized ( FactionsPlusUpdate.class ) { String content = null; URLConnection connection = null; String v = FactionsPlus.version; FactionsPlusPlugin.info( "Checking for updates ... " ); Scanner scanner = null; try { connection = new URL( "http: //TODO: validate these timeouts connection.setReadTimeout(15 * 1000); // Read time out after 15 seconds. connection.setConnectTimeout(15 * 1000); // Connect time out after 15 seconds scanner = new Scanner( connection.getInputStream() ); scanner.useDelimiter( "\\Z" ); content = scanner.next(); }catch (java.net.UnknownHostException uhe) { FactionsPlusPlugin.info( "Failed to check for updates. Cannot resolve host "+uhe.getMessage() ); return; }catch (java.net.ConnectException ce) { FactionsPlusPlugin.info( "Failed to check for updates. "+ce.getMessage() ); return; }catch( java.net.SocketTimeoutException ste ) { FactionsPlusPlugin.info( "Failed to check for updates, the connection timed out (15 seconds): "+ste.getMessage() ); return; }catch ( Exception ex ) { ex.printStackTrace(); FactionsPlusPlugin.info( "Failed to check for updates." ); return; } finally { if ( null != scanner ) { scanner.close(); } } // advanced checking if ( !content.trim().equalsIgnoreCase( v.trim() ) ) { int web, current; String tempWeb = content.trim().replace( ".", "" ); String tempThis = v.trim().replace( ".", "" ); web = Integer.parseInt( tempWeb ); current = Integer.parseInt( tempThis ); // Check if version lengths are the same if ( tempWeb.length() == tempThis.length() ) { if ( web > current ) { // Version lengths different, unable to advance compare FactionsPlus.log.warning( "! -=====================================- !" ); FactionsPlus.log.warning( "FactionsPlus has an update, you" ); FactionsPlus.log.warning( "can upgrade to version " + content.trim() + " via" ); FactionsPlus.log.warning( "http://dev.bukkit.org/server-mods/factionsplus/" ); FactionsPlus.log.warning( "! -=====================================- !" ); for (Player player : Bukkit.getServer().getOnlinePlayers()) { if (player.isOp()) { player.sendMessage(ChatColor.RED + "FactionsPlus version " + ChatColor.GOLD + content.trim() + ChatColor.RED + " is out! You should upgrade to avoid bugs, and deprecated code. (+ new features, come on!) " ); } } } else { FactionsPlusPlugin.info( "Up to date!" ); } } else { // Version lengths different, unable to advance compare FactionsPlus.log.warning( "! -=====================================- !" ); FactionsPlus.log.warning( "FactionsPlus has an update, you" ); FactionsPlus.log.warning( "can upgrade to version " + content.trim() + " via" ); FactionsPlus.log.warning( "http://dev.bukkit.org/server-mods/factionsplus/" ); FactionsPlus.log.warning( "! -=====================================- !" ); for (Player player : Bukkit.getServer().getOnlinePlayers()) { if (player.isOp()) { player.sendMessage(ChatColor.RED + "FactionsPlus version " + ChatColor.GOLD + content.trim() + ChatColor.RED + " is out! You should upgrade to avoid bugs, and deprecated code. (+ new features, come on!) " ); } } } } else { FactionsPlusPlugin.info( "Up to date!" ); } } } }
package model.supervised.svm.kernels; import utils.array.ArrayUtil; public class PolynomialK implements Kernel { public static double DEGREE = 2.0D; public static double COEF = 1.0D; public static double GAMMA = 1.0D; @Override public double similarity(double[] x1, double[] x2) { double innerProduct = ArrayUtil.innerProduct(x1, x2); return Math.pow((GAMMA * innerProduct) + COEF, DEGREE); } }
//Title: TASSELMainFrame //Company: NCSU package net.maizegenetics.tassel; import net.maizegenetics.baseplugins.*; import net.maizegenetics.baseplugins.chart.ChartDisplayPlugin; import net.maizegenetics.baseplugins.genomicselection.RidgeRegressionEmmaPlugin; import net.maizegenetics.baseplugins.numericaltransform.NumericalTransformPlugin; import net.maizegenetics.gui.PrintHeapAction; import net.maizegenetics.plugindef.*; import net.maizegenetics.prefs.TasselPrefs; import net.maizegenetics.progress.ProgressPanel; import net.maizegenetics.util.Utils; import org.apache.log4j.Logger; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.io.*; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * TASSELMainFrame * */ public class TASSELMainFrame extends JFrame implements ActionListener { private static final Logger myLogger = Logger.getLogger(TASSELMainFrame.class); public static final String version = "5.0.0"; public static final String versionDate = "December 5, 2013"; private DataTreePanel myDataTreePanel; private String tasselDataFile = "TasselDataFile"; //a variable to control when the progress bar was last updated private JFileChooser filerSave = new JFileChooser(); private JFileChooser filerOpen = new JFileChooser(); private JScrollPane reportPanelScrollPane = new JScrollPane(); private JTextArea reportPanelTextArea = new JTextArea(); JScrollPane mainPanelScrollPane = new JScrollPane(); JPanel mainDisplayPanel = new JPanel(); private JTextArea mainPanelTextArea = new JTextArea(); private JTextField myStatusTextField = new JTextField(); private JMenuItem openCompleteDataTreeMenuItem = new JMenuItem(); private JMenuItem openDataMenuItem = new JMenuItem(); private JMenuItem saveCompleteDataTreeMenuItem = new JMenuItem(); private JMenuItem saveDataTreeAsMenuItem = new JMenuItem(); private PreferencesDialog thePreferencesDialog; private final ProgressPanel myProgressPanel = ProgressPanel.getInstance(); private HashMap<JMenuItem, Plugin> myMenuItemHash = new HashMap<JMenuItem, Plugin>(); public TASSELMainFrame() { try { loadSettings(); myDataTreePanel = new DataTreePanel(this); myDataTreePanel.setToolTipText("Data Tree Panel"); addMenuBar(); initializeMyFrame(); this.setTitle("TASSEL (Trait Analysis by aSSociation, Evolution, and Linkage) " + version); myLogger.info("Tassel Version: " + version + " Date: " + versionDate); myLogger.info("Max Available Memory Reported by JVM: " + Utils.getMaxHeapSizeMB() + " MB"); } catch (Exception e) { e.printStackTrace(); } } //Component initialization private void initializeMyFrame() throws Exception { getContentPane().setLayout(new BorderLayout()); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // it is time for TASSEL to claim more (almost all) of the screen real estate for itself // this size was selected so as to encourage the user to resize to full screen, thereby // insuring that all parts of the frame are visible. setSize(new Dimension(screenSize.width * 19 / 20, screenSize.height * 19 / 20)); setTitle("TASSEL (Trait Analysis by aSSociation, Evolution, and Linkage)"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); filerSave.setDialogType(JFileChooser.SAVE_DIALOG); JSplitPane dataTreeReportPanelsSplitPanel = new JSplitPane(); dataTreeReportPanelsSplitPanel.setOrientation(JSplitPane.VERTICAL_SPLIT); reportPanelTextArea.setEditable(false); reportPanelTextArea.setToolTipText("Report Panel"); mainPanelTextArea.setDoubleBuffered(true); mainPanelTextArea.setEditable(false); mainPanelTextArea.setFont(new java.awt.Font("Monospaced", 0, 12)); mainPanelTextArea.setToolTipText("Main Panel"); myStatusTextField.setBackground(Color.lightGray); myStatusTextField.setBorder(null); saveCompleteDataTreeMenuItem.setText("Save Data Tree"); saveCompleteDataTreeMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveCompleteDataTreeMenuItem_actionPerformed(e); } }); saveDataTreeAsMenuItem.setText("Save Data Tree As ..."); saveDataTreeAsMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { saveDataTreeMenuItem_actionPerformed(e); } }); openCompleteDataTreeMenuItem.setText("Open Data Tree"); openCompleteDataTreeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { openCompleteDataTreeMenuItem_actionPerformed(e); } }); openDataMenuItem.setText("Open Data Tree..."); openDataMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { openDataMenuItem_actionPerformed(e); } }); JSplitPane dataTreeReportMainPanelsSplitPanel = new JSplitPane(); getContentPane().add(dataTreeReportMainPanelsSplitPanel, BorderLayout.CENTER); dataTreeReportMainPanelsSplitPanel.add(dataTreeReportPanelsSplitPanel, JSplitPane.LEFT); dataTreeReportPanelsSplitPanel.add(myDataTreePanel, JSplitPane.TOP); JSplitPane reportProgressSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); JPanel reportPanel = new JPanel(new BorderLayout()); reportProgressSplitPane.add(reportPanel, JSplitPane.TOP); reportPanel.add(reportPanelScrollPane, BorderLayout.CENTER); reportPanelScrollPane.getViewport().add(reportPanelTextArea, null); reportProgressSplitPane.add(new JScrollPane(myProgressPanel), JSplitPane.BOTTOM); dataTreeReportPanelsSplitPanel.add(reportProgressSplitPane, JSplitPane.BOTTOM); dataTreeReportMainPanelsSplitPanel.add(mainDisplayPanel, JSplitPane.RIGHT); mainDisplayPanel.setLayout(new BorderLayout()); mainPanelScrollPane.getViewport().add(mainPanelTextArea, null); mainDisplayPanel.add(mainPanelScrollPane, BorderLayout.CENTER); mainPanelScrollPane.getViewport().add(mainPanelTextArea, null); getContentPane().add(myStatusTextField, BorderLayout.SOUTH); dataTreeReportMainPanelsSplitPanel.setDividerLocation(getSize().width / 4); dataTreeReportPanelsSplitPanel.setDividerLocation((int) (getSize().height / 3.5)); reportProgressSplitPane.setDividerLocation((int) (getSize().height / 3.5)); } private void addMenuBar() { JMenuBar jMenuBar = new JMenuBar(); jMenuBar.add(getFileMenu()); jMenuBar.add(getDataMenu()); jMenuBar.add(getFiltersMenu()); jMenuBar.add(getAnalysisMenu()); jMenuBar.add(getResultsMenu()); jMenuBar.add(getHelpMenu()); this.setJMenuBar(jMenuBar); } //Help | About action performed private void helpAbout_actionPerformed(ActionEvent e) { AboutBox dlg = new AboutBox(this); Dimension dlgSize = dlg.getPreferredSize(); Dimension frmSize = getSize(); Point loc = getLocation(); dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y); dlg.setModal(true); dlg.setVisible(true); } public void sendMessage(String text) { myStatusTextField.setForeground(Color.BLACK); myStatusTextField.setText(text); } public void sendErrorMessage(String text) { myStatusTextField.setForeground(Color.RED); myStatusTextField.setText(text); } public void setMainText(String text) { mainPanelTextArea.setText(text); } public void setNoteText(String text) { reportPanelTextArea.setText(text); } private void loadSettings() { filerOpen.setCurrentDirectory(new File(TasselPrefs.getOpenDir())); filerSave.setCurrentDirectory(new File(TasselPrefs.getSaveDir())); } /** * Provides a save filer that remembers the last location something was * saved to */ private File getSaveFile() { File saveFile = null; int returnVal = filerSave.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { saveFile = filerSave.getSelectedFile(); TasselPrefs.putSaveDir(filerSave.getCurrentDirectory().getPath()); } return saveFile; } /** * Provides a open filer that remember the last location something was * opened from */ private File getOpenFile() { File openFile = null; int returnVal = filerOpen.showOpenDialog(this); System.out.println("returnVal = " + returnVal); System.out.println("JFileChooser.OPEN_DIALOG " + JFileChooser.OPEN_DIALOG); if (returnVal == JFileChooser.OPEN_DIALOG || returnVal == JFileChooser.APPROVE_OPTION) { openFile = filerOpen.getSelectedFile(); System.out.println("openFile = " + openFile); TasselPrefs.putOpenDir(filerOpen.getCurrentDirectory().getPath()); } return openFile; } public void addDataSet(DataSet theDataSet, String defaultNode) { myDataTreePanel.addDataSet(theDataSet, defaultNode); } private void saveDataTree(String file) { Map dataToSerialize = new LinkedHashMap(); Map dataFromTree = myDataTreePanel.getDataList(); StringBuilder builder = new StringBuilder(); Iterator itr = dataFromTree.keySet().iterator(); while (itr.hasNext()) { Datum currentDatum = (Datum) itr.next(); String currentNode = (String) dataFromTree.get(currentDatum); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(currentDatum); oos.close(); if (out.toByteArray().length > 0) { dataToSerialize.put(currentDatum, currentNode); } } catch (Exception e) { myLogger.warn("saveDataTree: object: " + currentDatum.getName() + " type: " + currentDatum.getData().getClass().getName() + " does not serialize."); myLogger.warn("saveDataTree: message: " + e.getMessage()); if (builder.length() == 0) { builder.append("Due to error, these data sets could not\n"); builder.append("included in the saved file..."); } builder.append("Data set: "); builder.append(currentDatum.getName()); builder.append(" type: "); builder.append(currentDatum.getData().getClass().getName()); builder.append("\n"); } } try { File theFile = new File(Utils.addSuffixIfNeeded(file, ".zip")); FileOutputStream fos = new FileOutputStream(theFile); java.util.zip.ZipOutputStream zos = new ZipOutputStream(fos); ZipEntry thisEntry = new ZipEntry("DATA"); zos.putNextEntry(thisEntry); ObjectOutputStream oos = new ObjectOutputStream(zos); oos.writeObject(dataToSerialize); oos.flush(); zos.closeEntry(); fos.close(); sendMessage("Data saved to " + theFile.getAbsolutePath()); } catch (Exception ee) { sendErrorMessage("Data could not be saved: " + ee); ee.printStackTrace(); } if (builder.length() != 0) { JOptionPane.showMessageDialog(this, builder.toString(), "These data sets not saved...", JOptionPane.INFORMATION_MESSAGE); } } private boolean readDataTree(String file) { String dataTreeLoadFailed = "Unable to open the saved data tree. The file format of this version is " + "incompatible with other versions."; boolean loadedDataTreePanel = false; try { FileInputStream fis = null; ObjectInputStream ois = null; if (file.endsWith("zip")) { fis = new FileInputStream(file); java.util.zip.ZipInputStream zis = new java.util.zip.ZipInputStream(fis); zis.getNextEntry(); ois = new ObjectInputStream(zis); } else { fis = new FileInputStream(file); ois = new ObjectInputStream(fis); } try { Map data = (Map) ois.readObject(); Iterator itr = data.keySet().iterator(); while (itr.hasNext()) { Datum currentDatum = (Datum) itr.next(); String currentNode = (String) data.get(currentDatum); myDataTreePanel.addDatum(currentNode, currentDatum); } loadedDataTreePanel = true; } catch (InvalidClassException ice) { JOptionPane.showMessageDialog(this, dataTreeLoadFailed, "Incompatible File Format", JOptionPane.INFORMATION_MESSAGE); } finally { fis.close(); } if (loadedDataTreePanel) { sendMessage("Data loaded."); } } catch (FileNotFoundException fnfe) { JOptionPane.showMessageDialog(this, "File not found: " + file, "File not found", JOptionPane.INFORMATION_MESSAGE); sendErrorMessage("Data tree could not be loaded."); return false; } catch (Exception ee) { JOptionPane.showMessageDialog(this, dataTreeLoadFailed + ee, "Incompatible File Format", JOptionPane.INFORMATION_MESSAGE); sendErrorMessage("Data tree could not be loaded."); return false; } return loadedDataTreePanel; } private void helpButton_actionPerformed(ActionEvent e) { HelpDialog theHelpDialog = new HelpDialog(this); theHelpDialog.setLocationRelativeTo(this); theHelpDialog.setVisible(true); } private void openCompleteDataTreeMenuItem_actionPerformed(ActionEvent e) { String dataFileName = tasselDataFile + ".zip"; File dataFile = new File(dataFileName); if (dataFile.exists()) { readDataTree(dataFileName); } else if (new File("QPGADataFile").exists()) { // this exists to maintain backward compatibility with previous versions (pre-v0.99) readDataTree("QPGADataFile"); } else { JOptionPane.showMessageDialog(this, "File: " + dataFile.getAbsolutePath() + " does not exist.\n" + "Try using File/Open Data Tree..."); } } private void openDataMenuItem_actionPerformed(ActionEvent e) { File f = getOpenFile(); if (f != null) { readDataTree(f.getAbsolutePath()); } } private void saveDataTreeMenuItem_actionPerformed(ActionEvent e) { File f = getSaveFile(); if (f != null) { saveDataTree(f.getAbsolutePath()); } } private void saveCompleteDataTreeMenuItem_actionPerformed(ActionEvent e) { saveDataTree(tasselDataFile + ".zip"); } private void preferencesMenuItem_actionPerformed(ActionEvent e) { if (thePreferencesDialog == null) { thePreferencesDialog = new PreferencesDialog(); thePreferencesDialog.pack(); } thePreferencesDialog.setLocationRelativeTo(this); thePreferencesDialog.setVisible(true); } public void updateMainDisplayPanel(JPanel panel) { mainDisplayPanel.removeAll(); mainDisplayPanel.add(panel, BorderLayout.CENTER); mainDisplayPanel.repaint(); mainDisplayPanel.validate(); } public DataTreePanel getDataTreePanel() { return myDataTreePanel; } public ProgressPanel getProgressPanel() { return myProgressPanel; } private JMenuItem createMenuItem(Plugin theTP) { return createMenuItem(theTP, -1); } private JMenuItem createMenuItem(Plugin theTP, int mnemonic) { ImageIcon icon = theTP.getIcon(); JMenuItem menuItem = new JMenuItem(theTP.getButtonName(), icon); if (mnemonic != -1) { menuItem.setMnemonic(mnemonic); } int pixels = 30; if (icon != null) { pixels -= icon.getIconWidth(); pixels /= 2; } menuItem.setIconTextGap(pixels); menuItem.setBackground(Color.white); menuItem.setMargin(new Insets(2, 2, 2, 2)); menuItem.setToolTipText(theTP.getToolTipText()); menuItem.addActionListener(this); theTP.addListener(myDataTreePanel); myMenuItemHash.put(menuItem, theTP); return menuItem; } private JMenu getFiltersMenu() { JMenu result = new JMenu("Filter"); result.setMnemonic(KeyEvent.VK_F); result.add(createMenuItem(new FilterAlignmentPlugin(this, true))); result.add(createMenuItem(new FilterSiteNamePlugin(this, true))); result.add(createMenuItem(new FilterTaxaAlignmentPlugin(this, true))); result.add(createMenuItem(new FilterTaxaPropertiesPlugin(this, true))); result.add(createMenuItem(new FilterTraitsPlugin(this, true))); return result; } private JMenu getDataMenu() { JMenu result = new JMenu("Data"); result.setMnemonic(KeyEvent.VK_D); PlinkLoadPlugin plinkLoadPlugin = new PlinkLoadPlugin(this, true); plinkLoadPlugin.addListener(myDataTreePanel); FlapjackLoadPlugin flapjackLoadPlugin = new FlapjackLoadPlugin(this, true); flapjackLoadPlugin.addListener(myDataTreePanel); result.add(createMenuItem(new FileLoadPlugin(this, true, plinkLoadPlugin, flapjackLoadPlugin), KeyEvent.VK_L)); result.add(createMenuItem(new ExportPlugin(this, true))); result.add(createMenuItem(new GenotypeImputationPlugin(this, true))); result.add(createMenuItem(new NumericalTransformPlugin(this, true))); result.add(createMenuItem(new SynonymizerPlugin(this, true))); result.add(createMenuItem(new IntersectionAlignmentPlugin(this, true))); result.add(createMenuItem(new UnionAlignmentPlugin(this, true))); result.add(createMenuItem(new MergeAlignmentsPlugin(this, true))); result.add(createMenuItem(new SeparatePlugin(this, true))); result.addSeparator(); JMenuItem delete = new JMenuItem("Delete Dataset"); delete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { myDataTreePanel.deleteSelectedNodes(); } }); delete.setToolTipText("Delete Dataset"); URL imageURL = TASSELMainFrame.class.getResource("images/trash.gif"); if (imageURL == null) { delete.setIconTextGap(30); } else { delete.setIcon(new ImageIcon(imageURL)); delete.setIconTextGap(6); } delete.setIconTextGap(6); result.add(delete); return result; } private JMenu getAnalysisMenu() { JMenu result = new JMenu("Analysis"); result.setMnemonic(KeyEvent.VK_A); result.add(createMenuItem(new SequenceDiversityPlugin(this, true))); result.add(createMenuItem(new LinkageDisequilibriumPlugin(this, true))); result.add(createMenuItem(new CreateTreePlugin(this, true))); result.add(createMenuItem(new KinshipPlugin(this, true))); result.add(createMenuItem(new FixedEffectLMPlugin(this, true))); result.add(createMenuItem(new MLMPlugin(this, true))); result.add(createMenuItem(new RidgeRegressionEmmaPlugin(this, true))); result.add(createMenuItem(new GenotypeSummaryPlugin(this, true))); // result.add(createMenuItem(new StepwiseOLSModelFitterPlugin(this, true))); return result; } private JMenu getResultsMenu() { JMenu result = new JMenu("Results"); result.setMnemonic(KeyEvent.VK_R); result.add(createMenuItem(new TableDisplayPlugin(this, true))); result.add(createMenuItem(new ArchaeopteryxPlugin(this, true))); result.add(createMenuItem(new Grid2dDisplayPlugin(this, true))); result.add(createMenuItem(new LinkageDiseqDisplayPlugin(this, true))); result.add(createMenuItem(new ChartDisplayPlugin(this, true))); result.add(createMenuItem(new QQDisplayPlugin(this, true))); result.add(createMenuItem(new ManhattanDisplayPlugin(this, true))); return result; } private JMenu getFileMenu() { JMenu fileMenu = new JMenu(); fileMenu.setText("File"); fileMenu.add(saveCompleteDataTreeMenuItem); fileMenu.add(openCompleteDataTreeMenuItem); fileMenu.add(saveDataTreeAsMenuItem); fileMenu.add(openDataMenuItem); JMenuItem preferencesMenuItem = new JMenuItem(); preferencesMenuItem.setText("Set Preferences"); preferencesMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { preferencesMenuItem_actionPerformed(e); } }); fileMenu.add(preferencesMenuItem); fileMenu.addSeparator(); JMenuItem exitMenuItem = new JMenuItem("Exit"); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); fileMenu.add(exitMenuItem); return fileMenu; } private JMenu getHelpMenu() { JMenu helpMenu = new JMenu(); helpMenu.setMnemonic(KeyEvent.VK_H); helpMenu.setText("Help"); JMenuItem helpMenuItem = new JMenuItem("Help Manual"); helpMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { helpButton_actionPerformed(e); } }); helpMenu.add(helpMenuItem); JMenuItem aboutMenuItem = new JMenuItem("About"); aboutMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { helpAbout_actionPerformed(e); } }); helpMenu.add(aboutMenuItem); JMenuItem memoryUsage = new JMenuItem("Show Memory"); memoryUsage.addActionListener(PrintHeapAction.getInstance(this)); memoryUsage.setToolTipText("Show Memory Usage"); helpMenu.add(memoryUsage); return helpMenu; } @Override public void actionPerformed(ActionEvent e) { JMenuItem theMenuItem = (JMenuItem) e.getSource(); Plugin theTP = this.myMenuItemHash.get(theMenuItem); PluginEvent event = new PluginEvent(myDataTreePanel.getSelectedTasselDataSet()); ProgressPanel progressPanel = getProgressPanel(); progressPanel.addPlugin(theTP); ThreadedPluginListener thread = new ThreadedPluginListener(theTP, event); thread.start(); } }
//Title: TASSELMainFrame //Company: NCSU package net.maizegenetics.tassel; import net.maizegenetics.pal.alignment.Alignment; import net.maizegenetics.pal.alignment.PhenotypeUtils; import net.maizegenetics.pal.report.TableReportUtils; import net.maizegenetics.plugindef.DataSet; import net.maizegenetics.plugindef.Datum; import net.maizegenetics.prefs.TasselPrefs; import net.maizegenetics.gui.PrintTextArea; import javax.swing.*; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Event; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.*; import java.awt.image.ImageProducer; import java.io.*; import java.net.URL; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import net.maizegenetics.baseplugins.ExportPlugin; import net.maizegenetics.gui.PrintHeapAction; import net.maizegenetics.plugindef.PluginEvent; import net.maizegenetics.plugindef.ThreadedPluginListener; import net.maizegenetics.progress.ProgressPanel; import net.maizegenetics.util.Utils; import net.maizegenetics.wizard.Wizard; import net.maizegenetics.wizard.WizardPanelDescriptor; import net.maizegenetics.wizard.panels.TestPanel1Descriptor; import net.maizegenetics.wizard.panels.TestPanel2Descriptor; import net.maizegenetics.wizard.panels.TestPanel3Descriptor; import net.maizegenetics.wizard.panels.TestPanel4Descriptor; import org.apache.log4j.Logger; /** * TASSELMainFrame * */ public class TASSELMainFrame extends JFrame { private static final Logger myLogger = Logger.getLogger(TASSELMainFrame.class); public static final String version = "4.0.11"; public static final String versionDate = "March 15, 2012"; DataTreePanel theDataTreePanel; DataControlPanel theDataControlPanel; AnalysisControlPanel theAnalysisControlPanel; ResultControlPanel theResultControlPanel; private String tasselDataFile = "TasselDataFile"; //a variable to control when the progress bar was last updated private long lastProgressPaint = 0; private String dataTreeLoadFailed = "Unable to open the saved data tree. The file format of this version is " + "incompatible with other versions."; static final String GENOTYPE_DATA_NEEDED = "Please select genotypic data from the data tree."; static final String RESULTS_DATA_NEEDED = "Please select results data from the data tree."; JFileChooser filerSave = new JFileChooser(); JFileChooser filerOpen = new JFileChooser(); JPanel mainPanel = new JPanel(); JPanel dataTreePanelPanel = new JPanel(); JPanel reportPanel = new JPanel(); JPanel optionsPanel = new JPanel(); JPanel optionsPanelPanel = new JPanel(); JPanel modeSelectorsPanel = new JPanel(); JPanel buttonPanel = new JPanel(); GridLayout buttonPanelLayout = new GridLayout(); GridLayout optionsPanelLayout = new GridLayout(2, 1); JSplitPane dataTreeReportMainPanelsSplitPanel = new JSplitPane(); JSplitPane dataTreeReportPanelsSplitPanel = new JSplitPane(); JScrollPane reportPanelScrollPane = new JScrollPane(); JTextArea reportPanelTextArea = new JTextArea(); JScrollPane mainPanelScrollPane = new JScrollPane(); JPanel mainDisplayPanel = new JPanel(); //mainPanelTextArea corresponds to what is called Main Panel in the user documentation ThreadedJTextArea mainPanelTextArea = new ThreadedJTextArea(); JTextField statusBar = new JTextField(); JButton resultButton = new JButton(); JButton saveButton = new JButton(); JButton dataButton = new JButton(); JButton deleteButton = new JButton(); JButton printButton = new JButton(); JButton analysisButton = new JButton(); JPopupMenu mainPopupMenu = new JPopupMenu(); JMenuBar jMenuBar = new JMenuBar(); JMenu fileMenu = new JMenu(); JMenu toolsMenu = new JMenu(); JMenuItem saveMainMenuItem = new JMenuItem(); JCheckBoxMenuItem matchCheckBoxMenuItem = new JCheckBoxMenuItem(); JMenuItem openCompleteDataTreeMenuItem = new JMenuItem(); JMenuItem openDataMenuItem = new JMenuItem(); JMenuItem saveAsDataTreeMenuItem = new JMenuItem(); JMenuItem saveCompleteDataTreeMenuItem = new JMenuItem(); JMenuItem saveDataTreeAsMenuItem = new JMenuItem(); JMenuItem exitMenuItem = new JMenuItem(); JMenu helpMenu = new JMenu(); JMenuItem helpMenuItem = new JMenuItem(); JMenuItem preferencesMenuItem = new JMenuItem(); JMenuItem aboutMenuItem = new JMenuItem(); PreferencesDialog thePreferencesDialog; String UserComments = ""; private final ProgressPanel myProgressPanel = ProgressPanel.getInstance(); JButton wizardButton = new JButton(); ExportPlugin myExportPlugin = null; public TASSELMainFrame(boolean debug) { try { loadSettings(); addMenuBar(); theDataTreePanel = new DataTreePanel(this, true, debug); theDataTreePanel.setToolTipText("Data Tree Panel"); theDataControlPanel = new DataControlPanel(this, theDataTreePanel); theAnalysisControlPanel = new AnalysisControlPanel(this, theDataTreePanel); theResultControlPanel = new ResultControlPanel(this, theDataTreePanel); theResultControlPanel.setToolTipText("Report Panel"); initializeMyFrame(); setIcon(); initDataMode(); this.setTitle("TASSEL (Trait Analysis by aSSociation, Evolution, and Linkage) " + this.version); } catch (Exception e) { e.printStackTrace(); } } private void setIcon() { URL url = this.getClass().getResource("Logo_small.png"); if (url == null) { return; } Image img = null; try { img = createImage((ImageProducer) url.getContent()); } catch (Exception e) { } if (img != null) { setIconImage(img); } } private void initWizard() { Wizard wizard = new Wizard(theDataTreePanel); wizard.getDialog().setTitle("TASSEL Wizard (In development)"); WizardPanelDescriptor descriptor1 = new TestPanel1Descriptor(); wizard.registerWizardPanel(TestPanel1Descriptor.IDENTIFIER, descriptor1); WizardPanelDescriptor descriptor2 = new TestPanel2Descriptor(); wizard.registerWizardPanel(TestPanel2Descriptor.IDENTIFIER, descriptor2); WizardPanelDescriptor descriptor3 = new TestPanel3Descriptor(); wizard.registerWizardPanel(TestPanel3Descriptor.IDENTIFIER, descriptor3); WizardPanelDescriptor descriptor4 = new TestPanel4Descriptor(); wizard.registerWizardPanel(TestPanel4Descriptor.IDENTIFIER, descriptor4); wizard.setCurrentPanel(TestPanel1Descriptor.IDENTIFIER); wizard.getDialog().setLocationRelativeTo(this); int ret = wizard.showModalDialog(); // System.out.println("Dialog return code is (0=Finish,1=Cancel,2=Error): " + ret); // System.out.println("Second panel selection is: " + // (((TestPanel2)descriptor2.getPanelComponent()).getRadioButtonSelected())); // System.exit(0); } private JButton getHeapButton() { JButton heapButton = new JButton(PrintHeapAction.getInstance(this)); heapButton.setText("Show Memory"); heapButton.setToolTipText("Show Memory Usage"); return heapButton; } private void initDataMode() { buttonPanel.removeAll(); buttonPanel.add(theDataControlPanel, null); dataTreePanelPanel.removeAll(); dataTreePanelPanel.add(theDataTreePanel, BorderLayout.CENTER); this.validate(); repaint(); } private void initAnalysisMode() { buttonPanel.removeAll(); buttonPanel.add(theAnalysisControlPanel, null); dataTreePanelPanel.removeAll(); dataTreePanelPanel.add(theDataTreePanel, BorderLayout.CENTER); this.validate(); repaint(); } private void initResultMode() { buttonPanel.removeAll(); buttonPanel.add(theResultControlPanel, null); dataTreePanelPanel.removeAll(); dataTreePanelPanel.add(theDataTreePanel, BorderLayout.CENTER); this.validate(); repaint(); } //Component initialization private void initializeMyFrame() throws Exception { this.getContentPane().setLayout(new BorderLayout()); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // it is time for TASSEL to claim more (almost all) of the screen real estate for itself // this size was selected so as to encourage the user to resize to full screen, thereby // insuring that all parts of the frame are visible. this.setSize(new Dimension(screenSize.width * 19 / 20, screenSize.height * 19 / 20)); this.setTitle("TASSEL (Trait Analysis by aSSociation, Evolution, and Linkage)"); this.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(WindowEvent e) { this_windowClosing(e); } }); filerSave.setDialogType(JFileChooser.SAVE_DIALOG); mainPanel.setLayout(new BorderLayout()); dataTreeReportPanelsSplitPanel.setOrientation(JSplitPane.VERTICAL_SPLIT); optionsPanelPanel.setLayout(new BorderLayout()); dataTreePanelPanel.setLayout(new BorderLayout()); dataTreePanelPanel.setToolTipText("Data Tree Panel"); reportPanel.setLayout(new BorderLayout()); reportPanelTextArea.setEditable(false); reportPanelTextArea.setToolTipText("Report Panel"); mainPanelTextArea.setDoubleBuffered(true); mainPanelTextArea.setEditable(false); mainPanelTextArea.setFont(new java.awt.Font("Monospaced", 0, 12)); mainPanelTextArea.setToolTipText("Main Panel"); mainPanelTextArea.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(MouseEvent e) { mainTextArea_mouseClicked(e); } }); statusBar.setBackground(Color.lightGray); statusBar.setBorder(null); statusBar.setText("Program Status"); modeSelectorsPanel.setLayout(new GridBagLayout()); modeSelectorsPanel.setMinimumSize(new Dimension(380, 32)); modeSelectorsPanel.setPreferredSize(new Dimension(700, 32)); URL imageURL = TASSELMainFrame.class.getResource("images/help1.gif"); ImageIcon helpIcon = null; if (imageURL != null) { helpIcon = new ImageIcon(imageURL); } JButton helpButton = new JButton(); helpButton.setIcon(helpIcon); helpButton.setMargin(new Insets(0, 0, 0, 0)); helpButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { helpButton_actionPerformed(e); } }); helpButton.setBackground(Color.white); helpButton.setMinimumSize(new Dimension(20, 20)); helpButton.setToolTipText("Help me!!"); resultButton.setText("Results"); resultButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { resultButton_actionPerformed(e); } }); resultButton.setMargin(new Insets(2, 2, 2, 2)); imageURL = TASSELMainFrame.class.getResource("images/Results.gif"); ImageIcon resultsIcon = null; if (imageURL != null) { resultsIcon = new ImageIcon(imageURL); } if (resultsIcon != null) { resultButton.setIcon(resultsIcon); } resultButton.setPreferredSize(new Dimension(90, 25)); resultButton.setMinimumSize(new Dimension(87, 25)); resultButton.setMaximumSize(new Dimension(90, 25)); resultButton.setBackground(Color.white); wizardButton.setText("Wizard"); wizardButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { wizardButton_actionPerformed(e); } }); wizardButton.setMargin(new Insets(2, 2, 2, 2)); wizardButton.setPreferredSize(new Dimension(90, 25)); wizardButton.setMinimumSize(new Dimension(87, 25)); wizardButton.setMaximumSize(new Dimension(90, 25)); wizardButton.setBackground(Color.white); saveButton.setMargin(new Insets(0, 0, 0, 0)); saveButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { saveButton_actionPerformed(e); } }); saveButton.setBackground(Color.white); saveButton.setMinimumSize(new Dimension(20, 20)); saveButton.setToolTipText("Save selected data to text file"); imageURL = TASSELMainFrame.class.getResource("images/save1.gif"); ImageIcon saveIcon = null; if (imageURL != null) { saveIcon = new ImageIcon(imageURL); } if (saveIcon != null) { saveButton.setIcon(saveIcon); } dataButton.setBackground(Color.white); dataButton.setMaximumSize(new Dimension(90, 25)); dataButton.setMinimumSize(new Dimension(87, 25)); dataButton.setPreferredSize(new Dimension(90, 25)); imageURL = TASSELMainFrame.class.getResource("images/DataSeq.gif"); ImageIcon dataSeqIcon = null; if (imageURL != null) { dataSeqIcon = new ImageIcon(imageURL); } if (dataSeqIcon != null) { dataButton.setIcon(dataSeqIcon); } dataButton.setMargin(new Insets(2, 2, 2, 2)); dataButton.setText("Data"); dataButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { dataButton_actionPerformed(e); } }); printButton.setBackground(Color.white); printButton.setToolTipText("Print selected datum"); imageURL = TASSELMainFrame.class.getResource("images/print1.gif"); ImageIcon printIcon = null; if (imageURL != null) { printIcon = new ImageIcon(imageURL); } if (printIcon != null) { printButton.setIcon(printIcon); } printButton.setMargin(new Insets(0, 0, 0, 0)); printButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { printButton_actionPerformed(e); } }); analysisButton.setText("Analysis"); analysisButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { analysisButton_actionPerformed(e); } }); analysisButton.setMargin(new Insets(2, 2, 2, 2)); imageURL = TASSELMainFrame.class.getResource("images/Analysis.gif"); ImageIcon analysisIcon = null; if (imageURL != null) { analysisIcon = new ImageIcon(imageURL); } if (analysisIcon != null) { analysisButton.setIcon(analysisIcon); } analysisButton.setPreferredSize(new Dimension(90, 25)); analysisButton.setMinimumSize(new Dimension(87, 25)); analysisButton.setMaximumSize(new Dimension(90, 25)); analysisButton.setBackground(Color.white); // delete button added moved from data panel by yogesh. deleteButton.setOpaque(true); deleteButton.setForeground(Color.RED); deleteButton.setText("Delete"); deleteButton.setFont(new java.awt.Font("Dialog", 1, 12)); deleteButton.setToolTipText("Delete Dataset"); deleteButton.setMargin(new Insets(2, 2, 2, 2)); deleteButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { theDataTreePanel.deleteSelectedNodes(); } }); optionsPanel.setLayout(optionsPanelLayout); buttonPanel.setLayout(buttonPanelLayout); buttonPanel.setMinimumSize(new Dimension(300, 34)); buttonPanel.setPreferredSize(new Dimension(300, 34)); buttonPanelLayout.setHgap(0); buttonPanelLayout.setVgap(0); optionsPanel.setToolTipText("Options Panel"); optionsPanelLayout.setVgap(0); mainPopupMenu.setInvoker(this); saveMainMenuItem.setText("Save"); matchCheckBoxMenuItem.setText("Match"); matchCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { matchCheckBoxMenuItem_actionPerformed(e); } }); fileMenu.setText("File"); toolsMenu.setText("Tools"); saveCompleteDataTreeMenuItem.setText("Save Data Tree"); saveCompleteDataTreeMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveCompleteDataTreeMenuItem_actionPerformed(e); } }); saveDataTreeAsMenuItem.setText("Save Data Tree As ..."); saveDataTreeAsMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { saveDataTreeMenuItem_actionPerformed(e); } }); openCompleteDataTreeMenuItem.setText("Open Data Tree"); openCompleteDataTreeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { openCompleteDataTreeMenuItem_actionPerformed(e); } }); openDataMenuItem.setText("Open Data Tree..."); openDataMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { openDataMenuItem_actionPerformed(e); } }); saveAsDataTreeMenuItem.setText("Save Selected As..."); saveAsDataTreeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { ExportPlugin plugin = getExportPlugin(); PluginEvent event = new PluginEvent(theDataTreePanel.getSelectedTasselDataSet()); ProgressPanel progressPanel = getProgressPanel(); ThreadedPluginListener thread = new ThreadedPluginListener(plugin, event); thread.start(); progressPanel.addPlugin(plugin); } }); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { exitMenuItem_actionPerformed(e); } }); helpMenu.setText("Help"); helpMenuItem.setText("Help Manual"); helpMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { helpButton_actionPerformed(e); } }); preferencesMenuItem.setText("Set Preferences"); preferencesMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { preferencesMenuItem_actionPerformed(e); } }); aboutMenuItem.setText("About"); aboutMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { helpAbout_actionPerformed(e); } }); this.getContentPane().add(dataTreeReportMainPanelsSplitPanel, BorderLayout.CENTER); dataTreeReportMainPanelsSplitPanel.add(optionsPanelPanel, JSplitPane.TOP); optionsPanelPanel.add(dataTreeReportPanelsSplitPanel, BorderLayout.CENTER); dataTreeReportPanelsSplitPanel.add(dataTreePanelPanel, JSplitPane.TOP); dataTreePanelPanel.add(theDataTreePanel, BorderLayout.CENTER); JSplitPane reportProgress = new JSplitPane(JSplitPane.VERTICAL_SPLIT); reportProgress.add(reportPanel, JSplitPane.TOP); reportPanel.add(reportPanelScrollPane, BorderLayout.CENTER); reportPanelScrollPane.getViewport().add(reportPanelTextArea, null); reportProgress.add(new JScrollPane(myProgressPanel), JSplitPane.BOTTOM); dataTreeReportPanelsSplitPanel.add(reportProgress, JSplitPane.BOTTOM); dataTreeReportMainPanelsSplitPanel.add(mainPanel, JSplitPane.BOTTOM); /** * Provides a save filer that remembers the last location something was saved to */ public File getSaveFile() { File saveFile = null; int returnVal = filerSave.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { saveFile = filerSave.getSelectedFile(); TasselPrefs.putSaveDir(filerSave.getCurrentDirectory().getPath()); } return saveFile; } /** * Provides a open filer that remember the last location something was opened from */ public File getOpenFile() { File openFile = null; int returnVal = filerOpen.showOpenDialog(this); System.out.println("returnVal = " + returnVal); System.out.println("JFileChooser.OPEN_DIALOG " + JFileChooser.OPEN_DIALOG); if (returnVal == JFileChooser.OPEN_DIALOG || returnVal == JFileChooser.APPROVE_OPTION) { openFile = filerOpen.getSelectedFile(); System.out.println("openFile = " + openFile); TasselPrefs.putOpenDir(filerOpen.getCurrentDirectory().getPath()); } return openFile; } void this_windowClosing(WindowEvent e) { exitMenuItem_actionPerformed(null); } public void addDataSet(DataSet theDataSet, String defaultNode) { theDataTreePanel.addDataSet(theDataSet, defaultNode); } private void saveDataTree(String file) { Map dataToSerialize = new LinkedHashMap(); Map dataFromTree = theDataTreePanel.getDataList(); StringBuilder builder = new StringBuilder(); Iterator itr = dataFromTree.keySet().iterator(); while (itr.hasNext()) { Datum currentDatum = (Datum) itr.next(); String currentNode = (String) dataFromTree.get(currentDatum); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(currentDatum); oos.close(); if (out.toByteArray().length > 0) { dataToSerialize.put(currentDatum, currentNode); } } catch (Exception e) { myLogger.warn("saveDataTree: object: " + currentDatum.getName() + " type: " + currentDatum.getData().getClass().getName() + " does not serialize."); myLogger.warn("saveDataTree: message: " + e.getMessage()); if (builder.length() == 0) { builder.append("Due to error, these data sets could not\n"); builder.append("included in the saved file..."); } builder.append("Data set: "); builder.append(currentDatum.getName()); builder.append(" type: "); builder.append(currentDatum.getData().getClass().getName()); builder.append("\n"); } } try { File theFile = new File(Utils.addSuffixIfNeeded(file, ".zip")); FileOutputStream fos = new FileOutputStream(theFile); java.util.zip.ZipOutputStream zos = new ZipOutputStream(fos); Map data = theDataTreePanel.getDataList(); ZipEntry thisEntry = new ZipEntry("DATA"); zos.putNextEntry(thisEntry); ObjectOutputStream oos = new ObjectOutputStream(zos); oos.writeObject(dataToSerialize); oos.flush(); zos.closeEntry(); fos.close(); sendMessage("Data saved to " + theFile.getAbsolutePath()); } catch (Exception ee) { sendErrorMessage("Data could not be saved: " + ee); ee.printStackTrace(); } if (builder.length() != 0) { JOptionPane.showMessageDialog(this, builder.toString(), "These data sets not saved...", JOptionPane.INFORMATION_MESSAGE); } } private boolean readDataTree(String file) { boolean loadedDataTreePanel = false; try { FileInputStream fis = null; ObjectInputStream ois = null; if (file.endsWith("zip")) { fis = new FileInputStream(file); java.util.zip.ZipInputStream zis = new java.util.zip.ZipInputStream(fis); zis.getNextEntry(); ois = new ObjectInputStream(zis); } else { fis = new FileInputStream(file); ois = new ObjectInputStream(fis); } try { Map data = (Map) ois.readObject(); Iterator itr = data.keySet().iterator(); while (itr.hasNext()) { Datum currentDatum = (Datum) itr.next(); String currentNode = (String) data.get(currentDatum); theDataTreePanel.addDatum(currentNode, currentDatum); } loadedDataTreePanel = true; } catch (InvalidClassException ice) { JOptionPane.showMessageDialog(this, dataTreeLoadFailed, "Incompatible File Format", JOptionPane.INFORMATION_MESSAGE); } finally { fis.close(); } if (loadedDataTreePanel) { sendMessage("Data loaded."); } } catch (FileNotFoundException fnfe) { JOptionPane.showMessageDialog(this, "File not found: " + file, "File not found", JOptionPane.INFORMATION_MESSAGE); sendErrorMessage("Data tree could not be loaded."); return false; } catch (Exception ee) { JOptionPane.showMessageDialog(this, dataTreeLoadFailed + ee, "Incompatible File Format", JOptionPane.INFORMATION_MESSAGE); sendErrorMessage("Data tree could not be loaded."); return false; } return loadedDataTreePanel; } private void wizardButton_actionPerformed(ActionEvent e) { initWizard(); } private void dataButton_actionPerformed(ActionEvent e) { initDataMode(); } private void analysisButton_actionPerformed(ActionEvent e) { initAnalysisMode(); } private void resultButton_actionPerformed(ActionEvent e) { initResultMode(); } private void saveButton_actionPerformed(ActionEvent e) { File theFile = getSaveFile(); if (theFile == null) { return; } DataSet ds = theDataTreePanel.getSelectedTasselDataSet(); try { FileWriter fw = new FileWriter(theFile); PrintWriter pw = new PrintWriter(fw); for (int i = 0; i < ds.getSize(); i++) { if (ds.getData(i).getData() instanceof Alignment) { pw.println(ds.getData(i).getData().toString()); } else if (ds.getData(i).getData() instanceof net.maizegenetics.pal.alignment.Phenotype) { PhenotypeUtils.saveAs((net.maizegenetics.pal.alignment.Phenotype) ds.getData(i).getData(), pw); } else if (ds.getData(i).getData() instanceof net.maizegenetics.pal.report.TableReport) { // TableReportUtils tbu=new TableReportUtils((net.maizegenetics.pal.report.TableReport)data[i]); pw.println(TableReportUtils.toDelimitedString((net.maizegenetics.pal.report.TableReport) ds.getData(i).getData(), "\t")); } else { pw.println(ds.getData(i).getData().toString()); } pw.println(""); } fw.flush(); fw.close(); } catch (Exception ee) { System.err.println("saveButton_actionPerformed:" + ee); } this.statusBar.setText("Datasets were saved to " + theFile.getName()); } private void printButton_actionPerformed(ActionEvent e) { DataSet ds = theDataTreePanel.getSelectedTasselDataSet(); try { for (int i = 0; i < ds.getSize(); i++) { PrintTextArea pta = new PrintTextArea(this); pta.printThis(ds.getData(i).getData().toString()); } } catch (Exception ee) { System.err.println("printButton_actionPerformed:" + ee); } this.statusBar.setText("Datasets were sent to the printer"); } private void helpButton_actionPerformed(ActionEvent e) { HelpDialog theHelpDialog = new HelpDialog(this); theHelpDialog.setLocationRelativeTo(this); theHelpDialog.setVisible(true); } private void mainTextArea_mouseClicked(MouseEvent e) { // For this example event, we are checking for right-mouse click. if (e.getModifiers() == Event.META_MASK) { mainPanelTextArea.add(mainPopupMenu); // JPopupMenu must be added to the component whose event is chosen. // Make the jPopupMenu visible relative to the current mouse position in the container. mainPopupMenu.show(mainPanelTextArea, e.getX(), e.getY()); } } private void matchCheckBoxMenuItem_actionPerformed(ActionEvent e) { //theSettings.matchChar = matchCheckBoxMenuItem.isSelected(); } private void openCompleteDataTreeMenuItem_actionPerformed(ActionEvent e) { String dataFileName = this.tasselDataFile + ".zip"; File dataFile = new File(dataFileName); if (dataFile.exists()) { readDataTree(dataFileName); } else if (new File("QPGADataFile").exists()) { // this exists to maintain backward compatibility with previous versions (pre-v0.99) readDataTree("QPGADataFile"); } else { JOptionPane.showMessageDialog(this, "File: " + dataFile.getAbsolutePath() + " does not exist.\n" + "Try using File/Open Data Tree..."); } } private void openDataMenuItem_actionPerformed(ActionEvent e) { File f = getOpenFile(); if (f != null) { readDataTree(f.getAbsolutePath()); } } private void saveDataTreeMenuItem_actionPerformed(ActionEvent e) { File f = getSaveFile(); if (f != null) { saveDataTree(f.getAbsolutePath()); } } private void saveCompleteDataTreeMenuItem_actionPerformed(ActionEvent e) { saveDataTree(this.tasselDataFile + ".zip"); } private void exitMenuItem_actionPerformed(ActionEvent e) { System.exit(0); } private void preferencesMenuItem_actionPerformed(ActionEvent e) { if (thePreferencesDialog == null) { thePreferencesDialog = new PreferencesDialog(); thePreferencesDialog.pack(); } thePreferencesDialog.setLocationRelativeTo(this); thePreferencesDialog.setVisible(true); } public void updateMainDisplayPanel(JPanel panel) { mainDisplayPanel.removeAll(); mainDisplayPanel.add(panel, BorderLayout.CENTER); mainDisplayPanel.repaint(); mainDisplayPanel.validate(); } public void addMenu(JMenu menu) { jMenuBar.add(menu); } public DataTreePanel getDataTreePanel() { return theDataTreePanel; } public ProgressPanel getProgressPanel() { return myProgressPanel; } }
package net.openvision.tools.restlight.test; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import net.openvision.tools.restlight.ParseException; import net.openvision.tools.restlight.RouteTreeParser; import net.openvision.tools.restlight.Routes; public class Test { public static void main(String[] args) throws FileNotFoundException, IOException { String filename = "routes"; try { RouteTreeParser parser = new RouteTreeParser(); Routes routes = parser.parse(new FileReader(filename)); System.out.println(routes.toString()); for (String a : routes.getActions()) { System.out.println(a); } } catch (ParseException e) { System.err.println(filename + ":" + e.getLine() + " - " + e.getLocalizedMessage()); } } }
package nl.sense_os.service.commonsense; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.zip.GZIPOutputStream; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import nl.sense_os.service.ISenseService; import nl.sense_os.service.constants.SenseDataTypes; import nl.sense_os.service.constants.SensePrefs; import nl.sense_os.service.constants.SensePrefs.Auth; import nl.sense_os.service.constants.SensePrefs.Main.Advanced; import nl.sense_os.service.constants.SenseUrls; import nl.sense_os.service.constants.SensorData.SensorNames; import nl.sense_os.service.push.GCMReceiver; import org.apache.http.conn.ssl.SSLSocketFactory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Build; import android.telephony.TelephonyManager; import android.util.Log; public class SenseApi { /** * Application secrets that give an app access to the current CommonSense session ID. * * @see ISenseService#getSessionId(String) */ private static class AppSecrets { static final String SENSE = "]C@+[G1be,f)@3mz|2cj4gq~Jz(8WE&_$7g:,-KOI;v:iQt<r;1OQ@=mr}jmE8>!"; static final String ASK = "3$2Sp16096H*Rg!n*<G<411&8QlMvg!pMyN]q?m[5c|<N+$=/~Su{quv$/j5s`+6"; static final String RDAM_CS = "0$HTLi8e_}9^s7r#[_L~-ndz=t5z)e}I-ai#L22-?0+i7jfF2,~)oyi|H)q*GL$Y"; } private static final String TAG = "SenseApi"; private static final long CACHE_REFRESH = 1000l * 60 * 60; // 1 hour /** * Gets a list of all registered sensors for a user at the CommonSense API. Uses caching for * increased performance. * * @param context * Application context, used for getting preferences. * @return The list of sensors * @throws IOException * In case of communication failure to CommonSense * @throws JSONException * In case of unparseable response from CommonSense */ public static JSONArray getAllSensors(Context context) throws IOException, JSONException { final SharedPreferences authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE); // try to get list of sensors from the cache try { String cachedSensors = authPrefs.getString(Auth.SENSOR_LIST_COMPLETE, null); long cacheTime = authPrefs.getLong(Auth.SENSOR_LIST_COMPLETE_TIME, 0); boolean isOutdated = System.currentTimeMillis() - cacheTime > CACHE_REFRESH; // return cached list of it is still valid if (false == isOutdated && null != cachedSensors) { return new JSONArray(cachedSensors); } } catch (Exception e) { // unlikely to ever happen. Just get the list from CommonSense instead Log.e(TAG, "Failed to get list of sensors from cache!", e); } // if we make it here, the list was not in the cache Log.v(TAG, "List of sensor IDs is missing or outdated, refreshing..."); // request fresh list of sensors for this device from CommonSense String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null); SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false); if (devMode) { Log.i(TAG, "Using development server to get registered sensors"); } String url = devMode ? SenseUrls.DEV_ALL_SENSORS : SenseUrls.ALL_SENSORS; Map<String, String> response = SenseApi.request(context, url, null, cookie); String responseCode = response.get("http response code"); if (!"200".equals(responseCode)) { Log.w(TAG, "Failed to get list of sensors! Response code: " + responseCode); throw new IOException("Incorrect response from CommonSense: " + responseCode); } // parse response and store the list JSONObject content = new JSONObject(response.get("content")); JSONArray sensorList = content.getJSONArray("sensors"); // store the new sensor list Editor authEditor = authPrefs.edit(); authEditor.putString(Auth.SENSOR_LIST_COMPLETE, sensorList.toString()); authEditor.putLong(Auth.SENSOR_LIST_COMPLETE_TIME, System.currentTimeMillis()); authEditor.commit(); return sensorList; } /** * @param context * Context for accessing phone details * @return The default device type, i.e. the phone's model String */ public static String getDefaultDeviceType(Context context) { final SharedPreferences authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE); return authPrefs.getString(Auth.DEVICE_TYPE, Build.MODEL); } /** * @param context * Context for accessing phone details * @return The default device UUID, e.g. the phone's IMEI String */ @TargetApi(9) public static String getDefaultDeviceUuid(Context context) { String uuid = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)) .getDeviceId(); if (null == uuid) { // device has no IMEI, try using the Android serial code if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { uuid = Build.SERIAL; } else { Log.w(TAG, "Cannot get reliable device UUID!"); } } return uuid; } private static List<JSONObject> getMatchingSensors(Context context, String name, String description, String dataType) throws IOException, JSONException { // get list of all registered sensors for this device JSONArray sensors = getAllSensors(context); // check sensors with similar names and descriptions in the list List<JSONObject> result = new ArrayList<JSONObject>(); for (int i = 0; i < sensors.length(); i++) { JSONObject sensor = (JSONObject) sensors.get(i); if (sensor.getString("name").equalsIgnoreCase(name) && ((null == description) || sensor.getString("device_type").equalsIgnoreCase( description)) && ((null == dataType) || sensor.getString("data_type").equalsIgnoreCase( dataType))) { result.add(sensor); } else if (name.equals(SensorNames.ACCELEROMETER) || name.equals(SensorNames.ORIENT) || name.equals(SensorNames.GYRO) || name.equals(SensorNames.LIN_ACCELERATION) || name.equals(SensorNames.MAGNET_FIELD)) { // special case to take care of changed motion sensor descriptions since Gingerbread if (name.equals(sensor.getString("name"))) { // Log.d(TAG, "Using inexact match for '" + name + "' sensor ID..."); result.add(sensor); } } } return result; } /** * Gets the sensor ID at CommonSense , which can be used to modify the sensor information and * data. * * @param context * Context for getting preferences * @param name * Sensor name, to match with registered sensors. * @param description * Sensor description (previously 'device_type'), to match with registered sensors. * @param dataType * Sensor data type, to match with registered sensors. * @param deviceUuid * (Optional) UUID of the device that should hold the sensor. * @return String with the sensor's ID, or null if the sensor does not exist at CommonSense * (yet). * @throws IOException * If the request to CommonSense failed. * @throws JSONException * If the response from CommonSense could not be parsed. */ public static String getSensorId(Context context, String name, String description, String dataType, String deviceUuid) throws IOException, JSONException { // Log.d(TAG, "Get sensor ID. name: '" + name + "', deviceUuid: '" + deviceUuid + "'"); // get list of sensors with matching description List<JSONObject> sensors = getMatchingSensors(context, name, description, dataType); // check the devices that the sensors are connected to String id = null; for (JSONObject sensor : sensors) { if (null != deviceUuid) { // check if the device UUID matches JSONObject device = sensor.optJSONObject("device"); if (null != device && deviceUuid.equals(device.optString("uuid"))) { id = sensor.getString("id"); break; } } else { // we do not care about the device, just accept the first match we find id = sensor.getString("id"); break; } } return id; } /** * Gets the sensors that are connected to another sensor. Typically used * * @param context * @param sensorId * @return List of IDs for connected sensors * @throws IOException * @throws JSONException */ public static List<String> getConnectedSensors(Context context, String sensorId) throws IOException, JSONException { SharedPreferences authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE); // request fresh list of sensors for this device from CommonSense String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null); SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false); if (devMode) { Log.i(TAG, "Using development server to get connected sensors"); } String url = devMode ? SenseUrls.DEV_CONNECTED_SENSORS : SenseUrls.CONNECTED_SENSORS; url = url.replace("<id>", sensorId); Map<String, String> response = SenseApi.request(context, url, null, cookie); String responseCode = response.get("http response code"); if (!"200".equals(responseCode)) { Log.w(TAG, "Failed to get list of connected sensors! Response code: " + responseCode); throw new IOException("Incorrect response from CommonSense: " + responseCode); } // parse response and store the list JSONObject content = new JSONObject(response.get("content")); JSONArray sensorList = content.getJSONArray("sensors"); List<String> result = new ArrayList<String>(); for (int i = 0; i < sensorList.length(); i++) { JSONObject sensor = sensorList.getJSONObject(0); result.add(sensor.getString("id")); } return result; } /** * Get this device_id registered in common sense * * @param context * @throws IOException * @throws JSONException */ public static String getDeviceId(Context context) throws IOException, JSONException { String device_id = null; final SharedPreferences authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE); final SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null); boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false); String url = devMode ? SenseUrls.DEV_DEVICES : SenseUrls.DEVICES; Map<String, String> response = SenseApi.request(context, url, null, cookie); String responseCode = response.get("http response code"); if (!"200".equals(responseCode)) { Log.w(TAG, "Failed to get devices data: " + responseCode); throw new IOException("Incorrect response from CommonSense: " + responseCode); } // check registration result JSONObject res = new JSONObject(response.get("content")); JSONArray arr = res.getJSONArray("devices"); String deviceType = getDefaultDeviceType(context); String deviceUUID = getDefaultDeviceUuid(context); for (int i = 0; i < arr.length(); i++) { JSONObject row = arr.getJSONObject(i); String cid = row.getString("id"); String ctype = row.getString("type"); String cuuid = row.getString("uuid"); if (deviceType.equals(ctype) && deviceUUID.equals(cuuid)) { device_id = cid; break; } } return device_id; } /** * Gets the URL at CommonSense to which the data must be sent. * * @param context * Context for getting preferences * @param name * Sensor name, to match with registered sensors. * @param description * Sensor description (previously 'device_type'), to match with registered sensors. * @param dataType * Sensor data type, to match with registered sensors. * @param deviceUuid * (Optional) UUID of the device that holds the sensor. Set null to use the default * device. * @return String with the sensor's URL, or null if sensor does not have an ID (yet) * @throws JSONException * If there was unexpected response getting the sensor ID. * @throws IOException * If there was a problem during communication with CommonSense. */ public static String getSensorUrl(Context context, String name, String description, String dataType, String deviceUuid) throws IOException, JSONException { String id = getSensorId(context, name, description, dataType, deviceUuid); if (id == null) { Log.e(TAG, "Failed to get URL for sensor '" + name + "': sensor ID is not available"); return null; } SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false); // found the right sensor if (dataType.equals(SenseDataTypes.FILE)) { String url = devMode ? SenseUrls.DEV_SENSOR_FILE : SenseUrls.SENSOR_FILE; return url.replaceFirst("<id>", id); } else { String url = devMode ? SenseUrls.DEV_SENSOR_DATA : SenseUrls.SENSOR_DATA; return url.replaceFirst("<id>", id); } } public static String getSessionId(Context context, String appId) throws IllegalAccessException { SharedPreferences prefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE); if (AppSecrets.ASK.equals(appId)) { // Log.v(TAG, "An ASK app accessed the CommonSense session ID"); return prefs.getString(Auth.LOGIN_COOKIE, null); } else if (AppSecrets.RDAM_CS.equals(appId)) { // Log.v(TAG, "A Rotterdam CS app accessed the CommonSense session ID"); return prefs.getString(Auth.LOGIN_COOKIE, null); } else if (AppSecrets.SENSE.equals(appId)) { // Log.v(TAG, "A Sense app accessed the CommonSense session ID"); return prefs.getString(Auth.LOGIN_COOKIE, null); } else { Log.e(TAG, "App is not allowed access to the CommonSense session!"); throw new IllegalAccessException( "App is not allowed access to the CommonSense session!"); } } /** * @param hashMe * "clear" password String to be hashed before sending it to CommonSense * @return Hashed String */ public static String hashPassword(String hashMe) { final byte[] unhashedBytes = hashMe.getBytes(); try { final MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(unhashedBytes); final byte[] hashedBytes = algorithm.digest(); final StringBuffer hexString = new StringBuffer(); for (final byte element : hashedBytes) { final String hex = Integer.toHexString(0xFF & element); if (hex.length() == 1) { hexString.append(0); } hexString.append(hex); } return hexString.toString(); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } /** * Tries to log in at CommonSense using the supplied username and password. After login, the * cookie containing the session ID is stored in the preferences. * * @param context * Context for getting preferences * @param username * Username for authentication * @param password * Hashed password for authentication * @return 0 if login completed successfully, -2 if login was forbidden, and -1 for any other * errors. * @throws JSONException * In case of unparseable response from CommonSense * @throws IOException * In case of communication failure to CommonSense */ public static int login(Context context, String username, String password) throws JSONException, IOException { // preferences final SharedPreferences authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE); final Editor authEditor = authPrefs.edit(); SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false); if (devMode) Log.i(TAG, "Using developmentserver to log in"); final String url = devMode ? SenseUrls.DEV_LOGIN : SenseUrls.LOGIN; Log.v(TAG, "loggin to url:" + url); final JSONObject user = new JSONObject(); user.put("username", username); user.put("password", password); // perform actual request Map<String, String> response = request(context, url, user, null); // if response code is not 200 (OK), the login was incorrect String responseCode = response.get("http response code"); int result = -1; if ("403".equalsIgnoreCase(responseCode)) { Log.w(TAG, "CommonSense login refused! Response: forbidden!"); result = -2; } else if (!"200".equalsIgnoreCase(responseCode)) { Log.w(TAG, "CommonSense login failed! Response: " + responseCode); result = -1; } else { // received 200 response result = 0; } // get the cookie from the response String cookie = response.get("set-cookie"); if (result == 0 && response.get("set-cookie") == null) { // something went horribly wrong Log.w(TAG, "CommonSense login failed: no cookie received?!"); result = -1; } // handle result switch (result) { case 0: // logged in authEditor.putString(Auth.LOGIN_COOKIE, cookie); authEditor.commit(); break; case -1: // error break; case -2: // unauthorized authEditor.remove(Auth.LOGIN_COOKIE); authEditor.commit(); break; default: Log.e(TAG, "Unexpected login result: " + result); } return result; } /** * Registers a new sensor for this device at CommonSense. Also connects the sensor to this * device. * * @param context * The application context, used to retrieve preferences. * @param name * The name of the sensor. * @param displayName * The sensor's pretty display name. * @param description * The sensor description (previously "device_type"). * @param dataType * The sensor data type. * @param value * An example sensor value, used to determine the data structure for JSON type * sensors. * @param deviceType * (Optional) Type of the device that holds the sensor. Set null to use the default * device. * @param deviceUuid * (Optional) UUID of the device that holds the sensor. Set null to use the default * device. * @return The new sensor ID at CommonSense, or <code>null</code> if the registration failed. * @throws JSONException * In case of invalid sensor details or if the request returned unparseable * response. * @throws IOException * In case of communication failure during creation of the sensor. */ public static String registerSensor(Context context, String name, String displayName, String description, String dataType, String value, String deviceType, String deviceUuid) throws JSONException, IOException { final SharedPreferences authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE); String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null); SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false); // prepare request to create new sensor String url = devMode ? SenseUrls.DEV_CREATE_SENSOR : SenseUrls.CREATE_SENSOR; JSONObject postData = new JSONObject(); JSONObject sensor = new JSONObject(); sensor.put("name", name); sensor.put("device_type", description); sensor.put("display_name", displayName); sensor.put("pager_type", ""); sensor.put("data_type", dataType); if (dataType.compareToIgnoreCase("json") == 0) { JSONObject dataStructJSon = new JSONObject(value); JSONArray fieldNames = dataStructJSon.names(); for (int x = 0; x < fieldNames.length(); x++) { String fieldName = fieldNames.getString(x); int start = dataStructJSon.get(fieldName).getClass().getName().lastIndexOf("."); dataStructJSon.put(fieldName, dataStructJSon.get(fieldName).getClass().getName() .substring(start + 1)); } sensor.put("data_structure", dataStructJSon.toString().replaceAll("\"", "\\\"")); } postData.put("sensor", sensor); // perform actual request Map<String, String> response = request(context, url, postData, cookie); // check response code String code = response.get("http response code"); if (!"201".equals(code)) { Log.e(TAG, "Failed to register sensor at CommonSense! Response code: " + code); throw new IOException("Incorrect response from CommonSense: " + code); } // retrieve the newly created sensor ID String content = response.get("content"); JSONObject responseJson = new JSONObject(content); JSONObject jsonSensor = responseJson.getJSONObject("sensor"); final String id = jsonSensor.getString("id"); // get device properties from preferences, so it matches the properties in CommonSense if (null == deviceUuid) { deviceUuid = getDefaultDeviceUuid(context); deviceType = getDefaultDeviceType(context); } // Add sensor to this device at CommonSense url = devMode ? SenseUrls.DEV_ADD_SENSOR_TO_DEVICE : SenseUrls.ADD_SENSOR_TO_DEVICE; url = url.replaceFirst("<id>", id); postData = new JSONObject(); JSONObject device = new JSONObject(); device.put("type", deviceType); device.put("uuid", deviceUuid); postData.put("device", device); response = request(context, url, postData, cookie); // check response code code = response.get("http response code"); if (!"201".equals(code)) { Log.e(TAG, "Failed to add sensor to device at CommonSense! Response code: " + code); throw new IOException("Incorrect response from CommonSense: " + code); } // store the new sensor in the preferences jsonSensor.put("device", device); JSONArray sensors = getAllSensors(context); sensors.put(jsonSensor); Editor authEditor = authPrefs.edit(); authEditor.putString(Auth.SENSOR_LIST_COMPLETE, sensors.toString()); authEditor.commit(); Log.d(TAG, "Created sensor: '" + name + "' for device: '" + deviceType + "'"); // return the new sensor ID return id; } /** * Tries to register a new user at CommonSense. Discards private data of any previous users. * * @param context * Context for getting preferences * @param username * Username to register * @param password * Hashed password for the new user * @return 0 if registration completed successfully, -2 if the user already exists, and -1 for * any other unexpected responses. * @throws JSONException * In case of unparseable response from CommonSense * @throws IOException * In case of communication failure to CommonSense */ public static int registerUser(Context context, String username, String password, String name, String surname, String email, String mobile) throws JSONException, IOException { SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false); final String url = devMode ? SenseUrls.DEV_REG : SenseUrls.REG; // create JSON object to POST final JSONObject data = new JSONObject(); final JSONObject user = new JSONObject(); user.put("username", username); user.put("password", password); if (null != name) { user.put("name", name); } if (null != surname) { user.put("surname", surname); } if (null != email) { user.put("email", email); } if (null != mobile) { user.put("mobile", mobile); } data.put("user", user); // perform actual request Map<String, String> response = SenseApi.request(context, url, data, null); String responseCode = response.get("http response code"); int result = -1; if ("201".equalsIgnoreCase(responseCode)) { result = 0; } else if ("409".equalsIgnoreCase(responseCode)) { Log.e(TAG, "Error registering new user! User already exists"); result = -2; } else { Log.e(TAG, "Error registering new user! Response code: " + responseCode); result = -1; } return result; } /** * Performs request at CommonSense API. Returns the response code, content, and headers. * * @param context * Application context, used to read preferences. * @param urlString * Complete URL to perform request to. * @param content * (Optional) Content for the request. If the content is not null, the request method * is automatically POST. The default method is GET. * @param cookie * (Optional) Cookie header for the request. * @return Map with "content" and "http response code" fields, plus fields for all response * headers. * @throws IOException */ public static Map<String, String> request(Context context, String urlString, JSONObject content, String cookie) throws IOException { HttpURLConnection urlConnection = null; HashMap<String, String> result = new HashMap<String, String>(); try { // Log.d(TAG, "API request: " + (content == null ? "GET" : "POST") + " " + urlString // + " cookie:" + cookie); // get compression preference final SharedPreferences mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); final boolean compress = mainPrefs.getBoolean(Advanced.COMPRESS, true); // open new URL connection channel. URL url = new URL(urlString); if ("https".equals(url.getProtocol().toLowerCase())) { trustAllHosts(); HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); urlConnection = https; } else { urlConnection = (HttpURLConnection) url.openConnection(); } // some parameters urlConnection.setUseCaches(false); urlConnection.setInstanceFollowRedirects(false); // set cookie (if available) if (null != cookie) { urlConnection.setRequestProperty("Cookie", cookie); } // send content (if available) if (null != content) { urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); // send content DataOutputStream printout; if (compress) { // do not set content size urlConnection.setRequestProperty("Transfer-Encoding", "chunked"); urlConnection.setRequestProperty("Content-Encoding", "gzip"); GZIPOutputStream zipStream = new GZIPOutputStream( urlConnection.getOutputStream()); printout = new DataOutputStream(zipStream); } else { // set content size urlConnection.setFixedLengthStreamingMode(content.toString().length()); urlConnection.setRequestProperty("Content-Length", "" + content.toString().length()); printout = new DataOutputStream(urlConnection.getOutputStream()); } printout.writeBytes(content.toString()); printout.flush(); printout.close(); } // get response, or read error message InputStream inputStream; try { inputStream = urlConnection.getInputStream(); } catch (IOException e) { inputStream = urlConnection.getErrorStream(); } if (null == inputStream) { throw new IOException("could not get InputStream"); } BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 1024); String line; StringBuffer responseContent = new StringBuffer(); while ((line = reader.readLine()) != null) { responseContent.append(line); responseContent.append('\r'); } reader.close(); result.put("content", responseContent.toString()); result.put("http response code", "" + urlConnection.getResponseCode()); // get headers Map<String, List<String>> headerFields = urlConnection.getHeaderFields(); for (Entry<String, List<String>> entry : headerFields.entrySet()) { String key = entry.getKey(); List<String> value = entry.getValue(); if (null != key && null != value) { key = key.toLowerCase(); String valueString = value.toString(); valueString = valueString.substring(1, valueString.length() - 1); // Log.d(TAG, "Header field '" + key + "': '" + valueString + "'"); result.put(key, valueString); } else { // Log.d(TAG, "Skipped header field '" + key + "': '" + value + "'"); } } return result; } finally { if (urlConnection != null) { urlConnection.disconnect(); } } } /** * Trust every server - do not check for any certificate */ // TODO Solve issue with security certificate for HTTPS. private static void trustAllHosts() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[] {}; } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } } public static void registerGCMId(Context context, String registrationId) throws IOException, JSONException { final SharedPreferences authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE); final SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); // Check if already synced with common sense String pref_registration_id = authPrefs.getString(Auth.GCM_REGISTRATION_ID, ""); if (registrationId.equals(pref_registration_id)) { Log.v(TAG, "GCM registration id is already sync with commonSense"); return; } String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null); boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false); String url = devMode ? SenseUrls.DEV_REGISTER_GCM_ID : SenseUrls.REGISTER_GCM_ID; // Get the device ID String device_id = getDeviceId(context); if (device_id == null) { Log.v(TAG, "Register GCM id failed, can not get the device id for this device"); return; } url = url.replaceFirst("<id>", device_id); final JSONObject data = new JSONObject(); data.put("registration_id", registrationId); Map<String, String> response = SenseApi.request(context, url, data, cookie); String responseCode = response.get("http response code"); if (!"200".equals(responseCode)) { Log.w(TAG, "Failed to register gcm id! Response code: " + responseCode); throw new IOException("Incorrect response from CommonSense: " + responseCode); } // check registration result JSONObject res = new JSONObject(response.get("content")); if (!registrationId.equals(res.getJSONObject("device").getString(GCMReceiver.KEY_GCM_ID))) { Log.w(TAG, "GCM registration_id does not match with the common sense"); throw new IllegalStateException("GCM registration_id not match with response"); } Editor authEditor = authPrefs.edit(); authEditor.putString(Auth.GCM_REGISTRATION_ID, registrationId); authEditor.commit(); Log.v(TAG, "Successfully registerd GCM id to common sense"); } /** * Get device configuration from commonSense * * @throws JSONException * @throws IOException * */ public static String getDeviceConfiguration(Context context) throws IOException, JSONException { final SharedPreferences authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE); final SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null); boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false); String url = devMode ? SenseUrls.DEV_DEVICE_UPDATE_CONFIGURATION : SenseUrls.DEV_DEVICE_UPDATE_CONFIGURATION; // Get the device ID String device_id = getDeviceId(context); url = url.replaceFirst("<id>", device_id); Map<String, String> response = SenseApi.request(context, url, null, cookie); String responseCode = response.get("http response code"); if (!"200".equals(responseCode)) { Log.w(TAG, "Failed to register gcm id! Response code: " + responseCode); throw new IOException("Incorrect response from CommonSense: " + responseCode); } return response.get("content"); } }
package org.biojava.spice; import org.biojava.bio.structure.Chain ; import java.awt.Color; import java.awt.Graphics; import java.awt.Canvas; import java.awt.Image; import java.awt.image.BufferedImage; import java.awt.Font ; import java.awt.Dimension; import java.awt.Event; import java.awt.event.MouseListener ; import java.awt.event.MouseMotionListener ; import java.awt.event.MouseEvent ; import java.awt.Graphics2D ; import java.awt.* ; import java.util.List ; import java.util.ArrayList ; import java.util.HashMap ; import java.io.* ; import java.util.Iterator ; import java.util.Date ; import java.util.Calendar ; import java.util.logging.* ; import javax.swing.JPanel ; import javax.swing.JLabel ; import javax.swing.ImageIcon ; //import ToolTip.* ; /** * A class the provides a graphical reqpresentation of the Features of a protein sequences. Requires an arraylist of features. @author Andreas Prlic */ public class SeqFeatureCanvas extends JPanel implements SeqPanel, MouseListener, MouseMotionListener { public static final int DEFAULT_X_START = 60 ; public static final int DEFAULT_X_RIGHT_BORDER = 20 ; public static final int DEFAULT_Y_START = 16 ; public static final int DEFAULT_Y_STEP = 10 ; public static final int DEFAULT_Y_HEIGHT = 4 ; public static final int DEFAULT_Y_BOTTOM = 16 ; public static final int TIMEDELAY = 0 ; int selectStart ; int selectEnd ; int mouseDragStart ; // the master application SPICEFrame spice ; //Image imbuf; //Dimension imbufDim; Color[] entColors ; Color seqColorOld ; Color strucColorOld ; int current_chainnumber; //int seqPosOld, strucPosOld ; float scale ; List drawLines ; //ArrayList features ; Chain chain ; Color cursorColor ; //mouse events Date lastHighlight ; // highliting Font plainFont ; Logger logger ; public SeqFeatureCanvas(SPICEFrame spicefr ) { super(); logger = Logger.getLogger("org.biojava.spice"); setDoubleBuffered(true) ; // TODO Auto-generated constructor stub Dimension dstruc=this.getSize(); //imbuf = this.createImage(dstruc.width, dstruc.height); //imbuf = null ; //imbufDim = dstruc; //Graphics gstruc=imbuf.getGraphics(); //gstruc.drawImage(imbuf, 0, 0, this); spice = spicefr; //features = new ArrayList(); drawLines = new ArrayList(); chain = null ; entColors = new Color [7]; entColors[0] = Color.blue; entColors[1] = Color.pink; entColors[2] = Color.green; entColors[3] = Color.magenta; entColors[4] = Color.orange; entColors[5] = Color.pink; entColors[6] = Color.cyan; //this.setBackground(Color.black) ; //super.setBackground(Color.black) ; /* float r = Color.GRAY.getRed(); float g = Color.GRAY.getGreen(); float b = Color.GRAY.getBlue(); float a = 0.5f ; */ cursorColor = new Color(0.7f, 0.7f, 0.7f, 0.5f); lastHighlight = new Date(); current_chainnumber = -1 ; plainFont = new Font("SansSerif", Font.PLAIN, 10); setOpaque(true); //this.paintComponent(this.getGraphics()); //ImageIcon icon = new ImageIcon(imbuf); //setIcon(icon); //this.repaint(); selectStart = -1 ; selectEnd = 1 ; mouseDragStart = -1 ; } public void paintComponent( Graphics g) { super.paintComponent(g); //logger.finest("DasCanv - paintComponent"); if ( chain == null ) return ; Dimension dstruc=this.getSize(); BufferedImage imbuf = (BufferedImage)this.createImage(dstruc.width,dstruc.height); Graphics2D g2D = (Graphics2D)g ; // Set current alpha Composite oldComposite = g2D.getComposite(); g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,1.0f)); g2D.setFont(plainFont); float chainlength = chain.getLength() ; // scale should span the whole length ... scale = (dstruc.width ) / (DEFAULT_X_START + chainlength + DEFAULT_X_RIGHT_BORDER ) ; //logger.finest("scale:" +scale+ " width: "+dstruc.width + " chainlength: "+chainlength ); // draw scale g2D.setColor(Color.GRAY); //gstruc.fillRect(0, 0, seqx, 1); for (int i =0 ; i< chainlength ; i++){ if ( (i%100) == 0 ) { int xpos = Math.round(i*scale)+DEFAULT_X_START ; g2D.fillRect(xpos, 0, 1, 8); }else if ( (i%50) == 0 ) { int xpos = Math.round(i*scale)+DEFAULT_X_START ; g2D.fillRect(xpos, 0, 1, 6); } else if ( (i%10) == 0 ) { int xpos = Math.round(i*scale)+DEFAULT_X_START ; g2D.fillRect(xpos, 0, 1, 4); } } // draw sequence g2D.setColor(Color.white); int seqx = java.lang.Math.round(chainlength * scale) ; g2D.fillRect(0+DEFAULT_X_START, 10, seqx, 6); int y = DEFAULT_Y_START ; // draw features //logger.finest("number features: "+features.size()); int aminosize = Math.round(1 * scale) ; boolean secstruc = false ; for (int i = 0 ; i< drawLines.size();i++) { //logger.finest(i%entColors.length); //g2D.setColor(entColors[i%entColors.length]); y = y + DEFAULT_Y_STEP ; List features = (List) drawLines.get(i) ; for ( int f =0 ; f< features.size();f++) { Feature feature = (Feature) features.get(f); // line separator if ( feature.getMethod().equals("_SPICE_LINESEPARATOR")) { //logger.finest("_SPICE_LINESEPARATOR"); String ds = feature.getSource(); g2D.setColor(Color.white); g2D.drawString(ds,DEFAULT_X_START,y+DEFAULT_Y_HEIGHT); continue ; } List segments = feature.getSegments() ; // draw text if ( segments.size() < 1) { //logger.finest(feature.getMethod()); continue ; } Segment seg0 = (Segment) segments.get(0) ; Color col = seg0.getColor(); g2D.setColor(col); g2D.drawString(feature.getName(), 1,y+DEFAULT_Y_HEIGHT); for (int s=0; s<segments.size();s++){ Segment segment=(Segment) segments.get(s); int start = segment.getStart()-1 ; int end = segment.getEnd() -1 ; col = segment.getColor(); g2D.setColor(col); int xstart = java.lang.Math.round(start * scale) + DEFAULT_X_START; int width = java.lang.Math.round(end * scale) - xstart + DEFAULT_X_START+aminosize ; int height = DEFAULT_Y_HEIGHT ; //logger.finest(feature+ " " + end +" " + width); //logger.finest("color"+entColors[i%entColors.length]); //logger.finest("new feature ("+i+"): x1:"+ xstart+" y1:"+y+" width:"+width+" height:"+height); String type = feature.getType() ; if ( type.equals("DISULFID")){ g2D.fillRect(xstart,y,aminosize,height); g2D.fillRect(xstart,y+(height/2),width,1); g2D.fillRect(xstart+width-aminosize,y,aminosize,height); } else { g2D.fillRect(xstart,y,width,height); } } } } //int seqpos = java.lang.Math.round(x/scale) ; if ( selectStart > -1 ) { g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.8f)); g2D.setColor(cursorColor); seqx = java.lang.Math.round(selectStart*scale)+DEFAULT_X_START ; int selectEndX = java.lang.Math.round(selectEnd * scale)-seqx + DEFAULT_X_START +aminosize; if ( selectEndX < aminosize) selectEndX = aminosize ; if ( selectEndX < 1 ) selectEndX = 1 ; Rectangle selection = new Rectangle(seqx , 0, selectEndX, dstruc.height); g2D.fill(selection); //g2D.setComposite(originalComposite); } g2D.setComposite(oldComposite); // g.drawImage(imbuf,0,0,this.getBackground(),this); } public void setFeatures( List feats) { logger.entering(this.getClass().getName(), "setFeatures", new Object[]{" features size: " +feats.size()}); //logger.finest("DasCanv setFeatures"); //features = feats ; // check if features are overlapping, if yes, add to a new line drawLines = new ArrayList(); List currentLine = new ArrayList(); Feature oldFeature = new Feature(); boolean start = true ; String featureSource = "" ; for (int i=0; i< feats.size(); i++) { Feature feat = (Feature)feats.get(i); String ds =feat.getSource(); // check if new feature source if ( ! featureSource.equals(ds) ) { //logger.finest("new DAS source " + ds ); if ( ! start) { drawLines.add(currentLine); } Feature tmpfeat = new Feature(); tmpfeat.setSource(ds); tmpfeat.setMethod("_SPICE_LINESEPARATOR"); currentLine = new ArrayList(); currentLine.add(tmpfeat); drawLines.add(currentLine); currentLine = new ArrayList(); } featureSource = ds ; // check for type //logger.finest(feat); if (oldFeature.getType().equals(feat.getType())){ // see if they are overlapping if ( overlap(oldFeature,feat)) { //logger.finest("OVERLAP found!" + oldFeature+ " "+ feat); drawLines.add(currentLine); currentLine = new ArrayList(); currentLine.add(feat); oldFeature = feat ; } else { // not overlapping, they fit into the same line //logger.finest("same line" + oldFeature+ " "+ feat); currentLine.add(feat); oldFeature = feat ; } } else { // a new feature type has been found // always put into a new line if ( ! start ) { drawLines.add(currentLine); currentLine = new ArrayList(); } start = false; currentLine.add(feat); oldFeature = feat ; } } drawLines.add(currentLine); int height = getImageHeight(); Dimension dstruc=this.getSize(); int width = dstruc.width ; this.setPreferredSize(new Dimension(width,height)) ; this.setMaximumSize(new Dimension(width,height)); this.repaint(); } /** return height of image. dpends on number of features! */ private int getImageHeight(){ int h = DEFAULT_Y_START + drawLines.size() * DEFAULT_Y_STEP + DEFAULT_Y_BOTTOM; //logger.finest("setting height " + h); return h ; } // an overlap occurs if any of the segments overlap ... private boolean overlap (Feature a, Feature b) { List segmentsa = a.getSegments() ; List segmentsb = b.getSegments(); for ( int i =0; i< segmentsa.size();i++) { Segment sa = (Segment)segmentsa.get(i) ; int starta = sa.getStart(); int enda = sa.getEnd(); for (int j = 0; j<segmentsb.size();j++){ Segment sb = (Segment)segmentsb.get(j) ; // compare boundaries: int startb = sb.getStart(); int endb = sb.getEnd(); // overlap! if (( starta <= endb ) && ( enda >= startb)) return true ; if (( startb <= enda ) && ( endb >= starta)) return true ; } } return false ; } public void setChain(Chain c,int chainnumber) { chain = c; current_chainnumber = chainnumber ; //this.paintComponent(this.getGraphics()); this.repaint(); } /** select a single segment */ private void selectSegment (Segment segment) { logger.finest("select Segment"); /* // clicked on a segment! Color col = segment.getColor(); //seqColorOld = col ; //spice.setOldColor(col) ; int start = segment.getStart() ; int end = segment.getEnd() ; String type = segment.getType() ; if ( type.equals("DISULFID")){ logger.finest("selectSegment DISULFID " + (start+1) + " " + (end+1)); //String cmd = spice.getSelectStr(current_chainnumber,start+1); //cmd += spice.getSelectStr(current_chainnumber,end+1); String pdb1 = spice.getSelectStrSingle(current_chainnumber,start+1); String pdb2 = spice.getSelectStrSingle(current_chainnumber,end+1); String cmd = "select "+pdb1 +", " + pdb2 + "; spacefill on; cpk on;" ; spice.executeCmd(cmd); } else { spice.select(current_chainnumber,start+1,end+1); } */ } /** highlite a single segment */ private void highliteSegment (Segment segment) { logger.finest("highlite Segment"); //logger.finest("segment"); // clicked on a segment! String col = segment.getTxtColor(); //seqColorOld = col ; //spice.setOldColor(col) ; int start = segment.getStart(); int end = segment.getEnd() ; start = start -1 ; end = end -1 ; String type = segment.getParent().getType() ; //logger.finest(start+" " + end+" "+type); //logger.finest(segment); if ( type.equals("DISULFID")){ spice.highlite(current_chainnumber,start); spice.highlite(current_chainnumber,end); String pdb1 = spice.getSelectStrSingle(current_chainnumber,start); String pdb2 = spice.getSelectStrSingle(current_chainnumber,end); String cmd = "select "+pdb1 +", " + pdb2 + "; spacefill on; colour cpk;" ; spice.executeCmd(cmd); } else if (type.equals("METAL") ){ spice.highlite(current_chainnumber,start+1,end+1 ,"cpk"); } else if ( type.equals("MSD_SITE")) { spice.highlite(current_chainnumber,start+1,end+1 ,"wireframe"); } else if ( (end - start) == 0 ) { // feature of size 1 spice.highlite(current_chainnumber,start+1,start+1 ,"cpk"); } else { spice.colour(current_chainnumber,start+1 ,end+1 ,col); } } /** highlite all segments of a feature */ private String highliteFeature(Feature feature){ logger.finest("highlite feature " + feature); //Feature feature = (Feature) features.get(featurenr) ; //logger.finest("highlite feature " + feature); List segments = feature.getSegments() ; String cmd = "" ; for ( int i =0; i< segments.size() ; i++ ) { Segment segment = (Segment) segments.get(i); //highliteSegment(segment); int start = segment.getStart(); int end = segment.getEnd(); //logger.finest("highilte feature " +featurenr+" " + start + " " +end ); if ( feature.getType().equals("DISULFID")){ cmd += spice.getSelectStr(current_chainnumber,start-1); cmd += "colour cpk; spacefill on;"; cmd += spice.getSelectStr(current_chainnumber,end-1); cmd += "colour cpk; spacefill on;"; } else { cmd += spice.getSelectStr(current_chainnumber,start,end); String col = segment.getTxtColor(); cmd += "color "+ col +";"; } //if ( start == end ) { //cmd += " spacefill on;"; } if ( ( feature.getType().equals("METAL")) || ( feature.getType().equals("SITE")) || ( feature.getType().equals("ACT_SITE")) ){ cmd += " spacefill on; " ; } else if ( feature.getType().equals("MSD_SITE") ) { cmd += " wireframe on; " ; } //logger.finest("cmd: "+cmd); return cmd ; } /** select single position select a position */ public void select(int seqpos){ highlite(seqpos); } /** select range */ public void select(int start, int end) { highlite(start,end); } /** same as select here. draw a line at current seqence position * only if chain_number is currently being displayed */ public void highlite( int seqpos){ if ( chain == null ) return ; if ( seqpos > chain.getLength()) return ; selectStart = seqpos ; selectEnd = 1 ; this.repaint(); } /** highlite a region */ public void highlite( int start , int end){ if ( chain == null ) return ; if ( (start > chain.getLength()) || (end > chain.getLength()) ) return ; selectStart = start ; selectEnd = end ; this.repaint(); } /* check if the mouse is over a feature and if it is * return the feature number * @author andreas * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ private int getLineNr(MouseEvent e){ int mouseY = e.getY(); float top = mouseY - DEFAULT_Y_START +1 ; // java.lang.Math.round((y-DEFAULT_Y_START)/ (DEFAULT_Y_STEP + DEFAULT_Y_HEIGHT-1)); float interval = DEFAULT_Y_STEP ; int linenr = java.lang.Math.round(top/interval) -1 ; //logger.finest("top "+top+" interval "+ interval + " top/interval =" + (top/interval) ); if ( linenr >= drawLines.size()){ // can happen at bottom part // simply skip it ... return -1; } return linenr ; } private Feature getFeatureAt(int seqpos, int lineNr){ //logger.finest("getFeatureAt " + seqpos + " " + lineNr); Segment s = getSegmentUnder(seqpos,lineNr); if (s == null ) return null; return s.getParent(); } /** check if mouse is over a segment and if it is, return the segment */ private Segment getSegmentUnder( int seqpos,int lineNr){ if ( ( lineNr < 0) || ( lineNr >= drawLines.size() ) ){ return null ; } List features = (List) drawLines.get(lineNr); for ( int i =0; i<features.size();i++ ){ Feature feature = (Feature) features.get(i) ; List segments = feature.getSegments() ; for ( int j =0; j< segments.size() ; j++ ) { Segment segment = (Segment) segments.get(j); int start = segment.getStart() -1 ; int end = segment.getEnd() -1 ; if ( (start <= seqpos) && (end >= seqpos) ) { return segment ; } } } return null ; } /** create a tooltip string */ private String getToolString(int seqpos, Segment segment){ //logger.finest("getToolString"); // current position is seqpos String toolstr = spice.getToolString(current_chainnumber,seqpos); //logger.finest("getToolString"); Feature parent = segment.getParent() ; String method = parent.getMethod() ; String type = parent.getType() ; String note = parent.getNote() ; int start = segment.getStart() -1 ; int end = segment.getEnd() -1 ; toolstr += " " + type + " start " + start + " end " + end + " Note:" + note; //logger.finest(toolstr); //new ToolTip(toolstr, this); //this.repaint(); return toolstr ; } /** test if the click was on the name of the feature */ private boolean nameClicked(MouseEvent e) { int x = e.getX(); if (x <= DEFAULT_X_START) { return true ; } return false ; } /** get the sequence position of the current mouse event */ private int getSeqPos(MouseEvent e) { int x = e.getX(); int y = e.getY(); int seqpos = java.lang.Math.round((x-DEFAULT_X_START)/scale) ; return seqpos ; } public void mouseMoved(MouseEvent e) { //, int x, int y int seqpos = getSeqPos(e); int linenr = getLineNr(e); //int featurenr = get_featurenr(y); if ( linenr < 0 ) return ; if ( seqpos < 0 ) return ; // and the feature display Feature feature = getFeatureAt(seqpos,linenr); Segment segment = getSegmentUnder(seqpos,linenr); if ( segment != null) { String toolstr = getToolString(seqpos,segment); //gfeat.drawString(toolstr,5,13); spice.showStatus(toolstr) ; // display ToolTip this.setToolTipText(toolstr); } else { this.setToolTipText(null); } //spice.showSeqPos(current_chainnumber,seqpos); spice.select(current_chainnumber,seqpos); return ; } public void mouseClicked(MouseEvent e) { //logger.finest("CLICK"); int seqpos = getSeqPos(e); int lineNr = getLineNr(e); //int featurenr = get_featurenr(y) ; //logger.finest("CLICK! "+seqpos + " " +lineNr+ " " + chain.getLength()); if ( lineNr < 0 ) return ; if ( seqpos < 0 ) { // check if the name was clicked if (nameClicked(e)){ // highlight all features in the line //Feature feature = getFeatureAt(seqpos,lineNr); List features = (List) drawLines.get(lineNr); String cmd = ""; for ( int i=0; i<features.size(); i++) { Feature feature = (Feature) features.get(i); cmd += highliteFeature(feature); } //logger.finest(cmd); spice.executeCmd(cmd); return ; } } if ( seqpos > chain.getLength()) return ; String drstr = "x "+ seqpos + " y " + lineNr ; spice.showStatus(drstr); Segment segment = getSegmentUnder(seqpos,lineNr); //logger.finest(segment); if (segment != null ) { highliteSegment(segment); String toolstr = getToolString(seqpos,segment); spice.showStatus(drstr + " " + toolstr) ; this.setToolTipText(toolstr); } else { spice.highlite(current_chainnumber,seqpos); this.setToolTipText(null); } //this.repaint(); //Color col = entColors[featurenr%entColors.length] ; //logger.finest("clicked outa space"); return ; } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { mouseDragStart = getSeqPos(e); } public void mouseReleased(MouseEvent e) { mouseDragStart = -1 ; } public void mouseDragged(MouseEvent e) { //System.out.println("dragging mouse "+e); if ( mouseDragStart < 0 ) return ; int selEnd = getSeqPos(e); int start = mouseDragStart ; int end = selEnd ; if ( selEnd < mouseDragStart ) { start = selEnd ; end = mouseDragStart ; } spice.highlite(current_chainnumber,start,end); } }
package org.broad.igv.ui.color; import javax.swing.*; import javax.swing.border.LineBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.Serializable; import java.util.ArrayList; /** * @author Jim Robinson */ public class ColorChooserPanel extends JPanel implements Serializable { Color selectedColor; java.util.List<ActionListener> listeners = new ArrayList<ActionListener>(); public ColorChooserPanel() { this(Color.white); } public ColorChooserPanel(Color selectedColor) { this.selectedColor = selectedColor; initComponents(); setSelectedColor(selectedColor); } public void setSelectedColor(Color selectedColor) { this.selectedColor = selectedColor; colorPanel.setBackground(selectedColor); } public Color getSelectedColor() { return selectedColor; } public void addActionListener(ActionListener listener) { listeners.add(listener); } private void changeButtonActionPerformed(ActionEvent e) { changeColorAction(); } private void colorPanelMouseClicked(MouseEvent e) { changeColorAction(); } private void changeColorAction() { JColorChooser colorChooser = new JColorChooser(selectedColor); JDialog dialog = JColorChooser.createDialog(this, "Dialog Title", true, colorChooser, null, null); dialog.setVisible(true); Color c = colorChooser.getColor(); if (c != null) { setSelectedColor(c); } ActionEvent evt = new ActionEvent(this, 0, ""); for (ActionListener l : listeners) { l.actionPerformed(evt); } } private void initComponents() { colorPanel = new JPanel(); changeButton = new JButton(); if (UIManager.getLookAndFeel().getName().toLowerCase().contains("metal")) { changeButton = new JMenuItem(); } setLayout(new GridBagLayout()); ((GridBagLayout) getLayout()).columnWidths = new int[]{30, 0, 0}; ((GridBagLayout) getLayout()).rowHeights = new int[]{0, 0}; ((GridBagLayout) getLayout()).columnWeights = new double[]{1.0, 1.0, 1.0E-4}; ((GridBagLayout) getLayout()).rowWeights = new double[]{1.0, 1.0E-4}; { colorPanel.setPreferredSize(new Dimension(20, 15)); colorPanel.setMinimumSize(new Dimension(20, 5)); colorPanel.setMaximumSize(new Dimension(20, 15)); colorPanel.setFocusable(false); colorPanel.setBorder(LineBorder.createBlackLineBorder()); colorPanel.setBackground(new Color(204, 204, 255)); colorPanel.setLayout(null); colorPanel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent mouseEvent) { colorPanelMouseClicked(mouseEvent); } }); } add(colorPanel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); changeButton.setHorizontalAlignment(SwingConstants.LEFT); changeButton.setIcon(UIManager.getIcon("Menu.arrowIcon")); changeButton.setToolTipText("Change color"); changeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { changeButtonActionPerformed(e); } }); add(changeButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); // JFormDesigner - End of component initialization //GEN-END:initComponents } // JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables private JPanel colorPanel; private AbstractButton changeButton; // JFormDesigner - End of variables declaration //GEN-END:variables }
package org.citydb.api.event.global; import java.util.HashMap; import java.util.Map; import org.citydb.api.event.Event; public final class GenericEvent extends Event { private final String id; private HashMap<String, Object> properties; public GenericEvent(String id, Map<String, Object> properties, Object channel, Object source) { super(GlobalEvents.GENERIC_EVENT, channel, source); this.id = id; if (properties != null) this.properties = new HashMap<String, Object>(properties); else this.properties = new HashMap<String, Object>(); } public GenericEvent(String id, Map<String, Object> properties, Object source) { this(id, properties, GLOBAL_CHANNEL, source); } public GenericEvent(String id, Object channel, Object source) { this(id, null, channel, source); } public GenericEvent(String id, Object source) { this(id, null, GLOBAL_CHANNEL, source); } public String getId() { return id; } public boolean hasProperties() { return !properties.isEmpty(); } public boolean isSetPropery(String key) { return properties.containsKey(key); } public Map<String, Object> getProperties() { return properties; } public Object getProperty(String key) { return properties.get(key); } public Object setProperty(String key, Object property) { return properties.put(key, property); } }
package org.dhappy.habits; import org.dhappy.habits.contentprovider.HabitContentProvider; import org.dhappy.habits.database.DescriptorTable; import org.dhappy.habits.database.GoalTable; import org.dhappy.habits.database.ReadingTable; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.ContentValues; import android.content.DialogInterface; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.SeekBar; import android.widget.Toast; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; public class DescriptorWeightDialog extends DialogFragment { private String TAG = "DescriptorWeightDialog"; public final static String DESCRIPTOR_ID = "org.dhappy.habits.mood.descriptor.id"; public interface DescriptorWeightDialogListener { public void onRecordWeight(int descriptorId, double weight); } DescriptorWeightDialogListener mListener; @Override public void onAttach(Activity activity) { super.onAttach(activity); try { //mListener = (DescriptorWeightDialogListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement NoticeDialogListener"); } } public static int colorForWeight(double weight) { return Color.rgb( (int) (255 * Math.max(0, -weight)), (int) (255 * Math.max(0, weight)), (int) (255 * (1 - Math.abs(weight))) ); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.weight_dialog, null); final TextView weight = (TextView) view.findViewById(R.id.weight); final SeekBar weightSelect = (SeekBar) view.findViewById(R.id.weight_select); weightSelect.setMax(200); weightSelect.setProgress(100); weightSelect.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int position, boolean fromUser) { position -= 100; // shift from 0-200 weight.setText(Integer.toString(position)); float pos = position / 100f; weight.setTextColor(colorForWeight(pos)); } @Override public void onStartTrackingTouch(SeekBar arg0) {} @Override public void onStopTrackingTouch(SeekBar arg0) {} }); final int descriptorId = this.getArguments().getInt(DESCRIPTOR_ID, 0); String[] projection = { DescriptorTable.COLUMN_NAME, DescriptorTable.COLUMN_COLOR }; Uri uri = Uri.parse(HabitContentProvider.DESCRIPTORS_URI + "/" + descriptorId); Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null); final String descriptor = (cursor.moveToFirst() ? cursor.getString(cursor.getColumnIndexOrThrow(DescriptorTable.COLUMN_NAME)) : "Unknown"); final DescriptorWeightDialog self = this; builder.setView(view) .setMessage(descriptor) .setPositiveButton(R.string.weight_confirm, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { double weight = (weightSelect.getProgress() - 100) / 100f; ((DescriptorWeightDialogListener) getTargetFragment()).onRecordWeight(descriptorId, weight); } }) .setNegativeButton(R.string.weight_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); return builder.create(); } }
package org.dukeofxor.jtalker.gui; import org.dukeofxor.jtalker.server.ClientThread; import org.dukeofxor.jtalker.server.Server; import javafx.collections.ObservableList; public class CommandHandler { public static final String TO_MANY_ARGUMENTS = "Too many arguments for command "; public static final String MISSING_ARGUMENT = "Missing arguments for command "; public static final String USAGE = "Usage: "; //syntax helps for each command public static final String START_USAGE = "start"; public static final String STOP_USAGE = "stop"; public static final String CLEAR_USAGE = "clear"; public static final String EXIT_USAGE = "exit"; public static final String LIST_USAGE = "list"; public static final String KICK_USAGE = "kick <clientname>"; private static final String WHISPER_USAGE = "whisper username message"; private static final String SHUTDOWN_USAGE = "shutdown"; private ServerGUI gui; public CommandHandler(ServerGUI gui) { this.gui = gui; } public void handleCommand(String command){ String[] cmd = command.split("\\s+"); if(cmd[0].equals("start")){ startServer(cmd); return; } if(cmd[0].equals("stop")){ stopServer(cmd); return; } if(cmd[0].equals("clear")){ clearConsole(cmd); return; } if(cmd[0].equals("exit")){ exit(cmd); return; } if(cmd[0].equals("shutdown")){ shutdown(cmd); return; } if(cmd[0].equals("list")){ clientList(cmd); return; } if(cmd[0].equals("kick")){ kickClient(cmd); return; } } private void shutdown(String[] cmd) { if(cmd.length > 1){ gui.displayMessage(TO_MANY_ARGUMENTS + cmd[0] + "\n" + USAGE + SHUTDOWN_USAGE); return; } if(gui.getLanChatServer().isRunning()){ gui.getLanChatServer().shutdown(); } gui.close(); } private void kickClient(String[] cmd) { if(cmd.length == 2){ gui.getLanChatServer().kickClient(cmd[1]); return; } if(cmd.length > 2){ gui.displayMessage(TO_MANY_ARGUMENTS + cmd[0] + "\n" + USAGE + KICK_USAGE); return; } if(cmd.length < 2){ gui.displayMessage(MISSING_ARGUMENT + cmd[0] + "\n" + USAGE + KICK_USAGE); } } private void clientList(String[] cmd) { if(cmd.length > 1){ gui.displayMessage(TO_MANY_ARGUMENTS + cmd[0] + "\n" + USAGE + LIST_USAGE); return; } if(gui.getLanChatServer().isRunning()){ ObservableList<ClientThread> connectedClients = gui.getLanChatServer().getConnectedClients(); StringBuilder output = new StringBuilder("Connected clients:"); for (ClientThread clientThread : connectedClients) { output.append("\n"); output.append(clientThread.getIp() + ", "); output.append(clientThread.getUsername()); } gui.displayMessage(output.toString()); } else { gui.displayMessage("Please start the server before you execute this command"); } } private void startServer(String[] cmd){ if(cmd.length > 1){ gui.displayMessage(TO_MANY_ARGUMENTS + cmd[0] + "\n" + USAGE + START_USAGE); return; } if(!gui.getLanChatServer().isRunning()){ gui.setLanChatServer(new Server(gui)); gui.getLanChatServer().start(); } else { gui.displayMessage("Server already running"); } } private void stopServer(String[] cmd) { if(cmd.length > 1){ gui.displayMessage(TO_MANY_ARGUMENTS + cmd[0] + "\n" + USAGE + STOP_USAGE); return; } if(gui.getLanChatServer().isRunning()){ gui.getLanChatServer().shutdown(); } else { gui.displayMessage("Server not running"); } } private void clearConsole(String[] cmd) { if(cmd.length > 1){ gui.displayMessage(TO_MANY_ARGUMENTS + cmd[0] + "\n" + USAGE + CLEAR_USAGE); return; } gui.clearConsole(); } private void exit(String[] cmd) { if(cmd.length > 1){ gui.displayMessage(TO_MANY_ARGUMENTS + cmd[0] + "\n" + USAGE + EXIT_USAGE); return; } if(gui.getLanChatServer().isRunning()){ gui.displayMessage("Can't exit while server is running. Plase stop the server before executing this command"); return; } gui.close(); } }
package org.immopoly.android.app; import java.util.Vector; import org.immopoly.android.R; import org.immopoly.android.constants.Const; import org.immopoly.android.helper.Settings; import org.immopoly.android.helper.TrackingManager; import org.immopoly.android.model.Flat; import org.immopoly.android.model.ImmopolyUser; import org.immopoly.android.tasks.AddToPortfolioTask; import org.immopoly.android.tasks.GetUserInfoTask; import org.immopoly.android.tasks.ReleaseFromPortfolioTask; import android.app.Activity; import android.app.AlertDialog; import android.content.ContextWrapper; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; import com.google.android.apps.analytics.GoogleAnalyticsTracker; /** * contains methods that interact with the immopoly server. - login/signup * (using UserSignupActivity) - getUserInfo (using GetUserInfoTask) - * addToPortfolio (using AddToPortfolioTask) - releaseFromPortfolio (using * ReleaseFromPortfolioTask) * * @author bjoern TODO re-enable addToPortfolio after signup * */ public class UserDataManager { public static final int USER_UNKNOWN = 0; public static final int LOGIN_PENDING = 1; // TODO unused (yet) public static final int LOGGED_IN = 2; private boolean actionPending; private int state = USER_UNKNOWN; private Activity activity; private GoogleAnalyticsTracker mTracker; private Vector<UserDataListener> listeners = new Vector<UserDataListener>(); private Flat flatToAddAfterLogin; // the singleton instance public static final UserDataManager instance = new UserDataManager(); private UserDataManager() { } public void setActivity(Activity activity) { this.activity = activity; // try to get user info on first activity start if we have a token String token = ImmopolyUser.getInstance().readToken(activity); if (state == USER_UNKNOWN && token != null && token.length() > 0) { getUserInfo(); } if (mTracker == null) { mTracker = GoogleAnalyticsTracker.getInstance(); // Start the tracker in manual dispatch mode... mTracker.startNewSession(TrackingManager.UA_ACCOUNT, Const.ANALYTICS_INTERVAL, activity.getApplicationContext()); } } public void addUserDataListener(UserDataListener udl) { listeners.add(udl); } public void removeUserDataListener(UserDataListener udl) { listeners.remove(udl); } public int getState() { return state; } /** * summons UserSignupActivity to login or register informs listeners on * successful operation */ public void login() { Log.i(Const.LOG_TAG, "UserDataManager.login() state = " + state); if (actionPending) { Log.w(Const.LOG_TAG, "Refusing to log in while another server request is running"); return; } if (state != USER_UNKNOWN) { Log.e(Const.LOG_TAG, "Already logged in. Log out first."); return; } actionPending = true; state = LOGIN_PENDING; Intent intent = new Intent(activity, UserSignupActivity.class); activity.startActivityForResult(intent, Const.USER_SIGNUP); } public boolean logout() { Log.i(Const.LOG_TAG, "UserDataManager.logout() state = " + state); if (actionPending) { Log.w(Const.LOG_TAG, "Refusing to log out while another server request is running"); return false; } if (state != LOGGED_IN) { Log.e(Const.LOG_TAG, "Already logged in. Log out first."); return false; } state = USER_UNKNOWN; ImmopolyUser.resetInstance(); if (null != this.activity) setToken(activity, null); fireUsedDataChanged(); return true; } /** * Receives results from Actitvies (UserSignupActivity for now) * * informs listeners if signup succeeded * * ! Must be invoked from ImmopolyActivity.onActivityResult * */ void onActivityResult(int requestCode, int resultCode, Intent data) { Log.i(Const.LOG_TAG, "UserDataManager.onActivityResult() state = " + state); actionPending = false; if (requestCode == Const.USER_SIGNUP) { if (resultCode == Activity.RESULT_OK) { state = LOGGED_IN; Log.i(Const.LOG_TAG, "UserDataManager.onActivityResult() state2 = " + state); fireUsedDataChanged(); if (flatToAddAfterLogin != null) addToPortfolio(flatToAddAfterLogin); } else { Log.i(Const.LOG_TAG, "UserDataManager.onActivityResult() state3 = " + state); state = USER_UNKNOWN; fireUsedDataChanged(); } } Log.i(Const.LOG_TAG, "UserDataManager.onActivityResult() state4 = " + state); } /** * retrieves UserInfo data from server and fills ImmopolyUser.instance * * informs listeners on successful operation */ public void getUserInfo() { Log.i(Const.LOG_TAG, "UserDataManager.getUserInfo() state = " + state); if (actionPending) { Log.w(Const.LOG_TAG, "Refusing to get user info while another server request is running"); return; } Log.i(Const.LOG_TAG, "UserDataManager.getUserInfo() state2 = " + state); actionPending = true; state = LOGIN_PENDING; Log.i(Const.LOG_TAG, "UserDataManager.getUserInfo() state3 = " + state); GetUserInfoTask task = new GetUserInfoTask(activity) { @Override protected void onPostExecute(ImmopolyUser user) { actionPending = false; if (user != null) { state = LOGGED_IN; } else { state = USER_UNKNOWN; } Log.i(Const.LOG_TAG, "UserDataManager.getUserInfo() state4 = " + state); fireUsedDataChanged(); } }; task.execute(ImmopolyUser.getInstance().getToken()); } /** * Tries to add a flat to the users portfolio using AddToPortfolioTask. * Informs listeners on successful operation * * @param flat * the flat to add */ public void addToPortfolio(final Flat flat) { Log.i(Const.LOG_TAG, "UserDataManager.addToPortfolio() tracker: " + mTracker); // login first if not yet if (state == USER_UNKNOWN) { flatToAddAfterLogin = flat; login(); return; } if (!checkState()) return; actionPending = true; new AddToPortfolioTask(activity, mTracker) { protected void onPostExecute(final AddToPortfolioTask.Result result) { super.onPostExecute(result); if (result.success) { flat.owned = true; flat.takeoverDate = System.currentTimeMillis(); ImmopolyUser.getInstance().getPortfolio().add(flat); /** * show the feedback in a dialog, from there the user can either share the result or */ showExposeDialog(flat, result); } fireUsedDataChanged(); actionPending = false; } private void showExposeDialog(final Flat flat, final AddToPortfolioTask.Result result) { AlertDialog.Builder builder = new AlertDialog.Builder( activity); builder.setTitle(activity.getString(R.string.take_over_try)); builder.setMessage(result.historyEvent.mText); //builder.setContentView(R.layout.maindialog); builder.setCancelable(true).setNegativeButton( activity.getString(R.string.share_item), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Settings.getFlatLink(flat.uid.toString(), false); Settings.shareMessage(activity, activity .getString(R.string.take_over_try), result.historyEvent.mText, Settings.getFlatLink( flat.uid.toString(), false) /* LINk */); mTracker.trackEvent( TrackingManager.CATEGORY_ALERT, TrackingManager.ACTION_SHARE, TrackingManager.LABEL_POSITIVE, 0); } }); builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { mTracker.trackEvent( TrackingManager.CATEGORY_ALERT, TrackingManager.ACTION_SHARE, TrackingManager.LABEL_NEGATIVE, 0); } }); AlertDialog alert = builder.create(); alert.show(); }; }.execute(flat); } /** * Tries to release a flat from the users portfolio using * RemoveFromPortfolioTask. Informs listeners on successful operation * * @param flat * the flat to add */ public void releaseFromPortfolio(final Flat flat) { Log.i(Const.LOG_TAG, "UserDataManager.releaseFromPortfolio()"); if (!checkState()) return; actionPending = true; new ReleaseFromPortfolioTask(activity, mTracker) { @Override protected void onPostExecute(ReleaseFromPortfolioTask.Result result) { super.onPostExecute(result); if (result.success) { // remove the flat from users portfolio // list flat.owned = false; Flat toBeRemoved = null; // flat in users list, which was // eventually created from DB, // while the parameter flat was // probably created from is24 // data for (Flat f : ImmopolyUser.getInstance().getPortfolio()) if (f.uid == flat.uid) toBeRemoved = f; if (toBeRemoved != null) { Log.i(Const.LOG_TAG, "UserDataManager.releaseFromPortfolio() Flat removed: " + flat.name); ImmopolyUser.getInstance().getPortfolio() .remove(toBeRemoved); toBeRemoved.owned = false; } else { Log.w(Const.LOG_TAG, "UserDataManager.releaseFromPortfolio() Flat NOT removed: " + flat.name); } fireUsedDataChanged(); actionPending = false; } }; }.execute(String.valueOf(flat.uid)); } private void fireUsedDataChanged() { Log.i(Const.LOG_TAG, "UserDataManager.fireUsedDataChanged()"); for (UserDataListener listener : listeners) listener.onUserDataUpdated(); } private boolean checkState() { if (actionPending) { Log.w(Const.LOG_TAG, "Refusing to send request while another server request is running"); return false; } if (state != LOGGED_IN) { Log.e(Const.LOG_TAG, "Not logged in."); return false; } return true; } // handle the token only here set null to remove public static void setToken(ContextWrapper context, String token) { SharedPreferences shared = context.getSharedPreferences( ImmopolyUser.sPREF_USER, 0); SharedPreferences.Editor editor = shared.edit(); if (token == null) editor.remove(ImmopolyUser.sPREF_TOKEN); // TODO schtief remove does // not work else editor.putString(ImmopolyUser.sPREF_TOKEN, token); editor.commit(); } }
package org.lockss.util; import java.util.*; import javax.xml.XMLConstants; import javax.xml.namespace.NamespaceContext; import org.apache.commons.collections4.bidimap.DualHashBidiMap; import org.apache.commons.collections4.iterators.SingletonIterator; import org.apache.commons.collections4.BidiMap; /** * <p> * Provides a concrete implementation of {@link NamespaceContext} (as none are * readily available from the JDK or Apache Commons) that encapsulates a * one-to-one mapping between prefixes and namespace URIs. * </p> * <p> * The {@link #put(String, String)} and {@link #remove(String)} methods return * the instance itself so that calls can be chained to quickly build an instance * without a prior map. * </p> * * @author Thib Guicherd-Callin * @since 1.67.5 */ public class OneToOneNamespaceContext implements NamespaceContext { /** * @since 1.67.5 */ protected BidiMap<String, String> bidiMap; /** * <p> * Builds a new instance that initially maps * {@link XMLConstants#DEFAULT_NS_PREFIX} to {@link XMLConstants#NULL_NS_URI}. * </p> * * @since 1.67.5 */ public OneToOneNamespaceContext() { this.bidiMap = new DualHashBidiMap<String, String>(); put(XMLConstants.DEFAULT_NS_PREFIX, XMLConstants.NULL_NS_URI); } /** * <p> * Builds a new instance that initially has the same mappings as the given * map, and adds a mapping from {@link XMLConstants#DEFAULT_NS_PREFIX} to * {@link XMLConstants#NULL_NS_URI} if there is no mapping for it initially. * </p> * * @param map * An initial mapping of prefixes to namespace URIs. * @since 1.67.5 */ public OneToOneNamespaceContext(Map<String, String> map) { this.bidiMap = new DualHashBidiMap<String, String>(map); if (!bidiMap.containsKey(XMLConstants.DEFAULT_NS_PREFIX)) { put(XMLConstants.DEFAULT_NS_PREFIX, XMLConstants.NULL_NS_URI); } } /** * @since 1.67.5 */ public OneToOneNamespaceContext put(String prefix, String namespaceURI) { bidiMap.put(prefix, namespaceURI); return this; } /** * @since 1.67.5 */ public OneToOneNamespaceContext remove(String prefix) { bidiMap.remove(prefix); return this; } @Override public String getNamespaceURI(String prefix) { return bidiMap.get(prefix); } @Override public String getPrefix(String namespaceURI) { return bidiMap.getKey(namespaceURI); } @Override public Iterator<String> getPrefixes(String namespaceURI) { return new SingletonIterator<String>(getPrefix(namespaceURI)); } }
package org.myrobotlab.service; import java.awt.Color; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import org.myrobotlab.control.ServoOrchestratorGUI_middlemiddle_panel; import org.myrobotlab.framework.Service; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.interfaces.ServiceInterface; import org.slf4j.Logger; /** * based on _TemplateService * "Clock-Code" modified from "Clock-Service" */ /** * * @author LunDev (github), Ma. Vo. (MyRobotlab) */ public class ServoOrchestrator extends Service { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory .getLogger(ServoOrchestrator.class); org.myrobotlab.control.ServoOrchestratorGUI sogui_ref; // TODO - don't define size (or at least make it bigger) // rework, that it could be made bigger int sizex = 5; int sizey = 5; SettingsItemHolder[] settingsitemholder; Servo[] servos; public boolean isClockRunning; public int interval = 1; public transient ClockThread myClock = null; int middleright_shownitem; boolean click_play = true; int pos1; int pos2; int pos3; public ServoOrchestrator(String n) { super(n); // intializing variables settingsitemholder = new SettingsItemHolder[sizey]; servos = new Servo[sizey]; for (int i = 0; i < settingsitemholder.length; i++) { SettingsItemHolder sih = new SettingsItemHolder(); sih.name = "Channel " + (i + 1); sih.min = 0; sih.max = 180; sih.startvalue = (sih.min + sih.max) / 2; sih.arduinopos = 0; sih.pinpos = 0; sih.attached = false; settingsitemholder[i] = sih; } pos1 = 1; pos2 = 1; pos3 = 000; } @Override public void startService() { super.startService(); } @Override public void stopService() { super.stopService(); } @Override public String getDescription() { return "organize your Servo-movements"; } public void setsoguireference( org.myrobotlab.control.ServoOrchestratorGUI so_ref) { sogui_ref = so_ref; } public void setmiddlemiddlesize() { sogui_ref.sizex = sizex; sogui_ref.sizey = sizey; } public void set_middleright_arduino_list_items() { List<ServiceInterface> services = Runtime.getServices(); ArrayList<String> arduinolist = new ArrayList<String>(); for (ServiceInterface service : services) { String type = service.getType(); String typ = type.substring(23); if (typ.equals("Arduino")) { String name = service.getName(); arduinolist.add(name); } } String[] arduinoarray = new String[arduinolist.size() + 2]; arduinoarray[0] = " "; arduinoarray[1] = "refresh"; for (int i = 0; i < arduinolist.size(); i++) { arduinoarray[i + 2] = arduinolist.get(i); } sogui_ref.middleright_arduino_list.setListData(arduinoarray); } public void middleright_update_button() { settingsitemholder[middleright_shownitem].name = sogui_ref.middleright_name_textfield .getText(); settingsitemholder[middleright_shownitem].min = Integer .parseInt(sogui_ref.middleright_min_textfield.getText()); settingsitemholder[middleright_shownitem].max = Integer .parseInt(sogui_ref.middleright_max_textfield.getText()); settingsitemholder[middleright_shownitem].startvalue = Integer .parseInt(sogui_ref.middleright_startvalue_textfield.getText()); } public void middleright_attach_button() { if (!settingsitemholder[middleright_shownitem].attached) { settingsitemholder[middleright_shownitem].arduinopos = sogui_ref.middleright_arduino_list .getSelectedIndex(); settingsitemholder[middleright_shownitem].pinpos = sogui_ref.middleright_pin_list .getSelectedIndex(); String arduino = (String) sogui_ref.middleright_arduino_list .getSelectedValue(); int pin = Integer.parseInt((String) sogui_ref.middleright_pin_list .getSelectedValue()); servos[middleright_shownitem] = (Servo) Runtime.start("so." + middleright_shownitem, "Servo"); servos[middleright_shownitem].attach(arduino, pin); boolean attach = servos[middleright_shownitem].attach(); if (attach) { sogui_ref.middleright_attach_button.setText("Detach"); settingsitemholder[middleright_shownitem].attached = true; } } else { boolean detach = servos[middleright_shownitem].detach(); servos[middleright_shownitem] = null; if (detach) { sogui_ref.middleright_attach_button.setText("Attach"); settingsitemholder[middleright_shownitem].attached = false; } } } public void bottommiddlerighttop_update_button() { pos1 = Integer.parseInt(sogui_ref.bottommiddlerighttop_textfield_1 .getText()); pos2 = Integer.parseInt(sogui_ref.bottommiddlerighttop_textfield_2 .getText()); pos3 = Integer.parseInt(sogui_ref.bottommiddlerighttop_textfield_3 .getText()); play_updatetime(true, true, true); play_updatepanels(pos1); } public void bottommiddlerightbottom_button_1() { play_go_ba(); } public void bottommiddlerightbottom_button_2() { play_go_fa(); } public void bottommiddlerightbottom_button_3() { play_go_b1(); } public void bottommiddlerightbottom_button_4() { play_go_f1(); } public void bottommiddlerightbottom_button_5() { // TODO - add functionality } public void bottommiddlerightbottom_button_6() { play_go_stop(); } public void bottommiddlerightbottom_button_7() { play_go_start(); } public void bottommiddlerightbottom_button_8() { // TODO - add functionality } public void bottomright_click_checkbox() { click_play = sogui_ref.bottomright_click_checkbox.isSelected(); } public void middleright_arduino_list() { String selvalue = (String) sogui_ref.middleright_arduino_list .getSelectedValue(); if (selvalue == null) { } else if (selvalue.equals(" ")) { } else if (selvalue.equals("refresh")) { set_middleright_arduino_list_items(); } else { } } public void externalcall_loadsettings(int pos) { middleright_shownitem = pos; sogui_ref.middleright_name_textfield .setText(settingsitemholder[pos].name); sogui_ref.middleright_min_textfield.setText(settingsitemholder[pos].min + ""); sogui_ref.middleright_max_textfield.setText(settingsitemholder[pos].max + ""); sogui_ref.middleright_startvalue_textfield .setText(settingsitemholder[pos].startvalue + ""); sogui_ref.middleright_arduino_list .setSelectedIndex(settingsitemholder[middleright_shownitem].arduinopos); sogui_ref.middleright_pin_list .setSelectedIndex(settingsitemholder[middleright_shownitem].pinpos); if (!settingsitemholder[middleright_shownitem].attached) { sogui_ref.middleright_attach_button.setText("Attach"); } else { sogui_ref.middleright_attach_button.setText("Detach"); } } public void play_go_start() { sogui_ref.bottommiddlerightbottom_button_6.setEnabled(true); sogui_ref.bottommiddlerightbottom_button_7.setEnabled(false); startClock(); } public void play_go_stop() { sogui_ref.bottommiddlerightbottom_button_6.setEnabled(false); sogui_ref.bottommiddlerightbottom_button_7.setEnabled(true); stopClock(); } public void play_go_f1() { pos1++; play_updatetime(true, false, false); play_updatepanels(pos1); } public void play_go_b1() { pos1 play_updatetime(true, false, false); play_updatepanels(pos1); } public void play_go_fa() { pos1 = sogui_ref.middlemiddle_ref.getRandomDragAndDropPanels()[0].length; pos2 = 4; pos3 = 999; play_updatetime(true, true, true); play_updatepanels(pos1); } public void play_go_ba() { pos1 = 1; pos2 = 1; pos3 = 0; play_updatetime(true, true, true); play_updatepanels(pos1); } public void play_play_1_1() { pos1++; if (pos1 > sizex) { play_go_stop(); } play_updatetime(true, false, false); play_playreally(pos1); } public void play_play_2_1() { pos2++; if (pos2 > 4) { play_play_1_1(); pos2 -= 4; } play_updatetime(false, true, false); } public void play_play_3_1() { pos3++; if (pos3 > 999) { play_play_2_1(); pos3 -= 999; } play_updatetime(false, false, true); } public void play_checktime() { if (pos1 > sogui_ref.middlemiddle_ref.getRandomDragAndDropPanels()[0].length) { pos1 = sogui_ref.middlemiddle_ref.getRandomDragAndDropPanels()[0].length; } else if (pos1 < 1) { pos1 = 1; } if (pos2 > 4) { pos2 = 4; } else if (pos2 < 1) { pos2 = 1; } if (pos3 > 999) { pos3 = 999; } else if (pos3 < 0) { pos3 = 0; } } public void play_updatetime(boolean t1, boolean t2, boolean t3) { play_checktime(); if (t1) { sogui_ref.bottommiddlerighttop_textfield_1.setText(pos1 + ""); } if (t2) { sogui_ref.bottommiddlerighttop_textfield_2.setText(pos2 + ""); } if (t3) { sogui_ref.bottommiddlerighttop_textfield_3.setText(pos3 + ""); } } public void play_updatepanels(int pos) { for (int i = 0; i < sogui_ref.middlemiddle_ref .getRandomDragAndDropPanels()[0].length; i++) { sogui_ref.middlemiddle_ref.prep[sogui_ref.middlemiddle_ref .getRandomDragAndDropPanels()[0].length + i] .setBackground(Color.green); } sogui_ref.middlemiddle_ref.prep[sogui_ref.middlemiddle_ref .getRandomDragAndDropPanels()[0].length + pos - 1] .setBackground(Color.red); sogui_ref.middlemiddle_ref.relayout(); } public void play_playreally(int pos) { play_updatepanels(pos); if (click_play) { play_playclick(); } if (pos >= sizex) { play_searchblocks(pos); } } public void play_playclick() { try { AudioInputStream audioInputStream = AudioSystem .getAudioInputStream(new File( "C:\\Users\\Marvin\\Desktop\\temp\\click.wav") .getAbsoluteFile()); Clip clip = AudioSystem.getClip(); clip.open(audioInputStream); clip.start(); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { e.printStackTrace(); } } public void play_searchblocks(int pos) { for (int i = 0; i < sizey; i++) { ServoOrchestratorGUI_middlemiddle_panel panels11 = sogui_ref.middlemiddle_ref .getRandomDragAndDropPanels()[pos][i]; if (panels11 != null) { play_playblock(i, panels11); } } } public void play_playblock(int channel, ServoOrchestratorGUI_middlemiddle_panel block) { switch (block.type) { case "timesection": break; case "channel": break; case "servo": if (servos[channel] != null) { int movetopos = Integer.parseInt(block.servo_goal.getText()); servos[channel].moveTo(movetopos); } break; } } public class SettingsItemHolder { String name; int min; int max; int startvalue; int arduinopos; int pinpos; boolean attached; } public class ClockThread implements Runnable { public Thread thread = null; ClockThread() { thread = new Thread(this, getName() + "_ticking_thread"); thread.start(); } public void run() { try { while (isClockRunning == true) { play_play_3_1(); Thread.sleep(interval); } } catch (InterruptedException e) { isClockRunning = false; } } } public void startClock() { if (myClock == null) { isClockRunning = true; myClock = new ClockThread(); } } public void stopClock() { if (myClock != null) { isClockRunning = false; myClock.thread.interrupt(); myClock.thread = null; myClock = null; } isClockRunning = false; } public static void main(String[] args) throws InterruptedException { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.INFO); try { Runtime.start("gui", "GUIService"); Runtime.start("servoorchestrator", "ServoOrchestrator"); } catch (Exception e) { Logging.logException(e); } } }
package org.nutz.ioc.loader.combo; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.nutz.aop.interceptor.async.AsyncAopIocLoader; import org.nutz.aop.interceptor.ioc.TransIocLoader; import org.nutz.ioc.IocLoader; import org.nutz.ioc.IocLoading; import org.nutz.ioc.ObjectLoadException; import org.nutz.ioc.loader.annotation.AnnotationIocLoader; import org.nutz.ioc.loader.json.JsonLoader; import org.nutz.ioc.loader.properties.PropertiesIocLoader; import org.nutz.ioc.loader.xml.XmlIocLoader; import org.nutz.ioc.meta.IocObject; import org.nutz.json.Json; import org.nutz.lang.Lang; import org.nutz.lang.Mirror; import org.nutz.log.Log; import org.nutz.log.Logs; /** * IocLoader * * @author wendal(wendal1985@gmail.com) * */ public class ComboIocLoader implements IocLoader { private static final Log log = Logs.get(); private List<IocLoader> iocLoaders = new ArrayList<IocLoader>(); /** * * <p/> * ,*,, <code>*org.nutz.ioc.loader.json.JsonLoader</code> * <p/> * : js, json, xml, annotation, anno, trans, async, props, tx, quartz * <p/> * , * <p/> * , (*),IocLoader,* * <p/> * <p/> * : * <p/> * <code>{"*js","ioc/dao.js","ioc/service.js","*xml","ioc/config.xml", "*anoo", "net.wendal.nutzbook"}</code> * <p/> * , {"ioc/dao.js","ioc/service.js"}JsonLoader,{"ioc/dao.xml"} * XmlIocLoader, "net.wendal.nutzbook"AnnotationIocLoader * * @throws ClassNotFoundException * * */ @SuppressWarnings("unchecked") public ComboIocLoader(String... args) throws ClassNotFoundException { if (loaders.isEmpty()) { loaders.put("js", JsonLoader.class); loaders.put("json", JsonLoader.class); loaders.put("xml", XmlIocLoader.class); loaders.put("annotation", AnnotationIocLoader.class); loaders.put("anno", AnnotationIocLoader.class); loaders.put("trans", TransIocLoader.class); loaders.put("tx", TransIocLoader.class); loaders.put("props", PropertiesIocLoader.class); loaders.put("properties", PropertiesIocLoader.class); loaders.put("async", AsyncAopIocLoader.class); try { loaders.put("cache", (Class<? extends IocLoader>) Lang.loadClass("org.nutz.jcache.NutCacheIocLoader")); } catch (ClassNotFoundException e) {} try { loaders.put("quartz", (Class<? extends IocLoader>) Lang.loadClass("org.nutz.integration.quartz.QuartzIocLoader")); } catch (ClassNotFoundException e) {} } ArrayList<String> argsList = null; String currentClassName = null; for (String str : args) { if (str.length() > 0 && str.charAt(0) == '*') { if (argsList != null) createIocLoader(currentClassName, argsList); currentClassName = str.substring(1); argsList = new ArrayList<String>(); } else { if (argsList == null) { throw new IllegalArgumentException("ioc args without Loader ClassName. " + Arrays.toString(args)); } argsList.add(str); } } if (currentClassName != null) createIocLoader(currentClassName, argsList); Set<String> beanNames = new HashSet<String>(); for (IocLoader loader : iocLoaders) { for (String beanName : loader.getName()) { if (!beanNames.add(beanName) && log.isWarnEnabled()) log.warnf("Found Duplicate beanName=%s, pls check you config! loader=%s", beanName,loader.getClass()); } } } @SuppressWarnings("unchecked") private void createIocLoader(String className, List<String> args) throws ClassNotFoundException { Class<? extends IocLoader> klass = loaders.get(className); if (klass == null) klass = (Class<? extends IocLoader>) Lang.loadClass(className); iocLoaders.add((IocLoader) Mirror.me(klass).born(args.toArray(new Object[args.size()]))); } public ComboIocLoader(IocLoader... loaders) { for (IocLoader iocLoader : loaders) if (iocLoader != null) iocLoaders.add(iocLoader); } public String[] getName() { ArrayList<String> list = new ArrayList<String>(); for (IocLoader iocLoader : iocLoaders) { for (String name : iocLoader.getName()) list.add(name); } return list.toArray(new String[list.size()]); } public boolean has(String name) { for (IocLoader iocLoader : iocLoaders) if (iocLoader.has(name)) return true; return false; } public IocObject load(IocLoading loading, String name) throws ObjectLoadException { for (IocLoader iocLoader : iocLoaders) if (iocLoader.has(name)) { IocObject iocObject = iocLoader.load(loading, name); if (log.isDebugEnabled()) log.debugf("Found IocObject(%s) in IocLoader(%s)", name, iocLoader.getClass().getSimpleName() + "@" + iocLoader.hashCode()); return iocObject; } throw new ObjectLoadException("Object '" + name + "' without define!"); } public void addLoader(IocLoader loader) { if (null != loader) { if (iocLoaders.contains(loader)) return; iocLoaders.add(loader); if (log.isInfoEnabled()) log.infof("add loader : %s : \n - %s", loader.getClass(), Lang.concat("\n - ", loader.getName())); } } protected static Map<String, Class<? extends IocLoader>> loaders = new HashMap<String, Class<? extends IocLoader>>(); // TODO ... public String toString() { StringBuilder sb = new StringBuilder(); sb.append("/*ComboIocLoader*/\n{"); for (IocLoader loader : iocLoaders) { String str = Json.toJson(loader); str = str.replaceFirst("[{]", ""); int index = str.lastIndexOf("}"); StringBuilder sb2 = new StringBuilder(str); sb2.setCharAt(index, ' '); sb.append(sb2).append("\n"); } sb.append("}"); return sb.toString(); } }
package org.opencms.ui.apps.scheduler; import org.opencms.scheduler.CmsScheduledJobInfo; import org.opencms.ui.CmsCssIcon; import org.opencms.ui.components.OpenCmsTheme; import org.opencms.util.CmsUUID; import java.util.Date; import com.vaadin.server.Resource; /** * Don't use CmsScheduledJobInfo directly, so we don't need to change it if we want to change how the values are * rendered, and having only the fields we want displayed in the table makes it easier to understand. */ public class CmsJobBean { /** The job icon resource. */ private static CmsCssIcon ICON = new CmsCssIcon(OpenCmsTheme.ICON_JOB); /** Internal id. */ private CmsUUID m_id = new CmsUUID(); /** The wrapped scheduled job info. */ protected CmsScheduledJobInfo m_jobInfo; /** * Creates a new instance.<p> * * @param info the scheduled job info to wrap */ public CmsJobBean(CmsScheduledJobInfo info) { m_jobInfo = info; } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (obj instanceof CmsJobBean) { return ((CmsJobBean)obj).m_id.equals(m_id); } return false; } /** * Gets the class name for the job.<p> * * @return the class name */ public String getClassName() { return m_jobInfo.getClassName(); } /** * Returns the job icon resource.<p> * * @return the job icon resource */ public Resource getIcon() { return ICON; } /** * Gets the scheduled job.<p> * * @return the scheduled job */ public CmsScheduledJobInfo getJob() { return m_jobInfo; } /** * Gets the last execution date.<p> * * @return the last execution date */ public Date getLastExecution() { return m_jobInfo.getExecutionTimePrevious(); } /** * Gets the job name.<p> * * @return the job name */ public String getName() { return m_jobInfo.getJobName(); } /** * Gets the next execution date.<p> * * @return the next execution date */ public Date getNextExecution() { return m_jobInfo.getExecutionTimeNext(); } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return m_id.hashCode(); } }
package org.trifort.rootbeer.runtime; import java.util.Map; import java.util.TreeMap; public class RootbeerGpu { private static boolean m_isOnGpu; private static byte[] m_sharedMem; private static int m_blockIdxx; private static int m_threadIdxx; private static int m_threadId; private static long m_gridDimx; private static int m_blockDimx; private static Map<Integer, Object> m_sharedArrayMap; static { m_isOnGpu = false; m_sharedMem = new byte[48*1024]; m_sharedArrayMap = new TreeMap<Integer, Object>(); } public static boolean isOnGpu(){ return m_isOnGpu; } public static void setIsOnGpu(boolean value){ m_isOnGpu = value; } /** * @return blockIdx.x * blockDim.x + threadIdx.x; */ public static int getThreadId() { return m_threadId; } public static int getThreadIdxx() { return m_threadIdxx; } public static int getBlockIdxx() { return m_blockIdxx; } public static int getBlockDimx(){ return m_blockDimx; } public static long getGridDimx(){ return m_gridDimx; } public static void setThreadId(int thread_id){ m_threadId = thread_id; } public static void setThreadIdxx(int thread_idxx){ m_threadIdxx = thread_idxx; } public static void setBlockIdxx(int block_idxx){ m_blockIdxx = block_idxx; } public static void setBlockDimx(int block_dimx){ m_blockDimx = block_dimx; } public static void setGridDimx(long grid_dimx){ m_gridDimx = grid_dimx; } public static void syncthreads(){ } public static void threadfence(){ } public static void threadfenceBlock(){ } public static void threadfenceSystem(){ } public static long getRef(Object obj) { return 0; } public static Object getSharedObject(int index){ return null; } public static void setSharedObject(int index, Object value){ } public static byte getSharedByte(int index){ return m_sharedMem[index]; } public static void setSharedByte(int index, byte value){ m_sharedMem[index] = value; } public static char getSharedChar(int index){ char ret = 0; ret |= m_sharedMem[index] & 0xff; ret |= (m_sharedMem[index + 1] << 8) & 0xff00; return ret; } public static void setSharedChar(int index, char value){ m_sharedMem[index] = (byte) (value & 0xff); m_sharedMem[index + 1] = (byte) ((value >> 8) & 0xff); } public static boolean getSharedBoolean(int index){ if(m_sharedMem[index] == 1){ return true; } else { return false; } } public static void setSharedBoolean(int index, boolean value){ byte value_byte; if(value == true){ value_byte = 1; } else { value_byte = 0; } m_sharedMem[index] = value_byte; } public static short getSharedShort(int index){ short ret = 0; ret |= m_sharedMem[index] & 0xff; ret |= (m_sharedMem[index + 1] << 8) & 0xff00; return ret; } public static void setSharedShort(int index, short value){ m_sharedMem[index] = (byte) (value & 0xff); m_sharedMem[index + 1] = (byte) ((value >> 8) & 0xff); } public static int getSharedInteger(int index){ int ret = 0; ret |= m_sharedMem[index] & 0x000000ff; ret |= (m_sharedMem[index + 1] << 8) & 0x0000ff00; ret |= (m_sharedMem[index + 2] << 16) & 0x00ff0000; ret |= (m_sharedMem[index + 3] << 24) & 0xff000000; return ret; } public static void setSharedInteger(int index, int value){ m_sharedMem[index] = (byte) (value & 0xff); m_sharedMem[index + 1] = (byte) ((value >> 8) & 0xff); m_sharedMem[index + 2] = (byte) ((value >> 16) & 0xff); m_sharedMem[index + 3] = (byte) ((value >> 24) & 0xff); } public static long getSharedLong(int index){ long ret = 0; ret |= (long) m_sharedMem[index] & 0x00000000000000ffL; ret |= ((long) m_sharedMem[index + 1] << 8) & 0x000000000000ff00L; ret |= ((long) m_sharedMem[index + 2] << 16) & 0x0000000000ff0000L; ret |= ((long) m_sharedMem[index + 3] << 24) & 0x00000000ff000000L; ret |= ((long) m_sharedMem[index + 4] << 32) & 0x000000ff00000000L; ret |= ((long) m_sharedMem[index + 5] << 40) & 0x0000ff0000000000L; ret |= ((long) m_sharedMem[index + 6] << 48) & 0x00ff000000000000L; ret |= ((long) m_sharedMem[index + 7] << 56) & 0xff00000000000000L; return ret; } public static void setSharedLong(int index, long value){ m_sharedMem[index] = (byte) (value & 0xff); m_sharedMem[index + 1] = (byte) ((value >> 8) & 0xff); m_sharedMem[index + 2] = (byte) ((value >> 16) & 0xff); m_sharedMem[index + 3] = (byte) ((value >> 24) & 0xff); m_sharedMem[index + 4] = (byte) ((value >> 32) & 0xff); m_sharedMem[index + 5] = (byte) ((value >> 40) & 0xff); m_sharedMem[index + 6] = (byte) ((value >> 48) & 0xff); m_sharedMem[index + 7] = (byte) ((value >> 56) & 0xff); } public static float getSharedFloat(int index){ int value_int = getSharedInteger(index); return Float.intBitsToFloat(value_int); } public static void setSharedFloat(int index, float value){ int value_int = Float.floatToIntBits(value); setSharedInteger(index, value_int); } public static double getSharedDouble(int index){ long value_long = getSharedLong(index); return Double.longBitsToDouble(value_long); } public static void setSharedDouble(int index, double value){ long value_long = Double.doubleToLongBits(value); setSharedLong(index, value_long); } public static double sin(double value){ return 0; } public static void atomicAddGlobal(int[] array, int index, int addValue){ synchronized(array){ array[index] += addValue; } } public static void atomicAddGlobal(long[] array, int index, long addValue){ synchronized(array){ array[index] += addValue; } } public static void atomicAddGlobal(float[] array, int index, float addValue){ synchronized(array){ array[index] += addValue; } } public static void atomicSubGlobal(int[] array, int index, int subValue){ synchronized(array){ array[index] -= subValue; } } public static int atomicExchGlobal(int[] array, int index, int value){ synchronized(array){ int ret = array[index]; array[index] = value; return ret; } } public static long atomicExchGlobal(long[] array, int index, long value){ synchronized(array){ long ret = array[index]; array[index] = value; return ret; } } public static float atomicExchGlobal(float[] array, int index, float value){ synchronized(array){ float ret = array[index]; array[index] = value; return ret; } } public static int atomicMinGlobal(int[] array, int index, int value){ synchronized(array){ int old = array[index]; if(value < old){ array[index] = value; } return old; } } public static int atomicMaxGlobal(int[] array, int index, int value){ synchronized(array){ int old = array[index]; if(value > old){ array[index] = value; } return old; } } public static int atomicCASGlobal(int[] array, int index, int compare, int value){ synchronized(array){ int old = array[index]; if(old == compare){ array[index] = value; } return old; } } public static int atomicAndGlobal(int[] array, int index, int value){ synchronized(array){ int old = array[index]; array[index] = old & value; return old; } } public static int atomicOrGlobal(int[] array, int index, int value){ synchronized(array){ int old = array[index]; array[index] = old | value; return old; } } public static int atomicXorGlobal(int[] array, int index, int value){ synchronized(array){ int old = array[index]; array[index] = old ^ value; return old; } } }
package org.usfirst.frc.team997.robot; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketTimeoutException; public class UDPReceive { private DatagramSocket dsocket; private DatagramPacket packet; private byte[] buffer; private String string = ""; public UDPReceive() { try { int port = 10030; // Create a socket to listen on the port. dsocket = new DatagramSocket(port); dsocket.setSoTimeout(10); // Create a buffer to read datagrams into. buffer = new byte[2048]; // Create a packet to receive data into the buffer packet = new DatagramPacket(buffer, buffer.length); } catch (Exception e) { e.printStackTrace(); } } public VisionStorage work() { VisionStorage result = null; try { // Wait to receive a datagram dsocket.receive(packet); // Convert the contents to a string, and display them string += new String(buffer, 0, packet.getLength()); int packetEnd; if ((packetEnd = string.indexOf(';')) != -1) { float hypotnuse = Float.parseFloat(string.substring(0, 8)); float horizontalOffset = Float.parseFloat(string.substring(9, 17)); float distance = (float) Math.sqrt((hypotnuse*hypotnuse)-(56*56)); string = string.substring(packetEnd + 1); result = new VisionStorage(distance, horizontalOffset); } // Reset the length of the packet before reusing it. packet.setLength(buffer.length); } catch (Exception e) { e.printStackTrace();; } return result; } }
package protocolsupport.protocol.utils; import java.util.List; import java.util.Map.Entry; import java.util.StringJoiner; import java.util.UUID; import org.bukkit.NamespacedKey; import protocolsupport.protocol.types.NetworkItemStack; import protocolsupport.protocol.types.nbt.NBT; import protocolsupport.protocol.types.nbt.NBTByte; import protocolsupport.protocol.types.nbt.NBTCompound; import protocolsupport.protocol.types.nbt.NBTIntArray; import protocolsupport.protocol.types.nbt.NBTList; import protocolsupport.protocol.types.nbt.NBTNumber; import protocolsupport.protocol.types.nbt.NBTShort; import protocolsupport.protocol.types.nbt.NBTString; import protocolsupport.protocol.types.networkentity.NetworkEntityType; import protocolsupport.protocol.utils.minecraftdata.MinecraftPotionData; public class CommonNBT { private CommonNBT() { } public static NBTCompound getOrCreateRootTag(NetworkItemStack itemstack) { NBTCompound tag = itemstack.getNBT(); if (tag == null) { tag = new NBTCompound(); itemstack.setNBT(tag); } return tag; } public static final String BLOCK_TAG = "BlockEntityTag"; public static final String DISPLAY = "display"; public static final String DISPLAY_NAME = "Name"; public static final String DISPLAY_LORE = "Lore"; public static NBTCompound getOrCreateDisplayTag(NBTCompound rootTag) { NBTCompound display = rootTag.getCompoundTagOrNull(DISPLAY); if (display == null) { display = new NBTCompound(); rootTag.setTag(DISPLAY, display); } return display; } public static final String ATTRIBUTES = "AttributeModifiers"; public static final String ATTRIBUTE_ID = "AttributeName"; public static final String ATTRIBUTE_UUID = "UUID"; public static String[] getSignLines(NBTCompound tag) { String[] lines = new String[4]; for (int i = 0; i < lines.length; i++) { lines[i] = tag.getStringTagValueOrDefault("Text" + (i + 1), ""); } return lines; } public static final String BOOK_PAGES = "pages"; public static final String BOOK_TITLE = "title"; public static String[] getBookPages(NBTCompound tag) { List<NBTString> pagesTags = tag.getStringListTagOrThrow(CommonNBT.BOOK_PAGES).getTags(); String[] pages = new String[pagesTags.size()]; for (int i = 0; i < pagesTags.size(); i++) { pages[i] = pagesTags.get(i).getValue(); } return pages; } public static final String BOOK_ENCHANTMENTS = "StoredEnchantments"; public static final String MODERN_ENCHANTMENTS = "Enchantments"; public static final String LEGACY_ENCHANTMENTS = "ench"; @SuppressWarnings("deprecation") public static final NamespacedKey FAKE_ENCHANTMENT_KEY = new NamespacedKey("ps", "fake"); public static final String FAKE_ENCHANTMENT_KEY_STR = FAKE_ENCHANTMENT_KEY.toString(); public static NBTCompound createFakeEnchantmentTag() { NBTCompound tag = new NBTCompound(); tag.setTag("id", new NBTString(FAKE_ENCHANTMENT_KEY_STR)); tag.setTag("lvl", new NBTShort((short) 1)); return tag; } public static final String MOB_SPAWNER_SPAWNDATA = "SpawnData"; public static NetworkEntityType getSpawnedMobType(NBTCompound spawndataTag) { return NetworkEntityType.getByRegistrySTypeId(spawndataTag.getStringTagValueOrNull("id")); } public static final String POTION_TYPE = "Potion"; public static String getPotionEffectType(NBTCompound tag) { NBTString potionType = tag.getStringTagOrNull(POTION_TYPE); if (potionType != null) { return potionType.getValue(); } NBTList<NBTCompound> customPotionEffects = tag.getCompoundListTagOrNull("CustomPotionEffects"); if (customPotionEffects != null) { for (NBTCompound customPotionEffect : customPotionEffects.getTags()) { NBTNumber potionId = customPotionEffect.getNumberTagOrNull("Id"); if (potionId != null) { return MinecraftPotionData.getNameById(potionId.getAsInt()); } } } return null; } public static final String ITEM_DAMAGE = "Damage"; public static final String MAP_ID = "map"; public static final String BANNER_BASE = "Base"; public static final String BANNER_PATTERNS = "Patterns"; public static final String BANNER_PATTERN_COLOR = "Color"; public static final String PLAYERHEAD_PROFILE = "SkullOwner"; public static final String ITEMSTACK_STORAGE_ID = "id"; public static final String ITEMSTACK_STORAGE_COUNT = "Count"; public static final String ITEMSTACK_STORAGE_NBT = "tag"; public static NetworkItemStack deserializeItemStackFromNBT(NBTCompound rootTag) { NetworkItemStack itemstack = new NetworkItemStack(); NBTString idTag = rootTag.getStringTagOrNull(ITEMSTACK_STORAGE_ID); if (idTag != null) { itemstack.setTypeId(ItemMaterialLookup.getRuntimeId(ItemMaterialLookup.getByKey(idTag.getValue()))); } NBTNumber countTag = rootTag.getNumberTagOrNull(ITEMSTACK_STORAGE_COUNT); if (countTag != null) { itemstack.setAmount(countTag.getAsInt()); } NBTCompound tagTag = rootTag.getCompoundTagOrNull(ITEMSTACK_STORAGE_NBT); if (tagTag != null) { itemstack.setNBT(tagTag); } return itemstack; } public static NBTCompound serializeItemStackToNBT(NetworkItemStack itemstack) { NBTCompound rootTag = new NBTCompound(); rootTag.setTag(ITEMSTACK_STORAGE_ID, new NBTString(ItemMaterialLookup.getByRuntimeId(itemstack.getTypeId()).getKey().toString())); rootTag.setTag(ITEMSTACK_STORAGE_COUNT, new NBTByte((byte) itemstack.getAmount())); rootTag.setTag(ITEMSTACK_STORAGE_NBT, itemstack.getNBT()); return rootTag; } public static String deserializeBlockDataFromNBT(NBTCompound compound) { String name = compound.getStringTagValueOrThrow("Name"); NBTCompound propertiesTag = compound.getCompoundTagOrNull("Properties"); if (propertiesTag == null) { return name; } else { StringJoiner joiner = new StringJoiner(",", name + "[", "]"); for (Entry<String, NBT> entry : propertiesTag.getTags().entrySet()) { NBT valueTag = entry.getValue(); if (valueTag instanceof NBTString stringTag) { joiner.add(entry.getKey() + "=" + stringTag.getValue()); } } return joiner.toString(); } } public static NBTIntArray serializeUUID(UUID uuid) { long most = uuid.getMostSignificantBits(); long least = uuid.getLeastSignificantBits(); return new NBTIntArray(new int[] {(int) (most >>> 32), (int) most, (int) least >>> 32, (int) least}); } public static UUID deserializeUUID(NBTIntArray tag) { if (tag == null) { return null; } int[] array = tag.getValue(); try { return new UUID( (((long) array[0]) << 32L) | Integer.toUnsignedLong(array[1]), (((long) array[2]) << 32L) | Integer.toUnsignedLong(array[3]) ); } catch (IllegalArgumentException t) { return null; } } }
package pucrs.alpro3.graph; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class UndirectedGraphMatrix implements UndirectedGraph { private boolean[][] matrix; private List<String> names; public UndirectedGraphMatrix() { matrix = new boolean[5][5]; names = new ArrayList<String>(); } @Override public void addVertice(String vertice) { if (vertice == null) throw new IllegalArgumentException("O vertice nao pode ser null"); if (vertice.trim().isEmpty()) throw new IllegalArgumentException("O vertice nao pode ser vazio"); if (names.contains(vertice)) throw new IllegalArgumentException("O vertice ja se encontra cadastrado: " + vertice); names.add(vertice); } @Override public void addEdge(String strOrig, String strDest) { int posOrig = names.indexOf(strOrig); int posDest = names.indexOf(strDest); matrix[posOrig][posDest] = true; matrix[posDest][posOrig] = true; } @Override public int getDegree(String vertice) { return getAllAdjacents(vertice).size(); } @Override public ArrayList<String> getAllAdjacents(String vertice) { ArrayList<String> r = new ArrayList<>(); int pos = names.indexOf(vertice); for (int i = 0; i < matrix.length; i++) if (matrix[pos][i] == true) r.add(names.get(i)); return r; } @Override public String toString() { String r = ""; r += names.toString(); for (int i = 0; i < matrix.length; i++) r += "\n" + Arrays.toString(matrix[i]); return r; } }
package logica; import java.util.ArrayList; /** * * @author dark */ public class Reporte implements ExportFile{ private int con_area_nacimiento = 0; private ArrayList<FilaEstadisticaVitalNacimientos> area_nacimiento = new ArrayList<>(); private int con_sitio_nacimiento = 0; private ArrayList<FilaEstadisticaVitalNacimientos> sitio_nacimiento = new ArrayList<>(); private int con_semana_gestacion = 0; private ArrayList<FilaEstadisticaVitalNacimientos> semana_gestacion = new ArrayList<>(); private int con_peso = 0; private ArrayList<FilaEstadisticaVitalNacimientos> peso = new ArrayList<>(); private int con_peso_tiempo_gestacion = 0; private ArrayList<FilaEstadisticaVitalNacimientos> peso_tiempo_gestacion = new ArrayList<>(); private int con_talla = 0; private ArrayList<FilaEstadisticaVitalNacimientos> talla = new ArrayList<>(); private int con_peso_tiempo_gestacion_talla = 0; private ArrayList<FilaEstadisticaVitalNacimientos> peso_tiempo_gestacion_talla = new ArrayList<>(); private int con_grupo_sanguineo = 0; private ArrayList<FilaEstadisticaVitalNacimientos> grupo_sanguineo = new ArrayList<>(); private int con_factor_rh = 0; private ArrayList<FilaEstadisticaVitalNacimientos> factor_rh = new ArrayList<>(); private int con_direccion = 0; private ArrayList<FilaEstadisticaVitalNacimientos> direccion = new ArrayList<>(); private int con_edad_padre = 0; private ArrayList<FilaEstadisticaVitalNacimientos> edad_padre = new ArrayList<>(); private int con_estado = 0; private ArrayList<FilaEstadisticaVitalNacimientos> estado = new ArrayList<>(); private int con_multiplicidad = 0; private ArrayList<FilaEstadisticaVitalNacimientos> multiplicidad = new ArrayList<>(); private int municipio; private ArrayList<EstadisticaVital_defuncion> area_defuncion = new ArrayList<>(); private ArrayList<EstadisticaVital_defuncion> tipo_defuncion = new ArrayList<>(); private ArrayList<EstadisticaVital_defuncion> direccion_defuncion = new ArrayList<>(); private ArrayList<EstadisticaVital_defuncion> mujeres = new ArrayList<>(); private ArrayList<EstadisticaVital_defuncion> tipo_profesional = new ArrayList<>(); private ArrayList<EstadisticaVital_defuncion> estado_defuncion =new ArrayList<>(); public Reporte(int con_area_nacimiento, ArrayList<FilaEstadisticaVitalNacimientos> area_nacimiento, int con_sitio_nacimiento, ArrayList<FilaEstadisticaVitalNacimientos> sitio_nacimiento, int con_semana_gestacion, ArrayList<FilaEstadisticaVitalNacimientos> semana_gestacion, int con_peso, ArrayList<FilaEstadisticaVitalNacimientos> peso, int con_peso_tiempo_gestacion, ArrayList<FilaEstadisticaVitalNacimientos> peso_tiempo_gestacion, int con_talla, ArrayList<FilaEstadisticaVitalNacimientos> talla, int con_peso_tiempo_gestacion_talla, ArrayList<FilaEstadisticaVitalNacimientos> peso_tiempo_gestacion_talla, int con_grupo_sanguineo, ArrayList<FilaEstadisticaVitalNacimientos> grupo_sanguineo, int con_factor_rh, ArrayList<FilaEstadisticaVitalNacimientos> factor_rh, int con_direccion, ArrayList<FilaEstadisticaVitalNacimientos> direccion, int con_edad_padre, ArrayList<FilaEstadisticaVitalNacimientos> edad_padre, int con_estado, ArrayList<FilaEstadisticaVitalNacimientos> estado, int con_multiplicidad, ArrayList<FilaEstadisticaVitalNacimientos> multiplicidad, ArrayList<EstadisticaVital_defuncion> area_defuncion, ArrayList<EstadisticaVital_defuncion> tipo_defuncion, ArrayList<EstadisticaVital_defuncion> direccion_defuncion, ArrayList<EstadisticaVital_defuncion> mujeres, ArrayList<EstadisticaVital_defuncion> tipo_profesional, ArrayList<EstadisticaVital_defuncion> estado_defuncion) { this.con_area_nacimiento = con_area_nacimiento; this.area_nacimiento =area_nacimiento; this.con_sitio_nacimiento = con_sitio_nacimiento; this.sitio_nacimiento =sitio_nacimiento; this.con_semana_gestacion = con_semana_gestacion; this.semana_gestacion = semana_gestacion; this.con_peso=con_peso; this.peso = peso; this.con_peso_tiempo_gestacion = con_peso_tiempo_gestacion; this.peso_tiempo_gestacion = peso_tiempo_gestacion; this.con_talla = con_talla; this.talla = talla; this.con_peso_tiempo_gestacion_talla = con_peso_tiempo_gestacion_talla; this.peso_tiempo_gestacion_talla = peso_tiempo_gestacion_talla; this.con_grupo_sanguineo = con_grupo_sanguineo; this.grupo_sanguineo = grupo_sanguineo; this.con_factor_rh = con_factor_rh; this.factor_rh = factor_rh; this.con_direccion = con_direccion; this.direccion = direccion; this.con_edad_padre=con_edad_padre; this.edad_padre = edad_padre; this.con_estado = con_estado; this.estado = estado; this.con_multiplicidad = con_multiplicidad; this.multiplicidad = multiplicidad; this.area_defuncion = area_defuncion; this.tipo_defuncion = tipo_defuncion; this.direccion_defuncion = direccion_defuncion; this.mujeres =mujeres; this.tipo_profesional = tipo_profesional; this.estado_defuncion = estado_defuncion; } public Reporte(int con_area_nacimiento, ArrayList<FilaEstadisticaVitalNacimientos> area_nacimiento, int con_sitio_nacimiento, ArrayList<FilaEstadisticaVitalNacimientos> sitio_nacimiento, int con_semana_gestacion, ArrayList<FilaEstadisticaVitalNacimientos> semana_gestacion, int con_peso, ArrayList<FilaEstadisticaVitalNacimientos> peso, int con_peso_tiempo_gestacion, ArrayList<FilaEstadisticaVitalNacimientos> peso_tiempo_gestacion, int con_talla, ArrayList<FilaEstadisticaVitalNacimientos> talla, int con_peso_tiempo_gestacion_talla, ArrayList<FilaEstadisticaVitalNacimientos> peso_tiempo_gestacion_talla, int con_grupo_sanguineo, ArrayList<FilaEstadisticaVitalNacimientos> grupo_sanguineo, int con_factor_rh, ArrayList<FilaEstadisticaVitalNacimientos> factor_rh, int con_direccion, ArrayList<FilaEstadisticaVitalNacimientos> direccion, int con_edad_padre, ArrayList<FilaEstadisticaVitalNacimientos> edad_padre, int con_estado, ArrayList<FilaEstadisticaVitalNacimientos> estado, int con_multiplicidad, ArrayList<FilaEstadisticaVitalNacimientos> multiplicidad, ArrayList<EstadisticaVital_defuncion> area_defuncion, ArrayList<EstadisticaVital_defuncion> tipo_defuncion, ArrayList<EstadisticaVital_defuncion> direccion_defuncion, ArrayList<EstadisticaVital_defuncion> mujeres, ArrayList<EstadisticaVital_defuncion> tipo_profesional, ArrayList<EstadisticaVital_defuncion> estado_defuncion, int municipio) { this.con_area_nacimiento = con_area_nacimiento; this.area_nacimiento =area_nacimiento; this.con_sitio_nacimiento = con_sitio_nacimiento; this.sitio_nacimiento =sitio_nacimiento; this.con_semana_gestacion = con_semana_gestacion; this.semana_gestacion = semana_gestacion; this.con_peso=con_peso; this.peso = peso; this.con_peso_tiempo_gestacion = con_peso_tiempo_gestacion; this.peso_tiempo_gestacion = peso_tiempo_gestacion; this.con_talla = con_talla; this.talla = talla; this.con_peso_tiempo_gestacion_talla = con_peso_tiempo_gestacion_talla; this.peso_tiempo_gestacion_talla = peso_tiempo_gestacion_talla; this.con_grupo_sanguineo = con_grupo_sanguineo; this.grupo_sanguineo = grupo_sanguineo; this.con_factor_rh = con_factor_rh; this.factor_rh = factor_rh; this.con_direccion = con_direccion; this.direccion = direccion; this.con_edad_padre=con_edad_padre; this.edad_padre = edad_padre; this.con_estado = con_estado; this.estado = estado; this.con_multiplicidad = con_multiplicidad; this.multiplicidad = multiplicidad; this.municipio = municipio; this.area_defuncion = area_defuncion; this.tipo_defuncion = tipo_defuncion; this.direccion_defuncion = direccion_defuncion; this.mujeres =mujeres; this.tipo_profesional = tipo_profesional; this.estado_defuncion = estado_defuncion; } @Override public void writeFile() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public int getCon_area_nacimiento() { return con_area_nacimiento; } public void setCon_area_nacimiento(int con_area_nacimiento) { this.con_area_nacimiento = con_area_nacimiento; } public ArrayList<FilaEstadisticaVitalNacimientos> getArea_nacimiento() { return area_nacimiento; } public void setArea_nacimiento(ArrayList<FilaEstadisticaVitalNacimientos> area_nacimiento) { this.area_nacimiento = area_nacimiento; } public int getCon_sitio_nacimiento() { return con_sitio_nacimiento; } public void setCon_sitio_nacimiento(int con_sitio_nacimiento) { this.con_sitio_nacimiento = con_sitio_nacimiento; } public ArrayList<FilaEstadisticaVitalNacimientos> getSitio_nacimiento() { return sitio_nacimiento; } public void setSitio_nacimiento(ArrayList<FilaEstadisticaVitalNacimientos> sitio_nacimiento) { this.sitio_nacimiento = sitio_nacimiento; } public int getCon_semana_gestacion() { return con_semana_gestacion; } public void setCon_semana_gestacion(int con_semana_gestacion) { this.con_semana_gestacion = con_semana_gestacion; } public ArrayList<FilaEstadisticaVitalNacimientos> getSemana_gestacion() { return semana_gestacion; } public void setSemana_gestacion(ArrayList<FilaEstadisticaVitalNacimientos> semana_gestacion) { this.semana_gestacion = semana_gestacion; } public int getCon_peso() { return con_peso; } public void setCon_peso(int con_peso) { this.con_peso = con_peso; } public ArrayList<FilaEstadisticaVitalNacimientos> getPeso() { return peso; } public void setPeso(ArrayList<FilaEstadisticaVitalNacimientos> peso) { this.peso = peso; } public int getCon_peso_tiempo_gestacion() { return con_peso_tiempo_gestacion; } public void setCon_peso_tiempo_gestacion(int con_peso_tiempo_gestacion) { this.con_peso_tiempo_gestacion = con_peso_tiempo_gestacion; } public ArrayList<FilaEstadisticaVitalNacimientos> getPeso_tiempo_gestacion() { return peso_tiempo_gestacion; } public void setPeso_tiempo_gestacion(ArrayList<FilaEstadisticaVitalNacimientos> peso_tiempo_gestacion) { this.peso_tiempo_gestacion = peso_tiempo_gestacion; } public int getCon_talla() { return con_talla; } public void setCon_talla(int con_talla) { this.con_talla = con_talla; } public ArrayList<FilaEstadisticaVitalNacimientos> getTalla() { return talla; } public void setTalla(ArrayList<FilaEstadisticaVitalNacimientos> talla) { this.talla = talla; } public int getCon_peso_tiempo_gestacion_talla() { return con_peso_tiempo_gestacion_talla; } public void setCon_peso_tiempo_gestacion_talla(int con_peso_tiempo_gestacion_talla) { this.con_peso_tiempo_gestacion_talla = con_peso_tiempo_gestacion_talla; } public ArrayList<FilaEstadisticaVitalNacimientos> getPeso_tiempo_gestacion_talla() { return peso_tiempo_gestacion_talla; } public void setPeso_tiempo_gestacion_talla(ArrayList<FilaEstadisticaVitalNacimientos> peso_tiempo_gestacion_talla) { this.peso_tiempo_gestacion_talla = peso_tiempo_gestacion_talla; } public int getCon_grupo_sanguineo() { return con_grupo_sanguineo; } public void setCon_grupo_sanguineo(int con_grupo_sanguineo) { this.con_grupo_sanguineo = con_grupo_sanguineo; } public ArrayList<FilaEstadisticaVitalNacimientos> getGrupo_sanguineo() { return grupo_sanguineo; } public void setGrupo_sanguineo(ArrayList<FilaEstadisticaVitalNacimientos> grupo_sanguineo) { this.grupo_sanguineo = grupo_sanguineo; } public int getCon_factor_rh() { return con_factor_rh; } public void setCon_factor_rh(int con_factor_rh) { this.con_factor_rh = con_factor_rh; } public ArrayList<FilaEstadisticaVitalNacimientos> getFactor_rh() { return factor_rh; } public void setFactor_rh(ArrayList<FilaEstadisticaVitalNacimientos> factor_rh) { this.factor_rh = factor_rh; } public int getCon_direccion() { return con_direccion; } public void setCon_direccion(int con_direccion) { this.con_direccion = con_direccion; } public ArrayList<FilaEstadisticaVitalNacimientos> getDireccion() { return direccion; } public void setDireccion(ArrayList<FilaEstadisticaVitalNacimientos> direccion) { this.direccion = direccion; } public int getCon_edad_padre() { return con_edad_padre; } public void setCon_edad_padre(int con_edad_padre) { this.con_edad_padre = con_edad_padre; } public ArrayList<FilaEstadisticaVitalNacimientos> getEdad_padre() { return edad_padre; } public void setEdad_padre(ArrayList<FilaEstadisticaVitalNacimientos> edad_padre) { this.edad_padre = edad_padre; } public int getCon_estado() { return con_estado; } public void setCon_estado(int con_estado) { this.con_estado = con_estado; } public ArrayList<FilaEstadisticaVitalNacimientos> getEstado() { return estado; } public void setEstado(ArrayList<FilaEstadisticaVitalNacimientos> estado) { this.estado = estado; } public int getCon_multiplicidad() { return con_multiplicidad; } public void setCon_multiplicidad(int con_multiplicidad) { this.con_multiplicidad = con_multiplicidad; } public ArrayList<FilaEstadisticaVitalNacimientos> getMultiplicidad() { return multiplicidad; } public void setMultiplicidad(ArrayList<FilaEstadisticaVitalNacimientos> multiplicidad) { this.multiplicidad = multiplicidad; } public int getMunicipio() { return municipio; } public void setMunicipio(int municipio) { this.municipio = municipio; } public ArrayList<EstadisticaVital_defuncion> getArea_defuncion() { return area_defuncion; } public void setArea_defuncion(ArrayList<EstadisticaVital_defuncion> area_defuncion) { this.area_defuncion = area_defuncion; } public ArrayList<EstadisticaVital_defuncion> getTipo_defuncion() { return tipo_defuncion; } public void setTipo_defuncion(ArrayList<EstadisticaVital_defuncion> tipo_defuncion) { this.tipo_defuncion = tipo_defuncion; } public ArrayList<EstadisticaVital_defuncion> getDireccion_defuncion() { return direccion_defuncion; } public void setDireccion_defuncion(ArrayList<EstadisticaVital_defuncion> direccion_defuncion) { this.direccion_defuncion = direccion_defuncion; } public ArrayList<EstadisticaVital_defuncion> getMujeres() { return mujeres; } public void setMujeres(ArrayList<EstadisticaVital_defuncion> mujeres) { this.mujeres = mujeres; } public ArrayList<EstadisticaVital_defuncion> getTipo_profesional() { return tipo_profesional; } public void setTipo_profesional(ArrayList<EstadisticaVital_defuncion> tipo_profesional) { this.tipo_profesional = tipo_profesional; } public ArrayList<EstadisticaVital_defuncion> getEstado_defuncion() { return estado_defuncion; } public void setEstado_defuncion(ArrayList<EstadisticaVital_defuncion> estado_defuncion) { this.estado_defuncion = estado_defuncion; } }
// A u d i v e r i s // // This software is released under the terms of the GNU General Public // // to report bugs & suggestions. // /** * Class <code>Audiveris</code> is simply the entry point to OMR, which * delegates the call to {@link omr.Main#main}. * * @author Herv&eacute; Bitteur * @version $Id$ */ public final class Audiveris { // Audiveris // /** To avoid instantiation */ private Audiveris () { } // main // /** * The main entry point, which just calls {@link omr.Main#main} * * @param args These args are simply passed to Main */ public static void main (final String[] args) { omr.Main.main(args, Audiveris.class); } }
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.Scanner; import java.util.Set; public class Mainclass extends Thread { private static int run_times = 1; // Counts the times crawler has ran private static int layers = 1; // Default layers is 1 private static char answer; // If user desires or not to receive a result // email private static long timer; // store time private static String email; // User email private static String path; // Path of output private static int position = 1; private static String path2; // Root path of link folders private static String t1name; // thread 1 name private static String t2name; // thread 2 name private static String t3name; // thread 3 name private static String link1 = "https://github.com/milouk"; private static String link2 = "https://review.cyanogenmod.org/"; private static String link3 = "https: // thread 1 result list private static ArrayList<String> thread1_list = new ArrayList<String>(); private static Set<String> thread1_set = new LinkedHashSet<String>(); // thread 2 result list private static ArrayList<String> thread2_list = new ArrayList<String>(); private static Set<String> thread2_set = new LinkedHashSet<String>(); // thread 3 result list private static ArrayList<String> thread3_list = new ArrayList<String>(); private static Set<String> thread3_set = new LinkedHashSet<String>(); // Final Result List private static ArrayList<String> finalist = new ArrayList<String>(); private static Scanner input; private static Scanner inputpath; private static Scanner yorn; private static Scanner mail; public static void main(String[] args) { Mainclass thread = new Mainclass(); input = new Scanner(System.in); inputpath = new Scanner(System.in); yorn = new Scanner(System.in); mail = new Scanner(System.in); // Ask user to send an email when process finishes System.out.print("Would you like the results to be sent in an email? [Y/N] : "); answer = yorn.next().charAt(0); while (answer != 'Y' && answer != 'y' && answer != 'N' && answer != 'n') { System.out.printf("%s", "Please Enter a Valid Answer : "); answer = yorn.next().charAt(0); } // Acquire Users Email if (answer == 'y' || answer == 'Y') { System.out.printf("%s", "Enter a Valid Email : "); email = mail.nextLine(); } System.out.printf("%s", "Enter How Many Layers You Would Like The Crawler To Complete (Default is 1 Layer) : "); layers = input.nextInt(); // if user enters 0 for layers number, Program terminates if (layers != 0) { if (run_times == 1) { System.out.printf("%s", "Enter a Valid Path To Create All Html Files : "); path = inputpath.nextLine(); HtmlFiles.checkPath(path); } System.out.println("\n****************************************************"); System.out.println("*Crawler Will Update The Database Every 24 Hours...*"); System.out.println("****************************************************\n\n"); thread.start(); } else { if (answer == 'Y' || answer == 'y') { GetCredentials.emailCredentials( "C:\\Users\\Michalis\\Business\\DMST\\3rd Semester\\Programming II\\workplace\\Web Crawler\\src\\com\\complet\\EmailCredentials.txt"); EmailSending.email(email); } System.out.println("\n************"); System.out.println("* Finished *"); System.out.println("************\n\n"); } } @Override public final void run() { for (;;) { System.out.println("Running for " + run_times + " time!"); try { crawl(); } catch (Exception e) { } run_times++; try { // to be changed to 86400 * 1000 Thread.sleep(4000); } catch (InterruptedException e) { } } } public static void crawl() throws Exception { // Create & Start Threads RunClass.begin(); // Concatenate all lists to final list finalist.addAll(thread1_list); finalist.addAll(thread2_list); finalist.addAll(thread3_list); thread1_list.removeAll(thread1_list); thread2_list.removeAll(thread2_list); thread3_list.removeAll(thread3_list); /// REMOVING System.out.println(finalist.size()); RobotTags.remover(); System.out.println(finalist.size()); /// END OF REMOVING if (answer == 'Y' || answer == 'y') { GetCredentials.emailCredentials( "C:\\Users\\Michalis\\Business\\DMST\\3rd Semester\\Programming II\\workplace\\Web Crawler\\src\\com\\complet\\EmailCredentials.txt"); EmailSending.email(email); } System.out.println("Creating HTML Files in : " + path + " !..."); // Delete Old Files in order to replace them with new ones. if (Mainclass.getRun_times() > 1) { File dir = new File(path2); HtmlFiles.deleteDirectory(dir); dir.mkdir(); // GetCredentials.dbCredentials("db credentials.txt path"); // DatabaseConnection.deleteData("DatabaseOfURLs"); } for (int i = 0; i < finalist.size(); i++) { try { if (i == 0) { path = path2.concat("\\1-100"); File theDir = new File(path); theDir.mkdir(); } else if (i % 100 == 0) { path = path2.concat("\\") .concat(String.valueOf(i + 1).concat(" - ").concat(String.valueOf(i + 100))); File theDir = new File(path); theDir.mkdir(); } HtmlFiles.createFile(finalist.get(i), path, i + 1); Database.insertData(finalist.get(i), path); position++; try { Thread.sleep(800); } catch (InterruptedException e) { } } catch (IOException e) { System.err.println("IO Exception Handled"); } } // Empty Finalist for Next Run finalist.removeAll(finalist); System.out.println("\n************"); System.out.println("* Finished *"); System.out.println("************\n\n"); } public static int getRun_times() { return run_times; } public static int getLayers() { return layers; } public static ArrayList<String> getThread1_list() { return thread1_list; } public static Set<String> getThread1_set() { return thread1_set; } public static ArrayList<String> getThread2_list() { return thread2_list; } public static Set<String> getThread2_set() { return thread2_set; } public static ArrayList<String> getThread3_list() { return thread3_list; } public static Set<String> getThread3_set() { return thread3_set; } public static ArrayList<String> getFinalist() { return finalist; } public static void setPath(String path) { Mainclass.path = path; } public static String getT1name() { return t1name; } public static void setT1name(String t1name) { Mainclass.t1name = t1name; } public static String getT2name() { return t2name; } public static void setT2name(String t2name) { Mainclass.t2name = t2name; } public static String getT3name() { return t3name; } public static void setT3name(String t3name) { Mainclass.t3name = t3name; } public static String getLink1() { return link1; } public static String getLink2() { return link2; } public static Scanner getInputpath() { return inputpath; } public static String getLink3() { return link3; } public static long getTimer() { return timer; } public static int getPosition() { return position; } public static String getPath2() { return path2; } public static void setPath2(String path2) { Mainclass.path2 = path2; } public static String getPath() { return path; } }
import Misc.Constants; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.json.JSONException; import org.json.JSONObject; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Main extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Connection connection = getConnection(response); if (connection != null) { String path = request.getRequestURI(); String[] pathPieces = path.split("/"); if (pathPieces[1].equals("profile") && pathPieces.length == 3) getProfile.getProfile(request, response, connection, pathPieces[2]); else if (pathPieces[1].equals("suggestions") && pathPieces.length == 3) getSuggestions.getSuggestions(request, response, connection, pathPieces[2]); else response.setStatus(Constants.NOT_FOUND); connection.close(); } } catch (Exception e) { response.setStatus(Constants.INTERNAL_SERVER_ERROR); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get request body into string StringBuilder requestBody = new StringBuilder(); String line; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { requestBody.append(line); } } catch (IOException e) { response.setStatus(Constants.INTERNAL_SERVER_ERROR); response.getWriter().print(Constants.READ_BODY_FAIL); return; } // Get connection to DB Connection connection = getConnection(response); if (connection != null) { // Business logic try { JSONObject jsonObject = new JSONObject(requestBody.toString()); String path = request.getRequestURI(); String[] pathPieces = path.split("/"); if (pathPieces[1].equals("createAccount")) createAccount.createAccount(request, response, connection, jsonObject); else if (pathPieces[1].equals("login")) Login.login(request, response, connection, jsonObject); else if (pathPieces[1].equals("connections")) { if (pathPieces[2].equals("request")) sendConn.sendConn(request, response, connection, jsonObject); else if (pathPieces[2].equals("accept")) acceptConn.acceptConn(request, response, connection, jsonObject); else if (pathPieces[2].equals("reject")) rejectConn.rejectConn(request, response, connection, jsonObject); else response.setStatus(Constants.NOT_FOUND); } else response.setStatus(Constants.NOT_FOUND); //response.getWriter().print("POST!"); } catch (JSONException e) { response.setStatus(Constants.BAD_REQUEST); response.getWriter().print(Constants.BAD_BODY_MESSAGE); } finally { try { connection.close(); } catch (SQLException ignored) {} } } } public static String getStackTrace(Throwable aThrowable) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); aThrowable.printStackTrace(printWriter); return result.toString(); } private static Connection getConnection(HttpServletResponse response) throws IOException { try { URI dbUri = new URI(System.getenv("DATABASE_URL")); String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath(); return DriverManager.getConnection(dbUrl, username, password); } catch (URISyntaxException|SQLException e) { response.setStatus(Constants.INTERNAL_SERVER_ERROR); response.getWriter().print(Constants.DB_CONNECTION_FAIL); return null; } } public static void main(String[] args) throws Exception { Server server = new Server(Integer.valueOf(System.getenv("PORT"))); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context);
import org.apache.http.HttpEntity; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpResponseException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.BufferedReader; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.*; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.PasswordAuthentication; import java.net.URL; import java.nio.charset.Charset; import java.util.Map; public class Main extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { URL proximo = new URL(System.getenv("PROXIMO_URL")); String userInfo = proximo.getUserInfo(); String user = userInfo.substring(0, userInfo.indexOf(':')); String password = userInfo.substring(userInfo.indexOf(':') + 1); System.setProperty('socksProxyHost', proximo.getHost()); // System.setProperty('socksProxyPort', PROXIMO_PORT); Authenticator.setDefault(new ProxyAuthenticator(user, password)); String urlStr = "http://httpbin.org/ip"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet request = new HttpGet(urlStr); CloseableHttpResponse response = httpClient.execute(request); try { resp.getWriter().print("Hello from Java! " + handleResponse(response)); } catch (Exception e) { resp.getWriter().print(e.getMessage()); } } private static String handleResponse(CloseableHttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException( statusLine.getStatusCode(), statusLine.getReasonPhrase()); } if (entity == null) { throw new ClientProtocolException("Response contains no content"); } return readStream(entity.getContent()); } private static String readStream(InputStream is) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String output = ""; String tmp = reader.readLine(); while (tmp != null) { output += tmp; tmp = reader.readLine(); } return output; } private class ProxyAuthenticator extends Authenticator { private final PasswordAuthentication passwordAuthentication; private ProxyAuthenticator(String user, String password) { passwordAuthentication = new PasswordAuthentication(user, password.toCharArray()); } @Override protected PasswordAuthentication getPasswordAuthentication() { return passwordAuthentication; } } }
import java.util.Arrays; import java.util.HashMap; import java.util.ArrayList; import java.util.Map; import static spark.Spark.*; import spark.template.freemarker.FreeMarkerEngine; import spark.ModelAndView; import static spark.Spark.get; import spark.Request; import spark.Response; /** * Clase que contiene las ejecuciones principales del programa * @author Eduardo Arevalo Forero */ public class Main { /** * Metodo: Logica inicial y principal del programa * @param args */ public static void main(String[] args) { port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); get("/taller07", (Request request, Response response) -> { ArrayList<Double> EstimatedProxySize = new ArrayList<Double>(Arrays.asList(130.0,650.0,99.0,150.0,128.0,302.0,95.0,945.0,368.0,961.0)); ArrayList<Double> PlanAddedandModifiedSize = new ArrayList<Double>(Arrays.asList(163.0,765.0,141.0,166.0,137.0, 355.0, 136.0, 1206.0, 433.0,1130.0)); ArrayList<Double> ActualAddedandModifiedSize = new ArrayList<Double>(Arrays.asList(186.0,699.0,132.0,272.0,291.0,331.0,199.0,1890.0,788.0,1601.0)); ArrayList<Double> ActualDevelopmentHours = new ArrayList<Double>(Arrays.asList(15.0,69.9,6.5,22.4,28.4,65.9,19.4,198.7,38.8,138.2)); ArrayList<Double> xArrayList = new ArrayList<Double>(EstimatedProxySize); ArrayList<Double> yArrayList = new ArrayList<Double>(ActualAddedandModifiedSize); String resultadoTest1= Estadistica.calculoPrograma7(EstimatedProxySize,ActualAddedandModifiedSize, 386); String resultadoTest2= Estadistica.calculoPrograma7(EstimatedProxySize,ActualDevelopmentHours, 386); //String resultadoTest3= Estadistica.calculoPrograma7(EstimatedProxySize,ActualAddedandModifiedSize); //String resultadoTest4= Estadistica.calculoPrograma7(EstimatedProxySize,ActualDevelopmentHours); Map<String, Object> atributes = new HashMap<>(); atributes.put("test1", resultadoTest1); atributes.put("test2", resultadoTest2); //atributes.put("test3", resultadoTest3); //atributes.put("test4", resultadoTest4); return new ModelAndView(atributes, "taller07.ftl"); }, new FreeMarkerEngine()); get("/hello", (req, res) -> "Hello World"); } }
import java.sql.*; import java.util.HashMap; import java.util.ArrayList; import java.util.Map; import org.json.JSONObject; import java.net.URI; import java.net.URISyntaxException; import static spark.Spark.*; import spark.template.freemarker.FreeMarkerEngine; import spark.ModelAndView; import static spark.Spark.get; import com.google.gson.Gson; import com.heroku.sdk.jdbc.DatabaseUrl; import spark.Request; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class Main { public static void main(String[] args) { port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); Gson gson = new Gson(); //get json new StockController(new StockService()); //Using freemarker template get("/users", (req, res) -> { ArrayList<String> users = new ArrayList<String>(); users.add("belowtenthousand"); users.add("abovetenthousand"); Map<String, Object> attributes = new HashMap<>(); attributes.put("users", users); attributes.put("message", "The more you invest ,the less you pay for fees."); return new ModelAndView(attributes, "users.ftl"); }, new FreeMarkerEngine()); //get xml get("/about", (req, res) -> { Connection connection = null; // res.type("application/xml"); //Return as XML Map<String, Object> attributes = new HashMap<>(); try { String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<About>"; xml += "<Branch>"; xml += "<FirstName>Jacob</FirstName>"; xml += "<LastName>McCarthy</LastName>"; xml += "<Street>35_Highland_Road</Street>"; xml += "<Country>United States</Country>"; xml += "<State>Pennsylvania</State>"; xml += "<City>Pittsburgh</City>"; xml += "<Status>Full-time</Status>"; xml += "<Phone>412-961-2098</Phone>"; xml += "<Email>VSS9@pitt.edu</Email>"; xml += "</Branch>"; xml += "</About>"; res.type("text/xml"); return xml; } catch (Exception e) { attributes.put("message", "There was an error: " + e); return attributes; } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }); //get json get("/api/register/:firstname", (req, res) -> { Map<String, Object> data = new HashMap<>(); String firstname=req.params("firstname"); // String lastname = req.params("lastname"); // String username=req.queryParams("username"); // String password = req.queryParams("password"); // String confpassword=req.queryParams("confpassword"); // String email = req.queryParams("email"); data.put("firstname", firstname); // data.put("lastname", lastname); // data.put("username", username); // data.put("password", password); // data.put("confpassword", confpassword); // data.put("email", email); return data; }, gson::toJson); post("/api/about", (req, res) -> { Map<String, Object> data = new HashMap<>(); data.put("content1", "Grow your savings to cover 3 to 6 months of unplanned expenses in a conservatively invested portfolio.40%stocks and 60%bonds"); data.put("content2", "Invest long-term with a target of $1,827,000 for an annual retirement income of $89,037. This can be a regular investment account, or an IRA account.90%stocks and 10%bonds"); data.put("content3", "Grow and preserve capital over time. This is an excellent goal type for unknown future needs or money you plan to pass to future generations.80%stocks and 20%bonds"); return data; }, gson::toJson); // //POST JSON // post("api/register", (req, res) -> { // Connection connection = null; // //Testing // System.out.println(req.body()); // try { // connection = DatabaseUrl.extract().getConnection(); // JSONObject obj = new JSONObject(req.body()); // String username = obj.getString("username"); // String password = obj.getString("password"); // String email = obj.getString("email"); // String fname = obj.getString("fname"); // String lname = obj.getString("lname"); // String sql = "INSERT INTO users VALUES ('"+ username + "','" + password + "','" + email + "','" + fname + "','"+ lname + "')"; // connection = DatabaseUrl.extract().getConnection(); // Statement stmt = connection.createStatement(); // stmt.executeUpdate(sql); // ResultSet rs = stmt.executeQuery("SELECT * FROM users where username ='" + username + "'"); // Map<String, Object> currentuser = new HashMap<>(); // currentuser.put("username", rs.getString("username")); // currentuser.put("email", rs.getString("email")); // return currentuser; // // return req.body(); // } catch (Exception e) { // return e.getMessage(); // } finally { // if (connection != null) try{connection.close();} catch(SQLException e){} // //get("/hello", (req, res) -> "Hello World"); // /* get("/", (request, response) -> { // Map<String, Object> attributes = new HashMap<>(); // attributes.put("message", "Hello World!"); // return new ModelAndView(attributes, "index.ftl"); // }, new FreeMarkerEngine()); // */ // get("/db", (req, res) -> { // Connection connection = null; // Map<String, Object> attributes = new HashMap<>(); // try { // connection = DatabaseUrl.extract().getConnection(); // Statement stmt = connection.createStatement(); // stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); // stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); // ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); // ArrayList<String> output = new ArrayList<String>(); // while (rs.next()) { // output.add( "Read from DB: " + rs.getTimestamp("tick")); // attributes.put("results", output); // return new ModelAndView(attributes, "db.ftl"); // } catch (Exception e) { // attributes.put("message", "There was an error: " + e); // return new ModelAndView(attributes, "error.ftl"); // } finally { // if (connection != null) try{connection.close();} catch(SQLException e){} // }, new FreeMarkerEngine()); // // POST JSON // post("api/register", (req, res) -> { // Connection connection = null; // //Testing // System.out.println(req.body()); // try { // connection = DatabaseUrl.extract().getConnection(); // JSONObject obj = new JSONObject(req.body()); // String username= obj.getString("username"); // String password = obj.getString("password"); // String email = obj.getString("email"); // String fname = obj.getString("fname"); // String lname = obj.getString("lname"); // String gender = obj.getString("gender"); // String language = obj.getString("language"); // String planguage = obj.getString("planguage"); // String topic = obj.getString("topic"); // String sql = "INSERT INTO users (username,password) VALUES ('"+ username + "','" + password + "')"; // connection = DatabaseUrl.extract().getConnection(); // Statement stmt = connection.createStatement(); // stmt.executeUpdate(sql); // ResultSet rs = stmt.executeQuery("SELECT * FROM users where username ='" + username + "'"); // Map<String, Object> currentuser = new HashMap<>(); // currentuser.put("username", rs.getString("username")); // // // currentuser.put("email", rs.getString("email")); // return currentuser; // //return req.body(); // } catch (Exception e) { // return e.getMessage(); // } finally { // if (connection != null) try{connection.close();} catch(SQLException e){} get("/db", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { output.add( "Read from DB: " + rs.getTimestamp("tick")); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }, new FreeMarkerEngine()); // get("/api/home", (req, res) -> { // Map<String, Object> data = new HashMap<>(); // data.put("title", "Professor"); // data.put("name", "Brian"); // data.put("description", "INFSCI 2560"); // data.put("profession", "Education"); // return data; // }, gson::toJson); // get("/api/time/now", (req, res) -> { // Map<String, Object> data = new HashMap<>(); // data.put("currentTime", new Date()); // return data; // }, gson::toJson); /* get("/api/time/now.xml", (req, res) -> { Map<String, Object> data = new HashMap<>(); data.put("currentTime", new Date()); return data; }, gson::toJson); */ } }
package com.ffbit.bencode; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.HashMap; import static java.util.Arrays.asList; import static java.util.Collections.singletonMap; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class BDecoderTest { private BDecoder decoder; @Before public void setUp() throws Exception { decoder = new BDecoder(); } @Test public void itShouldDecodeStringAndInteger() throws Exception { assertThat(decoder.decode("3:fooi42e"), is(asList((Object) "foo", 42))); } @Test public void itShouldDecodeListOfStringAndIntegerOld() throws Exception { assertThat(decoder.decode("l3:fooi42ee"), is(asList((Object) asList("foo", 42)))); } @Test public void itShouldParseListOfIntegers() throws Exception { InputStream in = new ByteArrayInputStream("li1ei2ee".getBytes()); decoder = new BDecoder(in); assertThat(decoder.decode(), is((Object) asList(1, 2))); } @Test public void itShouldDecodeListOfStringAndInteger() throws Exception { InputStream in = new ByteArrayInputStream("li1e1:ae".getBytes()); decoder = new BDecoder(in); assertThat(decoder.decode(), is((Object) asList(1, "a"))); } @Test public void itShouldDecodeListOfStringAndIntegerAndNestedList() throws Exception { InputStream in = new ByteArrayInputStream("li1e1:ali2eee".getBytes()); decoder = new BDecoder(in); assertThat(decoder.decode(), is((Object) asList(1, "a", asList(2)))); } @Test public void itShouldDecodeDictionaryOfSingleIntegerValue() throws Exception { InputStream in = new ByteArrayInputStream("d1:ai1ee".getBytes()); decoder = new BDecoder(in); assertThat(decoder.decode(), is((Object) singletonMap("a", 1))); } @Test public void itShouldDecodeDictionaryOfMultipleIntegerValues() throws Exception { InputStream in = new ByteArrayInputStream("d1:ai2e3:fooi42ee".getBytes()); decoder = new BDecoder(in); HashMap<String, Object> expected = new HashMap<String, Object>() {{ put("a", 2); put("foo", 42); }}; assertThat(decoder.decode(), is((Object) expected)); } @Test public void itShouldDecodeDictionaryOfMultipleIntegerValuesAndNestedList() throws Exception { InputStream in = new ByteArrayInputStream("d1:ai2e3:fooi42e1:lli1eee".getBytes()); decoder = new BDecoder(in); HashMap<String, Object> expected = new HashMap<String, Object>() {{ put("a", 2); put("foo", 42); put("l", asList(1)); }}; assertThat(decoder.decode(), is((Object) expected)); } }
package com.jcabi.github; import javax.json.Json; import org.apache.commons.lang3.RandomStringUtils; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Assume; import org.junit.Test; /** * Test case for {@link RtForks}. * * @author Carlos Miranda (miranda.cma@gmail.com) * @version $Id$ */ public class RtForksITCase { /** * RtForks should be able to iterate its forks. * * @throws Exception if a problem occurs. */ @Test public final void retrievesForks() throws Exception { final String organization = System.getProperty( "failsafe.github.organization" ); Assume.assumeThat(organization, Matchers.notNullValue()); final Repo repo = RtForksITCase.repos().create( Json.createObjectBuilder().add( // @checkstyle MagicNumber (1 line) "name", RandomStringUtils.randomNumeric(5) ).build() ); try { final Fork fork = repo.forks().create(organization); MatcherAssert.assertThat(fork, Matchers.notNullValue()); final Iterable<Fork> forks = repo.forks().iterate("newest"); MatcherAssert.assertThat(forks, Matchers.notNullValue()); MatcherAssert.assertThat( forks, Matchers.not(Matchers.emptyIterable()) ); MatcherAssert.assertThat( forks, Matchers.contains(fork) ); } finally { RtForksITCase.repos().remove(repo.coordinates()); } } /** * Returns github repos. * @return Github repos. */ private static Repos repos() { final String key = System.getProperty("failsafe.github.key"); Assume.assumeThat(key, Matchers.notNullValue()); return new RtGithub(key).repos(); } }
package com.jcabi.github; import com.jcabi.log.Logger; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Assume; import org.junit.Test; /** * Integration case for {@link Issue}. * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @checkstyle ClassDataAbstractionCoupling (500 lines) */ public final class RtIssueITCase { /** * RtIssue can talk in github. * @throws Exception If some problem inside */ @Test public void talksInGithubProject() throws Exception { final Issue issue = RtIssueITCase.issue(); final Comment comment = issue.comments().post("hey, works?"); MatcherAssert.assertThat( new Comment.Smart(comment).body(), Matchers.startsWith("hey, ") ); MatcherAssert.assertThat( issue.comments().iterate(), Matchers.<Comment>iterableWithSize(1) ); final User.Smart author = new User.Smart( new Comment.Smart(comment) .author() ); final User.Smart self = new User.Smart( issue.repo().github().users().self() ); if (author.hasName() && self.hasName()) { MatcherAssert.assertThat( author.name(), Matchers.equalTo( self.name() ) ); } comment.remove(); } /** * RtIssue can change title and body. * @throws Exception If some problem inside */ @Test public void changesTitleAndBody() throws Exception { final Issue issue = RtIssueITCase.issue(); new Issue.Smart(issue).title("test one more time"); MatcherAssert.assertThat( new Issue.Smart(issue).title(), Matchers.startsWith("test o") ); new Issue.Smart(issue).body("some new body of the issue"); MatcherAssert.assertThat( new Issue.Smart(issue).body(), Matchers.startsWith("some new ") ); } /** * RtIssue can change issue state. * @throws Exception If some problem inside */ @Test public void changesIssueState() throws Exception { final Issue issue = RtIssueITCase.issue(); new Issue.Smart(issue).close(); MatcherAssert.assertThat( new Issue.Smart(issue).isOpen(), Matchers.is(false) ); new Issue.Smart(issue).open(); MatcherAssert.assertThat( new Issue.Smart(issue).isOpen(), Matchers.is(true) ); } @Test public void identifyAssignee() throws Exception { final Issue issue = RtIssueITCase.issue(); final String login = issue.repo().github().users().self().login(); try { new Issue.Smart(issue).assign(login); } catch (final AssertionError error) { Logger.warn(this, "Test failed with error: %s", error.getMessage()); Assume.assumeFalse( "Something wrong with your test account. Read test's java-doc.", true ); } final User assignee = new Issue.Smart(issue).assignee(); MatcherAssert.assertThat( assignee.login(), Matchers.equalTo(login) ); } /** * RtIssue can check whether it is a pull request. * @throws Exception If some problem inside */ @Test public void checksForPullRequest() throws Exception { final Issue issue = RtIssueITCase.issue(); MatcherAssert.assertThat( new Issue.Smart(issue).isPull(), Matchers.is(false) ); } /** * GhIssue can list issue events. * @throws Exception If some problem inside */ @Test public void listsIssueEvents() throws Exception { final Issue issue = RtIssueITCase.issue(); new Issue.Smart(issue).close(); MatcherAssert.assertThat( new Event.Smart(issue.events().iterator().next()).type(), Matchers.equalTo(Event.CLOSED) ); } /** * Issue.Smart can find the latest event. * @throws Exception If some problem inside */ @Test public void findsLatestEvent() throws Exception { final Issue.Smart issue = new Issue.Smart(RtIssueITCase.issue()); issue.close(); MatcherAssert.assertThat( new Event.Smart( new Issue.Smart(issue).latestEvent(Event.CLOSED) ).author().login(), Matchers.equalTo(issue.author().login()) ); } /** * Create and return issue to test. * @return Issue * @throws Exception If some problem inside */ private static Issue issue() throws Exception { final String key = System.getProperty("failsafe.github.key"); Assume.assumeThat(key, Matchers.notNullValue()); return new RtGithub(key).repos().get( new Coordinates.Simple(System.getProperty("failsafe.github.repo")) ).issues().create("test issue title", "test issue body"); } }
package com.thindeck.dynamo; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.jcabi.dynamo.Attributes; import com.jcabi.dynamo.Item; import com.jcabi.dynamo.Region; import com.jcabi.dynamo.Table; import com.jcabi.dynamo.mock.H2Data; import com.jcabi.dynamo.mock.MkRegion; import com.jcabi.urn.URN; import com.thindeck.api.Repo; import java.io.IOException; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; import org.mockito.Mockito; /** * Tests for {@link DyUser}. * * @author Krzysztof Krason (Krzysztof.Krason@gmail.com) * @version $Id$ */ public final class DyUserTest { /** * DyUser can return URN from dynamo. */ @Test public void returnsUrnFromDynamo() { final URN urn = URN.create("urn:foo:3"); final Item item = Mockito.mock(Item.class); final AttributeValue value = Mockito.mock(AttributeValue.class); Mockito.when(value.getS()).thenReturn(urn.toString()); try { Mockito.when(item.get(DyUser.ATTR_URN)).thenReturn(value); } catch (final IOException ex) { throw new IllegalStateException(ex); } MatcherAssert.assertThat( new DyUser(item).urn(), Matchers.equalTo(urn) ); } /** * DyUser can obtain associated repos. * @throws Exception If something goes wrong. */ @Test public void canGetRepos() throws Exception { final Region region = new MkRegion( new H2Data().with( DyRepo.TBL, new String[] {DyRepo.ATTR_NAME}, new String[] {DyRepo.ATTR_UPDATED} ) ); final Table table = region.table(DyRepo.TBL); table.put( new Attributes() .with(DyRepo.ATTR_NAME, "test-repo") .with(DyRepo.ATTR_UPDATED, System.currentTimeMillis()) ); MatcherAssert.assertThat( new DyUser(table.frame().iterator().next()).repos().iterate(), Matchers.<Repo>iterableWithSize(1) ); } }
package greed.template; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import greed.conf.ConfigException; import greed.model.Language; import greed.util.Utils; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.HashMap; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class CppTemplateTest { private InputStream codeTemplate; private InputStream testTemplate; Map<String, Object> model = TestModelFixtures.buildStubbingModel(); @BeforeClass public static void initializeGreed() throws ConfigException { // TODO : Why at all do we need this? Utils.initialize(); } @Before public void setupTemplates() throws IOException { this.codeTemplate = getClass().getResourceAsStream("/templates/source/cpp.tmpl"); assertThat(this.codeTemplate, notNullValue()); this.testTemplate = getClass().getResourceAsStream("/templates/test/cpp.tmpl"); assertThat(this.testTemplate, notNullValue()); TemplateEngine.switchLanguage(Language.CPP); } @Test public void renderCppCode() { String test = TemplateEngine.render(testTemplate, model); model.put("TestCode", test); String code = TemplateEngine.render(codeTemplate, model); System.out.println(code); // TODO verify to make test fail on malfunctioning } @Test public void renderCppCode_cxx11() { Map<String,String> mp = new HashMap<String,String>(); mp.put("Cpp11", "true"); model.put("Options", mp); String test = TemplateEngine.render(testTemplate, model); model.put("TestCode", test); String code = TemplateEngine.render(codeTemplate, model); System.out.println(code); // TODO verify to make test fail on malfunctioning } }
package mho.qbar.objects; import mho.wheels.iterables.ExhaustiveProvider; import mho.wheels.iterables.IterableUtils; import mho.wheels.iterables.RandomProvider; import mho.wheels.ordering.Ordering; import mho.wheels.structures.Pair; import mho.wheels.structures.Triple; import mho.qbar.iterableProviders.QBarExhaustiveProvider; import mho.qbar.iterableProviders.QBarIterableProvider; import mho.qbar.iterableProviders.QBarRandomProvider; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.List; import java.util.Random; import static mho.wheels.iterables.IterableUtils.*; import static mho.qbar.objects.Rational.*; import static mho.wheels.misc.Readers.findBigDecimalIn; public class RationalDemos { private static final boolean USE_RANDOM = false; private static final String RATIONAL_CHARS = "-/0123456789"; private static final int SMALL_LIMIT = 1000; private static final int TINY_LIMIT = 100; private static int LIMIT; private static QBarIterableProvider P; private static void initialize() { if (USE_RANDOM) { P = new QBarRandomProvider(new Random(0x6af477d9a7e54fcaL)); LIMIT = 1000; } else { P = QBarExhaustiveProvider.INSTANCE; LIMIT = 10000; } } public static void demoGetNumerator() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println("getNumerator(" + r + ") = " + r.getNumerator()); } } public static void demoGetDenominator() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println("getDenominator(" + r + ") = " + r.getDenominator()); } } public static void demoOf_BigInteger_BigInteger() { initialize(); Iterable<Pair<BigInteger, BigInteger>> ps = filter( p -> { assert p.b != null; return !p.b.equals(BigInteger.ZERO); }, P.pairs(P.bigIntegers()) ); for (Pair<BigInteger, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; System.out.println("of(" + p.a + ", " + p.b + ") = " + of(p.a, p.b)); } } public static void demoOf_long_long() { initialize(); Iterable<Pair<Long, Long>> ps = filter(p -> p.b != 0, P.pairs(P.longs())); for (Pair<Long, Long> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; System.out.println("of(" + p.a + ", " + p.b + ") = " + of(p.a, p.b)); } } public static void demoOf_int_int() { initialize(); Iterable<Pair<Integer, Integer>> ps = filter(p -> p.b != 0, P.pairs(P.integers())); for (Pair<Integer, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; System.out.println("of(" + p.a + ", " + p.b + ") = " + of(p.a, p.b)); } } public static void demoOf_BigInteger() { initialize(); for (BigInteger i : take(LIMIT, P.bigIntegers())) { System.out.println("of(" + i + ") = " + of(i)); } } public static void demoOf_long() { initialize(); for (long l : take(LIMIT, P.longs())) { System.out.println("of(" + l + ") = " + of(l)); } } public static void demoOf_int() { initialize(); for (int i : take(LIMIT, P.integers())) { System.out.println("of(" + i + ") = " + of(i)); } } public static void demoOf_float() { initialize(); for (float f : take(LIMIT, P.floats())) { System.out.println("of(" + f + ") = " + of(f)); } } public static void demoOf_double() { initialize(); for (double d : take(LIMIT, P.doubles())) { System.out.println("of(" + d + ") = " + of(d)); } } public static void demoOfExact_float() { initialize(); for (float f : take(LIMIT, P.floats())) { System.out.println("ofExact(" + f + ") = " + ofExact(f)); } } public static void demoOfExact_double() { initialize(); for (double d : take(LIMIT, P.doubles())) { System.out.println("ofExact(" + d + ") = " + ofExact(d)); } } public static void demoOf_BigDecimal() { initialize(); for (BigDecimal bd : take(LIMIT, P.bigDecimals())) { System.out.println("of(" + bd + ") = " + of(bd)); } } public static void demoIsInteger() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println(r + " is " + (r.isInteger() ? "" : "not ") + "an integer"); } } public static void demoBigIntegerValue_RoundingMode() { initialize(); Iterable<Pair<Rational, RoundingMode>> ps = filter( p -> { assert p.a != null; return p.b != RoundingMode.UNNECESSARY || p.a.isInteger(); }, P.pairs(P.rationals(), P.roundingModes()) ); for (Pair<Rational, RoundingMode> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; System.out.println("bigIntegerValue(" + p.a + ", " + p.b + ") = " + p.a.bigIntegerValue(p.b)); } } public static void demoBigIntegerValue() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println("bigIntegerValue(" + r + ") = " + r.bigIntegerValue()); } } public static void demoBigIntegerValueExact() { initialize(); for (Rational r : take(LIMIT, map(Rational::of, P.bigIntegers()))) { System.out.println("bigIntegerValueExact(" + r + ") = " + r.bigIntegerValueExact()); } } public static void demoByteValueExact() { initialize(); for (Rational r : take(LIMIT, map(Rational::of, P.bytes()))) { System.out.println("byteValueExact(" + r + ") = " + r.byteValueExact()); } } public static void demoShortValueExact() { initialize(); for (Rational r : take(LIMIT, map(Rational::of, P.shorts()))) { System.out.println("shortValueExact(" + r + ") = " + r.shortValueExact()); } } public static void demoIntValueExact() { initialize(); for (Rational r : take(LIMIT, map(Rational::of, P.integers()))) { System.out.println("intValueExact(" + r + ") = " + r.intValueExact()); } } public static void demoLongValueExact() { initialize(); for (Rational r : take(LIMIT, map(Rational::of, P.longs()))) { System.out.println("longValueExact(" + r + ") = " + r.longValueExact()); } } public static void demoHasTerminatingDecimalExpansion() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println(r + (r.hasTerminatingDecimalExpansion() ? " has " : " does not have ") + "a terminating decimal expansion"); } } public static void demoBigDecimalValue_int_RoundingMode() { initialize(); Iterable<Pair<Rational, Pair<Integer, RoundingMode>>> ps; if (P instanceof ExhaustiveProvider) { ps = P.pairs( P.rationals(), (Iterable<Pair<Integer, RoundingMode>>) P.pairs(P.naturalIntegers(), P.roundingModes()) ); } else { ps = P.pairs( P.rationals(), (Iterable<Pair<Integer, RoundingMode>>) P.pairs( ((RandomProvider) P).naturalIntegersGeometric(20), P.roundingModes() ) ); } ps = filter( p -> { try { assert p.a != null; assert p.b != null; assert p.b.a != null; assert p.b.b != null; p.a.bigDecimalValue(p.b.a, p.b.b); return true; } catch (ArithmeticException e) { return false; } }, ps ); for (Pair<Rational, Pair<Integer, RoundingMode>> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; assert p.b.a != null; assert p.b.b != null; System.out.println("bigDecimalValue(" + p.a + ", " + p.b.a + ", " + p.b.b + ") = " + p.a.bigDecimalValue(p.b.a, p.b.b)); } } public static void demoBigDecimalValue_int() { initialize(); Iterable<Pair<Rational, Integer>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.rationals(), P.naturalIntegers()); } else { ps = P.pairs(P.rationals(), ((RandomProvider) P).naturalIntegersGeometric(20)); } ps = filter( p -> { try { assert p.a != null; assert p.b != null; p.a.bigDecimalValue(p.b); return true; } catch (ArithmeticException e) { return false; } }, ps ); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; System.out.println("bigDecimalValue(" + p.a + ", " + p.b + ") = " + p.a.bigDecimalValue(p.b)); } } public static void demoBigDecimalValueExact() { initialize(); Iterable<Rational> rs = filter(Rational::hasTerminatingDecimalExpansion, P.rationals()); for (Rational r : take(LIMIT, rs)) { System.out.println("bigDecimalValueExact(" + r + ") = " + r.bigDecimalValueExact()); } } public static void demoBinaryExponent() { initialize(); for (Rational r : take(LIMIT, P.positiveRationals())) { System.out.println("binaryExponent(" + r + ") = " + r.binaryExponent()); } } public static void demoFloatValue_RoundingMode() { initialize(); Iterable<Pair<Rational, RoundingMode>> ps = filter( p -> { assert p.a != null; return p.b != RoundingMode.UNNECESSARY || ofExact(p.a.floatValue(RoundingMode.FLOOR)).equals(p.a); }, P.pairs(P.rationals(), P.roundingModes()) ); for (Pair<Rational, RoundingMode> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; System.out.println("floatValue(" + p.a + ", " + p.b + ") = " + p.a.floatValue(p.b)); } } public static void demoFloatValue() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println("floatValue(" + r + ") = " + r.floatValue()); } } public static void demoFloatValueExact() { initialize(); Iterable<Rational> rs = map( Rational::ofExact, filter(f -> !Float.isNaN(f) && Float.isFinite(f) && !f.equals(-0.0f), P.floats()) ); for (Rational r : take(LIMIT, rs)) { System.out.println("floatValueExact(" + r + ") = " + r.floatValueExact()); } } public static void demoDoubleValue_RoundingMode() { initialize(); Iterable<Pair<Rational, RoundingMode>> ps = filter( p -> { assert p.a != null; return p.b != RoundingMode.UNNECESSARY || ofExact(p.a.floatValue(RoundingMode.FLOOR)).equals(p.a); }, P.pairs(P.rationals(), P.roundingModes())); for (Pair<Rational, RoundingMode> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; System.out.println("doubleValue(" + p.a + ", " + p.b + ") = " + p.a.doubleValue(p.b)); } } public static void demoDoubleValue() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println("doubleValue(" + r + ") = " + r.doubleValue()); } } public static void demoDoubleValueExact() { initialize(); Iterable<Rational> rs = map( Rational::ofExact, filter(d -> !Double.isNaN(d) && Double.isFinite(d) && !d.equals(-0.0), P.doubles()) ); for (Rational r : take(LIMIT, rs)) { System.out.println("doubleValueExact(" + r + ") = " + r.doubleValueExact()); } } public static void demoNegate() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println("-(" + r + ") = " + r.negate()); } } public static void demoInvert() { initialize(); for (Rational r : take(LIMIT, filter(s -> s != ZERO, P.rationals()))) { System.out.println("1/(" + r + ") = " + r.invert()); } } public static void demoAbs() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println("|" + r + "| = " + r.abs()); } } public static void demoSignum() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println("sgn(" + r + ") = " + r.signum()); } } public static void demoAdd() { initialize(); for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { assert p.a != null; assert p.b != null; System.out.println(p.a + " + " + p.b + " = " + p.a.add(p.b)); } } public static void demoSubtract() { initialize(); for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { assert p.a != null; assert p.b != null; System.out.println(p.a + " - " + p.b + " = " + p.a.subtract(p.b)); } } public static void demoMultiply_Rational() { initialize(); for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { assert p.a != null; assert p.b != null; System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b)); } } public static void demoMultiply_BigInteger() { initialize(); for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(P.rationals(), P.bigIntegers()))) { assert p.a != null; assert p.b != null; System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b)); } } public static void demoMultiply_int() { initialize(); for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), P.integers()))) { assert p.a != null; assert p.b != null; System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b)); } } public static void demoDivide_Rational() { initialize(); Iterable<Pair<Rational, Rational>> ps = filter(p -> p.b != ZERO, P.pairs(P.rationals())); for (Pair<Rational, Rational> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b)); } } public static void demoDivide_BigInteger() { initialize(); Iterable<Pair<Rational, BigInteger>> ps = P.pairs( P.rationals(), filter(bi -> !bi.equals(BigInteger.ZERO), P.bigIntegers()) ); for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b)); } } public static void demoDivide_int() { initialize(); for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), filter(i -> i != 0, P.integers())))) { assert p.a != null; assert p.b != null; System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b)); } } public static void demoSum() { initialize(); for (List<Rational> rs : take(LIMIT, P.lists(P.rationals()))) { String listString = tail(init(rs.toString())); System.out.println("Σ(" + listString + ") = " + sum(rs)); } } public static void demoProduct() { initialize(); for (List<Rational> rs : take(LIMIT, P.lists(P.rationals()))) { String listString = tail(init(rs.toString())); System.out.println("Π(" + listString + ") = " + product(rs)); } } public static void demoDelta() { initialize(); for (List<Rational> rs : take(LIMIT, filter(xs -> !xs.isEmpty(), P.lists(P.rationals())))) { String listString = tail(init(rs.toString())); System.out.println("Δ(" + listString + ") = " + IterableUtils.toString(20, delta(rs))); } } public static void demoHarmonicNumber() { initialize(); Iterable<Integer> is; if (P instanceof ExhaustiveProvider) { is = P.positiveIntegers(); } else { is = ((RandomProvider) P).positiveIntegersGeometric(100); } for (int i : take(SMALL_LIMIT, is)) { System.out.println("H_" + i + " = " + harmonicNumber(i)); } } public static void demoPow() { initialize(); Iterable<Integer> exps; if (P instanceof ExhaustiveProvider) { exps = P.integers(); } else { exps = ((RandomProvider) P).integersGeometric(50); } Iterable<Pair<Rational, Integer>> ps = filter(p -> p.b >= 0 || p.a != ZERO, P.pairs(P.rationals(), exps)); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; System.out.println(p.a + " ^ " + p.b + " = " + p.a.pow(p.b)); } } public static void demoFloor() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println("floor(" + r + ") = " + r.floor()); } } public static void demoCeiling() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println("ceil(" + r + ") = " + r.ceiling()); } } public static void demoFractionalPart() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println("fractionalPart(" + r + ") = " + r.fractionalPart()); } } public static void demoRoundToDenominator() { initialize(); Iterable<Triple<Rational, BigInteger, RoundingMode>> ts = filter( p -> { assert p.a != null; assert p.b != null; return p.c != RoundingMode.UNNECESSARY || p.b.mod(p.a.getDenominator()).equals(BigInteger.ZERO); }, P.triples(P.rationals(), P.positiveBigIntegers(), P.roundingModes()) ); for (Triple<Rational, BigInteger, RoundingMode> t : take(LIMIT, ts)) { assert t.a != null; assert t.b != null; assert t.c != null; System.out.println("roundToDenominator(" + t.a + ", " + t.b + ", " + t.c + ") = " + t.a.roundToDenominator(t.b, t.c)); } } public static void demoShiftLeft() { initialize(); Iterable<Integer> is; if (P instanceof QBarExhaustiveProvider) { is = P.integers(); } else { is = ((QBarRandomProvider) P).integersGeometric(50); } for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), is))) { assert p.a != null; assert p.b != null; System.out.println(p.a + " << " + p.b + " = " + p.a.shiftLeft(p.b)); } } public static void demoShiftRight() { initialize(); Iterable<Integer> is; if (P instanceof QBarExhaustiveProvider) { is = P.integers(); } else { is = ((QBarRandomProvider) P).integersGeometric(50); } for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), is))) { assert p.a != null; assert p.b != null; System.out.println(p.a + " >> " + p.b + " = " + p.a.shiftRight(p.b)); } } public static void demoContinuedFraction() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println("continuedFraction(" + r + ") = " + r.continuedFraction()); } } public static void demoFromContinuedFraction() { initialize(); Iterable<List<BigInteger>> iss = map( p -> { assert p.b != null; return toList(cons(p.a, p.b)); }, (Iterable<Pair<BigInteger, List<BigInteger>>>) P.pairs( P.bigIntegers(), P.lists(P.positiveBigIntegers()) ) ); for (List<BigInteger> is : take(LIMIT, iss)) { String listString = tail(init(is.toString())); System.out.println("fromContinuedFraction(" + listString + ") = " + fromContinuedFraction(is)); } } public static void demoConvergents() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println("convergents(" + r + ") = " + toList(r.convergents())); } } public static void demoPositionalNotation() { initialize(); Iterable<Pair<Rational, BigInteger>> ps; if (P instanceof ExhaustiveProvider) { ps = ((ExhaustiveProvider) P).pairsSquareRootOrder( cons(ZERO, P.positiveRationals()), P.rangeUp(BigInteger.valueOf(2)) ); } else { ps = P.pairs( cons(ZERO, ((QBarRandomProvider) P).positiveRationals(8)), map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20)) ); } for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) { assert p.a != null; assert p.b != null; System.out.println("positionalNotation(" + p.a + ", " + p.b + ") = " + p.a.positionalNotation(p.b)); } } public static void demoFromPositionalNotation() { initialize(); Iterable<Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>>> ps = P.dependentPairs( P.rangeUp(BigInteger.valueOf(2)), b -> filter( t -> !t.c.isEmpty(), P.triples(P.lists(P.range(BigInteger.ZERO, b.subtract(BigInteger.ONE)))) ) ); int limit = P instanceof ExhaustiveProvider ? LIMIT : TINY_LIMIT; for (Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>> p : take(limit, ps)) { assert p.a != null; assert p.b != null; assert p.b.a != null; assert p.b.b != null; assert p.b.c != null; System.out.println("fromPositionalNotation(" + p.a + ", " + p.b.a + ", " + p.b.b + ", " + p.b.c + ") = " + fromPositionalNotation(p.a, p.b.a, p.b.b, p.b.c)); } } // public static void digitsDemo() { // Generator<BigInteger> big = new FilteredGenerator<>( // POSITIVE_BIG_INTEGERS, // bi -> bi.compareTo(BigInteger.ONE) > 0 // Generator<Pair<Rational, BigInteger>> g = new SubExponentialPairGenerator<>(Rational.nonnegativeRationals(), big); // for (Pair<Rational, BigInteger> p : g.iterate(limit)) { // Pair<List<BigInteger>, Iterable<BigInteger>> digits = p.a.digits(p.b); // String beforeDecimalString = digits.a.toString(); // List<String> afterDecimalStrings = new ArrayList<>(); // int i = 0; // for (BigInteger digit : digits.b) { // if (i >= 20) { // afterDecimalStrings.add("..."); // break; // afterDecimalStrings.add(digit.toString()); // String resultString = "(" + beforeDecimalString + ", " + afterDecimalStrings + ")"; // System.out.println("digits(" + p.a + ", " + p.b + ") = " + resultString); public static void demoEquals_Rational() { initialize(); for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { assert p.a != null; assert p.b != null; System.out.println(p.a + (p.a.equals(p.b) ? " = " : " ≠ ") + p.b); } } public static void demoEquals_null() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { //noinspection ObjectEqualsNull System.out.println(r + (r.equals(null) ? " = " : " ≠ ") + null); } } public static void demoHashCode() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println("hashCode(" + r + ") = " + r.hashCode()); } } public static void demoCompareTo() { initialize(); for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { assert p.a != null; assert p.b != null; System.out.println(p.a + " " + Ordering.compare(p.a, p.b).toChar() + " " + p.b); } } public static void demoRead() { initialize(); for (String s : take(LIMIT, P.strings())) { System.out.println("read(" + s + ") = " + read(s)); } } public static void demoRead_targeted() { initialize(); Iterable<Character> cs; if (P instanceof QBarExhaustiveProvider) { cs = fromString(RATIONAL_CHARS); } else { cs = ((QBarRandomProvider) P).uniformSample(RATIONAL_CHARS); } for (String s : take(LIMIT, P.strings(cs))) { System.out.println("read(" + s + ") = " + read(s)); } } private static void demoFindIn() { initialize(); for (String s : take(LIMIT, P.strings())) { System.out.println("findIn(" + s + ") = " + findIn(s)); } } public static void demoFindIn_targeted() { initialize(); Iterable<Character> cs; if (P instanceof ExhaustiveProvider) { cs = fromString(RATIONAL_CHARS); } else { cs = ((RandomProvider) P).uniformSample(RATIONAL_CHARS); } for (String s : take(LIMIT, P.strings(cs))) { System.out.println("findIn(" + s + ") = " + findIn(s)); } } public static void demoToString() { initialize(); for (Rational r : take(LIMIT, P.rationals())) { System.out.println(r); } } }
package org.animotron.operator; import org.animotron.ATest; import org.animotron.Expression; import org.animotron.operator.compare.EQ; import org.animotron.operator.compare.WITH; import org.animotron.operator.query.ALL; import org.animotron.operator.relation.HAVE; import org.animotron.operator.relation.IS; import org.junit.Test; import static org.animotron.Expression._; import static org.animotron.Expression.text; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> * */ public class AllTest extends ATest { @Test public void testALL() throws Exception { new Expression( _(THE._, "A", _(HAVE._, "value")) ); new Expression( _(THE._, "B", _(IS._, "A"), _(HAVE._, "value", text("B"))) ); new Expression( _(THE._, "C", _(IS._, "B"), _(HAVE._, "value", text("C"))) ); Expression D = new Expression( _(THE._, "D", _(ALL._, "A")) ); assertAnimo(D, "<the:D><the:B><is:A/><have:value>B</have:value></the:B><the:C><is:B/><have:value>C</have:value></the:C></the:D>"); } @Test public void testALLwithWITH() throws Exception { new Expression( _(THE._, "A", _(HAVE._, "value")) ); new Expression( _(THE._, "B", _(IS._, "A"), _(HAVE._, "value", text("B"))) ); new Expression( _(THE._, "B1", _(IS._, "B"), _(HAVE._, "value", text("B"))) ); new Expression( _(THE._, "C", _(IS._, "B"), _(HAVE._, "value", text("C"))) ); new Expression( _(THE._, "C1", _(IS._, "C"), _(HAVE._, "value", text("C"))) ); Expression D = new Expression( _(THE._, "D", _(ALL._, "A", _(WITH._, "value", text("B")))) ); assertAnimo(D, "<the:D><the:B><is:A/><have:value>B</have:value></the:B><the:B1><is:B/><have:value>B</have:value></the:B1></the:D>"); Expression E = new Expression( _(THE._, "E", _(ALL._, "A", _(WITH._, "value", text("C")))) ); assertAnimo(E, "<the:E><the:C><is:B/><have:value>C</have:value></the:C><the:C1><is:C/><have:value>C</have:value></the:C1></the:E>"); } @Test public void ALLwithEQ() throws Exception { new Expression( _(THE._, "text-plain", _(IS._, "mime-type"), _(IS._, "text"), _(HAVE._, "type", text("text/plain")), _(HAVE._, "name", text("Plain text")), _(HAVE._, "extension", text("txt")) ) ); new Expression( _(THE._, "application-atom", _(IS._, "mime-type"), _(IS._, "application"), _(HAVE._, "type", text("application/atom+xml")), _(HAVE._, "name", text("Atom Feed Document")), _(HAVE._, "extension", text("atom")) ) ); Expression test = new Expression( _(THE._, "test", _(ALL._, "mime-type", _(EQ._, "extension", text("txt"))) ) ); assertAnimo(test, "<the:test><the:text-plain><is:mime-type/><is:text/><have:type>text/plain</have:type><have:name>Plain text</have:name><have:extension>txt</have:extension></the:text-plain></the:test>"); } }
package org.jenetics.util; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.Serializable; import java.util.Random; import javolution.context.LocalContext; import javolution.lang.Immutable; import javolution.lang.Reflection; import javolution.lang.Reflection.Method; import javolution.xml.XMLSerializable; import org.jenetics.util.Array; import org.jenetics.util.Factory; import org.jenetics.util.RandomRegistry; import org.testng.Assert; import org.testng.annotations.Test; public abstract class ObjectTester<T> { protected abstract Factory<T> getFactory(); protected Array<T> newSameObjects(final int nobjects) { final Array<T> objects = new Array<>(nobjects); for (int i = 0; i < nobjects; ++i) { LocalContext.enter(); try { RandomRegistry.setRandom(new Random(23487589)); objects.set(i, getFactory().newInstance()); } finally { LocalContext.exit(); } } return objects; } @Test public void equals() { final Array<T> same = newSameObjects(5); final Object that = same.get(0); for (int i = 1; i < same.length(); ++i) { final Object other = same.get(i); Assert.assertEquals(other, other); Assert.assertEquals(other, that); Assert.assertEquals(that, other); Assert.assertFalse(other.equals(null)); } } @Test public void notEquals() { for (int i = 0; i < 10; ++i) { final Object that = getFactory().newInstance(); final Object other = getFactory().newInstance(); if (that.equals(other)) { Assert.assertTrue(other.equals(that)); Assert.assertEquals(that.hashCode(), other.hashCode()); } else { Assert.assertFalse(other.equals(that)); } } } @Test public void notEqualsDifferentType() { final Object that = getFactory().newInstance(); Assert.assertFalse(that.equals(null)); Assert.assertFalse(that.equals("")); Assert.assertFalse(that.equals(23)); } @Test public void hashcode() { final Array<T> same = newSameObjects(5); final Object that = same.get(0); for (int i = 1; i < same.length(); ++i) { final Object other = same.get(i); Assert.assertEquals(that.hashCode(), other.hashCode()); } } @Test public void cloning() { final Object that = getFactory().newInstance(); if (that instanceof Cloneable) { final Method clone = Reflection.getMethod(String.format( "%s.clone()", that.getClass().getName() )); final Object other = clone.invoke(that); Assert.assertEquals(other, that); Assert.assertNotSame(other, that); } } @Test public void tostring() { final Array<T> same = newSameObjects(5); final Object that = same.get(0); for (int i = 1; i < same.length(); ++i) { final Object other = same.get(i); Assert.assertEquals(that.toString(), other.toString()); Assert.assertNotNull(other.toString()); } } @Test public void isValid() { final T a = getFactory().newInstance(); if (a instanceof Verifiable) { Assert.assertTrue(((Verifiable)a).isValid()); } } @Test public void typeConsistency() throws Exception { final T a = getFactory().newInstance(); Assert.assertFalse(a instanceof Cloneable && a instanceof Immutable); Assert.assertFalse(a instanceof Copyable<?> && a instanceof Immutable); if (a instanceof Immutable) { final BeanInfo info = Introspector.getBeanInfo(a.getClass()); for (PropertyDescriptor prop : info.getPropertyDescriptors()) { Assert.assertNull(prop.getWriteMethod()); } } } @Test public void xmlSerialize() throws Exception { final Object object = getFactory().newInstance(); if (object instanceof XMLSerializable) { for (int i = 0; i < 10; ++i) { final XMLSerializable serializable = (XMLSerializable)getFactory().newInstance(); serialize.testXMLSerialization(serializable); } } } @Test public void objectSerialize() throws Exception { final Object object = getFactory().newInstance(); if (object instanceof Serializable) { for (int i = 0; i < 10; ++i) { final Serializable serializable = (Serializable)getFactory().newInstance(); serialize.testSerialization(serializable); } } } }
package org.mapdb; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicLong; import static org.junit.Assert.*; /** * @author Jan Kotek */ @SuppressWarnings({ "unchecked", "rawtypes" }) public class AsyncWriteEngineTest extends TestFile{ AsyncWriteEngine engine; @Before public void reopenStore() throws IOException { assertNotNull(index); if(engine !=null) engine.close(); engine = new AsyncWriteEngine(new StoreDirect(fac)); } @Test(timeout = 1000000) public void write_fetch_update_delete() throws IOException { long recid = engine.put("aaa", Serializer.STRING_NOSIZE); assertEquals("aaa", engine.get(recid, Serializer.STRING_NOSIZE)); reopenStore(); assertEquals("aaa", engine.get(recid, Serializer.STRING_NOSIZE)); engine.update(recid, "bbb", Serializer.STRING_NOSIZE); assertEquals("bbb", engine.get(recid, Serializer.STRING_NOSIZE)); reopenStore(); assertEquals("bbb", engine.get(recid, Serializer.STRING_NOSIZE)); } @Test(timeout = 0xFFFF) public void concurrent_updates_test() throws InterruptedException, IOException { final int threadNum = 16; final int updates = 1000; final CountDownLatch latch = new CountDownLatch(threadNum); final Map<Integer,Long> recids = new ConcurrentHashMap<Integer, Long>(); for(int i = 0;i<threadNum; i++){ final int num = i; new Thread(new Runnable() { @Override public void run() { long recid = engine.put("START-", Serializer.STRING_NOSIZE); recids.put(num, recid); for(int i = 0;i<updates; i++){ String str= engine.get(recid, Serializer.STRING_NOSIZE); str +=num+","; engine.update(recid, str, Serializer.STRING_NOSIZE); } latch.countDown(); } }).start(); } latch.await(); reopenStore(); assertEquals(recids.size(),threadNum); for(int i = 0;i<threadNum; i++){ long recid = recids.get(i); String expectedStr ="START-"; for(int j=0;j<updates;j++) expectedStr +=i+","; String v = engine.get(recid, Serializer.STRING_NOSIZE); assertEquals(expectedStr, v); } } @Test(timeout = 1000000) public void async_commit(){ final AtomicLong putCounter = new AtomicLong(); StoreWAL t = new StoreWAL(fac){ @Override public <A> long put(A value, Serializer<A> serializer) { putCounter.incrementAndGet(); return super.put(value, serializer); } @Override public <A> void update(long recid, A value, Serializer<A> serializer) { putCounter.incrementAndGet(); super.update(recid, value, serializer); } }; AsyncWriteEngine a = new AsyncWriteEngine(t); byte[] b = new byte[124]; long max = 100; ArrayList<Long> l = new ArrayList<Long>(); for(int i=0;i<max;i++){ long recid = a.put(b, Serializer.BASIC); l.add(recid); } //make commit just after bunch of records was added, // we need to test that all records made it into transaction log a.commit(); assertEquals(max, putCounter.longValue() ); assertTrue(a.writeCache.isEmpty()); a.close(); //now reopen db and check ths t = new StoreWAL(fac); a = new AsyncWriteEngine(t); for(Long recid : l){ assertArrayEquals(b, (byte[]) a.get(recid, Serializer.BASIC)); } a.close(); } }
package org.mineskin.test; import org.junit.Test; import org.mineskin.MineskinClient; import org.mineskin.SkinOptions; import org.mineskin.data.Skin; import org.mineskin.data.SkinCallback; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; public class GenerateTest { private final MineskinClient client = new MineskinClient(); @Test(timeout = 90000L) public void urlTest() throws InterruptedException { Thread.sleep(7000); CountDownLatch latch = new CountDownLatch(1); final String name = "JavaClient-Test-Url"; this.client.generateUrl("https://i.imgur.com/0Fna2GH.png", SkinOptions.name(name), new SkinCallback() { @Override public void exception(Exception exception) { fail(exception.getMessage()); latch.countDown(); } @Override public void error(String errorMessage) { fail(errorMessage); latch.countDown(); } @Override public void waiting(long delay) { System.out.println("Waiting " + delay); } @Override public void done(Skin skin) { validateSkin(skin, name); latch.countDown(); } }); latch.await(10000, TimeUnit.SECONDS); Thread.sleep(1000); } @Test(timeout = 90000L) public void uploadTest() throws InterruptedException, IOException { Thread.sleep(7000); CountDownLatch latch = new CountDownLatch(1); final String name = "JavaClient-Test-Upload-" + System.currentTimeMillis(); File file = File.createTempFile("mineskin-temp-upload-image", ".png"); ImageIO.write(randomImage(64, 32), "png", file); this.client.generateUpload(file, SkinOptions.name(name), new SkinCallback() { @Override public void exception(Exception exception) { fail(exception.getMessage()); latch.countDown(); } @Override public void error(String errorMessage) { fail(errorMessage); latch.countDown(); } @Override public void waiting(long delay) { System.out.println("Waiting " + delay); } @Override public void done(Skin skin) { validateSkin(skin, name); latch.countDown(); } }); latch.await(10000, TimeUnit.SECONDS); Thread.sleep(1000); } void validateSkin(Skin skin, String name) { assertNotNull(skin); assertNotNull(skin.data); assertNotNull(skin.data.texture); assertEquals(name, skin.name); } BufferedImage randomImage(int width, int height) { Random random = new Random(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { float r = random.nextFloat(); float g = random.nextFloat(); float b = random.nextFloat(); image.setRGB(x, y, new Color(r, g, b).getRGB()); } } return image; } }
class WhileStatementTest { public static void main(String[] args) { int i; int[] ia; long l; long[] la; boolean b; A cA; B cB; while (i) {} // INVALID_CONDITION_TYPE while (ia) {} // INVALID_CONDITION_TYPE while (l) {} // INVALID_CONDITION_TYPE while (la) {} // INVALID_CONDITION_TYPE //while (b) {} // OK while (cA) {} // INVALID_CONDITION_TYPE } } class A {} class B {}
package org.perl6.nqp.runtime; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.net.InetAddress; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.FileTime; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TimerTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.perl6.nqp.io.AsyncFileHandle; import org.perl6.nqp.io.FileHandle; import org.perl6.nqp.io.IIOAsyncReadable; import org.perl6.nqp.io.IIOAsyncWritable; import org.perl6.nqp.io.IIOBindable; import org.perl6.nqp.io.IIOCancelable; import org.perl6.nqp.io.IIOClosable; import org.perl6.nqp.io.IIOEncodable; import org.perl6.nqp.io.IIOInteractive; import org.perl6.nqp.io.IIOLineSeparable; import org.perl6.nqp.io.IIOSeekable; import org.perl6.nqp.io.IIOSyncReadable; import org.perl6.nqp.io.IIOSyncWritable; import org.perl6.nqp.io.ProcessHandle; import org.perl6.nqp.io.ServerSocketHandle; import org.perl6.nqp.io.SocketHandle; import org.perl6.nqp.io.StandardReadHandle; import org.perl6.nqp.io.StandardWriteHandle; import org.perl6.nqp.jast2bc.JASTCompiler; import org.perl6.nqp.sixmodel.BoolificationSpec; import org.perl6.nqp.sixmodel.ContainerConfigurer; import org.perl6.nqp.sixmodel.ContainerSpec; import org.perl6.nqp.sixmodel.InvocationSpec; import org.perl6.nqp.sixmodel.REPRRegistry; import org.perl6.nqp.sixmodel.STable; import org.perl6.nqp.sixmodel.SerializationContext; import org.perl6.nqp.sixmodel.SerializationReader; import org.perl6.nqp.sixmodel.SerializationWriter; import org.perl6.nqp.sixmodel.SixModelObject; import org.perl6.nqp.sixmodel.StorageSpec; import org.perl6.nqp.sixmodel.TypeObject; import org.perl6.nqp.sixmodel.reprs.AsyncTaskInstance; import org.perl6.nqp.sixmodel.reprs.CallCaptureInstance; import org.perl6.nqp.sixmodel.reprs.ConcBlockingQueueInstance; import org.perl6.nqp.sixmodel.reprs.ConditionVariable; import org.perl6.nqp.sixmodel.reprs.ConditionVariableInstance; import org.perl6.nqp.sixmodel.reprs.ContextRef; import org.perl6.nqp.sixmodel.reprs.ContextRefInstance; import org.perl6.nqp.sixmodel.reprs.IOHandleInstance; import org.perl6.nqp.sixmodel.reprs.JavaObjectWrapper; import org.perl6.nqp.sixmodel.reprs.LexoticInstance; import org.perl6.nqp.sixmodel.reprs.MultiCacheInstance; import org.perl6.nqp.sixmodel.reprs.NFA; import org.perl6.nqp.sixmodel.reprs.NFAInstance; import org.perl6.nqp.sixmodel.reprs.NFAStateInfo; import org.perl6.nqp.sixmodel.reprs.P6bigintInstance; import org.perl6.nqp.sixmodel.reprs.ReentrantMutexInstance; import org.perl6.nqp.sixmodel.reprs.SCRefInstance; import org.perl6.nqp.sixmodel.reprs.SemaphoreInstance; import org.perl6.nqp.sixmodel.reprs.VMArray; import org.perl6.nqp.sixmodel.reprs.VMArrayInstance; import org.perl6.nqp.sixmodel.reprs.VMArrayInstance_i16; import org.perl6.nqp.sixmodel.reprs.VMArrayInstance_i32; import org.perl6.nqp.sixmodel.reprs.VMArrayInstance_i8; import org.perl6.nqp.sixmodel.reprs.VMArrayInstance_u16; import org.perl6.nqp.sixmodel.reprs.VMArrayInstance_u32; import org.perl6.nqp.sixmodel.reprs.VMArrayInstance_u8; import org.perl6.nqp.sixmodel.reprs.VMExceptionInstance; import org.perl6.nqp.sixmodel.reprs.VMHash; import org.perl6.nqp.sixmodel.reprs.VMHashInstance; import org.perl6.nqp.sixmodel.reprs.VMIterInstance; import org.perl6.nqp.sixmodel.reprs.VMThreadInstance; /** * Contains complex operations that are more involved that the simple ops that the * JVM makes available. */ public final class Ops { /* I/O opcodes */ public static String print(String v, ThreadContext tc) { tc.gc.out.print(v); return v; } public static String say(String v, ThreadContext tc) { tc.gc.out.println(v); return v; } public static final int STAT_EXISTS = 0; public static final int STAT_FILESIZE = 1; public static final int STAT_ISDIR = 2; public static final int STAT_ISREG = 3; public static final int STAT_ISDEV = 4; public static final int STAT_CREATETIME = 5; public static final int STAT_ACCESSTIME = 6; public static final int STAT_MODIFYTIME = 7; public static final int STAT_CHANGETIME = 8; public static final int STAT_BACKUPTIME = 9; public static final int STAT_UID = 10; public static final int STAT_GID = 11; public static final int STAT_ISLNK = 12; public static final int STAT_PLATFORM_DEV = -1; public static final int STAT_PLATFORM_INODE = -2; public static final int STAT_PLATFORM_MODE = -3; public static final int STAT_PLATFORM_NLINKS = -4; public static final int STAT_PLATFORM_DEVTYPE = -5; public static final int STAT_PLATFORM_BLOCKSIZE = -6; public static final int STAT_PLATFORM_BLOCKS = -7; public static long stat(String filename, long status) { long rval = -1; switch ((int) status) { case STAT_EXISTS: rval = new File(filename).exists() ? 1 : 0; break; case STAT_FILESIZE: rval = new File(filename).length(); break; case STAT_ISDIR: try { rval = (Boolean) Files.getAttribute(Paths.get(filename), "basic:isDirectory") ? 1 : 0; } catch (Exception e) { rval = -1; } break; case STAT_ISREG: try { rval = (Boolean) Files.getAttribute(Paths.get(filename), "basic:isRegularFile") ? 1 : 0; } catch (Exception e) { rval = -1; } break; case STAT_ISDEV: try { rval = (Boolean) Files.getAttribute(Paths.get(filename), "basic:isOther") ? 1 : 0; } catch (Exception e) { rval = -1; } break; case STAT_CREATETIME: try { rval = ((Number) Files.getAttribute(Paths.get(filename), "basic:creationTime")).longValue(); } catch (Exception e) { rval = -1; } break; case STAT_ACCESSTIME: try { rval = ((FileTime) Files.getAttribute(Paths.get(filename), "basic:lastAccessTime")).to(TimeUnit.SECONDS); } catch (Exception e) { rval = -1; } break; case STAT_MODIFYTIME: try { rval = ((FileTime) Files.getAttribute(Paths.get(filename), "basic:lastModifiedTime")).to(TimeUnit.SECONDS); } catch (Exception e) { rval = -1; } break; case STAT_CHANGETIME: try { rval = ((FileTime) Files.getAttribute(Paths.get(filename), "unix:ctime")).to(TimeUnit.SECONDS); } catch (Exception e) { rval = -1; } break; case STAT_BACKUPTIME: rval = -1; break; case STAT_UID: try { rval = ((Number) Files.getAttribute(Paths.get(filename), "unix:uid")).longValue(); } catch (Exception e) { rval = -1; } break; case STAT_GID: try { rval = ((Number) Files.getAttribute(Paths.get(filename), "unix:gid")).longValue(); } catch (Exception e) { rval = -1; } break; case STAT_ISLNK: try { rval = (Boolean) Files.getAttribute(Paths.get(filename), "basic:isSymbolicLink", LinkOption.NOFOLLOW_LINKS) ? 1 : 0; } catch (Exception e) { rval = -1; } break; case STAT_PLATFORM_DEV: try { rval = ((Number) Files.getAttribute(Paths.get(filename), "unix:dev")).longValue(); } catch (Exception e) { rval = -1; } break; case STAT_PLATFORM_INODE: try { rval = ((Number) Files.getAttribute(Paths.get(filename), "unix:ino")).longValue(); } catch (Exception e) { rval = -1; } break; case STAT_PLATFORM_MODE: try { rval = ((Number) Files.getAttribute(Paths.get(filename), "unix:mode")).longValue(); } catch (Exception e) { rval = -1; } break; case STAT_PLATFORM_NLINKS: try { rval = ((Number) Files.getAttribute(Paths.get(filename), "unix:nlink")).longValue(); } catch (Exception e) { rval = -1; } break; case STAT_PLATFORM_DEVTYPE: try { rval = ((Number) Files.getAttribute(Paths.get(filename), "unix:rdev")).longValue(); } catch (Exception e) { rval = -1; } break; case STAT_PLATFORM_BLOCKSIZE: throw new UnsupportedOperationException("STAT_PLATFORM_BLOCKSIZE not supported"); case STAT_PLATFORM_BLOCKS: throw new UnsupportedOperationException("STAT_PLATFORM_BLOCKS not supported"); default: break; } return rval; } public static SixModelObject open(String path, String mode, ThreadContext tc) { SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance h = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); h.handle = new FileHandle(tc, path, mode); return h; } public static SixModelObject openasync(String path, String mode, ThreadContext tc) { SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance h = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); h.handle = new AsyncFileHandle(tc, path, mode); return h; } public static SixModelObject socket(long listener, ThreadContext tc) { SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance h = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); if (listener == 0) { h.handle = new SocketHandle(tc); } else if (listener > 0) { h.handle = new ServerSocketHandle(tc); } else { ExceptionHandling.dieInternal(tc, "Socket handle does not support a negative listener value"); } return h; } public static SixModelObject connect(SixModelObject obj, String host, long port, ThreadContext tc) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof SocketHandle) { ((SocketHandle)h.handle).connect(tc, host, (int) port); } else { ExceptionHandling.dieInternal(tc, "This handle does not support connect"); } return obj; } public static SixModelObject bindsock(SixModelObject obj, String host, long port, ThreadContext tc) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOBindable) { ((IIOBindable)h.handle).bind(tc, host, (int) port); } else { ExceptionHandling.dieInternal(tc, "This handle does not support bind"); } return obj; } public static SixModelObject accept(SixModelObject obj, ThreadContext tc) { IOHandleInstance listener = (IOHandleInstance)obj; if (listener.handle instanceof ServerSocketHandle) { SocketHandle handle = ((ServerSocketHandle)listener.handle).accept(tc); if (handle != null) { SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance h = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); h.handle = handle; return h; } } else { ExceptionHandling.dieInternal(tc, "This handle does not support accept"); } return null; } public static long filereadable(String path, ThreadContext tc) { Path path_o; long res; try { path_o = Paths.get(path); res = Files.isReadable(path_o) ? 1 : 0; } catch (Exception e) { die_s(e.getMessage(), tc); res = -1; /* unreachable */ } return res; } public static long filewritable(String path, ThreadContext tc) { Path path_o; long res; try { path_o = Paths.get(path); res = Files.isWritable(path_o) ? 1 : 0; } catch (Exception e) { die_s(e.getMessage(), tc); res = -1; /* unreachable */ } return res; } public static long fileexecutable(String path, ThreadContext tc) { Path path_o; long res; try { path_o = Paths.get(path); res = Files.isExecutable(path_o) ? 1 : 0; } catch (Exception e) { die_s(e.getMessage(), tc); res = -1; /* unreachable */ } return res; } public static long fileislink(String path, ThreadContext tc) { Path path_o; long res; try { path_o = Paths.get(path); res = Files.isSymbolicLink(path_o) ? 1 : 0; } catch (Exception e) { die_s(e.getMessage(), tc); res = -1; /* unreachable */ } return res; } public static SixModelObject getstdin(ThreadContext tc) { SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance h = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); h.handle = new StandardReadHandle(tc, tc.gc.in); return h; } public static SixModelObject getstdout(ThreadContext tc) { SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance h = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); h.handle = new StandardWriteHandle(tc, tc.gc.out); return h; } public static SixModelObject getstderr(ThreadContext tc) { SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance h = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); h.handle = new StandardWriteHandle(tc, tc.gc.err); return h; } public static SixModelObject setencoding(SixModelObject obj, String encoding, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; Charset cs; if (encoding.equals("ascii")) cs = Charset.forName("US-ASCII"); else if (encoding.equals("iso-8859-1")) cs = Charset.forName("ISO-8859-1"); else if (encoding.equals("utf8")) cs = Charset.forName("UTF-8"); else if (encoding.equals("utf16")) cs = Charset.forName("UTF-16"); else throw ExceptionHandling.dieInternal(tc, "Unsupported encoding " + encoding); if (h.handle instanceof IIOEncodable) ((IIOEncodable)h.handle).setEncoding(tc, cs); else throw ExceptionHandling.dieInternal(tc, "This handle does not support textual I/O"); } else { throw ExceptionHandling.dieInternal(tc, "setencoding requires an object with the IOHandle REPR"); } return obj; } public static SixModelObject setinputlinesep(SixModelObject obj, String sep, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOLineSeparable) ((IIOLineSeparable)h.handle).setInputLineSeparator(tc, sep); else throw ExceptionHandling.dieInternal(tc, "This handle does not support setting input line separator"); } else { throw ExceptionHandling.dieInternal(tc, "setinputlinesep requires an object with the IOHandle REPR"); } return obj; } public static SixModelObject seekfh(SixModelObject obj, long offset, long whence, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSeekable) { ((IIOSeekable)h.handle).seek(tc, offset, whence); return obj; } else throw ExceptionHandling.dieInternal(tc, "This handle does not support seek"); } else { throw ExceptionHandling.dieInternal(tc, "seekfh requires an object with the IOHandle REPR"); } } public static long tellfh(SixModelObject obj, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSeekable) return ((IIOSeekable)h.handle).tell(tc); else throw ExceptionHandling.dieInternal(tc, "This handle does not support tell"); } else { throw ExceptionHandling.dieInternal(tc, "tellfh requires an object with the IOHandle REPR"); } } public static SixModelObject readfh(SixModelObject io, SixModelObject res, long bytes, ThreadContext tc) { if (io instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)io; if (h.handle instanceof IIOSyncReadable) { if (res instanceof VMArrayInstance_i8) { VMArrayInstance_i8 arr = (VMArrayInstance_i8)res; byte[] array = ((IIOSyncReadable)h.handle).read(tc, (int)bytes); arr.elems = array.length; arr.start = 0; arr.slots = array; return res; } else if (res instanceof VMArrayInstance_u8) { VMArrayInstance_u8 arr = (VMArrayInstance_u8)res; byte[] array = ((IIOSyncReadable)h.handle).read(tc, (int)bytes); arr.elems = array.length; arr.start = 0; arr.slots = array; return res; } else { throw ExceptionHandling.dieInternal(tc, "readfh requires a Buf[int8] or a Buf[uint8]"); } } else { throw ExceptionHandling.dieInternal(tc, "This handle does not support read"); } } else { throw ExceptionHandling.dieInternal(tc, "readfh requires an object with the IOHandle REPR"); } } public static long writefh(SixModelObject obj, SixModelObject buf, ThreadContext tc) { ByteBuffer bb = Buffers.unstashBytes(buf, tc); long written; if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; byte[] bytesToWrite = new byte[bb.limit()]; bb.get(bytesToWrite); if (h.handle instanceof IIOSyncWritable) written = ((IIOSyncWritable)h.handle).write(tc, bytesToWrite); else throw ExceptionHandling.dieInternal(tc, "This handle does not support write"); } else { throw ExceptionHandling.dieInternal(tc, "writefh requires an object with the IOHandle REPR"); } return written; } public static long printfh(SixModelObject obj, String data, ThreadContext tc) { long written; if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSyncWritable) written = ((IIOSyncWritable)h.handle).print(tc, data); else throw ExceptionHandling.dieInternal(tc, "This handle does not support print"); } else { throw ExceptionHandling.dieInternal(tc, "printfh requires an object with the IOHandle REPR"); } return written; } public static long sayfh(SixModelObject obj, String data, ThreadContext tc) { long written; if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSyncWritable) written = ((IIOSyncWritable)h.handle).say(tc, data); else throw ExceptionHandling.dieInternal(tc, "This handle does not support say"); } else { throw ExceptionHandling.dieInternal(tc, "sayfh requires an object with the IOHandle REPR"); } return written; } public static SixModelObject flushfh(SixModelObject obj, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSyncWritable) ((IIOSyncWritable)h.handle).flush(tc); else throw ExceptionHandling.dieInternal(tc, "This handle does not support flush"); } else { die_s("flushfh requires an object with the IOHandle REPR", tc); } return obj; } public static String readlinefh(SixModelObject obj, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSyncReadable) return ((IIOSyncReadable)h.handle).readline(tc); else throw ExceptionHandling.dieInternal(tc, "This handle does not support readline"); } else { throw ExceptionHandling.dieInternal(tc, "readlinefh requires an object with the IOHandle REPR"); } } public static String readlineintfh(SixModelObject obj, String prompt, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOInteractive) return ((IIOInteractive)h.handle).readlineInteractive(tc, prompt); else throw ExceptionHandling.dieInternal(tc, "This handle does not support readline interactive"); } else { throw ExceptionHandling.dieInternal(tc, "readlineintfh requires an object with the IOHandle REPR"); } } public static String readallfh(SixModelObject obj, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSyncReadable) return ((IIOSyncReadable)h.handle).slurp(tc); else throw ExceptionHandling.dieInternal(tc, "This handle does not support slurp"); } else { throw ExceptionHandling.dieInternal(tc, "readallfh requires an object with the IOHandle REPR"); } } public static String getcfh(SixModelObject obj, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSyncReadable) return ((IIOSyncReadable)h.handle).getc(tc); else throw ExceptionHandling.dieInternal(tc, "This handle does not support getc"); } else { throw ExceptionHandling.dieInternal(tc, "getcfh requires an object with the IOHandle REPR"); } } public static long eoffh(SixModelObject obj, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSyncReadable) return ((IIOSyncReadable)h.handle).eof(tc) ? 1 : 0; else throw ExceptionHandling.dieInternal(tc, "This handle does not support eof"); } else { throw ExceptionHandling.dieInternal(tc, "eoffh requires an object with the IOHandle REPR"); } } public static SixModelObject slurpasync(SixModelObject obj, SixModelObject resultType, SixModelObject done, SixModelObject error, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOAsyncReadable) ((IIOAsyncReadable)h.handle).slurp(tc, resultType, done, error); else throw ExceptionHandling.dieInternal(tc, "This handle does not support async slurp"); } else { die_s("slurpasync requires an object with the IOHandle REPR", tc); } return obj; } public static SixModelObject spurtasync(SixModelObject obj, SixModelObject resultType, SixModelObject data, SixModelObject done, SixModelObject error, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOAsyncWritable) ((IIOAsyncWritable)h.handle).spurt(tc, resultType, data, done, error); else throw ExceptionHandling.dieInternal(tc, "This handle does not support async spurt"); } else { die_s("spurtasync requires an object with the IOHandle REPR", tc); } return obj; } @SuppressWarnings({ "unchecked", "rawtypes" }) public static SixModelObject linesasync(SixModelObject obj, SixModelObject resultType, long chomp, SixModelObject queue, SixModelObject done, SixModelObject error, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOAsyncReadable) ((IIOAsyncReadable)h.handle).lines(tc, resultType, chomp != 0, (LinkedBlockingQueue)((JavaObjectWrapper)queue).theObject, done, error); else throw ExceptionHandling.dieInternal(tc, "This handle does not support async lines"); } else { die_s("linesasync requires an object with the IOHandle REPR", tc); } return obj; } public static SixModelObject closefh(SixModelObject obj, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOClosable) ((IIOClosable)h.handle).close(tc); else throw ExceptionHandling.dieInternal(tc, "This handle does not support close"); } else { die_s("closefh requires an object with the IOHandle REPR", tc); } return obj; } public static Set<PosixFilePermission> modeToPosixFilePermission(long mode) { Set<PosixFilePermission> perms = EnumSet.noneOf(PosixFilePermission.class); if ((mode & 0001) != 0) perms.add(PosixFilePermission.OTHERS_EXECUTE); if ((mode & 0002) != 0) perms.add(PosixFilePermission.OTHERS_WRITE); if ((mode & 0004) != 0) perms.add(PosixFilePermission.OTHERS_READ); if ((mode & 0010) != 0) perms.add(PosixFilePermission.GROUP_EXECUTE); if ((mode & 0020) != 0) perms.add(PosixFilePermission.GROUP_WRITE); if ((mode & 0040) != 0) perms.add(PosixFilePermission.GROUP_READ); if ((mode & 0100) != 0) perms.add(PosixFilePermission.OWNER_EXECUTE); if ((mode & 0200) != 0) perms.add(PosixFilePermission.OWNER_WRITE); if ((mode & 0400) != 0) perms.add(PosixFilePermission.OWNER_READ); return perms; } public static long chmod(String path, long mode, ThreadContext tc) { Path path_o; try { path_o = Paths.get(path); Set<PosixFilePermission> perms = modeToPosixFilePermission(mode); Files.setPosixFilePermissions(path_o, perms); } catch (Exception e) { die_s(IOExceptionMessages.message(e), tc); } return 0; } public static long unlink(String path, ThreadContext tc) { try { if(!Files.deleteIfExists(Paths.get(path))) { return -2; } } catch (Exception e) { die_s(IOExceptionMessages.message(e), tc); } return 0; } public static long rmdir(String path, ThreadContext tc) { Path path_o = Paths.get(path); try { if (!Files.isDirectory(path_o)) { return -2; } Files.delete(path_o); } catch (Exception e) { die_s(IOExceptionMessages.message(e), tc); } return 0; } public static String cwd() { return System.getProperty("user.dir"); } public static String chdir(String path, ThreadContext tc) { die_s("chdir is not available on JVM", tc); return null; } public static long mkdir(String path, long mode, ThreadContext tc) { try { String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("win") >= 0) Files.createDirectory(Paths.get(path)); else Files.createDirectory(Paths.get(path), PosixFilePermissions.asFileAttribute(modeToPosixFilePermission(mode))); } catch (Exception e) { die_s(IOExceptionMessages.message(e), tc); } return 0; } public static long rename(String before, String after, ThreadContext tc) { Path before_o = Paths.get(before); Path after_o = Paths.get(after); try { Files.move(before_o, after_o); } catch (Exception e) { die_s(IOExceptionMessages.message(e), tc); } return 0; } public static long copy(String before, String after, ThreadContext tc) { Path before_o = Paths.get(before); Path after_o = Paths.get(after); try { Files.copy( before_o, after_o, StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { die_s(IOExceptionMessages.message(e), tc); } return 0; } public static long link(String before, String after, ThreadContext tc) { Path before_o = Paths.get(before); Path after_o = Paths.get(after); try { Files.createLink(after_o, before_o); } catch (Exception e) { die_s(IOExceptionMessages.message(e), tc); } return 0; } public static SixModelObject openpipe(String cmd, String dir, SixModelObject envObj, String errPath, ThreadContext tc) { // TODO: errPath NYI Map<String, String> env = new HashMap<String, String>(); SixModelObject iter = iter(envObj, tc); while (istrue(iter, tc) != 0) { SixModelObject kv = iter.shift_boxed(tc); String key = iterkey_s(kv, tc); String value = unbox_s(iterval(kv, tc), tc); env.put(key, value); } SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance h = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); h.handle = new ProcessHandle(tc, cmd, dir, env); return h; } public static String gethostname(){ try { String hostname = InetAddress.getLocalHost().getHostName(); return hostname; } catch (Exception e) { return null; } } // To be removed once shell3 is adopted public static long shell1(String cmd, ThreadContext tc) { return shell3(cmd, cwd(), getenvhash(tc), tc); } public static long shell3(String cmd, String dir, SixModelObject envObj, ThreadContext tc) { Map<String, String> env = new HashMap<String, String>(); SixModelObject iter = iter(envObj, tc); while (istrue(iter, tc) != 0) { SixModelObject kv = iter.shift_boxed(tc); String key = iterkey_s(kv, tc); String value = unbox_s(iterval(kv, tc), tc); env.put(key, value); } List<String> args = new ArrayList<String>(); String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("win") >= 0) { args.add("cmd"); args.add("/c"); args.add(cmd.replace('/', '\\')); } else { args.add("sh"); args.add("-c"); args.add(cmd); } return spawn(args, dir, env); } public static long spawn(SixModelObject argsObj, String dir, SixModelObject envObj, ThreadContext tc) { List<String> args = new ArrayList<String>(); SixModelObject argIter = iter(argsObj, tc); while (istrue(argIter, tc) != 0) { SixModelObject v = argIter.shift_boxed(tc); String arg = v.get_str(tc); args.add(arg); } Map<String, String> env = new HashMap<String, String>(); SixModelObject iter = iter(envObj, tc); while (istrue(iter, tc) != 0) { SixModelObject kv = iter.shift_boxed(tc); String key = iterkey_s(kv, tc); String value = unbox_s(iterval(kv, tc), tc); env.put(key, value); } return spawn(args, dir , env); } private static long spawn(List<String> args, String dir, Map<String, String> env) { long retval = 255; try { ProcessBuilder pb = new ProcessBuilder(args); pb.directory(new File(dir)); // Clear the JVM inherited environment and use provided only Map<String, String> pbEnv = pb.environment(); pbEnv.clear(); pbEnv.putAll(env); Process proc = pb.inheritIO().start(); boolean finished = false; do { try { proc.waitFor(); finished = true; } catch (InterruptedException e) { } } while (!finished); retval = proc.exitValue(); } catch (IOException e) { } /* Return exit code left shifted by 8 for POSIX emulation. */ return retval << 8; } public static long symlink(String before, String after, ThreadContext tc) { Path before_o = Paths.get(before); Path after_o = Paths.get(after); try { Files.createSymbolicLink(after_o, before_o); } catch (Exception e) { die_s(IOExceptionMessages.message(e), tc); } return 0; } public static SixModelObject opendir(String path, ThreadContext tc) { try { DirectoryStream<Path> dirstrm = Files.newDirectoryStream(Paths.get(path)); SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance ioh = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); ioh.dirstrm = dirstrm; ioh.diri = dirstrm.iterator(); return ioh; } catch (Exception e) { die_s("nqp::opendir: unable to get a DirectoryStream", tc); } return null; } public static String nextfiledir(SixModelObject obj, ThreadContext tc) { try { if (obj instanceof IOHandleInstance) { IOHandleInstance ioh = (IOHandleInstance)obj; if (ioh.dirstrm != null && ioh.diri != null) { if (ioh.diri.hasNext()) { return ioh.diri.next().toString(); } else { return null; } } else { die_s("called nextfiledir on an IOHandle without a dirstream and/or iterator.", tc); } } else { die_s("nextfiledir requires an object with the IOHandle REPR", tc); } } catch (Exception e) { die_s("nqp::nextfiledir: unhandled exception", tc); } return null; } public static long closedir(SixModelObject obj, ThreadContext tc) { try { if (obj instanceof IOHandleInstance) { IOHandleInstance ioh = (IOHandleInstance)obj; ioh.diri = null; ioh.dirstrm.close(); ioh.dirstrm = null; } else { die_s("closedir requires an object with the IOHandle REPR", tc); } } catch (Exception e) { die_s("nqp::closedir: unhandled exception", tc); } return 0; } /* Lexical lookup in current scope. */ public static long getlex_i(CallFrame cf, int i) { return cf.iLex[i]; } public static double getlex_n(CallFrame cf, int i) { return cf.nLex[i]; } public static String getlex_s(CallFrame cf, int i) { return cf.sLex[i]; } public static SixModelObject getlex_o(CallFrame cf, int i) { return cf.oLex[i]; } /* Lexical binding in current scope. */ public static long bindlex_i(long v, CallFrame cf, int i) { cf.iLex[i] = v; return v; } public static double bindlex_n(double v, CallFrame cf, int i) { cf.nLex[i] = v; return v; } public static String bindlex_s(String v, CallFrame cf, int i) { cf.sLex[i] = v; return v; } public static SixModelObject bindlex_o(SixModelObject v, CallFrame cf, int i) { cf.oLex[i] = v; return v; } /* Lexical lookup in outer scope. */ public static long getlex_i_si(CallFrame cf, int i, int si) { while (si cf = cf.outer; return cf.iLex[i]; } public static double getlex_n_si(CallFrame cf, int i, int si) { while (si cf = cf.outer; return cf.nLex[i]; } public static String getlex_s_si(CallFrame cf, int i, int si) { while (si cf = cf.outer; return cf.sLex[i]; } public static SixModelObject getlex_o_si(CallFrame cf, int i, int si) { while (si cf = cf.outer; return cf.oLex[i]; } /* Lexical binding in outer scope. */ public static long bindlex_i_si(long v, CallFrame cf, int i, int si) { while (si cf = cf.outer; cf.iLex[i] = v; return v; } public static double bindlex_n_si(double v, CallFrame cf, int i, int si) { while (si cf = cf.outer; cf.nLex[i] = v; return v; } public static String bindlex_s_si(String v, CallFrame cf, int i, int si) { while (si cf = cf.outer; cf.sLex[i] = v; return v; } public static SixModelObject bindlex_o_si(SixModelObject v, CallFrame cf, int i, int si) { while (si cf = cf.outer; cf.oLex[i] = v; return v; } /* Lexical lookup by name. */ public static SixModelObject getlex(String name, ThreadContext tc) { CallFrame curFrame = tc.curFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (found != null) return curFrame.oLex[found]; curFrame = curFrame.outer; } return null; } public static long getlex_i(String name, ThreadContext tc) { CallFrame curFrame = tc.curFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.iTryGetLexicalIdx(name); if (found != null) return curFrame.iLex[found]; curFrame = curFrame.outer; } throw ExceptionHandling.dieInternal(tc, "Lexical '" + name + "' not found"); } public static double getlex_n(String name, ThreadContext tc) { CallFrame curFrame = tc.curFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.nTryGetLexicalIdx(name); if (found != null) return curFrame.nLex[found]; curFrame = curFrame.outer; } throw ExceptionHandling.dieInternal(tc, "Lexical '" + name + "' not found"); } public static String getlex_s(String name, ThreadContext tc) { CallFrame curFrame = tc.curFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.sTryGetLexicalIdx(name); if (found != null) return curFrame.sLex[found]; curFrame = curFrame.outer; } throw ExceptionHandling.dieInternal(tc, "Lexical '" + name + "' not found"); } public static SixModelObject getlexouter(String name, ThreadContext tc) { CallFrame curFrame = tc.curFrame.outer; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (found != null) return curFrame.oLex[found]; curFrame = curFrame.outer; } throw ExceptionHandling.dieInternal(tc, "Lexical '" + name + "' not found"); } /* Lexical binding by name. */ public static SixModelObject bindlex(String name, SixModelObject value, ThreadContext tc) { CallFrame curFrame = tc.curFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (found != null) return curFrame.oLex[found] = value; curFrame = curFrame.outer; } throw ExceptionHandling.dieInternal(tc, "Lexical '" + name + "' not found"); } public static long bindlex_i(String name, long value, ThreadContext tc) { CallFrame curFrame = tc.curFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.iTryGetLexicalIdx(name); if (found != null) return curFrame.iLex[found] = value; curFrame = curFrame.outer; } throw ExceptionHandling.dieInternal(tc, "Lexical '" + name + "' not found"); } public static double bindlex_n(String name, double value, ThreadContext tc) { CallFrame curFrame = tc.curFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.nTryGetLexicalIdx(name); if (found != null) return curFrame.nLex[found] = value; curFrame = curFrame.outer; } throw ExceptionHandling.dieInternal(tc, "Lexical '" + name + "' not found"); } public static String bindlex_s(String name, String value, ThreadContext tc) { CallFrame curFrame = tc.curFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.sTryGetLexicalIdx(name); if (found != null) return curFrame.sLex[found] = value; curFrame = curFrame.outer; } throw ExceptionHandling.dieInternal(tc, "Lexical '" + name + "' not found"); } /* Dynamic lexicals. */ public static SixModelObject bindlexdyn(SixModelObject value, String name, ThreadContext tc) { CallFrame curFrame = tc.curFrame.caller; while (curFrame != null) { Integer idx = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (idx != null) { curFrame.oLex[idx] = value; return value; } curFrame = curFrame.caller; } throw ExceptionHandling.dieInternal(tc, "Dyanmic variable '" + name + "' not found"); } public static SixModelObject getlexdyn(String name, ThreadContext tc) { CallFrame curFrame = tc.curFrame.caller; while (curFrame != null) { Integer idx = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (idx != null) return curFrame.oLex[idx]; curFrame = curFrame.caller; } return null; } public static SixModelObject getlexcaller(String name, ThreadContext tc) { CallFrame curCallerFrame = tc.curFrame.caller; while (curCallerFrame != null) { CallFrame curFrame = curCallerFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (found != null) return curFrame.oLex[found]; curFrame = curFrame.outer; } curCallerFrame = curCallerFrame.caller; } return null; } /* Relative lexical lookups. */ public static SixModelObject getlexrel(SixModelObject ctx, String name, ThreadContext tc) { if (ctx instanceof ContextRefInstance) { CallFrame curFrame = ((ContextRefInstance)ctx).context; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (found != null) return curFrame.oLex[found]; curFrame = curFrame.outer; } return null; } else { throw ExceptionHandling.dieInternal(tc, "getlexrel requires an operand with REPR ContextRef"); } } public static SixModelObject getlexreldyn(SixModelObject ctx, String name, ThreadContext tc) { if (ctx instanceof ContextRefInstance) { CallFrame curFrame = ((ContextRefInstance)ctx).context; while (curFrame != null) { Integer idx = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (idx != null) return curFrame.oLex[idx]; curFrame = curFrame.caller; } return null; } else { throw ExceptionHandling.dieInternal(tc, "getlexreldyn requires an operand with REPR ContextRef"); } } public static SixModelObject getlexrelcaller(SixModelObject ctx, String name, ThreadContext tc) { if (ctx instanceof ContextRefInstance) { CallFrame curCallerFrame = ((ContextRefInstance)ctx).context; while (curCallerFrame != null) { CallFrame curFrame = curCallerFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (found != null) return curFrame.oLex[found]; curFrame = curFrame.outer; } curCallerFrame = curCallerFrame.caller; } return null; } else { throw ExceptionHandling.dieInternal(tc, "getlexrelcaller requires an operand with REPR ContextRef"); } } /* Context introspection. */ public static SixModelObject ctx(ThreadContext tc) { SixModelObject ContextRef = tc.gc.ContextRef; SixModelObject wrap = ContextRef.st.REPR.allocate(tc, ContextRef.st); ((ContextRefInstance)wrap).context = tc.curFrame; return wrap; } public static SixModelObject ctxouter(SixModelObject ctx, ThreadContext tc) { if (ctx instanceof ContextRefInstance) { CallFrame outer = ((ContextRefInstance)ctx).context.outer; if (outer == null) return null; SixModelObject ContextRef = tc.gc.ContextRef; SixModelObject wrap = ContextRef.st.REPR.allocate(tc, ContextRef.st); ((ContextRefInstance)wrap).context = outer; return wrap; } else { throw ExceptionHandling.dieInternal(tc, "ctxouter requires an operand with REPR ContextRef"); } } public static SixModelObject ctxcaller(SixModelObject ctx, ThreadContext tc) { if (ctx instanceof ContextRefInstance) { CallFrame caller = ((ContextRefInstance)ctx).context.caller; if (caller == null) return null; SixModelObject ContextRef = tc.gc.ContextRef; SixModelObject wrap = ContextRef.st.REPR.allocate(tc, ContextRef.st); ((ContextRefInstance)wrap).context = caller; return wrap; } else { throw ExceptionHandling.dieInternal(tc, "ctxcaller requires an operand with REPR ContextRef"); } } public static SixModelObject ctxouterskipthunks(SixModelObject ctx, ThreadContext tc) { if (ctx instanceof ContextRefInstance) { CallFrame outer = ((ContextRefInstance)ctx).context.outer; while (outer != null && outer.codeRef.staticInfo.isThunk) outer = outer.outer; if (outer == null) return null; SixModelObject ContextRef = tc.gc.ContextRef; SixModelObject wrap = ContextRef.st.REPR.allocate(tc, ContextRef.st); ((ContextRefInstance)wrap).context = outer; return wrap; } else { throw ExceptionHandling.dieInternal(tc, "ctxouter requires an operand with REPR ContextRef"); } } public static SixModelObject ctxcallerskipthunks(SixModelObject ctx, ThreadContext tc) { if (ctx instanceof ContextRefInstance) { CallFrame caller = ((ContextRefInstance)ctx).context.caller; while (caller != null && caller.codeRef.staticInfo.isThunk) caller = caller.caller; if (caller == null) return null; SixModelObject ContextRef = tc.gc.ContextRef; SixModelObject wrap = ContextRef.st.REPR.allocate(tc, ContextRef.st); ((ContextRefInstance)wrap).context = caller; return wrap; } else { throw ExceptionHandling.dieInternal(tc, "ctxcaller requires an operand with REPR ContextRef"); } } public static SixModelObject ctxlexpad(SixModelObject ctx, ThreadContext tc) { if (ctx instanceof ContextRefInstance) { // The context serves happily enough as the lexpad also (provides // the associative bit of the REPR API, mapped to the lexpad). return ctx; } else { throw ExceptionHandling.dieInternal(tc, "ctxlexpad requires an operand with REPR ContextRef"); } } public static SixModelObject curcode(ThreadContext tc) { return tc.curFrame.codeRef; } public static SixModelObject callercode(ThreadContext tc) { CallFrame caller = tc.curFrame.caller; return caller == null ? null : caller.codeRef; } public static long lexprimspec(SixModelObject pad, String key, ThreadContext tc) { if (pad instanceof ContextRefInstance) { StaticCodeInfo sci = ((ContextRefInstance)pad).context.codeRef.staticInfo; if (sci.oTryGetLexicalIdx(key) != null) return StorageSpec.BP_NONE; if (sci.iTryGetLexicalIdx(key) != null) return StorageSpec.BP_INT; if (sci.nTryGetLexicalIdx(key) != null) return StorageSpec.BP_NUM; if (sci.sTryGetLexicalIdx(key) != null) return StorageSpec.BP_STR; throw ExceptionHandling.dieInternal(tc, "Invalid lexical name passed to lexprimspec"); } else { throw ExceptionHandling.dieInternal(tc, "lexprimspec requires an operand with REPR ContextRef"); } } /* Invocation arity check. */ public static CallSiteDescriptor checkarity(CallFrame cf, CallSiteDescriptor cs, Object[] args, int required, int accepted) { if (cs.hasFlattening) cs = cs.explodeFlattening(cf, args); else cf.tc.flatArgs = args; int positionals = cs.numPositionals; if (positionals < required || positionals > accepted && accepted != -1) throw ExceptionHandling.dieInternal(cf.tc, "Wrong number of arguments passed; expected " + required + ".." + accepted + ", but got " + positionals); return cs; } /* Required positional parameter fetching. */ public static SixModelObject posparam_o(CallFrame cf, CallSiteDescriptor cs, Object[] args, int idx) { switch (cs.argFlags[idx]) { case CallSiteDescriptor.ARG_OBJ: return (SixModelObject)args[idx]; case CallSiteDescriptor.ARG_INT: return box_i((long)args[idx], cf.codeRef.staticInfo.compUnit.hllConfig.intBoxType, cf.tc); case CallSiteDescriptor.ARG_NUM: return box_n((double)args[idx], cf.codeRef.staticInfo.compUnit.hllConfig.numBoxType, cf.tc); case CallSiteDescriptor.ARG_STR: return box_s((String)args[idx], cf.codeRef.staticInfo.compUnit.hllConfig.strBoxType, cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } public static long posparam_i(CallFrame cf, CallSiteDescriptor cs, Object[] args, int idx) { switch (cs.argFlags[idx]) { case CallSiteDescriptor.ARG_INT: return (long)args[idx]; case CallSiteDescriptor.ARG_NUM: return (long)(double)args[idx]; case CallSiteDescriptor.ARG_STR: return coerce_s2i((String)args[idx]); case CallSiteDescriptor.ARG_OBJ: return decont(((SixModelObject)args[idx]), cf.tc).get_int(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } public static double posparam_n(CallFrame cf, CallSiteDescriptor cs, Object[] args, int idx) { switch (cs.argFlags[idx]) { case CallSiteDescriptor.ARG_NUM: return (double)args[idx]; case CallSiteDescriptor.ARG_INT: return (double)(long)args[idx]; case CallSiteDescriptor.ARG_STR: return coerce_s2n((String)args[idx]); case CallSiteDescriptor.ARG_OBJ: return decont(((SixModelObject)args[idx]), cf.tc).get_num(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } public static String posparam_s(CallFrame cf, CallSiteDescriptor cs, Object[] args, int idx) { switch (cs.argFlags[idx]) { case CallSiteDescriptor.ARG_STR: return (String)args[idx]; case CallSiteDescriptor.ARG_INT: return coerce_i2s((long)args[idx]); case CallSiteDescriptor.ARG_NUM: return coerce_n2s((double)args[idx]); case CallSiteDescriptor.ARG_OBJ: return decont(((SixModelObject)args[idx]), cf.tc).get_str(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } /* Optional positional parameter fetching. */ public static SixModelObject posparam_opt_o(CallFrame cf, CallSiteDescriptor cs, Object[] args, int idx) { if (idx < cs.numPositionals) { cf.tc.lastParameterExisted = 1; return posparam_o(cf, cs, args, idx); } else { cf.tc.lastParameterExisted = 0; return null; } } public static long posparam_opt_i(CallFrame cf, CallSiteDescriptor cs, Object[] args, int idx) { if (idx < cs.numPositionals) { cf.tc.lastParameterExisted = 1; return posparam_i(cf, cs, args, idx); } else { cf.tc.lastParameterExisted = 0; return 0; } } public static double posparam_opt_n(CallFrame cf, CallSiteDescriptor cs, Object[] args, int idx) { if (idx < cs.numPositionals) { cf.tc.lastParameterExisted = 1; return posparam_n(cf, cs, args, idx); } else { cf.tc.lastParameterExisted = 0; return 0.0; } } public static String posparam_opt_s(CallFrame cf, CallSiteDescriptor cs, Object[] args, int idx) { if (idx < cs.numPositionals) { cf.tc.lastParameterExisted = 1; return posparam_s(cf, cs, args, idx); } else { cf.tc.lastParameterExisted = 0; return null; } } /* Slurpy positional parameter. */ public static SixModelObject posslurpy(ThreadContext tc, CallFrame cf, CallSiteDescriptor cs, Object[] args, int fromIdx) { /* Create result. */ HLLConfig hllConfig = cf.codeRef.staticInfo.compUnit.hllConfig; SixModelObject resType = hllConfig.slurpyArrayType; SixModelObject result = resType.st.REPR.allocate(tc, resType.st); /* Populate it. */ for (int i = fromIdx; i < cs.numPositionals; i++) { switch (cs.argFlags[i]) { case CallSiteDescriptor.ARG_OBJ: result.push_boxed(tc, (SixModelObject)args[i]); break; case CallSiteDescriptor.ARG_INT: result.push_boxed(tc, box_i((long)args[i], hllConfig.intBoxType, tc)); break; case CallSiteDescriptor.ARG_NUM: result.push_boxed(tc, box_n((double)args[i], hllConfig.numBoxType, tc)); break; case CallSiteDescriptor.ARG_STR: result.push_boxed(tc, box_s((String)args[i], hllConfig.strBoxType, tc)); break; } } return result; } /* Required named parameter getting. */ public static SixModelObject namedparam_o(CallFrame cf, CallSiteDescriptor cs, Object[] args, String name) { if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); Integer lookup = cf.workingNameMap.remove(name); if (lookup != null) { switch (lookup & 7) { case CallSiteDescriptor.ARG_OBJ: return (SixModelObject)args[lookup >> 3]; case CallSiteDescriptor.ARG_INT: return box_i((long)args[lookup >> 3], cf.codeRef.staticInfo.compUnit.hllConfig.intBoxType, cf.tc); case CallSiteDescriptor.ARG_NUM: return box_n((double)args[lookup >> 3], cf.codeRef.staticInfo.compUnit.hllConfig.numBoxType, cf.tc); case CallSiteDescriptor.ARG_STR: return box_s((String)args[lookup >> 3], cf.codeRef.staticInfo.compUnit.hllConfig.strBoxType, cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } else throw ExceptionHandling.dieInternal(cf.tc, "Required named argument '" + name + "' not passed"); } public static long namedparam_i(CallFrame cf, CallSiteDescriptor cs, Object[] args, String name) { if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); Integer lookup = cf.workingNameMap.remove(name); if (lookup != null) { switch ((lookup & 7)) { case CallSiteDescriptor.ARG_INT: return (long)args[lookup >> 3]; case CallSiteDescriptor.ARG_NUM: return (long)(double)args[lookup >> 3]; case CallSiteDescriptor.ARG_STR: return coerce_s2i((String)args[lookup >> 3]); case CallSiteDescriptor.ARG_OBJ: return ((SixModelObject)args[lookup >> 3]).get_int(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } else throw ExceptionHandling.dieInternal(cf.tc, "Required named argument '" + name + "' not passed"); } public static double namedparam_n(CallFrame cf, CallSiteDescriptor cs, Object[] args, String name) { if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); Integer lookup = cf.workingNameMap.remove(name); if (lookup != null) { switch ((lookup & 7)) { case CallSiteDescriptor.ARG_NUM: return (double)args[lookup >> 3]; case CallSiteDescriptor.ARG_INT: return (double)(long)args[lookup >> 3]; case CallSiteDescriptor.ARG_STR: return coerce_s2n((String)args[lookup >> 3]); case CallSiteDescriptor.ARG_OBJ: return ((SixModelObject)args[lookup >> 3]).get_num(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } else throw ExceptionHandling.dieInternal(cf.tc, "Required named argument '" + name + "' not passed"); } public static String namedparam_s(CallFrame cf, CallSiteDescriptor cs, Object[] args, String name) { if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); Integer lookup = cf.workingNameMap.remove(name); if (lookup != null) { switch ((lookup & 7)) { case CallSiteDescriptor.ARG_STR: return (String)args[lookup >> 3]; case CallSiteDescriptor.ARG_INT: return coerce_i2s((long)args[lookup >> 3]); case CallSiteDescriptor.ARG_NUM: return coerce_n2s((double)args[lookup >> 3]); case CallSiteDescriptor.ARG_OBJ: return ((SixModelObject)args[lookup >> 3]).get_str(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } else throw ExceptionHandling.dieInternal(cf.tc, "Required named argument '" + name + "' not passed"); } /* Optional named parameter getting. */ public static SixModelObject namedparam_opt_o(CallFrame cf, CallSiteDescriptor cs, Object[] args, String name) { if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); Integer lookup = cf.workingNameMap.remove(name); if (lookup != null) { cf.tc.lastParameterExisted = 1; switch (lookup & 7) { case CallSiteDescriptor.ARG_OBJ: return (SixModelObject)args[lookup >> 3]; case CallSiteDescriptor.ARG_INT: return box_i((long)args[lookup >> 3], cf.codeRef.staticInfo.compUnit.hllConfig.intBoxType, cf.tc); case CallSiteDescriptor.ARG_NUM: return box_n((double)args[lookup >> 3], cf.codeRef.staticInfo.compUnit.hllConfig.numBoxType, cf.tc); case CallSiteDescriptor.ARG_STR: return box_s((String)args[lookup >> 3], cf.codeRef.staticInfo.compUnit.hllConfig.strBoxType, cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } else { cf.tc.lastParameterExisted = 0; return null; } } public static long namedparam_opt_i(CallFrame cf, CallSiteDescriptor cs, Object[] args, String name) { if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); Integer lookup = cf.workingNameMap.remove(name); if (lookup != null) { cf.tc.lastParameterExisted = 1; switch ((lookup & 7)) { case CallSiteDescriptor.ARG_INT: return (long)args[lookup >> 3]; case CallSiteDescriptor.ARG_NUM: return (long)(double)args[lookup >> 3]; case CallSiteDescriptor.ARG_STR: return coerce_s2i((String)args[lookup >> 3]); case CallSiteDescriptor.ARG_OBJ: return ((SixModelObject)args[lookup >> 3]).get_int(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } else { cf.tc.lastParameterExisted = 0; return 0; } } public static double namedparam_opt_n(CallFrame cf, CallSiteDescriptor cs, Object[] args, String name) { if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); Integer lookup = cf.workingNameMap.remove(name); if (lookup != null) { cf.tc.lastParameterExisted = 1; switch ((lookup & 7)) { case CallSiteDescriptor.ARG_NUM: return (double)args[lookup >> 3]; case CallSiteDescriptor.ARG_INT: return (double)(long)args[lookup >> 3]; case CallSiteDescriptor.ARG_STR: return coerce_s2n((String)args[lookup >> 3]); case CallSiteDescriptor.ARG_OBJ: return ((SixModelObject)args[lookup >> 3]).get_num(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } else { cf.tc.lastParameterExisted = 0; return 0.0; } } public static String namedparam_opt_s(CallFrame cf, CallSiteDescriptor cs, Object[] args, String name) { if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); Integer lookup = cf.workingNameMap.remove(name); if (lookup != null) { cf.tc.lastParameterExisted = 1; switch ((lookup & 7)) { case CallSiteDescriptor.ARG_STR: return (String)args[lookup >> 3]; case CallSiteDescriptor.ARG_INT: return coerce_i2s((long)args[lookup >> 3]); case CallSiteDescriptor.ARG_NUM: return coerce_n2s((double)args[lookup >> 3]); case CallSiteDescriptor.ARG_OBJ: return ((SixModelObject)args[lookup >> 3]).get_str(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } else { cf.tc.lastParameterExisted = 0; return null; } } /* Slurpy named parameter. */ public static SixModelObject namedslurpy(ThreadContext tc, CallFrame cf, CallSiteDescriptor cs, Object[] args) { /* Create result. */ HLLConfig hllConfig = cf.codeRef.staticInfo.compUnit.hllConfig; SixModelObject resType = hllConfig.slurpyHashType; SixModelObject result = resType.st.REPR.allocate(tc, resType.st); /* Populate it. */ if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); for (String name : cf.workingNameMap.keySet()) { Integer lookup = cf.workingNameMap.get(name); switch (lookup & 7) { case CallSiteDescriptor.ARG_OBJ: result.bind_key_boxed(tc, name, (SixModelObject)args[lookup >> 3]); break; case CallSiteDescriptor.ARG_INT: result.bind_key_boxed(tc, name, box_i((long)args[lookup >> 3], hllConfig.intBoxType, tc)); break; case CallSiteDescriptor.ARG_NUM: result.bind_key_boxed(tc, name, box_n((double)args[lookup >> 3], hllConfig.numBoxType, tc)); break; case CallSiteDescriptor.ARG_STR: result.bind_key_boxed(tc, name, box_s((String)args[lookup >> 3], hllConfig.strBoxType, tc)); break; } } return result; } /* Return value setting. */ public static void return_o(SixModelObject v, CallFrame cf) { CallFrame caller = cf.caller; if (caller == null) caller = cf.tc.dummyCaller; caller.oRet = v; caller.retType = CallFrame.RET_OBJ; } public static void return_i(long v, CallFrame cf) { CallFrame caller = cf.caller; if (caller == null) caller = cf.tc.dummyCaller; caller.iRet = v; caller.retType = CallFrame.RET_INT; } public static void return_n(double v, CallFrame cf) { CallFrame caller = cf.caller; if (caller == null) caller = cf.tc.dummyCaller; caller.nRet = v; caller.retType = CallFrame.RET_NUM; } public static void return_s(String v, CallFrame cf) { CallFrame caller = cf.caller; if (caller == null) caller = cf.tc.dummyCaller; caller.sRet = v; caller.retType = CallFrame.RET_STR; } /* Get returned result. */ public static SixModelObject result_o(CallFrame cf) { switch (cf.retType) { case CallFrame.RET_INT: return box_i(cf.iRet, cf.codeRef.staticInfo.compUnit.hllConfig.intBoxType, cf.tc); case CallFrame.RET_NUM: return box_n(cf.nRet, cf.codeRef.staticInfo.compUnit.hllConfig.numBoxType, cf.tc); case CallFrame.RET_STR: return box_s(cf.sRet, cf.codeRef.staticInfo.compUnit.hllConfig.strBoxType, cf.tc); default: return cf.oRet; } } public static long result_i(CallFrame cf) { switch (cf.retType) { case CallFrame.RET_INT: return cf.iRet; case CallFrame.RET_NUM: return (long)cf.nRet; case CallFrame.RET_STR: return coerce_s2i(cf.sRet); default: return unbox_i(cf.oRet, cf.tc); } } public static double result_n(CallFrame cf) { switch (cf.retType) { case CallFrame.RET_INT: return (double)cf.iRet; case CallFrame.RET_NUM: return cf.nRet; case CallFrame.RET_STR: return coerce_s2n(cf.sRet); default: return unbox_n(cf.oRet, cf.tc); } } public static String result_s(CallFrame cf) { switch (cf.retType) { case CallFrame.RET_INT: return coerce_i2s(cf.iRet); case CallFrame.RET_NUM: return coerce_n2s(cf.nRet); case CallFrame.RET_STR: return cf.sRet; default: return unbox_s(cf.oRet, cf.tc); } } /* Capture related operations. */ public static SixModelObject usecapture(ThreadContext tc, CallSiteDescriptor cs, Object[] args) { CallCaptureInstance cc = tc.savedCC; cc.descriptor = cs; cc.args = args.clone(); return cc; } public static SixModelObject savecapture(ThreadContext tc, CallSiteDescriptor cs, Object[] args) { SixModelObject CallCapture = tc.gc.CallCapture; CallCaptureInstance cc = (CallCaptureInstance)CallCapture.st.REPR.allocate(tc, CallCapture.st); cc.descriptor = cs; cc.args = args.clone(); return cc; } public static long captureposelems(SixModelObject obj, ThreadContext tc) { if (obj instanceof CallCaptureInstance) return ((CallCaptureInstance)obj).descriptor.numPositionals; else throw ExceptionHandling.dieInternal(tc, "captureposelems requires a CallCapture"); } public static SixModelObject captureposarg(SixModelObject obj, long idx, ThreadContext tc) { if (obj instanceof CallCaptureInstance) { CallCaptureInstance cc = (CallCaptureInstance)obj; int i = (int)idx; switch (cc.descriptor.argFlags[i]) { case CallSiteDescriptor.ARG_OBJ: return (SixModelObject)cc.args[i]; case CallSiteDescriptor.ARG_INT: return box_i((long)cc.args[i], tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.intBoxType, tc); case CallSiteDescriptor.ARG_NUM: return box_n((double)cc.args[i], tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.numBoxType, tc); case CallSiteDescriptor.ARG_STR: return box_s((String)cc.args[i], tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.strBoxType, tc); default: throw ExceptionHandling.dieInternal(tc, "Invalid positional argument access from capture"); } } else { throw ExceptionHandling.dieInternal(tc, "captureposarg requires a CallCapture"); } } public static long captureexistsnamed(SixModelObject obj, String name, ThreadContext tc) { if (obj instanceof CallCaptureInstance) { CallCaptureInstance cc = (CallCaptureInstance)obj; return cc.descriptor.nameMap.containsKey(name) ? 1 : 0; } else { throw ExceptionHandling.dieInternal(tc, "capturehasnameds requires a CallCapture"); } } public static long capturehasnameds(SixModelObject obj, ThreadContext tc) { if (obj instanceof CallCaptureInstance) { CallCaptureInstance cc = (CallCaptureInstance)obj; return cc.descriptor.names == null ? 0 : 1; } else { throw ExceptionHandling.dieInternal(tc, "capturehasnameds requires a CallCapture"); } } public static long captureposprimspec(SixModelObject obj, long idx, ThreadContext tc) { if (obj instanceof CallCaptureInstance) { CallCaptureInstance cc = (CallCaptureInstance)obj; switch (cc.descriptor.argFlags[(int)idx]) { case CallSiteDescriptor.ARG_INT: return StorageSpec.BP_INT; case CallSiteDescriptor.ARG_NUM: return StorageSpec.BP_NUM; case CallSiteDescriptor.ARG_STR: return StorageSpec.BP_STR; default: return StorageSpec.BP_NONE; } } else { throw ExceptionHandling.dieInternal(tc, "captureposarg requires a CallCapture"); } } /* Invocation. */ public static final CallSiteDescriptor emptyCallSite = new CallSiteDescriptor(new byte[0], null); public static final Object[] emptyArgList = new Object[0]; public static final CallSiteDescriptor invocantCallSite = new CallSiteDescriptor(new byte[] { CallSiteDescriptor.ARG_OBJ }, null); public static final CallSiteDescriptor storeCallSite = new CallSiteDescriptor(new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); public static final CallSiteDescriptor findmethCallSite = new CallSiteDescriptor(new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_STR }, null); public static final CallSiteDescriptor typeCheckCallSite = new CallSiteDescriptor(new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); public static final CallSiteDescriptor howObjCallSite = new CallSiteDescriptor(new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); public static void invokeLexotic(SixModelObject invokee, CallSiteDescriptor csd, Object[] args, ThreadContext tc) { LexoticException throwee = tc.theLexotic; throwee.target = ((LexoticInstance)invokee).target; switch (csd.argFlags[0]) { case CallSiteDescriptor.ARG_OBJ: throwee.payload = (SixModelObject)args[0]; break; case CallSiteDescriptor.ARG_INT: throwee.payload = box_i((long)args[0], tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.intBoxType, tc); break; case CallSiteDescriptor.ARG_NUM: throwee.payload = box_n((double)args[0], tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.numBoxType, tc); break; case CallSiteDescriptor.ARG_STR: throwee.payload = box_s((String)args[0], tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.strBoxType, tc); break; default: throw ExceptionHandling.dieInternal(tc, "Invalid lexotic invocation argument"); } throw throwee; } public static void invoke(SixModelObject invokee, int callsiteIndex, Object[] args, ThreadContext tc) throws Exception { // TODO Find a smarter way to do this without all the pointer chasing. if (callsiteIndex >= 0) invokeDirect(tc, invokee, tc.curFrame.codeRef.staticInfo.compUnit.callSites[callsiteIndex], args); else invokeDirect(tc, invokee, emptyCallSite, args); } public static void invokeArgless(ThreadContext tc, SixModelObject invokee) { invokeDirect(tc, invokee, emptyCallSite, new Object[0]); } public static void invokeMain(ThreadContext tc, SixModelObject invokee, String prog, String[] argv) { /* Build argument list from argv. */ SixModelObject Str = ((CodeRef)invokee).staticInfo.compUnit.hllConfig.strBoxType; Object[] args = new Object[argv.length + 1]; byte[] callsite = new byte[argv.length + 1]; args[0] = box_s(prog, Str, tc); callsite[0] = CallSiteDescriptor.ARG_OBJ; for (int i = 0; i < argv.length; i++) { args[i + 1] = box_s(argv[i], Str, tc); callsite[i + 1] = CallSiteDescriptor.ARG_OBJ; } /* Invoke with the descriptor and arg list. */ invokeDirect(tc, invokee, new CallSiteDescriptor(callsite, null), args); } public static void invokeDirect(ThreadContext tc, SixModelObject invokee, CallSiteDescriptor csd, Object[] args) { invokeDirect(tc, invokee, csd, true, args); } public static void invokeDirect(ThreadContext tc, SixModelObject invokee, CallSiteDescriptor csd, boolean barrier, Object[] args) { // If it's lexotic, throw the exception right off. if (invokee instanceof LexoticInstance) { invokeLexotic(invokee, csd, args, tc); } // Otherwise, get the code ref. CodeRef cr; if (invokee instanceof CodeRef) { cr = (CodeRef)invokee; } else { InvocationSpec is = invokee.st.InvocationSpec; if (is == null) throw ExceptionHandling.dieInternal(tc, "Can not invoke this object"); if (is.ClassHandle != null) cr = (CodeRef)invokee.get_attribute_boxed(tc, is.ClassHandle, is.AttrName, is.Hint); else { cr = (CodeRef)is.InvocationHandler; csd = csd.injectInvokee(tc, args, invokee); args = tc.flatArgs; } } try { ArgsExpectation.invokeByExpectation(tc, cr, csd, args); } catch (ControlException e) { if (barrier && (e instanceof SaveStackException)) ExceptionHandling.dieInternal(tc, "control operator crossed continuation barrier"); throw e; } catch (Throwable e) { ExceptionHandling.dieInternal(tc, e); } } public static SixModelObject invokewithcapture(SixModelObject invokee, SixModelObject capture, ThreadContext tc) throws Exception { if (capture instanceof CallCaptureInstance) { CallCaptureInstance cc = (CallCaptureInstance)capture; invokeDirect(tc, invokee, cc.descriptor, cc.args); return result_o(tc.curFrame); } else { throw ExceptionHandling.dieInternal(tc, "invokewithcapture requires a CallCapture"); } } /* Lexotic. */ public static SixModelObject lexotic(long target) { LexoticInstance res = new LexoticInstance(); res.target = target; return res; } public static SixModelObject lexotic_tc(long target, ThreadContext tc) { LexoticInstance res = new LexoticInstance(); res.st = tc.gc.Lexotic.st; res.target = target; return res; } /* Multi-dispatch cache. */ public static SixModelObject multicacheadd(SixModelObject cache, SixModelObject capture, SixModelObject result, ThreadContext tc) { if (!(cache instanceof MultiCacheInstance)) cache = tc.gc.MultiCache.st.REPR.allocate(tc, tc.gc.MultiCache.st); ((MultiCacheInstance)cache).add((CallCaptureInstance)capture, result, tc); return cache; } public static SixModelObject multicachefind(SixModelObject cache, SixModelObject capture, ThreadContext tc) { if (cache instanceof MultiCacheInstance) return ((MultiCacheInstance)cache).lookup((CallCaptureInstance)capture, tc); else return null; } /* Basic 6model operations. */ public static SixModelObject what(SixModelObject o) { return o.st.WHAT; } public static SixModelObject how(SixModelObject o) { return o.st.HOW; } public static SixModelObject who(SixModelObject o) { return o.st.WHO; } public static long where(SixModelObject o) { return o.hashCode(); } public static SixModelObject setwho(SixModelObject o, SixModelObject who) { o.st.WHO = who; return o; } public static SixModelObject what(SixModelObject o, ThreadContext tc) { return decont(o, tc).st.WHAT; } public static SixModelObject how(SixModelObject o, ThreadContext tc) { return decont(o, tc).st.HOW; } public static SixModelObject who(SixModelObject o, ThreadContext tc) { return decont(o, tc).st.WHO; } public static long where(SixModelObject o, ThreadContext tc) { return o.hashCode(); } public static SixModelObject setwho(SixModelObject o, SixModelObject who, ThreadContext tc) { decont(o, tc).st.WHO = who; return o; } public static SixModelObject rebless(SixModelObject obj, SixModelObject newType, ThreadContext tc) { obj = decont(obj, tc); newType = decont(newType, tc); if (obj.st != newType.st) { obj.st.REPR.change_type(tc, obj, newType); if (obj.sc != null) scwbObject(tc, obj); } return obj; } public static SixModelObject create(SixModelObject obj, ThreadContext tc) { SixModelObject res = obj.st.REPR.allocate(tc, obj.st); return res; } public static SixModelObject clone(SixModelObject obj, ThreadContext tc) { return decont(obj, tc).clone(tc); } public static long isconcrete(SixModelObject obj, ThreadContext tc) { return obj == null || decont(obj, tc) instanceof TypeObject ? 0 : 1; } public static SixModelObject knowhow(ThreadContext tc) { return tc.gc.KnowHOW; } public static SixModelObject knowhowattr(ThreadContext tc) { return tc.gc.KnowHOWAttribute; } public static SixModelObject bootint(ThreadContext tc) { return tc.gc.BOOTInt; } public static SixModelObject bootnum(ThreadContext tc) { return tc.gc.BOOTNum; } public static SixModelObject bootstr(ThreadContext tc) { return tc.gc.BOOTStr; } public static SixModelObject bootarray(ThreadContext tc) { return tc.gc.BOOTArray; } public static SixModelObject bootintarray(ThreadContext tc) { return tc.gc.BOOTIntArray; } public static SixModelObject bootnumarray(ThreadContext tc) { return tc.gc.BOOTNumArray; } public static SixModelObject bootstrarray(ThreadContext tc) { return tc.gc.BOOTStrArray; } public static SixModelObject boothash(ThreadContext tc) { return tc.gc.BOOTHash; } public static SixModelObject hlllist(ThreadContext tc) { return tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.listType; } public static SixModelObject hllhash(ThreadContext tc) { return tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.hashType; } public static SixModelObject findmethod(ThreadContext tc, SixModelObject invocant, String name) { if (invocant == null) throw ExceptionHandling.dieInternal(tc, "Can not call method '" + name + "' on a null object"); invocant = decont(invocant, tc); SixModelObject meth = invocant.st.MethodCache.get(name); if (meth == null) throw ExceptionHandling.dieInternal(tc, "Method '" + name + "' not found for invocant of class '" + typeName(invocant, tc) + "'"); return meth; } public static SixModelObject findmethod(SixModelObject invocant, String name, ThreadContext tc) { if (invocant == null) throw ExceptionHandling.dieInternal(tc, "Can not call method '" + name + "' on a null object"); invocant = decont(invocant, tc); Map<String, SixModelObject> cache = invocant.st.MethodCache; /* Try the by-name method cache, if the HOW published one. */ if (cache != null) { SixModelObject found = cache.get(name); if (found != null) return found; if ((invocant.st.ModeFlags & STable.METHOD_CACHE_AUTHORITATIVE) != 0) return null; } /* Otherwise delegate to the HOW. */ SixModelObject how = invocant.st.HOW; SixModelObject find_method = findmethod(how, "find_method", tc); invokeDirect(tc, find_method, findmethCallSite, new Object[] { how, invocant, name }); return result_o(tc.curFrame); } public static String typeName(SixModelObject invocant, ThreadContext tc) { invocant = decont(invocant, tc); SixModelObject how = invocant.st.HOW; SixModelObject nameMeth = findmethod(tc, how, "name"); invokeDirect(tc, nameMeth, howObjCallSite, new Object[] { how, invocant }); return result_s(tc.curFrame); } public static long can(SixModelObject invocant, String name, ThreadContext tc) { return findmethod(invocant, name, tc) == null ? 0 : 1; } public static long eqaddr(SixModelObject a, SixModelObject b) { return a == b ? 1 : 0; } public static long isnull(SixModelObject obj) { return obj == null ? 1 : 0; } public static long isnull_s(String str) { return str == null ? 1 : 0; } public static String reprname(SixModelObject obj) { return obj.st.REPR.name; } public static SixModelObject newtype(SixModelObject how, String reprname, ThreadContext tc) { return REPRRegistry.getByName(reprname).type_object_for(tc, decont(how, tc)); } public static SixModelObject composetype(SixModelObject obj, SixModelObject reprinfo, ThreadContext tc) { obj.st.REPR.compose(tc, obj.st, reprinfo); return obj; } public static SixModelObject setmethcache(SixModelObject obj, SixModelObject meths, ThreadContext tc) { SixModelObject iter = iter(meths, tc); HashMap<String, SixModelObject> cache = new HashMap<String, SixModelObject>(); while (istrue(iter, tc) != 0) { SixModelObject cur = iter.shift_boxed(tc); cache.put(iterkey_s(cur, tc), iterval(cur, tc)); } obj.st.MethodCache = cache; if (obj.st.sc != null) scwbSTable(tc, obj.st); return obj; } public static SixModelObject setmethcacheauth(SixModelObject obj, long flag, ThreadContext tc) { int newFlags = obj.st.ModeFlags & (~STable.METHOD_CACHE_AUTHORITATIVE); if (flag != 0) newFlags = newFlags | STable.METHOD_CACHE_AUTHORITATIVE; obj.st.ModeFlags = newFlags; if (obj.st.sc != null) scwbSTable(tc, obj.st); return obj; } public static SixModelObject settypecache(SixModelObject obj, SixModelObject types, ThreadContext tc) { long elems = types.elems(tc); SixModelObject[] cache = new SixModelObject[(int)elems]; for (long i = 0; i < elems; i++) cache[(int)i] = types.at_pos_boxed(tc, i); obj.st.TypeCheckCache = cache; if (obj.st.sc != null) scwbSTable(tc, obj.st); return obj; } public static SixModelObject settypecheckmode(SixModelObject obj, long mode, ThreadContext tc) { obj.st.ModeFlags = (int)mode | (obj.st.ModeFlags & (~STable.TYPE_CHECK_CACHE_FLAG_MASK)); if (obj.st.sc != null) scwbSTable(tc, obj.st); return obj; } public static long objprimspec(SixModelObject obj, ThreadContext tc) { return obj.st.REPR.get_storage_spec(tc, obj.st).boxed_primitive; } public static SixModelObject setinvokespec(SixModelObject obj, SixModelObject ch, String name, SixModelObject invocationHandler, ThreadContext tc) { InvocationSpec is = new InvocationSpec(); is.ClassHandle = ch; is.AttrName = name; is.Hint = STable.NO_HINT; is.InvocationHandler = invocationHandler; obj.st.InvocationSpec = is; return obj; } public static long isinvokable(SixModelObject obj, ThreadContext tc) { return obj instanceof CodeRef || obj.st.InvocationSpec != null ? 1 : 0; } public static long istype(SixModelObject obj, SixModelObject type, ThreadContext tc) { return istype_nodecont(decont(obj, tc), decont(type, tc), tc); } public static long istype_nodecont(SixModelObject obj, SixModelObject type, ThreadContext tc) { /* Null always type checks false. */ if (obj == null) return 0; /* Start by considering cache. */ int typeCheckMode = type.st.ModeFlags & STable.TYPE_CHECK_CACHE_FLAG_MASK; SixModelObject[] cache = obj.st.TypeCheckCache; if (cache != null) { /* We have the cache, so just look for the type object we * want to be in there. */ for (int i = 0; i < cache.length; i++) if (cache[i] == type) return 1; /* If the type check cache is definitive, we're done. */ if ((typeCheckMode & STable.TYPE_CHECK_CACHE_THEN_METHOD) == 0 && (typeCheckMode & STable.TYPE_CHECK_NEEDS_ACCEPTS) == 0) return 0; } /* If we get here, need to call .^type_check on the value we're * checking. */ if (cache == null || (typeCheckMode & STable.TYPE_CHECK_CACHE_THEN_METHOD) != 0) { SixModelObject tcMeth = findmethod(obj.st.HOW, "type_check", tc); if (tcMeth == null) return 0; /* TODO: Review why the following busts stuff. */ /*throw ExceptionHandling.dieInternal(tc, "No type check cache and no type_check method in meta-object");*/ invokeDirect(tc, tcMeth, typeCheckCallSite, new Object[] { obj.st.HOW, obj, type }); if (tc.curFrame.retType == CallFrame.RET_INT) { if (result_i(tc.curFrame) != 0) return 1; } else { if (istrue(result_o(tc.curFrame), tc) != 0) return 1; } } /* If the flag to call .accepts_type on the target value is set, do so. */ if ((typeCheckMode & STable.TYPE_CHECK_NEEDS_ACCEPTS) != 0) { SixModelObject atMeth = findmethod(type.st.HOW, "accepts_type", tc); if (atMeth == null) throw ExceptionHandling.dieInternal(tc, "Expected accepts_type method, but none found in meta-object"); invokeDirect(tc, atMeth, typeCheckCallSite, new Object[] { type.st.HOW, type, obj }); return istrue(result_o(tc.curFrame), tc); } /* If we get here, type check failed. */ return 0; } /* Box/unbox operations. */ public static SixModelObject box_i(long value, SixModelObject type, ThreadContext tc) { SixModelObject res = type.st.REPR.allocate(tc, type.st); res.set_int(tc, value); return res; } public static SixModelObject box_n(double value, SixModelObject type, ThreadContext tc) { SixModelObject res = type.st.REPR.allocate(tc, type.st); res.set_num(tc, value); return res; } public static SixModelObject box_s(String value, SixModelObject type, ThreadContext tc) { SixModelObject res = type.st.REPR.allocate(tc, type.st); res.set_str(tc, value); return res; } public static long unbox_i(SixModelObject obj, ThreadContext tc) { return decont(obj, tc).get_int(tc); } public static double unbox_n(SixModelObject obj, ThreadContext tc) { return decont(obj, tc).get_num(tc); } public static String unbox_s(SixModelObject obj, ThreadContext tc) { return decont(obj, tc).get_str(tc); } public static long isint(SixModelObject obj, ThreadContext tc) { StorageSpec ss = decont(obj, tc).st.REPR.get_storage_spec(tc, obj.st); return (ss.can_box & StorageSpec.CAN_BOX_INT) == 0 ? 0 : 1; } public static long isnum(SixModelObject obj, ThreadContext tc) { StorageSpec ss = decont(obj, tc).st.REPR.get_storage_spec(tc, obj.st); return (ss.can_box & StorageSpec.CAN_BOX_NUM) == 0 ? 0 : 1; } public static long isstr(SixModelObject obj, ThreadContext tc) { StorageSpec ss = decont(obj, tc).st.REPR.get_storage_spec(tc, obj.st); return (ss.can_box & StorageSpec.CAN_BOX_STR) == 0 ? 0 : 1; } /* Attribute operations. */ public static SixModelObject getattr(SixModelObject obj, SixModelObject ch, String name, ThreadContext tc) { return obj.get_attribute_boxed(tc, decont(ch, tc), name, STable.NO_HINT); } public static long getattr_i(SixModelObject obj, SixModelObject ch, String name, ThreadContext tc) { obj.get_attribute_native(tc, decont(ch, tc), name, STable.NO_HINT); if (tc.native_type == ThreadContext.NATIVE_INT) return tc.native_i; else throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native int"); } public static double getattr_n(SixModelObject obj, SixModelObject ch, String name, ThreadContext tc) { obj.get_attribute_native(tc, decont(ch, tc), name, STable.NO_HINT); if (tc.native_type == ThreadContext.NATIVE_NUM) return tc.native_n; else throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native num"); } public static String getattr_s(SixModelObject obj, SixModelObject ch, String name, ThreadContext tc) { obj.get_attribute_native(tc, decont(ch, tc), name, STable.NO_HINT); if (tc.native_type == ThreadContext.NATIVE_STR) return tc.native_s; else throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native str"); } public static SixModelObject getattr(SixModelObject obj, SixModelObject ch, String name, long hint, ThreadContext tc) { return obj.get_attribute_boxed(tc, decont(ch, tc), name, hint); } public static long getattr_i(SixModelObject obj, SixModelObject ch, String name, long hint, ThreadContext tc) { obj.get_attribute_native(tc, decont(ch, tc), name, hint); if (tc.native_type == ThreadContext.NATIVE_INT) return tc.native_i; else throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native int"); } public static double getattr_n(SixModelObject obj, SixModelObject ch, String name, long hint, ThreadContext tc) { obj.get_attribute_native(tc, decont(ch, tc), name, hint); if (tc.native_type == ThreadContext.NATIVE_NUM) return tc.native_n; else throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native num"); } public static String getattr_s(SixModelObject obj, SixModelObject ch, String name, long hint, ThreadContext tc) { obj.get_attribute_native(tc, decont(ch, tc), name, hint); if (tc.native_type == ThreadContext.NATIVE_STR) return tc.native_s; else throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native str"); } public static SixModelObject bindattr(SixModelObject obj, SixModelObject ch, String name, SixModelObject value, ThreadContext tc) { obj.bind_attribute_boxed(tc, decont(ch, tc), name, STable.NO_HINT, value); if (obj.sc != null) scwbObject(tc, obj); return value; } public static long bindattr_i(SixModelObject obj, SixModelObject ch, String name, long value, ThreadContext tc) { tc.native_i = value; obj.bind_attribute_native(tc, decont(ch, tc), name, STable.NO_HINT); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native int"); if (obj.sc != null) scwbObject(tc, obj); return value; } public static double bindattr_n(SixModelObject obj, SixModelObject ch, String name, double value, ThreadContext tc) { tc.native_n = value; obj.bind_attribute_native(tc, decont(ch, tc), name, STable.NO_HINT); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native num"); if (obj.sc != null) scwbObject(tc, obj); return value; } public static String bindattr_s(SixModelObject obj, SixModelObject ch, String name, String value, ThreadContext tc) { tc.native_s = value; obj.bind_attribute_native(tc, decont(ch, tc), name, STable.NO_HINT); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native str"); if (obj.sc != null) scwbObject(tc, obj); return value; } public static SixModelObject bindattr(SixModelObject obj, SixModelObject ch, String name, SixModelObject value, long hint, ThreadContext tc) { obj.bind_attribute_boxed(tc, decont(ch, tc), name, hint, value); if (obj.sc != null) scwbObject(tc, obj); return value; } public static long bindattr_i(SixModelObject obj, SixModelObject ch, String name, long value, long hint, ThreadContext tc) { tc.native_i = value; obj.bind_attribute_native(tc, decont(ch, tc), name, hint); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native int"); if (obj.sc != null) scwbObject(tc, obj); return value; } public static double bindattr_n(SixModelObject obj, SixModelObject ch, String name, double value, long hint, ThreadContext tc) { tc.native_n = value; obj.bind_attribute_native(tc, decont(ch, tc), name, hint); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native num"); if (obj.sc != null) scwbObject(tc, obj); return value; } public static String bindattr_s(SixModelObject obj, SixModelObject ch, String name, String value, long hint, ThreadContext tc) { tc.native_s = value; obj.bind_attribute_native(tc, decont(ch, tc), name, hint); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native str"); if (obj.sc != null) scwbObject(tc, obj); return value; } public static long attrinited(SixModelObject obj, SixModelObject ch, String name, ThreadContext tc) { return obj.is_attribute_initialized(tc, decont(ch, tc), name, STable.NO_HINT); } public static long attrhintfor(SixModelObject ch, String name, ThreadContext tc) { ch = decont(ch, tc); return ch.st.REPR.hint_for(tc, ch.st, ch, name); } /* Positional operations. */ public static SixModelObject atpos(SixModelObject arr, long idx, ThreadContext tc) { return arr.at_pos_boxed(tc, idx); } public static long atpos_i(SixModelObject arr, long idx, ThreadContext tc) { arr.at_pos_native(tc, idx); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "This is not a native int array"); return tc.native_i; } public static double atpos_n(SixModelObject arr, long idx, ThreadContext tc) { arr.at_pos_native(tc, idx); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "This is not a native num array"); return tc.native_n; } public static String atpos_s(SixModelObject arr, long idx, ThreadContext tc) { arr.at_pos_native(tc, idx); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "This is not a native str array"); return tc.native_s; } public static SixModelObject bindpos(SixModelObject arr, long idx, SixModelObject value, ThreadContext tc) { arr.bind_pos_boxed(tc, idx, value); if (arr.sc != null) { /*new Exception("bindpos").printStackTrace(); */ scwbObject(tc, arr); } return value; } public static long bindpos_i(SixModelObject arr, long idx, long value, ThreadContext tc) { tc.native_i = value; arr.bind_pos_native(tc, idx); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "This is not a native int array"); if (arr.sc != null) { /*new Exception("bindpos_i").printStackTrace(); */ scwbObject(tc, arr); } return value; } public static double bindpos_n(SixModelObject arr, long idx, double value, ThreadContext tc) { tc.native_n = value; arr.bind_pos_native(tc, idx); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "This is not a native num array"); if (arr.sc != null) { /*new Exception("bindpos_n").printStackTrace(); */ scwbObject(tc, arr); } return value; } public static String bindpos_s(SixModelObject arr, long idx, String value, ThreadContext tc) { tc.native_s = value; arr.bind_pos_native(tc, idx); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "This is not a native str array"); if (arr.sc != null) { /*new Exception("bindpos_s").printStackTrace(); */ scwbObject(tc, arr); } return value; } public static SixModelObject push(SixModelObject arr, SixModelObject value, ThreadContext tc) { arr.push_boxed(tc, value); if (arr.sc != null) scwbObject(tc, arr); return value; } public static long push_i(SixModelObject arr, long value, ThreadContext tc) { tc.native_i = value; arr.push_native(tc); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "This is not a native int array"); if (arr.sc != null) scwbObject(tc, arr); return value; } public static double push_n(SixModelObject arr, double value, ThreadContext tc) { tc.native_n = value; arr.push_native(tc); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "This is not a native num array"); if (arr.sc != null) scwbObject(tc, arr); return value; } public static String push_s(SixModelObject arr, String value, ThreadContext tc) { tc.native_s = value; arr.push_native(tc); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "This is not a native str array"); if (arr.sc != null) scwbObject(tc, arr); return value; } public static SixModelObject pop(SixModelObject arr, ThreadContext tc) { return arr.pop_boxed(tc); } public static long pop_i(SixModelObject arr, ThreadContext tc) { arr.pop_native(tc); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "This is not a native int array"); return tc.native_i; } public static double pop_n(SixModelObject arr, ThreadContext tc) { arr.pop_native(tc); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "This is not a native num array"); return tc.native_n; } public static String pop_s(SixModelObject arr, ThreadContext tc) { arr.pop_native(tc); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "This is not a native str array"); return tc.native_s; } public static SixModelObject unshift(SixModelObject arr, SixModelObject value, ThreadContext tc) { arr.unshift_boxed(tc, value); return value; } public static long unshift_i(SixModelObject arr, long value, ThreadContext tc) { tc.native_i = value; arr.unshift_native(tc); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "This is not a native int array"); return value; } public static double unshift_n(SixModelObject arr, double value, ThreadContext tc) { tc.native_n = value; arr.unshift_native(tc); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "This is not a native num array"); return value; } public static String unshift_s(SixModelObject arr, String value, ThreadContext tc) { tc.native_s = value; arr.unshift_native(tc); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "This is not a native str array"); return value; } public static SixModelObject shift(SixModelObject arr, ThreadContext tc) { return arr.shift_boxed(tc); } public static long shift_i(SixModelObject arr, ThreadContext tc) { arr.shift_native(tc); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "This is not a native int array"); return tc.native_i; } public static double shift_n(SixModelObject arr, ThreadContext tc) { arr.shift_native(tc); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "This is not a native num array"); return tc.native_n; } public static String shift_s(SixModelObject arr, ThreadContext tc) { arr.shift_native(tc); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "This is not a native str array"); return tc.native_s; } public static SixModelObject splice(SixModelObject arr, SixModelObject from, long offset, long count, ThreadContext tc) { arr.splice(tc, from, offset, count); return arr; } /* Associative operations. */ public static SixModelObject atkey(SixModelObject hash, String key, ThreadContext tc) { return hash.at_key_boxed(tc, key); } public static long atkey_i(SixModelObject hash, String key, ThreadContext tc) { hash.at_key_native(tc, key); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "This is not a native int hash"); return tc.native_i; } public static double atkey_n(SixModelObject hash, String key, ThreadContext tc) { hash.at_key_native(tc, key); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "This is not a native num hash"); return tc.native_n; } public static String atkey_s(SixModelObject hash, String key, ThreadContext tc) { hash.at_key_native(tc, key); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "This is not a native str hash"); return tc.native_s; } public static SixModelObject bindkey(SixModelObject hash, String key, SixModelObject value, ThreadContext tc) { hash.bind_key_boxed(tc, key, value); if (hash.sc != null) scwbObject(tc, hash); return value; } public static long bindkey_i(SixModelObject hash, String key, long value, ThreadContext tc) { tc.native_i = value; hash.bind_key_native(tc, key); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "This is not a native int hash"); if (hash.sc != null) scwbObject(tc, hash); return value; } public static double bindkey_n(SixModelObject hash, String key, double value, ThreadContext tc) { tc.native_n = value; hash.bind_key_native(tc, key); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "This is not a native num hash"); if (hash.sc != null) scwbObject(tc, hash); return value; } public static String bindkey_s(SixModelObject hash, String key, String value, ThreadContext tc) { tc.native_s = value; hash.bind_key_native(tc, key); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "This is not a native str hash"); if (hash.sc != null) scwbObject(tc, hash); return value; } public static long existskey(SixModelObject hash, String key, ThreadContext tc) { return hash.exists_key(tc, key); } public static SixModelObject deletekey(SixModelObject hash, String key, ThreadContext tc) { hash.delete_key(tc, key); if (hash.sc != null) scwbObject(tc, hash); return hash; } /* Terms */ public static long time_i() { return (long) (System.currentTimeMillis() / 1000); } public static double time_n() { return System.currentTimeMillis() / 1000.0; } /* Aggregate operations. */ public static long elems(SixModelObject agg, ThreadContext tc) { return agg.elems(tc); } public static SixModelObject setelems(SixModelObject agg, long elems, ThreadContext tc) { agg.set_elems(tc, elems); return agg; } public static long existspos(SixModelObject agg, long key, ThreadContext tc) { return agg.exists_pos(tc, key); } public static long islist(SixModelObject obj, ThreadContext tc) { return obj != null && obj.st.REPR instanceof VMArray ? 1 : 0; } public static long ishash(SixModelObject obj, ThreadContext tc) { return obj != null && obj.st.REPR instanceof VMHash ? 1 : 0; } /* Container operations. */ public static SixModelObject setcontspec(SixModelObject obj, String confname, SixModelObject confarg, ThreadContext tc) { if (obj.st.ContainerSpec != null) ExceptionHandling.dieInternal(tc, "Cannot change a type's container specification"); ContainerConfigurer cc = tc.gc.contConfigs.get(confname); if (cc == null) ExceptionHandling.dieInternal(tc, "No such container spec " + confname); cc.setContainerSpec(tc, obj.st); cc.configureContainerSpec(tc, obj.st, confarg); return obj; } public static long iscont(SixModelObject obj) { return obj == null || obj.st.ContainerSpec == null ? 0 : 1; } public static SixModelObject decont(SixModelObject obj, ThreadContext tc) { if (obj == null) return null; ContainerSpec cs = obj.st.ContainerSpec; return cs == null || obj instanceof TypeObject ? obj : cs.fetch(tc, obj); } public static SixModelObject assign(SixModelObject cont, SixModelObject value, ThreadContext tc) { ContainerSpec cs = cont.st.ContainerSpec; if (cs != null) cs.store(tc, cont, decont(value, tc)); else ExceptionHandling.dieInternal(tc, "Cannot assign to an immutable value"); return cont; } public static SixModelObject assignunchecked(SixModelObject cont, SixModelObject value, ThreadContext tc) { ContainerSpec cs = cont.st.ContainerSpec; if (cs != null) cs.storeUnchecked(tc, cont, decont(value, tc)); else ExceptionHandling.dieInternal(tc, "Cannot assign to an immutable value"); return cont; } /* Iteration. */ public static SixModelObject iter(SixModelObject agg, ThreadContext tc) { if (agg.st.REPR instanceof VMArray) { SixModelObject iterType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.arrayIteratorType; VMIterInstance iter = (VMIterInstance)iterType.st.REPR.allocate(tc, iterType.st); iter.target = agg; iter.idx = -1; iter.limit = agg.elems(tc); switch (agg.st.REPR.get_value_storage_spec(tc, agg.st).boxed_primitive) { case StorageSpec.BP_INT: iter.iterMode = VMIterInstance.MODE_ARRAY_INT; break; case StorageSpec.BP_NUM: iter.iterMode = VMIterInstance.MODE_ARRAY_NUM; break; case StorageSpec.BP_STR: iter.iterMode = VMIterInstance.MODE_ARRAY_STR; break; default: iter.iterMode = VMIterInstance.MODE_ARRAY; } return iter; } else if (agg.st.REPR instanceof VMHash) { SixModelObject iterType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.hashIteratorType; VMIterInstance iter = (VMIterInstance)iterType.st.REPR.allocate(tc, iterType.st); iter.target = agg; iter.hashKeyIter = ((VMHashInstance)agg).storage.keySet().iterator(); iter.iterMode = VMIterInstance.MODE_HASH; return iter; } else if (agg.st.REPR instanceof ContextRef) { /* Fake up a VMHash and then get its iterator. */ SixModelObject BOOTHash = tc.gc.BOOTHash; SixModelObject hash = BOOTHash.st.REPR.allocate(tc, BOOTHash.st); /* TODO: don't cheat and just shove the nulls in. It's enough for * the initial use case of this, though. */ StaticCodeInfo sci = ((ContextRefInstance)agg).context.codeRef.staticInfo; if (sci.oLexicalNames != null) { for (int i = 0; i < sci.oLexicalNames.length; i++) hash.bind_key_boxed(tc, sci.oLexicalNames[i], null); } if (sci.iLexicalNames != null) { for (int i = 0; i < sci.iLexicalNames.length; i++) hash.bind_key_boxed(tc, sci.iLexicalNames[i], null); } if (sci.nLexicalNames != null) { for (int i = 0; i < sci.nLexicalNames.length; i++) hash.bind_key_boxed(tc, sci.nLexicalNames[i], null); } if (sci.sLexicalNames != null) { for (int i = 0; i < sci.sLexicalNames.length; i++) hash.bind_key_boxed(tc, sci.sLexicalNames[i], null); } return iter(hash, tc); } else { throw ExceptionHandling.dieInternal(tc, "Can only use iter with representation VMArray and VMHash"); } } public static String iterkey_s(SixModelObject obj, ThreadContext tc) { return ((VMIterInstance)obj).key_s(tc); } public static SixModelObject iterval(SixModelObject obj, ThreadContext tc) { return ((VMIterInstance)obj).val(tc); } /* Boolification operations. */ public static SixModelObject setboolspec(SixModelObject obj, long mode, SixModelObject method, ThreadContext tc) { BoolificationSpec bs = new BoolificationSpec(); bs.Mode = (int)mode; bs.Method = method; obj.st.BoolificationSpec = bs; return obj; } public static long istrue(SixModelObject obj, ThreadContext tc) { obj = decont(obj, tc); BoolificationSpec bs = obj.st.BoolificationSpec; switch (bs == null ? BoolificationSpec.MODE_NOT_TYPE_OBJECT : bs.Mode) { case BoolificationSpec.MODE_CALL_METHOD: invokeDirect(tc, bs.Method, invocantCallSite, new Object[] { obj }); return istrue(result_o(tc.curFrame), tc); case BoolificationSpec.MODE_UNBOX_INT: return obj instanceof TypeObject || obj.get_int(tc) == 0 ? 0 : 1; case BoolificationSpec.MODE_UNBOX_NUM: return obj instanceof TypeObject || obj.get_num(tc) == 0.0 ? 0 : 1; case BoolificationSpec.MODE_UNBOX_STR_NOT_EMPTY: return obj instanceof TypeObject || obj.get_str(tc).equals("") ? 0 : 1; case BoolificationSpec.MODE_UNBOX_STR_NOT_EMPTY_OR_ZERO: if (obj instanceof TypeObject) return 0; String str = obj.get_str(tc); return str == null || str.equals("") || str.equals("0") ? 0 : 1; case BoolificationSpec.MODE_NOT_TYPE_OBJECT: return obj instanceof TypeObject ? 0 : 1; case BoolificationSpec.MODE_BIGINT: return obj instanceof TypeObject || getBI(tc, obj).compareTo(BigInteger.ZERO) == 0 ? 0 : 1; case BoolificationSpec.MODE_ITER: return ((VMIterInstance)obj).boolify() ? 1 : 0; case BoolificationSpec.MODE_HAS_ELEMS: return obj.elems(tc) == 0 ? 0 : 1; default: throw ExceptionHandling.dieInternal(tc, "Invalid boolification spec mode used"); } } public static long isfalse(SixModelObject obj, ThreadContext tc) { return istrue(obj, tc) == 0 ? 1 : 0; } public static long istrue_s(String str) { return str == null || str.equals("") || str.equals("0") ? 0 : 1; } public static long isfalse_s(String str) { return str == null || str.equals("") || str.equals("0") ? 1 : 0; } public static long not_i(long v) { return v == 0 ? 1 : 0; } /* Smart coercions. */ public static String smart_stringify(SixModelObject obj, ThreadContext tc) { obj = decont(obj, tc); // If it can unbox to a string, that wins right off. StorageSpec ss = obj.st.REPR.get_storage_spec(tc, obj.st); if ((ss.can_box & StorageSpec.CAN_BOX_STR) != 0 && !(obj instanceof TypeObject)) return obj.get_str(tc); // If it has a Str method, that wins. // We could put this in the generated code, but it's here to avoid the // bulk. SixModelObject numMeth = obj.st.MethodCache == null ? null : obj.st.MethodCache.get("Str"); if (numMeth != null) { invokeDirect(tc, numMeth, invocantCallSite, new Object[] { obj }); return result_s(tc.curFrame); } // If it's a type object, empty string. if (obj instanceof TypeObject) return ""; // See if it can unbox to another primitive we can stringify. if ((ss.can_box & StorageSpec.CAN_BOX_INT) != 0) return coerce_i2s(obj.get_int(tc)); if ((ss.can_box & StorageSpec.CAN_BOX_NUM) != 0) return coerce_n2s(obj.get_num(tc)); // If it's an exception, take the message. if (obj instanceof VMExceptionInstance) { String msg = ((VMExceptionInstance)obj).message; return msg == null ? "Died" : msg; } // If anything else, we can't do it. throw ExceptionHandling.dieInternal(tc, "Cannot stringify this"); } public static double smart_numify(SixModelObject obj, ThreadContext tc) { obj = decont(obj, tc); // If it can unbox as an int or a num, that wins right off. StorageSpec ss = obj.st.REPR.get_storage_spec(tc, obj.st); if ((ss.can_box & StorageSpec.CAN_BOX_INT) != 0) return (double)obj.get_int(tc); if ((ss.can_box & StorageSpec.CAN_BOX_NUM) != 0) return obj.get_num(tc); // Otherwise, look for a Num method. SixModelObject numMeth = obj.st.MethodCache.get("Num"); if (numMeth != null) { invokeDirect(tc, numMeth, invocantCallSite, new Object[] { obj }); return result_n(tc.curFrame); } // If it's a type object, empty string. if (obj instanceof TypeObject) return 0.0; // See if it can unbox to a primitive we can numify. if ((ss.can_box & StorageSpec.CAN_BOX_STR) != 0) return coerce_s2n(obj.get_str(tc)); if (obj instanceof VMArrayInstance || obj instanceof VMHashInstance) return obj.elems(tc); // If anything else, we can't do it. throw ExceptionHandling.dieInternal(tc, "Cannot numify this"); } /* Math operations. */ public static double sec_n(double val) { return 1 / Math.cos(val); } public static double asec_n(double val) { return Math.acos(1 / val); } public static double sech_n(double val) { return 1 / Math.cosh(val); } public static long gcd_i(long valA, long valB) { return BigInteger.valueOf(valA).gcd(BigInteger.valueOf(valB)) .longValue(); } public static SixModelObject gcd_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).gcd(getBI(tc, b))); } public static long lcm_i(long valA, long valB) { return valA * (valB / gcd_i(valA, valB)); } public static SixModelObject lcm_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { BigInteger valA = getBI(tc, a); BigInteger valB = getBI(tc, b); BigInteger gcd = valA.gcd(valB); return makeBI(tc, type, valA.multiply(valB).divide(gcd).abs()); } public static long isnanorinf(double n) { return Double.isInfinite(n) || Double.isNaN(n) ? 1 : 0; } public static double inf() { return Double.POSITIVE_INFINITY; } public static double neginf() { return Double.NEGATIVE_INFINITY ; } public static double nan() { return Double.NaN; } public static SixModelObject radix(long radix, String str, long zpos, long flags, ThreadContext tc) { double zvalue = 0.0; double zbase = 1.0; int chars = str.length(); double value = zvalue; double base = zbase; long pos = -1; char ch; boolean neg = false; if (radix > 36) { throw ExceptionHandling.dieInternal(tc, "Cannot convert radix of " + radix + " (max 36)"); } ch = (zpos < chars) ? str.charAt((int)zpos) : 0; if ((flags & 0x02) != 0 && (ch == '+' || ch == '-')) { neg = (ch == '-'); zpos++; ch = (zpos < chars) ? str.charAt((int)zpos) : 0; } while (zpos < chars) { if (ch >= '0' && ch <= '9') ch = (char)(ch - '0'); else if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 'a' + 10); else if (ch >= 'A' && ch <= 'Z') ch = (char)(ch - 'A' + 10); else break; if (ch >= radix) break; zvalue = zvalue * radix + ch; zbase = zbase * radix; zpos++; pos = zpos; if (ch != 0 || (flags & 0x04) == 0) { value=zvalue; base=zbase; } if (zpos >= chars) break; ch = str.charAt((int)zpos); if (ch != '_') continue; zpos++; if (zpos >= chars) break; ch = str.charAt((int)zpos); } if (neg || (flags & 0x01) != 0) { value = -value; } HLLConfig hllConfig = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig; SixModelObject result = hllConfig.slurpyArrayType.st.REPR.allocate(tc, hllConfig.slurpyArrayType.st); result.push_boxed(tc, box_n(value, hllConfig.numBoxType, tc)); result.push_boxed(tc, box_n(base, hllConfig.numBoxType, tc)); result.push_boxed(tc, box_n(pos, hllConfig.numBoxType, tc)); return result; } public static double rand_n(double n, ThreadContext tc) { return n * tc.random.nextDouble(); } public static long srand(long n, ThreadContext tc) { tc.random.setSeed(n); return n; } /* String operations. */ public static long chars(String val) { return val.length(); } public static String lc(String val) { return val.toLowerCase(); } public static String uc(String val) { return val.toUpperCase(); } public static String x(String val, long count) { StringBuilder retval = new StringBuilder(); for (long ii = 1; ii <= count; ii++) { retval.append(val); } return retval.toString(); } public static String concat(String valA, String valB) { return valA + valB; } public static String chr(long ord, ThreadContext tc) { if (ord < 0) throw ExceptionHandling.dieInternal(tc, "chr codepoint cannot be negative"); return (new StringBuffer()).append(Character.toChars((int)ord)).toString(); } public static String join(String delimiter, SixModelObject arr, ThreadContext tc) { final StringBuilder sb = new StringBuilder(); int prim = arr.st.REPR.get_value_storage_spec(tc, arr.st).boxed_primitive; if (prim != StorageSpec.BP_NONE && prim != StorageSpec.BP_STR) ExceptionHandling.dieInternal(tc, "Unsupported native array type in join"); final int numElems = (int) arr.elems(tc); for (int i = 0; i < numElems; i++) { if (i > 0) { sb.append(delimiter); } if (prim == StorageSpec.BP_STR) { arr.at_pos_native(tc, i); sb.append(tc.native_s); } else { sb.append(arr.at_pos_boxed(tc, i).get_str(tc)); } } return sb.toString(); } public static SixModelObject split(String delimiter, String string, ThreadContext tc) { if (string == null || delimiter == null) { return null; } HLLConfig hllConfig = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig; SixModelObject arrayType = hllConfig.slurpyArrayType; SixModelObject array = arrayType.st.REPR.allocate(tc, arrayType.st); int slen = string.length(); if (slen == 0) { return array; } int dlen = delimiter.length(); if (dlen == 0) { for (int i = 0; i < slen; i++) { String item = string.substring(i, i+1); SixModelObject value = box_s(item, hllConfig.strBoxType, tc); array.push_boxed(tc, value); } } else { int curpos = 0; int matchpos = string.indexOf(delimiter); while (matchpos > -1) { String item = string.substring(curpos, matchpos); SixModelObject value = box_s(item, hllConfig.strBoxType, tc); array.push_boxed(tc, value); curpos = matchpos + dlen; matchpos = string.indexOf(delimiter, curpos); } String tail = string.substring(curpos); SixModelObject value = box_s(tail, hllConfig.strBoxType, tc); array.push_boxed(tc, value); } return array; } public static long indexfrom(String string, String pattern, long fromIndex) { return string.indexOf(pattern, (int)fromIndex); } public static long rindexfromend(String string, String pattern) { return string.lastIndexOf(pattern); } public static long rindexfrom(String string, String pattern, long fromIndex) { return string.lastIndexOf(pattern, (int)fromIndex); } public static String substr2(String val, long offset) { if (offset >= val.length()) return ""; if (offset < 0) offset += val.length(); return val.substring((int)offset); } public static String substr3(String val, long offset, long length) { if (offset >= val.length()) return ""; int end = (int)(offset + length); if (end > val.length()) end = val.length(); return val.substring((int)offset, end); } // does haystack have needle as a substring at offset? public static long string_equal_at(String haystack, String needle, long offset) { long haylen = haystack.length(); long needlelen = needle.length(); if (offset < 0) { offset += haylen; if (offset < 0) { offset = 0; } } if (haylen - offset < needlelen) { return 0; } return haystack.regionMatches((int)offset, needle, 0, (int)needlelen) ? 1 : 0; } public static long ordfirst(String str) { return str.codePointAt(0); } public static long ordat(String str, long offset) { return str.codePointAt((int)offset); } public static String sprintf(String format, SixModelObject arr, ThreadContext tc) { // This function just assumes that Java's printf format is compatible // with NQP's printf format... final int numElems = (int) arr.elems(tc); Object[] args = new Object[numElems]; for (int i = 0; i < numElems; i++) { SixModelObject obj = arr.at_pos_boxed(tc, i); StorageSpec ss = obj.st.REPR.get_storage_spec(tc, obj.st); if ((ss.can_box & StorageSpec.CAN_BOX_INT) != 0) { args[i] = Long.valueOf(obj.get_int(tc)); } else if ((ss.can_box & StorageSpec.CAN_BOX_NUM) != 0) { args[i] = Double.valueOf(obj.get_num(tc)); } else if ((ss.can_box & StorageSpec.CAN_BOX_STR) != 0) { args[i] = obj.get_str(tc); } else { throw new IllegalArgumentException("sprintf only accepts ints, nums, and strs, not " + obj.getClass()); } } return String.format(format, args); } public static String escape(String str) { int len = str.length(); StringBuilder sb = new StringBuilder(2 * len); for (int i = 0; i < len; i++) { char c = str.charAt(i); switch (c) { case '\\': sb.append("\\\\"); break; case 7: sb.append("\\a"); break; case '\b': sb.append("\\b"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; case '\f': sb.append("\\f"); break; case '"': sb.append("\\\""); break; case 27: sb.append("\\e"); break; default: sb.append(c); } } return sb.toString(); } public static String flip(String str) { return new StringBuffer(str).reverse().toString(); } public static String replace(String str, long offset, long count, String repl) { return new StringBuffer(str).replace((int)offset, (int)(offset + count), repl).toString(); } /* Brute force, but not normally needed for most programs. */ private static volatile HashMap<String, Character> cpNameMap; public static long codepointfromname(String name) { HashMap<String, Character> names = cpNameMap; if (names == null) { names = new HashMap< >(); for (char i = 0; i < Character.MAX_VALUE; i++) if (Character.isValidCodePoint(i)) names.put(Character.getName(i), i); cpNameMap = names; } Character found = names.get(name); return found == null ? -1 : found; } public static SixModelObject encode(String str, String encoding, SixModelObject res, ThreadContext tc) { try { if (encoding.equals("utf8")) { Buffers.stashBytes(tc, res, str.getBytes("UTF-8")); } else if (encoding.equals("ascii")) { Buffers.stashBytes(tc, res, str.getBytes("US-ASCII")); } else if (encoding.equals("iso-8859-1")) { Buffers.stashBytes(tc, res, str.getBytes("ISO-8859-1")); } else if (encoding.equals("utf16")) { short[] buffer = new short[str.length()]; for (int i = 0; i < str.length(); i++) buffer[i] = (short)str.charAt(i); if (res instanceof VMArrayInstance_i16) { VMArrayInstance_i16 arr = (VMArrayInstance_i16)res; arr.elems = buffer.length; arr.start = 0; arr.slots = buffer; } else { res.set_elems(tc, buffer.length); for (int i = 0; i < buffer.length; i++) { tc.native_i = buffer[i]; res.bind_pos_native(tc, i); } } } else if (encoding.equals("utf32")) { int[] buffer = new int[str.length()]; /* Can be an overestimate. */ int bufPos = 0; for (int i = 0; i < str.length(); ) { int cp = str.codePointAt(i); buffer[bufPos++] = cp; i += Character.charCount(cp); } if (res instanceof VMArrayInstance_i32) { VMArrayInstance_i32 arr = (VMArrayInstance_i32)res; arr.elems = bufPos; arr.start = 0; arr.slots = buffer; } else { res.set_elems(tc, buffer.length); for (int i = 0; i < bufPos; i++) { tc.native_i = buffer[i]; res.bind_pos_native(tc, i); } } } else { throw ExceptionHandling.dieInternal(tc, "Unknown encoding '" + encoding + "'"); } return res; } catch (UnsupportedEncodingException e) { throw ExceptionHandling.dieInternal(tc, e); } } public static String decode8(SixModelObject buf, String csName, ThreadContext tc) { ByteBuffer bb = Buffers.unstashBytes(buf, tc); return Charset.forName(csName).decode(bb).toString(); } public static String decode(SixModelObject buf, String encoding, ThreadContext tc) { if (encoding.equals("utf8")) { return decode8(buf, "UTF-8", tc); } else if (encoding.equals("ascii")) { return decode8(buf, "US-ASCII", tc); } else if (encoding.equals("iso-8859-1")) { return decode8(buf, "ISO-8859-1", tc); } else if (encoding.equals("utf16") || encoding.equals("utf32")) { int n = (int)buf.elems(tc); StringBuilder sb = new StringBuilder(n); if (buf instanceof VMArrayInstance_u8 || buf instanceof VMArrayInstance_i8) { if (encoding.equals("utf16") && n % 2 == 1) { throw ExceptionHandling.dieInternal(tc, "Malformed UTF-16; odd number of bytes"); } if (encoding.equals("utf32") && n % 4 > 0) { throw ExceptionHandling.dieInternal(tc, "Malformed UTF-32; number of bytes must be factor of four"); } for (int i = 0; i < n;) { buf.at_pos_native(tc, i++); int a = (int)tc.native_i; buf.at_pos_native(tc, i++); int b = (int)tc.native_i; sb.appendCodePoint(a + (b << 8)); } } else if (buf instanceof VMArrayInstance_i16 || buf instanceof VMArrayInstance_u16) { for (int i = 0; i < n; i++) { buf.at_pos_native(tc, i); sb.appendCodePoint((int)tc.native_i); } } else if (buf instanceof VMArrayInstance_i32 || buf instanceof VMArrayInstance_u32) { for (int i = 0; i < n; i++) { buf.at_pos_native(tc, i); int a = (int)tc.native_i; sb.appendCodePoint(a & 0xFFFF); sb.appendCodePoint(a >> 16); } } else { throw ExceptionHandling.dieInternal(tc, "Unknown buf type: " + buf.getClass() + "/" + Ops.typeName(buf, tc)); } return sb.toString(); } else { throw ExceptionHandling.dieInternal(tc, "Unknown encoding '" + encoding + "'"); } } private static final int CCLASS_ANY = 65535; private static final int CCLASS_UPPERCASE = 1; private static final int CCLASS_LOWERCASE = 2; private static final int CCLASS_ALPHABETIC = 4; private static final int CCLASS_NUMERIC = 8; private static final int CCLASS_HEXADECIMAL = 16; private static final int CCLASS_WHITESPACE = 32; private static final int CCLASS_PRINTING = 64; private static final int CCLASS_BLANK = 256; private static final int CCLASS_CONTROL = 512; private static final int CCLASS_PUNCTUATION = 1024; private static final int CCLASS_ALPHANUMERIC = 2048; private static final int CCLASS_NEWLINE = 4096; private static final int CCLASS_WORD = 8192; private static final int PUNCT_TYPES = (1 << Character.CONNECTOR_PUNCTUATION) | (1 << Character.DASH_PUNCTUATION) | (1 << Character.END_PUNCTUATION) | (1 << Character.FINAL_QUOTE_PUNCTUATION) | (1 << Character.INITIAL_QUOTE_PUNCTUATION) | (1 << Character.OTHER_PUNCTUATION) | (1 << Character.START_PUNCTUATION); private static final int NONPRINT_TYPES = (1 << Character.CONTROL) | (1 << Character.SURROGATE) | (1 << Character.UNASSIGNED) | (1 << Character.LINE_SEPARATOR) | (1 << Character.PARAGRAPH_SEPARATOR); public static long iscclass(long cclass, String target, long offset) { if (offset < 0 || offset >= target.length()) return 0; char test = target.charAt((int)offset); switch ((int)cclass) { case CCLASS_ANY: return 1; case CCLASS_NUMERIC: return Character.isDigit(test) ? 1 : 0; case CCLASS_WHITESPACE: if (Character.isSpaceChar(test)) return 1; if (test >= '\t' && test <= '\r') return 1; if (test == '\u0085') return 1; return 0; case CCLASS_PRINTING: if (((1 << Character.getType(test)) & NONPRINT_TYPES) != 0) return 0; return test < '\t' || test > '\r' ? 1 : 0; case CCLASS_WORD: return test == '_' || Character.isLetterOrDigit(test) ? 1 : 0; case CCLASS_NEWLINE: return (Character.getType(test) == Character.LINE_SEPARATOR) || (test == '\n' || test == '\r' || test == '\u0085') ? 1 : 0; case CCLASS_ALPHABETIC: return Character.isAlphabetic(test) ? 1 : 0; case CCLASS_UPPERCASE: return Character.isUpperCase(test) ? 1 : 0; case CCLASS_LOWERCASE: return Character.isLowerCase(test) ? 1 : 0; case CCLASS_HEXADECIMAL: return Character.isDigit(test) || (test >= 'A' && test <= 'F' || test >= 'a' && test <= 'f') ? 1 : 0; case CCLASS_BLANK: return (Character.getType(test) == Character.SPACE_SEPARATOR) || (test == '\t') ? 1 : 0; case CCLASS_CONTROL: return Character.isISOControl(test) ? 1 : 0; case CCLASS_PUNCTUATION: return ((1 << Character.getType(test)) & PUNCT_TYPES) != 0 ? 1 : 0; case CCLASS_ALPHANUMERIC: return Character.isLetterOrDigit(test) ? 1 : 0; default: return 0; } } public static long checkcrlf(String tgt, long pos, long eos) { return (pos <= eos-2 && tgt.substring((int)pos, ((int) pos)+2).equals("\r\n")) ? pos+1 : pos; } public static long findcclass(long cclass, String target, long offset, long count) { long length = target.length(); long end = offset + count; end = length < end ? length : end; for (long pos = offset; pos < end; pos++) { if (iscclass(cclass, target, pos) > 0) { return pos; } } return end; } public static long findnotcclass(long cclass, String target, long offset, long count) { long length = target.length(); long end = offset + count; end = length < end ? length : end; for (long pos = offset; pos < end; pos++) { if (iscclass(cclass, target, pos) == 0) { return pos; } } return end; } private static HashMap<String,String> canonNames = new HashMap<String, String>(); private static HashMap<String,int[]> derivedProps = new HashMap<String, int[]>(); static { canonNames.put("inlatin1supplement", "InLatin-1Supplement"); canonNames.put("inlatinextendeda", "InLatinExtended-A"); canonNames.put("inlatinextendedb", "InLatinExtended-B"); canonNames.put("inarabicextendeda", "InArabicExtended-A"); canonNames.put("inmiscellaneousmathematicalsymbolsa", "InMiscellaneousMathematicalSymbols-A"); canonNames.put("insupplementalarrowsa", "InSupplementalArrows-A"); canonNames.put("insupplementalarrowsb", "InSupplementalArrows-B"); canonNames.put("inmiscellaneousmathematicalsymbolsb", "InMiscellaneousMathematicalSymbols-B"); canonNames.put("inlatinextendedc", "InLatinExtended-C"); canonNames.put("incyrillicextendeda", "InCyrillicExtended-A"); canonNames.put("incyrillicextendedb", "InCyrillicExtended-B"); canonNames.put("inlatinextendedd", "InLatinExtended-D"); canonNames.put("inhanguljamoextendeda", "InHangulJamoExtended-A"); canonNames.put("inmyanmarextendeda", "InMyanmarExtended-A"); canonNames.put("inethiopicextendeda", "InEthiopicExtended-A"); canonNames.put("inhanguljamoextendedb", "InHangulJamoExtended-B"); canonNames.put("inarabicpresentationformsa", "InArabicPresentationForms-A"); canonNames.put("inarabicpresentationformsb", "InArabicPresentationForms-B"); canonNames.put("insupplementaryprivateuseareaa", "InSupplementaryPrivateUseArea-A"); canonNames.put("insupplementaryprivateuseareab", "InSupplementaryPrivateUseArea-B"); canonNames.put("alphabetic", "IsAlphabetic"); canonNames.put("ideographic", "IsIdeographic"); canonNames.put("letter", "IsLetter"); canonNames.put("lowercase", "IsLowercase"); canonNames.put("uppercase", "IsUppercase"); canonNames.put("titlecase", "IsTitlecase"); canonNames.put("punctuation", "IsPunctuation"); canonNames.put("control", "IsControl"); canonNames.put("white_space", "IsWhite_Space"); canonNames.put("digit", "IsDigit"); canonNames.put("hex_digit", "IsHex_Digit"); canonNames.put("noncharacter_code_point", "IsNoncharacter_Code_Point"); canonNames.put("assigned", "IsAssigned"); canonNames.put("uppercaseletter", "Lu"); canonNames.put("lowercaseletter", "Ll"); canonNames.put("titlecaseletter", "Lt"); canonNames.put("casedletter", "LC"); canonNames.put("modifierletter", "Lm"); canonNames.put("otherletter", "Lo"); canonNames.put("letter", "L"); canonNames.put("nonspacingmark", "Mn"); canonNames.put("spacingmark", "Mc"); canonNames.put("enclosingmark", "Me"); canonNames.put("mark", "M"); canonNames.put("decimalnumber", "Nd"); canonNames.put("letternumber", "Nl"); canonNames.put("othernumber", "No"); canonNames.put("number", "N"); canonNames.put("connectorpunctuation", "Pc"); canonNames.put("dashpunctuation", "Pd"); canonNames.put("openpunctuation", "Ps"); canonNames.put("closepunctuation", "Pe"); canonNames.put("initialpunctuation", "Pi"); canonNames.put("finalpunctuation", "Pf"); canonNames.put("otherpunctuation", "Po"); canonNames.put("punctuation", "P"); canonNames.put("mathsymbol", "Sm"); canonNames.put("currencysymbol", "Sc"); canonNames.put("modifiersymbol", "Sk"); canonNames.put("othersymbol", "So"); canonNames.put("symbol", "S"); canonNames.put("spaceseparator", "Zs"); canonNames.put("lineseparator", "Zl"); canonNames.put("paragraphseparator", "Zp"); canonNames.put("separator", "Z"); canonNames.put("control", "Cc"); canonNames.put("format", "Cf"); canonNames.put("surrogate", "Cs"); canonNames.put("privateuse", "Co"); canonNames.put("unassigned", "Cn"); canonNames.put("other", "C"); derivedProps.put("WhiteSpace", new int[] { 9,13,32,32,133,133,160,160,5760,5760,6158,6158,8192,8202,8232,8232,8233,8233,8239,8239,8287,8287,12288,12288 }); derivedProps.put("BidiControl", new int[] { 8206,8207,8234,8238 }); derivedProps.put("JoinControl", new int[] { 8204,8205 }); derivedProps.put("Dash", new int[] { 45,45,1418,1418,1470,1470,5120,5120,6150,6150,8208,8213,8275,8275,8315,8315,8331,8331,8722,8722,11799,11799,11802,11802,11834,11835,12316,12316,12336,12336,12448,12448,65073,65074,65112,65112,65123,65123,65293,65293 }); derivedProps.put("Hyphen", new int[] { 45,45,173,173,1418,1418,6150,6150,8208,8209,11799,11799,12539,12539,65123,65123,65293,65293,65381,65381 }); derivedProps.put("QuotationMark", new int[] { 34,34,39,39,171,171,187,187,8216,8216,8217,8217,8218,8218,8219,8220,8221,8221,8222,8222,8223,8223,8249,8249,8250,8250,12300,12300,12301,12301,12302,12302,12303,12303,12317,12317,12318,12319,65089,65089,65090,65090,65091,65091,65092,65092,65282,65282,65287,65287,65378,65378,65379,65379 }); derivedProps.put("TerminalPunctuation", new int[] { 33,33,44,44,46,46,58,59,63,63,894,894,903,903,1417,1417,1475,1475,1548,1548,1563,1563,1567,1567,1748,1748,1792,1802,1804,1804,2040,2041,2096,2110,2142,2142,2404,2405,3674,3675,3848,3848,3853,3858,4170,4171,4961,4968,5741,5742,5867,5869,6100,6102,6106,6106,6146,6149,6152,6153,6468,6469,6824,6827,7002,7003,7005,7007,7227,7231,7294,7295,8252,8253,8263,8265,11822,11822,12289,12290,42238,42239,42509,42511,42739,42743,43126,43127,43214,43215,43311,43311,43463,43465,43613,43615,43743,43743,43760,43761,44011,44011,65104,65106,65108,65111,65281,65281,65292,65292,65294,65294,65306,65307,65311,65311,65377,65377,65380,65380,66463,66463,66512,66512,67671,67671,67871,67871,68410,68415,69703,69709,69822,69825,69953,69955,70085,70086,74864,74867 }); derivedProps.put("OtherMath", new int[] { 94,94,976,978,981,981,1008,1009,1012,1013,8214,8214,8242,8244,8256,8256,8289,8292,8317,8317,8318,8318,8333,8333,8334,8334,8400,8412,8417,8417,8421,8422,8427,8431,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8488,8488,8489,8489,8492,8493,8495,8497,8499,8500,8501,8504,8508,8511,8517,8521,8597,8601,8604,8607,8609,8610,8612,8613,8615,8615,8617,8621,8624,8625,8630,8631,8636,8653,8656,8657,8659,8659,8661,8667,8669,8669,8676,8677,9140,9141,9143,9143,9168,9168,9186,9186,9632,9633,9646,9654,9660,9664,9670,9671,9674,9675,9679,9683,9698,9698,9700,9700,9703,9708,9733,9734,9792,9792,9794,9794,9824,9827,9837,9838,10181,10181,10182,10182,10214,10214,10215,10215,10216,10216,10217,10217,10218,10218,10219,10219,10220,10220,10221,10221,10222,10222,10223,10223,10627,10627,10628,10628,10629,10629,10630,10630,10631,10631,10632,10632,10633,10633,10634,10634,10635,10635,10636,10636,10637,10637,10638,10638,10639,10639,10640,10640,10641,10641,10642,10642,10643,10643,10644,10644,10645,10645,10646,10646,10647,10647,10648,10648,10712,10712,10713,10713,10714,10714,10715,10715,10748,10748,10749,10749,65121,65121,65123,65123,65128,65128,65340,65340,65342,65342,119808,119892,119894,119964,119966,119967,119970,119970,119973,119974,119977,119980,119982,119993,119995,119995,119997,120003,120005,120069,120071,120074,120077,120084,120086,120092,120094,120121,120123,120126,120128,120132,120134,120134,120138,120144,120146,120485,120488,120512,120514,120538,120540,120570,120572,120596,120598,120628,120630,120654,120656,120686,120688,120712,120714,120744,120746,120770,120772,120779,120782,120831,126464,126467,126469,126495,126497,126498,126500,126500,126503,126503,126505,126514,126516,126519,126521,126521,126523,126523,126530,126530,126535,126535,126537,126537,126539,126539,126541,126543,126545,126546,126548,126548,126551,126551,126553,126553,126555,126555,126557,126557,126559,126559,126561,126562,126564,126564,126567,126570,126572,126578,126580,126583,126585,126588,126590,126590,126592,126601,126603,126619,126625,126627,126629,126633,126635,126651 }); derivedProps.put("HexDigit", new int[] { 48,57,65,70,97,102,65296,65305,65313,65318,65345,65350 }); derivedProps.put("ASCIIHexDigit", new int[] { 48,57,65,70,97,102 }); derivedProps.put("OtherAlphabetic", new int[] { 837,837,1456,1469,1471,1471,1473,1474,1476,1477,1479,1479,1552,1562,1611,1623,1625,1631,1648,1648,1750,1756,1761,1764,1767,1768,1773,1773,1809,1809,1840,1855,1958,1968,2070,2071,2075,2083,2085,2087,2089,2092,2276,2281,2288,2302,2304,2306,2307,2307,2362,2362,2363,2363,2366,2368,2369,2376,2377,2380,2382,2383,2389,2391,2402,2403,2433,2433,2434,2435,2494,2496,2497,2500,2503,2504,2507,2508,2519,2519,2530,2531,2561,2562,2563,2563,2622,2624,2625,2626,2631,2632,2635,2636,2641,2641,2672,2673,2677,2677,2689,2690,2691,2691,2750,2752,2753,2757,2759,2760,2761,2761,2763,2764,2786,2787,2817,2817,2818,2819,2878,2878,2879,2879,2880,2880,2881,2884,2887,2888,2891,2892,2902,2902,2903,2903,2914,2915,2946,2946,3006,3007,3008,3008,3009,3010,3014,3016,3018,3020,3031,3031,3073,3075,3134,3136,3137,3140,3142,3144,3146,3148,3157,3158,3170,3171,3202,3203,3262,3262,3263,3263,3264,3268,3270,3270,3271,3272,3274,3275,3276,3276,3285,3286,3298,3299,3330,3331,3390,3392,3393,3396,3398,3400,3402,3404,3415,3415,3426,3427,3458,3459,3535,3537,3538,3540,3542,3542,3544,3551,3570,3571,3633,3633,3636,3642,3661,3661,3761,3761,3764,3769,3771,3772,3789,3789,3953,3966,3967,3967,3968,3969,3981,3991,3993,4028,4139,4140,4141,4144,4145,4145,4146,4150,4152,4152,4155,4156,4157,4158,4182,4183,4184,4185,4190,4192,4194,4194,4199,4200,4209,4212,4226,4226,4227,4228,4229,4230,4252,4252,4253,4253,4959,4959,5906,5907,5938,5939,5970,5971,6002,6003,6070,6070,6071,6077,6078,6085,6086,6086,6087,6088,6313,6313,6432,6434,6435,6438,6439,6440,6441,6443,6448,6449,6450,6450,6451,6456,6576,6592,6600,6601,6679,6680,6681,6683,6741,6741,6742,6742,6743,6743,6744,6750,6753,6753,6754,6754,6755,6756,6757,6764,6765,6770,6771,6772,6912,6915,6916,6916,6965,6965,6966,6970,6971,6971,6972,6972,6973,6977,6978,6978,6979,6979,7040,7041,7042,7042,7073,7073,7074,7077,7078,7079,7080,7081,7084,7085,7143,7143,7144,7145,7146,7148,7149,7149,7150,7150,7151,7153,7204,7211,7212,7219,7220,7221,7410,7411,9398,9449,11744,11775,42612,42619,42655,42655,43043,43044,43045,43046,43047,43047,43136,43137,43188,43203,43302,43306,43335,43345,43346,43346,43392,43394,43395,43395,43444,43445,43446,43449,43450,43451,43452,43452,43453,43455,43561,43566,43567,43568,43569,43570,43571,43572,43573,43574,43587,43587,43596,43596,43597,43597,43696,43696,43698,43700,43703,43704,43710,43710,43755,43755,43756,43757,43758,43759,43765,43765,44003,44004,44005,44005,44006,44007,44008,44008,44009,44010,64286,64286,68097,68099,68101,68102,68108,68111,69632,69632,69633,69633,69634,69634,69688,69701,69762,69762,69808,69810,69811,69814,69815,69816,69888,69890,69927,69931,69932,69932,69933,69938,70016,70017,70018,70018,70067,70069,70070,70078,70079,70079,71339,71339,71340,71340,71341,71341,71342,71343,71344,71349,94033,94078 }); derivedProps.put("Ideographic", new int[] { 12294,12294,12295,12295,12321,12329,12344,12346,13312,19893,19968,40908,63744,64109,64112,64217,131072,173782,173824,177972,177984,178205,194560,195101 }); derivedProps.put("Diacritic", new int[] { 94,94,96,96,168,168,175,175,180,180,183,183,184,184,688,705,706,709,710,721,722,735,736,740,741,747,748,748,749,749,750,750,751,767,768,846,848,855,861,866,884,884,885,885,890,890,900,901,1155,1159,1369,1369,1425,1441,1443,1469,1471,1471,1473,1474,1476,1476,1611,1618,1623,1624,1759,1760,1765,1766,1770,1772,1840,1866,1958,1968,2027,2035,2036,2037,2072,2073,2276,2302,2364,2364,2381,2381,2385,2388,2417,2417,2492,2492,2509,2509,2620,2620,2637,2637,2748,2748,2765,2765,2876,2876,2893,2893,3021,3021,3149,3149,3260,3260,3277,3277,3405,3405,3530,3530,3655,3660,3662,3662,3784,3788,3864,3865,3893,3893,3895,3895,3897,3897,3902,3903,3970,3972,3974,3975,4038,4038,4151,4151,4153,4154,4231,4236,4237,4237,4239,4239,4250,4251,6089,6099,6109,6109,6457,6459,6773,6780,6783,6783,6964,6964,6980,6980,7019,7027,7082,7082,7083,7083,7222,7223,7288,7293,7376,7378,7379,7379,7380,7392,7393,7393,7394,7400,7405,7405,7412,7412,7468,7530,7620,7631,7677,7679,8125,8125,8127,8129,8141,8143,8157,8159,8173,8175,8189,8190,11503,11505,11823,11823,12330,12333,12334,12335,12441,12442,12443,12444,12540,12540,42607,42607,42620,42621,42623,42623,42736,42737,42775,42783,42784,42785,42888,42888,43000,43001,43204,43204,43232,43249,43307,43309,43310,43310,43347,43347,43443,43443,43456,43456,43643,43643,43711,43711,43712,43712,43713,43713,43714,43714,43766,43766,44012,44012,44013,44013,64286,64286,65056,65062,65342,65342,65344,65344,65392,65392,65438,65439,65507,65507,69817,69818,69939,69940,70080,70080,71350,71350,71351,71351,94095,94098,94099,94111,119143,119145,119149,119154,119163,119170,119173,119179,119210,119213 }); derivedProps.put("Extender", new int[] { 183,183,720,721,1600,1600,2042,2042,3654,3654,3782,3782,6154,6154,6211,6211,6823,6823,7222,7222,7291,7291,12293,12293,12337,12341,12445,12446,12540,12542,40981,40981,42508,42508,43471,43471,43632,43632,43741,43741,43763,43764,65392,65392 }); derivedProps.put("OtherLowercase", new int[] { 170,170,186,186,688,696,704,705,736,740,837,837,890,890,7468,7530,7544,7544,7579,7615,8305,8305,8319,8319,8336,8348,8560,8575,9424,9449,11388,11389,42864,42864,43000,43001 }); derivedProps.put("OtherUppercase", new int[] { 8544,8559,9398,9423 }); derivedProps.put("NoncharacterCodePoint", new int[] { 64976,65007,65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111 }); derivedProps.put("OtherGraphemeExtend", new int[] { 2494,2494,2519,2519,2878,2878,2903,2903,3006,3006,3031,3031,3266,3266,3285,3286,3390,3390,3415,3415,3535,3535,3551,3551,8204,8205,12334,12335,65438,65439,119141,119141,119150,119154 }); derivedProps.put("IDSBinaryOperator", new int[] { 12272,12273,12276,12283 }); derivedProps.put("IDSTrinaryOperator", new int[] { 12274,12275 }); derivedProps.put("Radical", new int[] { 11904,11929,11931,12019,12032,12245 }); derivedProps.put("UnifiedIdeograph", new int[] { 13312,19893,19968,40908,64014,64015,64017,64017,64019,64020,64031,64031,64033,64033,64035,64036,64039,64041,131072,173782,173824,177972,177984,178205 }); derivedProps.put("OtherDefaultIgnorableCodePoint", new int[] { 847,847,4447,4448,6068,6069,8293,8297,12644,12644,65440,65440,65520,65528,917504,917504,917506,917535,917632,917759,918000,921599 }); derivedProps.put("Deprecated", new int[] { 329,329,1651,1651,3959,3959,3961,3961,6051,6052,8298,8303,9001,9001,9002,9002,917505,917505,917536,917631 }); derivedProps.put("SoftDotted", new int[] { 105,106,303,303,585,585,616,616,669,669,690,690,1011,1011,1110,1110,1112,1112,7522,7522,7574,7574,7588,7588,7592,7592,7725,7725,7883,7883,8305,8305,8520,8521,11388,11388,119842,119843,119894,119895,119946,119947,119998,119999,120050,120051,120102,120103,120154,120155,120206,120207,120258,120259,120310,120311,120362,120363,120414,120415,120466,120467 }); derivedProps.put("LogicalOrderException", new int[] { 3648,3652,3776,3780,43701,43702,43705,43705,43707,43708 }); derivedProps.put("OtherIDStart", new int[] { 8472,8472,8494,8494,12443,12444 }); derivedProps.put("OtherIDContinue", new int[] { 183,183,903,903,4969,4977,6618,6618 }); derivedProps.put("STerm", new int[] { 33,33,46,46,63,63,1372,1372,1374,1374,1417,1417,1567,1567,1748,1748,1792,1794,2041,2041,2404,2405,4170,4171,4962,4962,4967,4968,5742,5742,5941,5942,6147,6147,6153,6153,6468,6469,6824,6827,7002,7003,7006,7007,7227,7228,7294,7295,8252,8253,8263,8265,11822,11822,12290,12290,42239,42239,42510,42511,42739,42739,42743,42743,43126,43127,43214,43215,43311,43311,43464,43465,43613,43615,43760,43761,44011,44011,65106,65106,65110,65111,65281,65281,65294,65294,65311,65311,65377,65377,68182,68183,69703,69704,69822,69825,69953,69955,70085,70086 }); derivedProps.put("VariationSelector", new int[] { 6155,6157,65024,65039,917760,917999 }); derivedProps.put("PatternWhiteSpace", new int[] { 9,13,32,32,133,133,8206,8207,8232,8232,8233,8233 }); derivedProps.put("PatternSyntax", new int[] { 33,35,36,36,37,39,40,40,41,41,42,42,43,43,44,44,45,45,46,47,58,59,60,62,63,64,91,91,92,92,93,93,94,94,96,96,123,123,124,124,125,125,126,126,161,161,162,165,166,166,167,167,169,169,171,171,172,172,174,174,176,176,177,177,182,182,187,187,191,191,215,215,247,247,8208,8213,8214,8215,8216,8216,8217,8217,8218,8218,8219,8220,8221,8221,8222,8222,8223,8223,8224,8231,8240,8248,8249,8249,8250,8250,8251,8254,8257,8259,8260,8260,8261,8261,8262,8262,8263,8273,8274,8274,8275,8275,8277,8286,8592,8596,8597,8601,8602,8603,8604,8607,8608,8608,8609,8610,8611,8611,8612,8613,8614,8614,8615,8621,8622,8622,8623,8653,8654,8655,8656,8657,8658,8658,8659,8659,8660,8660,8661,8691,8692,8959,8960,8967,8968,8971,8972,8991,8992,8993,8994,9000,9001,9001,9002,9002,9003,9083,9084,9084,9085,9114,9115,9139,9140,9179,9180,9185,9186,9203,9204,9215,9216,9254,9255,9279,9280,9290,9291,9311,9472,9654,9655,9655,9656,9664,9665,9665,9666,9719,9720,9727,9728,9838,9839,9839,9840,9983,9984,9984,9985,10087,10088,10088,10089,10089,10090,10090,10091,10091,10092,10092,10093,10093,10094,10094,10095,10095,10096,10096,10097,10097,10098,10098,10099,10099,10100,10100,10101,10101,10132,10175,10176,10180,10181,10181,10182,10182,10183,10213,10214,10214,10215,10215,10216,10216,10217,10217,10218,10218,10219,10219,10220,10220,10221,10221,10222,10222,10223,10223,10224,10239,10240,10495,10496,10626,10627,10627,10628,10628,10629,10629,10630,10630,10631,10631,10632,10632,10633,10633,10634,10634,10635,10635,10636,10636,10637,10637,10638,10638,10639,10639,10640,10640,10641,10641,10642,10642,10643,10643,10644,10644,10645,10645,10646,10646,10647,10647,10648,10648,10649,10711,10712,10712,10713,10713,10714,10714,10715,10715,10716,10747,10748,10748,10749,10749,10750,11007,11008,11055,11056,11076,11077,11078,11079,11084,11085,11087,11088,11097,11098,11263,11776,11777,11778,11778,11779,11779,11780,11780,11781,11781,11782,11784,11785,11785,11786,11786,11787,11787,11788,11788,11789,11789,11790,11798,11799,11799,11800,11801,11802,11802,11803,11803,11804,11804,11805,11805,11806,11807,11808,11808,11809,11809,11810,11810,11811,11811,11812,11812,11813,11813,11814,11814,11815,11815,11816,11816,11817,11817,11818,11822,11823,11823,11824,11833,11834,11835,11836,11903,12289,12291,12296,12296,12297,12297,12298,12298,12299,12299,12300,12300,12301,12301,12302,12302,12303,12303,12304,12304,12305,12305,12306,12307,12308,12308,12309,12309,12310,12310,12311,12311,12312,12312,12313,12313,12314,12314,12315,12315,12316,12316,12317,12317,12318,12319,12320,12320,12336,12336,64830,64830,64831,64831,65093,65094 }); derivedProps.put("Math", new int[] { 43,43,60,62,94,94,124,124,126,126,172,172,177,177,215,215,247,247,976,978,981,981,1008,1009,1012,1013,1014,1014,1542,1544,8214,8214,8242,8244,8256,8256,8260,8260,8274,8274,8289,8292,8314,8316,8317,8317,8318,8318,8330,8332,8333,8333,8334,8334,8400,8412,8417,8417,8421,8422,8427,8431,8450,8450,8455,8455,8458,8467,8469,8469,8472,8472,8473,8477,8484,8484,8488,8488,8489,8489,8492,8493,8495,8497,8499,8500,8501,8504,8508,8511,8512,8516,8517,8521,8523,8523,8592,8596,8597,8601,8602,8603,8604,8607,8608,8608,8609,8610,8611,8611,8612,8613,8614,8614,8615,8615,8617,8621,8622,8622,8624,8625,8630,8631,8636,8653,8654,8655,8656,8657,8658,8658,8659,8659,8660,8660,8661,8667,8669,8669,8676,8677,8692,8959,8968,8971,8992,8993,9084,9084,9115,9139,9140,9141,9143,9143,9168,9168,9180,9185,9186,9186,9632,9633,9646,9654,9655,9655,9660,9664,9665,9665,9670,9671,9674,9675,9679,9683,9698,9698,9700,9700,9703,9708,9720,9727,9733,9734,9792,9792,9794,9794,9824,9827,9837,9838,9839,9839,10176,10180,10181,10181,10182,10182,10183,10213,10214,10214,10215,10215,10216,10216,10217,10217,10218,10218,10219,10219,10220,10220,10221,10221,10222,10222,10223,10223,10224,10239,10496,10626,10627,10627,10628,10628,10629,10629,10630,10630,10631,10631,10632,10632,10633,10633,10634,10634,10635,10635,10636,10636,10637,10637,10638,10638,10639,10639,10640,10640,10641,10641,10642,10642,10643,10643,10644,10644,10645,10645,10646,10646,10647,10647,10648,10648,10649,10711,10712,10712,10713,10713,10714,10714,10715,10715,10716,10747,10748,10748,10749,10749,10750,11007,11056,11076,11079,11084,64297,64297,65121,65121,65122,65122,65123,65123,65124,65126,65128,65128,65291,65291,65308,65310,65340,65340,65342,65342,65372,65372,65374,65374,65506,65506,65513,65516,119808,119892,119894,119964,119966,119967,119970,119970,119973,119974,119977,119980,119982,119993,119995,119995,119997,120003,120005,120069,120071,120074,120077,120084,120086,120092,120094,120121,120123,120126,120128,120132,120134,120134,120138,120144,120146,120485,120488,120512,120513,120513,120514,120538,120539,120539,120540,120570,120571,120571,120572,120596,120597,120597,120598,120628,120629,120629,120630,120654,120655,120655,120656,120686,120687,120687,120688,120712,120713,120713,120714,120744,120745,120745,120746,120770,120771,120771,120772,120779,120782,120831,126464,126467,126469,126495,126497,126498,126500,126500,126503,126503,126505,126514,126516,126519,126521,126521,126523,126523,126530,126530,126535,126535,126537,126537,126539,126539,126541,126543,126545,126546,126548,126548,126551,126551,126553,126553,126555,126555,126557,126557,126559,126559,126561,126562,126564,126564,126567,126570,126572,126578,126580,126583,126585,126588,126590,126590,126592,126601,126603,126619,126625,126627,126629,126633,126635,126651,126704,126705 }); derivedProps.put("ID_Start", new int[] { 65,90,97,122,170,170,181,181,186,186,192,214,216,246,248,442,443,443,444,447,448,451,452,659,660,660,661,687,688,705,710,721,736,740,748,748,750,750,880,883,884,884,886,887,890,890,891,893,902,902,904,906,908,908,910,929,931,1013,1015,1153,1162,1319,1329,1366,1369,1369,1377,1415,1488,1514,1520,1522,1568,1599,1600,1600,1601,1610,1646,1647,1649,1747,1749,1749,1765,1766,1774,1775,1786,1788,1791,1791,1808,1808,1810,1839,1869,1957,1969,1969,1994,2026,2036,2037,2042,2042,2048,2069,2074,2074,2084,2084,2088,2088,2112,2136,2208,2208,2210,2220,2308,2361,2365,2365,2384,2384,2392,2401,2417,2417,2418,2423,2425,2431,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2493,2493,2510,2510,2524,2525,2527,2529,2544,2545,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2674,2676,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2785,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2877,2877,2908,2909,2911,2913,2929,2929,2947,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3024,3024,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3133,3160,3161,3168,3169,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3261,3261,3294,3294,3296,3297,3313,3314,3333,3340,3342,3344,3346,3386,3389,3389,3406,3406,3424,3425,3450,3455,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3585,3632,3634,3635,3648,3653,3654,3654,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3762,3763,3773,3773,3776,3780,3782,3782,3804,3807,3840,3840,3904,3911,3913,3948,3976,3980,4096,4138,4159,4159,4176,4181,4186,4189,4193,4193,4197,4198,4206,4208,4213,4225,4238,4238,4256,4293,4295,4295,4301,4301,4304,4346,4348,4348,4349,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5905,5920,5937,5952,5969,5984,5996,5998,6000,6016,6067,6103,6103,6108,6108,6176,6210,6211,6211,6212,6263,6272,6312,6314,6314,6320,6389,6400,6428,6480,6509,6512,6516,6528,6571,6593,6599,6656,6678,6688,6740,6823,6823,6917,6963,6981,6987,7043,7072,7086,7087,7098,7141,7168,7203,7245,7247,7258,7287,7288,7293,7401,7404,7406,7409,7413,7414,7424,7467,7468,7530,7531,7543,7544,7544,7545,7578,7579,7615,7680,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8305,8305,8319,8319,8336,8348,8450,8450,8455,8455,8458,8467,8469,8469,8472,8472,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8494,8494,8495,8500,8501,8504,8505,8505,8508,8511,8517,8521,8526,8526,8544,8578,8579,8580,8581,8584,11264,11310,11312,11358,11360,11387,11388,11389,11390,11492,11499,11502,11506,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11648,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,12293,12293,12294,12294,12295,12295,12321,12329,12337,12341,12344,12346,12347,12347,12348,12348,12353,12438,12443,12444,12445,12446,12447,12447,12449,12538,12540,12542,12543,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,40980,40981,40981,40982,42124,42192,42231,42232,42237,42240,42507,42508,42508,42512,42527,42538,42539,42560,42605,42606,42606,42623,42623,42624,42647,42656,42725,42726,42735,42775,42783,42786,42863,42864,42864,42865,42887,42888,42888,42891,42894,42896,42899,42912,42922,43000,43001,43002,43002,43003,43009,43011,43013,43015,43018,43020,43042,43072,43123,43138,43187,43250,43255,43259,43259,43274,43301,43312,43334,43360,43388,43396,43442,43471,43471,43520,43560,43584,43586,43588,43595,43616,43631,43632,43632,43633,43638,43642,43642,43648,43695,43697,43697,43701,43702,43705,43709,43712,43712,43714,43714,43739,43740,43741,43741,43744,43754,43762,43762,43763,43764,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44002,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65140,65142,65276,65313,65338,65345,65370,65382,65391,65392,65392,65393,65437,65438,65439,65440,65470,65474,65479,65482,65487,65490,65495,65498,65500,65536,65547,65549,65574,65576,65594,65596,65597,65599,65613,65616,65629,65664,65786,65856,65908,66176,66204,66208,66256,66304,66334,66352,66368,66369,66369,66370,66377,66378,66378,66432,66461,66464,66499,66504,66511,66513,66517,66560,66639,66640,66717,67584,67589,67592,67592,67594,67637,67639,67640,67644,67644,67647,67669,67840,67861,67872,67897,67968,68023,68030,68031,68096,68096,68112,68115,68117,68119,68121,68147,68192,68220,68352,68405,68416,68437,68448,68466,68608,68680,69635,69687,69763,69807,69840,69864,69891,69926,70019,70066,70081,70084,71296,71338,73728,74606,74752,74850,77824,78894,92160,92728,93952,94020,94032,94032,94099,94111,110592,110593,119808,119892,119894,119964,119966,119967,119970,119970,119973,119974,119977,119980,119982,119993,119995,119995,119997,120003,120005,120069,120071,120074,120077,120084,120086,120092,120094,120121,120123,120126,120128,120132,120134,120134,120138,120144,120146,120485,120488,120512,120514,120538,120540,120570,120572,120596,120598,120628,120630,120654,120656,120686,120688,120712,120714,120744,120746,120770,120772,120779,126464,126467,126469,126495,126497,126498,126500,126500,126503,126503,126505,126514,126516,126519,126521,126521,126523,126523,126530,126530,126535,126535,126537,126537,126539,126539,126541,126543,126545,126546,126548,126548,126551,126551,126553,126553,126555,126555,126557,126557,126559,126559,126561,126562,126564,126564,126567,126570,126572,126578,126580,126583,126585,126588,126590,126590,126592,126601,126603,126619,126625,126627,126629,126633,126635,126651,131072,173782,173824,177972,177984,178205,194560,195101 }); derivedProps.put("ID_Continue", new int[] { 48,57,65,90,95,95,97,122,170,170,181,181,183,183,186,186,192,214,216,246,248,442,443,443,444,447,448,451,452,659,660,660,661,687,688,705,710,721,736,740,748,748,750,750,768,879,880,883,884,884,886,887,890,890,891,893,902,902,903,903,904,906,908,908,910,929,931,1013,1015,1153,1155,1159,1162,1319,1329,1366,1369,1369,1377,1415,1425,1469,1471,1471,1473,1474,1476,1477,1479,1479,1488,1514,1520,1522,1552,1562,1568,1599,1600,1600,1601,1610,1611,1631,1632,1641,1646,1647,1648,1648,1649,1747,1749,1749,1750,1756,1759,1764,1765,1766,1767,1768,1770,1773,1774,1775,1776,1785,1786,1788,1791,1791,1808,1808,1809,1809,1810,1839,1840,1866,1869,1957,1958,1968,1969,1969,1984,1993,1994,2026,2027,2035,2036,2037,2042,2042,2048,2069,2070,2073,2074,2074,2075,2083,2084,2084,2085,2087,2088,2088,2089,2093,2112,2136,2137,2139,2208,2208,2210,2220,2276,2302,2304,2306,2307,2307,2308,2361,2362,2362,2363,2363,2364,2364,2365,2365,2366,2368,2369,2376,2377,2380,2381,2381,2382,2383,2384,2384,2385,2391,2392,2401,2402,2403,2406,2415,2417,2417,2418,2423,2425,2431,2433,2433,2434,2435,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2492,2492,2493,2493,2494,2496,2497,2500,2503,2504,2507,2508,2509,2509,2510,2510,2519,2519,2524,2525,2527,2529,2530,2531,2534,2543,2544,2545,2561,2562,2563,2563,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2620,2620,2622,2624,2625,2626,2631,2632,2635,2637,2641,2641,2649,2652,2654,2654,2662,2671,2672,2673,2674,2676,2677,2677,2689,2690,2691,2691,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2748,2748,2749,2749,2750,2752,2753,2757,2759,2760,2761,2761,2763,2764,2765,2765,2768,2768,2784,2785,2786,2787,2790,2799,2817,2817,2818,2819,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2876,2876,2877,2877,2878,2878,2879,2879,2880,2880,2881,2884,2887,2888,2891,2892,2893,2893,2902,2902,2903,2903,2908,2909,2911,2913,2914,2915,2918,2927,2929,2929,2946,2946,2947,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3006,3007,3008,3008,3009,3010,3014,3016,3018,3020,3021,3021,3024,3024,3031,3031,3046,3055,3073,3075,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3133,3134,3136,3137,3140,3142,3144,3146,3149,3157,3158,3160,3161,3168,3169,3170,3171,3174,3183,3202,3203,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3260,3260,3261,3261,3262,3262,3263,3263,3264,3268,3270,3270,3271,3272,3274,3275,3276,3277,3285,3286,3294,3294,3296,3297,3298,3299,3302,3311,3313,3314,3330,3331,3333,3340,3342,3344,3346,3386,3389,3389,3390,3392,3393,3396,3398,3400,3402,3404,3405,3405,3406,3406,3415,3415,3424,3425,3426,3427,3430,3439,3450,3455,3458,3459,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3530,3530,3535,3537,3538,3540,3542,3542,3544,3551,3570,3571,3585,3632,3633,3633,3634,3635,3636,3642,3648,3653,3654,3654,3655,3662,3664,3673,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3761,3761,3762,3763,3764,3769,3771,3772,3773,3773,3776,3780,3782,3782,3784,3789,3792,3801,3804,3807,3840,3840,3864,3865,3872,3881,3893,3893,3895,3895,3897,3897,3902,3903,3904,3911,3913,3948,3953,3966,3967,3967,3968,3972,3974,3975,3976,3980,3981,3991,3993,4028,4038,4038,4096,4138,4139,4140,4141,4144,4145,4145,4146,4151,4152,4152,4153,4154,4155,4156,4157,4158,4159,4159,4160,4169,4176,4181,4182,4183,4184,4185,4186,4189,4190,4192,4193,4193,4194,4196,4197,4198,4199,4205,4206,4208,4209,4212,4213,4225,4226,4226,4227,4228,4229,4230,4231,4236,4237,4237,4238,4238,4239,4239,4240,4249,4250,4252,4253,4253,4256,4293,4295,4295,4301,4301,4304,4346,4348,4348,4349,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4957,4959,4969,4977,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5905,5906,5908,5920,5937,5938,5940,5952,5969,5970,5971,5984,5996,5998,6000,6002,6003,6016,6067,6068,6069,6070,6070,6071,6077,6078,6085,6086,6086,6087,6088,6089,6099,6103,6103,6108,6108,6109,6109,6112,6121,6155,6157,6160,6169,6176,6210,6211,6211,6212,6263,6272,6312,6313,6313,6314,6314,6320,6389,6400,6428,6432,6434,6435,6438,6439,6440,6441,6443,6448,6449,6450,6450,6451,6456,6457,6459,6470,6479,6480,6509,6512,6516,6528,6571,6576,6592,6593,6599,6600,6601,6608,6617,6618,6618,6656,6678,6679,6680,6681,6683,6688,6740,6741,6741,6742,6742,6743,6743,6744,6750,6752,6752,6753,6753,6754,6754,6755,6756,6757,6764,6765,6770,6771,6780,6783,6783,6784,6793,6800,6809,6823,6823,6912,6915,6916,6916,6917,6963,6964,6964,6965,6965,6966,6970,6971,6971,6972,6972,6973,6977,6978,6978,6979,6980,6981,6987,6992,7001,7019,7027,7040,7041,7042,7042,7043,7072,7073,7073,7074,7077,7078,7079,7080,7081,7082,7082,7083,7083,7084,7085,7086,7087,7088,7097,7098,7141,7142,7142,7143,7143,7144,7145,7146,7148,7149,7149,7150,7150,7151,7153,7154,7155,7168,7203,7204,7211,7212,7219,7220,7221,7222,7223,7232,7241,7245,7247,7248,7257,7258,7287,7288,7293,7376,7378,7380,7392,7393,7393,7394,7400,7401,7404,7405,7405,7406,7409,7410,7411,7412,7412,7413,7414,7424,7467,7468,7530,7531,7543,7544,7544,7545,7578,7579,7615,7616,7654,7676,7679,7680,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8255,8256,8276,8276,8305,8305,8319,8319,8336,8348,8400,8412,8417,8417,8421,8432,8450,8450,8455,8455,8458,8467,8469,8469,8472,8472,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8494,8494,8495,8500,8501,8504,8505,8505,8508,8511,8517,8521,8526,8526,8544,8578,8579,8580,8581,8584,11264,11310,11312,11358,11360,11387,11388,11389,11390,11492,11499,11502,11503,11505,11506,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11647,11647,11648,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11744,11775,12293,12293,12294,12294,12295,12295,12321,12329,12330,12333,12334,12335,12337,12341,12344,12346,12347,12347,12348,12348,12353,12438,12441,12442,12443,12444,12445,12446,12447,12447,12449,12538,12540,12542,12543,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,40980,40981,40981,40982,42124,42192,42231,42232,42237,42240,42507,42508,42508,42512,42527,42528,42537,42538,42539,42560,42605,42606,42606,42607,42607,42612,42621,42623,42623,42624,42647,42655,42655,42656,42725,42726,42735,42736,42737,42775,42783,42786,42863,42864,42864,42865,42887,42888,42888,42891,42894,42896,42899,42912,42922,43000,43001,43002,43002,43003,43009,43010,43010,43011,43013,43014,43014,43015,43018,43019,43019,43020,43042,43043,43044,43045,43046,43047,43047,43072,43123,43136,43137,43138,43187,43188,43203,43204,43204,43216,43225,43232,43249,43250,43255,43259,43259,43264,43273,43274,43301,43302,43309,43312,43334,43335,43345,43346,43347,43360,43388,43392,43394,43395,43395,43396,43442,43443,43443,43444,43445,43446,43449,43450,43451,43452,43452,43453,43456,43471,43471,43472,43481,43520,43560,43561,43566,43567,43568,43569,43570,43571,43572,43573,43574,43584,43586,43587,43587,43588,43595,43596,43596,43597,43597,43600,43609,43616,43631,43632,43632,43633,43638,43642,43642,43643,43643,43648,43695,43696,43696,43697,43697,43698,43700,43701,43702,43703,43704,43705,43709,43710,43711,43712,43712,43713,43713,43714,43714,43739,43740,43741,43741,43744,43754,43755,43755,43756,43757,43758,43759,43762,43762,43763,43764,43765,43765,43766,43766,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44002,44003,44004,44005,44005,44006,44007,44008,44008,44009,44010,44012,44012,44013,44013,44016,44025,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64285,64286,64286,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65024,65039,65056,65062,65075,65076,65101,65103,65136,65140,65142,65276,65296,65305,65313,65338,65343,65343,65345,65370,65382,65391,65392,65392,65393,65437,65438,65439,65440,65470,65474,65479,65482,65487,65490,65495,65498,65500,65536,65547,65549,65574,65576,65594,65596,65597,65599,65613,65616,65629,65664,65786,65856,65908,66045,66045,66176,66204,66208,66256,66304,66334,66352,66368,66369,66369,66370,66377,66378,66378,66432,66461,66464,66499,66504,66511,66513,66517,66560,66639,66640,66717,66720,66729,67584,67589,67592,67592,67594,67637,67639,67640,67644,67644,67647,67669,67840,67861,67872,67897,67968,68023,68030,68031,68096,68096,68097,68099,68101,68102,68108,68111,68112,68115,68117,68119,68121,68147,68152,68154,68159,68159,68192,68220,68352,68405,68416,68437,68448,68466,68608,68680,69632,69632,69633,69633,69634,69634,69635,69687,69688,69702,69734,69743,69760,69761,69762,69762,69763,69807,69808,69810,69811,69814,69815,69816,69817,69818,69840,69864,69872,69881,69888,69890,69891,69926,69927,69931,69932,69932,69933,69940,69942,69951,70016,70017,70018,70018,70019,70066,70067,70069,70070,70078,70079,70080,70081,70084,70096,70105,71296,71338,71339,71339,71340,71340,71341,71341,71342,71343,71344,71349,71350,71350,71351,71351,71360,71369,73728,74606,74752,74850,77824,78894,92160,92728,93952,94020,94032,94032,94033,94078,94095,94098,94099,94111,110592,110593,119141,119142,119143,119145,119149,119154,119163,119170,119173,119179,119210,119213,119362,119364,119808,119892,119894,119964,119966,119967,119970,119970,119973,119974,119977,119980,119982,119993,119995,119995,119997,120003,120005,120069,120071,120074,120077,120084,120086,120092,120094,120121,120123,120126,120128,120132,120134,120134,120138,120144,120146,120485,120488,120512,120514,120538,120540,120570,120572,120596,120598,120628,120630,120654,120656,120686,120688,120712,120714,120744,120746,120770,120772,120779,120782,120831,126464,126467,126469,126495,126497,126498,126500,126500,126503,126503,126505,126514,126516,126519,126521,126521,126523,126523,126530,126530,126535,126535,126537,126537,126539,126539,126541,126543,126545,126546,126548,126548,126551,126551,126553,126553,126555,126555,126557,126557,126559,126559,126561,126562,126564,126564,126567,126570,126572,126578,126580,126583,126585,126588,126590,126590,126592,126601,126603,126619,126625,126627,126629,126633,126635,126651,131072,173782,173824,177972,177984,178205,194560,195101,917760,917999 }); } public static long ischarprop(String propName, String target, long offset) { int iOffset = (int)offset; if (offset >= target.length()) return 0; String check = target.codePointAt(iOffset) >= 65536 ? target.substring(iOffset, iOffset + 2) : target.substring(iOffset, iOffset + 1); int[] derived = derivedProps.get(propName); if (derived != null) { /* It's one of the derived properties; see of the codepoint is * in it. */ int cp = check.codePointAt(0); for (int i = 0; i < derived.length; i += 2) if (cp >= derived[i] && cp <= derived[i + 1]) return 1; return 0; } try { // This throws if we can't get the script name, meaning it's // not a script. Character.UnicodeScript script = Character.UnicodeScript.forName(propName); return Character.UnicodeScript.of(check.codePointAt(0)) == script ? 1 : 0; } catch (IllegalArgumentException e) { String canon = canonNames.get(propName.toLowerCase()); if (canon != null) propName = canon; return check.matches("\\p{" + propName + "}") ? 1 : 0; } } public static String bitor_s(String a, String b) { int alength = a.length(); int blength = b.length(); int mlength = alength > blength ? alength : blength; StringBuilder r = new StringBuilder(mlength); int apos = 0; int bpos = 0; while (apos < alength || bpos < blength) { int cpa = apos < alength ? a.codePointAt(apos) : 0; int cpb = bpos < blength ? b.codePointAt(bpos) : 0; r.appendCodePoint(cpa | cpb); apos += Character.charCount(cpa); bpos += Character.charCount(cpb); } return r.toString(); } public static String bitxor_s(String a, String b) { int alength = a.length(); int blength = b.length(); int mlength = alength > blength ? alength : blength; StringBuilder r = new StringBuilder(mlength); int apos = 0; int bpos = 0; while (apos < alength || bpos < blength) { int cpa = apos < alength ? a.codePointAt(apos) : 0; int cpb = bpos < blength ? b.codePointAt(bpos) : 0; r.appendCodePoint(cpa ^ cpb); apos += Character.charCount(cpa); bpos += Character.charCount(cpb); } return r.toString(); } public static String bitand_s(String a, String b) { int alength = a.length(); int blength = b.length(); int mlength = alength > blength ? alength : blength; StringBuilder r = new StringBuilder(mlength); int apos = 0; int bpos = 0; while (apos < alength && bpos < blength) { int cpa = a.codePointAt(apos); int cpb = b.codePointAt(bpos); r.appendCodePoint(cpa & cpb); apos += Character.charCount(cpa); bpos += Character.charCount(cpb); } return r.toString(); } /* serialization context related opcodes */ public static String sha1(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] inBytes = str.getBytes("UTF-8"); byte[] outBytes = md.digest(inBytes); StringBuilder sb = new StringBuilder(); for (byte b : outBytes) { sb.append(String.format("%02X", b)); } return sb.toString(); } public static SixModelObject createsc(String handle, ThreadContext tc) { if (tc.gc.scs.containsKey(handle)) return tc.gc.scRefs.get(handle); SerializationContext sc = new SerializationContext(handle); tc.gc.scs.put(handle, sc); SixModelObject SCRef = tc.gc.SCRef; SCRefInstance ref = (SCRefInstance)SCRef.st.REPR.allocate(tc, SCRef.st); ref.referencedSC = sc; tc.gc.scRefs.put(handle, ref); return ref; } public static SixModelObject scsetobj(SixModelObject scRef, long idx, SixModelObject obj, ThreadContext tc) { if (scRef instanceof SCRefInstance) { SerializationContext sc = ((SCRefInstance)scRef).referencedSC; ArrayList<SixModelObject> roots = sc.root_objects; if (roots.size() == idx) roots.add(obj); else roots.set((int)idx, obj); if (obj.st.sc == null) { sc.root_stables.add(obj.st); obj.st.sc = sc; } return obj; } else { throw ExceptionHandling.dieInternal(tc, "scsetobj can only operate on an SCRef"); } } public static SixModelObject scsetcode(SixModelObject scRef, long idx, SixModelObject obj, ThreadContext tc) { if (scRef instanceof SCRefInstance) { if (obj instanceof CodeRef) { ArrayList<CodeRef> roots = ((SCRefInstance)scRef).referencedSC.root_codes; if (roots.size() == idx) roots.add((CodeRef)obj); else roots.set((int)idx, (CodeRef)obj); obj.sc = ((SCRefInstance)scRef).referencedSC; return obj; } else { throw ExceptionHandling.dieInternal(tc, "scsetcode can only store a CodeRef"); } } else { throw ExceptionHandling.dieInternal(tc, "scsetcode can only operate on an SCRef"); } } public static SixModelObject scgetobj(SixModelObject scRef, long idx, ThreadContext tc) { if (scRef instanceof SCRefInstance) { return ((SCRefInstance)scRef).referencedSC.root_objects.get((int)idx); } else { throw ExceptionHandling.dieInternal(tc, "scgetobj can only operate on an SCRef"); } } public static String scgethandle(SixModelObject scRef, ThreadContext tc) { if (scRef instanceof SCRefInstance) { return ((SCRefInstance)scRef).referencedSC.handle; } else { throw ExceptionHandling.dieInternal(tc, "scgethandle can only operate on an SCRef"); } } public static String scgetdesc(SixModelObject scRef, ThreadContext tc) { if (scRef instanceof SCRefInstance) { return ((SCRefInstance)scRef).referencedSC.description; } else { throw ExceptionHandling.dieInternal(tc, "scgetdesc can only operate on an SCRef"); } } public static long scgetobjidx(SixModelObject scRef, SixModelObject find, ThreadContext tc) { if (scRef instanceof SCRefInstance) { int idx = ((SCRefInstance)scRef).referencedSC.root_objects.indexOf(find); if (idx < 0) throw ExceptionHandling.dieInternal(tc, "Object does not exist in this SC"); return idx; } else { throw ExceptionHandling.dieInternal(tc, "scgetobjidx can only operate on an SCRef"); } } public static String scsetdesc(SixModelObject scRef, String desc, ThreadContext tc) { if (scRef instanceof SCRefInstance) { ((SCRefInstance)scRef).referencedSC.description = desc; return desc; } else { throw ExceptionHandling.dieInternal(tc, "scsetdesc can only operate on an SCRef"); } } public static long scobjcount(SixModelObject scRef, ThreadContext tc) { if (scRef instanceof SCRefInstance) { return ((SCRefInstance)scRef).referencedSC.root_objects.size(); } else { throw ExceptionHandling.dieInternal(tc, "scobjcount can only operate on an SCRef"); } } public static SixModelObject setobjsc(SixModelObject obj, SixModelObject scRef, ThreadContext tc) { if (scRef instanceof SCRefInstance) { obj.sc = ((SCRefInstance)scRef).referencedSC; return obj; } else { throw ExceptionHandling.dieInternal(tc, "setobjsc requires an SCRef"); } } public static SixModelObject getobjsc(SixModelObject obj, ThreadContext tc) { SerializationContext sc = obj.sc; if (sc == null) return null; if (!tc.gc.scRefs.containsKey(sc.handle)) { SixModelObject SCRef = tc.gc.SCRef; SCRefInstance ref = (SCRefInstance)SCRef.st.REPR.allocate(tc, SCRef.st); ref.referencedSC = sc; tc.gc.scRefs.put(sc.handle, ref); } return tc.gc.scRefs.get(sc.handle); } public static String serialize(SixModelObject scRef, SixModelObject sh, ThreadContext tc) { if (scRef instanceof SCRefInstance) { ArrayList<String> stringHeap = new ArrayList<String>(); SerializationWriter sw = new SerializationWriter(tc, ((SCRefInstance)scRef).referencedSC, stringHeap); String serialized = sw.serialize(); int index = 0; for (String s : stringHeap) { tc.native_s = s; sh.bind_pos_native(tc, index++); } return serialized; } else { throw ExceptionHandling.dieInternal(tc, "serialize was not passed a valid SCRef"); } } public static String deserialize(String blob, SixModelObject scRef, SixModelObject sh, SixModelObject cr, SixModelObject conflict, ThreadContext tc) throws IOException { if (scRef instanceof SCRefInstance) { SerializationContext sc = ((SCRefInstance)scRef).referencedSC; String[] shArray = new String[(int)sh.elems(tc)]; for (int i = 0; i < shArray.length; i++) { sh.at_pos_native(tc, i); shArray[i] = tc.native_s; } CodeRef[] crArray; int crCount; CompilationUnit cu = tc.curFrame.codeRef.staticInfo.compUnit; if (cr == null) { crArray = cu.qbidToCodeRef; crCount = cu.serializedCodeRefCount(); } else { crArray = new CodeRef[(int)cr.elems(tc)]; crCount = crArray.length; for (int i = 0; i < crArray.length; i++) crArray[i] = (CodeRef)cr.at_pos_boxed(tc, i); } ByteBuffer binaryBlob; if (blob == null) { binaryBlob = ByteBuffer.wrap( LibraryLoader.readEverything( cu.getClass().getResourceAsStream( cu.getClass().getSimpleName() + ".serialized" ) ) ); } else { binaryBlob = Base64.decode(blob); } SerializationReader sr = new SerializationReader( tc, sc, shArray, crArray, crCount, binaryBlob); sr.deserialize(); return blob; } else { throw ExceptionHandling.dieInternal(tc, "deserialize was not passed a valid SCRef"); } } public static SixModelObject wval(String sc, long idx, ThreadContext tc) { return tc.gc.scs.get(sc).root_objects.get((int)idx); } public static long scwbdisable(ThreadContext tc) { return ++tc.scwbDisableDepth; } public static long scwbenable(ThreadContext tc) { return --tc.scwbDisableDepth; } public static SixModelObject pushcompsc(SixModelObject sc, ThreadContext tc) { if (sc instanceof SCRefInstance) { if (tc.compilingSCs == null) tc.compilingSCs = new ArrayList<SCRefInstance>(); tc.compilingSCs.add((SCRefInstance)sc); return sc; } else { throw ExceptionHandling.dieInternal(tc, "Can only push an SCRef with pushcompsc"); } } public static SixModelObject popcompsc(ThreadContext tc) { if (tc.compilingSCs == null) throw ExceptionHandling.dieInternal(tc, "No current compiling SC."); int idx = tc.compilingSCs.size() - 1; SixModelObject result = tc.compilingSCs.get(idx); tc.compilingSCs.remove(idx); if (idx == 0) tc.compilingSCs = null; return result; } /* SC write barriers (not really ops, but putting them here with the SC * related bits). */ public static void scwbObject(ThreadContext tc, SixModelObject obj) { int cscSize = tc.compilingSCs == null ? 0 : tc.compilingSCs.size(); if (cscSize == 0 || tc.scwbDisableDepth > 0) return; /* See if the object is actually owned by another, and it's the * owner we need to repossess. */ SixModelObject owner = obj.sc.owned_objects.get(obj); if (owner != null) obj = owner; SerializationContext compSC = tc.compilingSCs.get(cscSize - 1).referencedSC; if (obj.sc != compSC) { compSC.repossessObject(obj.sc, obj); obj.sc = compSC; } } public static void scwbSTable(ThreadContext tc, STable st) { int cscSize = tc.compilingSCs == null ? 0 : tc.compilingSCs.size(); if (cscSize == 0 || tc.scwbDisableDepth > 0) return; SerializationContext compSC = tc.compilingSCs.get(cscSize - 1).referencedSC; if (st.sc != compSC) { compSC.repossessSTable(st.sc, st); st.sc = compSC; } } /* bitwise operations. */ public static long bitor_i(long valA, long valB) { return valA | valB; } public static long bitxor_i(long valA, long valB) { return valA ^ valB; } public static long bitand_i(long valA, long valB) { return valA & valB; } public static long bitshiftl_i(long valA, long valB) { return valA << valB; } public static long bitshiftr_i(long valA, long valB) { return valA >> valB; } public static long bitneg_i(long val) { return ~val; } /* Relational. */ public static long cmp_i(long a, long b) { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; } } public static long iseq_i(long a, long b) { return a == b ? 1 : 0; } public static long isne_i(long a, long b) { return a != b ? 1 : 0; } public static long islt_i(long a, long b) { return a < b ? 1 : 0; } public static long isle_i(long a, long b) { return a <= b ? 1 : 0; } public static long isgt_i(long a, long b) { return a > b ? 1 : 0; } public static long isge_i(long a, long b) { return a >= b ? 1 : 0; } public static long cmp_n(double a, double b) { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; } } public static long iseq_n(double a, double b) { return a == b ? 1 : 0; } public static long isne_n(double a, double b) { return a != b ? 1 : 0; } public static long islt_n(double a, double b) { return a < b ? 1 : 0; } public static long isle_n(double a, double b) { return a <= b ? 1 : 0; } public static long isgt_n(double a, double b) { return a > b ? 1 : 0; } public static long isge_n(double a, double b) { return a >= b ? 1 : 0; } public static long cmp_s(String a, String b) { int result = a.compareTo(b); return result < 0 ? -1 : result > 0 ? 1 : 0; } public static long iseq_s(String a, String b) { return a.equals(b) ? 1 : 0; } public static long isne_s(String a, String b) { return a.equals(b) ? 0 : 1; } public static long islt_s(String a, String b) { return a.compareTo(b) < 0 ? 1 : 0; } public static long isle_s(String a, String b) { return a.compareTo(b) <= 0 ? 1 : 0; } public static long isgt_s(String a, String b) { return a.compareTo(b) > 0 ? 1 : 0; } public static long isge_s(String a, String b) { return a.compareTo(b) >= 0 ? 1 : 0; } /* Code object related. */ public static SixModelObject takeclosure(SixModelObject code, ThreadContext tc) { if (code instanceof CodeRef) { CodeRef clone = (CodeRef)code.clone(tc); clone.outer = tc.curFrame; return clone; } else { throw ExceptionHandling.dieInternal(tc, "takeclosure can only be used with a CodeRef"); } } public static SixModelObject getcodeobj(SixModelObject code, ThreadContext tc) { if (code instanceof CodeRef) return ((CodeRef)code).codeObject; else throw ExceptionHandling.dieInternal(tc, "getcodeobj can only be used with a CodeRef"); } public static SixModelObject setcodeobj(SixModelObject code, SixModelObject obj, ThreadContext tc) { if (code instanceof CodeRef) { ((CodeRef)code).codeObject = obj; return code; } else { throw ExceptionHandling.dieInternal(tc, "setcodeobj can only be used with a CodeRef"); } } public static String getcodename(SixModelObject code, ThreadContext tc) { if (code instanceof CodeRef) return ((CodeRef)code).name; else throw ExceptionHandling.dieInternal(tc, "getcodename can only be used with a CodeRef"); } public static SixModelObject setcodename(SixModelObject code, String name, ThreadContext tc) { if (code instanceof CodeRef) { ((CodeRef)code).name = name; return code; } else { throw ExceptionHandling.dieInternal(tc, "setcodename can only be used with a CodeRef"); } } public static String getcodecuid(SixModelObject code, ThreadContext tc) { if (code instanceof CodeRef) return ((CodeRef)code).staticInfo.uniqueId; else throw ExceptionHandling.dieInternal(tc, "getcodename can only be used with a CodeRef"); } public static SixModelObject forceouterctx(SixModelObject code, SixModelObject ctx, ThreadContext tc) { if (!(code instanceof CodeRef)) throw ExceptionHandling.dieInternal(tc, "forceouterctx first operand must be a CodeRef"); if (!(ctx instanceof ContextRefInstance)) throw ExceptionHandling.dieInternal(tc, "forceouterctx second operand must be a ContextRef"); ((CodeRef)code).outer = ((ContextRefInstance)ctx).context; return code; } public static SixModelObject freshcoderef(SixModelObject code, ThreadContext tc) { if (!(code instanceof CodeRef)) throw ExceptionHandling.dieInternal(tc, "freshcoderef must be used on a CodeRef"); CodeRef clone = (CodeRef)code.clone(tc); clone.staticInfo = clone.staticInfo.clone(); clone.staticInfo.staticCode = clone; return clone; } public static SixModelObject markcodestatic(SixModelObject code, ThreadContext tc) { if (!(code instanceof CodeRef)) throw ExceptionHandling.dieInternal(tc, "markcodestatic must be used on a CodeRef"); ((CodeRef)code).isStaticCodeRef = true; return code; } public static SixModelObject markcodestub(SixModelObject code, ThreadContext tc) { if (!(code instanceof CodeRef)) throw ExceptionHandling.dieInternal(tc, "markcodestub must be used on a CodeRef"); ((CodeRef)code).isCompilerStub = true; return code; } public static SixModelObject getstaticcode(SixModelObject code, ThreadContext tc) { if (code instanceof CodeRef) return ((CodeRef)code).staticInfo.staticCode; else throw ExceptionHandling.dieInternal(tc, "getstaticcode can only be used with a CodeRef"); } public static void takedispatcher(int lexIdx, ThreadContext tc) { if (tc.currentDispatcher != null) { tc.curFrame.oLex[lexIdx] = tc.currentDispatcher; tc.currentDispatcher = null; } } /* process related opcodes */ public static long exit(final long status, ThreadContext tc) { tc.gc.exit((int) status); return status; } public static double sleep(final double seconds) { // Is this really the right behavior, i.e., swallowing all // InterruptedExceptions? As far as I can tell the original // nqp::sleep could not be interrupted, so that behavior is // duplicated here, but that doesn't mean it's the right thing // to do on the JVM... long now = System.currentTimeMillis(); final long awake = now + (long) (seconds * 1000); while ((now = System.currentTimeMillis()) < awake) { long millis = awake - now; try { Thread.sleep(millis); } catch(InterruptedException e) { // swallow } } return seconds; } public static SixModelObject getenvhash(ThreadContext tc) { SixModelObject hashType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.hashType; SixModelObject strType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.strBoxType; SixModelObject res = hashType.st.REPR.allocate(tc, hashType.st); Map<String, String> env = System.getenv(); for (String envName : env.keySet()) res.bind_key_boxed(tc, envName, box_s(env.get(envName), strType, tc)); return res; } public static long getpid(ThreadContext tc) { try { java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory.getRuntimeMXBean(); java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm"); jvm.setAccessible(true); Object mgmt = jvm.get(runtime); java.lang.reflect.Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId"); pid_method.setAccessible(true); return (Integer)pid_method.invoke(mgmt); } catch (Throwable t) { throw ExceptionHandling.dieInternal(tc, t); } } public static SixModelObject jvmgetproperties(ThreadContext tc) { SixModelObject hashType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.hashType; SixModelObject strType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.strBoxType; SixModelObject res = hashType.st.REPR.allocate(tc, hashType.st); Properties env = System.getProperties(); for (String envName : env.stringPropertyNames()) { String propVal = env.getProperty(envName); if (envName.equals("os.name")) { // Normalize OS name (some cases likely missing). String pvlc = propVal.toLowerCase(); if (pvlc.indexOf("win") >= 0) propVal = "MSWin32"; else if (pvlc.indexOf("mac os x") >= 0) propVal = "darwin"; } res.bind_key_boxed(tc, envName, box_s(propVal, strType, tc)); } return res; } /* Thread related. */ static class CodeRunnable implements Runnable { private GlobalContext gc; private SixModelObject vmthread; private SixModelObject code; public CodeRunnable(GlobalContext gc, SixModelObject vmthread, SixModelObject code) { this.gc = gc; this.vmthread = vmthread; this.code = code; } public void run() { ThreadContext tc = gc.getCurrentThreadContext(); tc.VMThread = vmthread; invokeArgless(tc, code); } } public static SixModelObject newthread(SixModelObject code, long appLifetime, ThreadContext tc) { SixModelObject thread = tc.gc.Thread.st.REPR.allocate(tc, tc.gc.Thread.st); ((VMThreadInstance)thread).thread = new Thread(new CodeRunnable(tc.gc, thread, code)); ((VMThreadInstance)thread).thread.setDaemon(appLifetime != 0); return thread; } public static SixModelObject threadrun(SixModelObject thread, ThreadContext tc) { if (thread instanceof VMThreadInstance) ((VMThreadInstance)thread).thread.start(); else throw ExceptionHandling.dieInternal(tc, "threadrun requires an operand with REPR VMThread"); return thread; } public static SixModelObject threadjoin(SixModelObject thread, ThreadContext tc) { if (thread instanceof VMThreadInstance) { try { ((VMThreadInstance)thread).thread.join(); } catch (Exception e) { throw new RuntimeException(e); } } else { throw ExceptionHandling.dieInternal(tc, "threadjoin requires an operand with REPR VMThread"); } return thread; } public static long threadid(SixModelObject thread, ThreadContext tc) { if (thread instanceof VMThreadInstance) return ((VMThreadInstance)thread).thread.getId(); else throw ExceptionHandling.dieInternal(tc, "threadid requires an operand with REPR VMThread"); } public static long threadyield(ThreadContext tc) { Thread.yield(); return 0; } public static SixModelObject currentthread(ThreadContext tc) { SixModelObject thread = tc.VMThread; if (thread == null) { thread = tc.gc.Thread.st.REPR.allocate(tc, tc.gc.Thread.st); ((VMThreadInstance)thread).thread = Thread.currentThread(); tc.VMThread = thread; } return thread; } public static SixModelObject lock(SixModelObject lock, ThreadContext tc) { if (lock instanceof ReentrantMutexInstance) ((ReentrantMutexInstance)lock).lock.lock(); else throw ExceptionHandling.dieInternal(tc, "lock requires an operand with REPR ReentrantMutex"); return lock; } public static SixModelObject unlock(SixModelObject lock, ThreadContext tc) { if (lock instanceof ReentrantMutexInstance) ((ReentrantMutexInstance)lock).lock.unlock(); else throw ExceptionHandling.dieInternal(tc, "unlock requires an operand with REPR ReentrantMutex"); return lock; } public static SixModelObject getlockcondvar(SixModelObject lock, SixModelObject type, ThreadContext tc) { if (!(lock instanceof ReentrantMutexInstance)) throw ExceptionHandling.dieInternal(tc, "getlockcondvar requires an operand with REPR ReentrantMutex"); if (!(type.st.REPR instanceof ConditionVariable)) throw ExceptionHandling.dieInternal(tc, "getlockcondvar requires a result type with REPR ConditionVariable"); ConditionVariableInstance result = new ConditionVariableInstance(); result.st = type.st; result.condvar = ((ReentrantMutexInstance)lock).lock.newCondition(); return result; } public static SixModelObject condwait(SixModelObject cv, ThreadContext tc) throws InterruptedException { if (cv instanceof ConditionVariableInstance) ((ConditionVariableInstance)cv).condvar.await(); else throw ExceptionHandling.dieInternal(tc, "condwait requires an operand with REPR ConditionVariable"); return cv; } public static SixModelObject condsignalone(SixModelObject cv, ThreadContext tc) { if (cv instanceof ConditionVariableInstance) ((ConditionVariableInstance)cv).condvar.signal(); else throw ExceptionHandling.dieInternal(tc, "condsignalone requires an operand with REPR ConditionVariable"); return cv; } public static SixModelObject condsignalall(SixModelObject cv, ThreadContext tc) { if (cv instanceof ConditionVariableInstance) ((ConditionVariableInstance)cv).condvar.signalAll(); else throw ExceptionHandling.dieInternal(tc, "condsignalall requires an operand with REPR ConditionVariable"); return cv; } public static SixModelObject semacquire(SixModelObject sem, ThreadContext tc) { try { if (sem instanceof SemaphoreInstance) ((SemaphoreInstance)sem).sem.acquire(); else throw ExceptionHandling.dieInternal(tc, "semacquire requires an operand with REPR Semaphore"); } catch (InterruptedException e) { throw ExceptionHandling.dieInternal(tc, "semacquire was interrupted"); } return sem; } public static long semtryacquire(SixModelObject sem, ThreadContext tc) { boolean result; if (sem instanceof SemaphoreInstance) result = ((SemaphoreInstance)sem).sem.tryAcquire(); else throw ExceptionHandling.dieInternal(tc, "semtryacquire requires an operand with REPR Semaphore"); return result ? 1 : 0; } public static SixModelObject semrelease(SixModelObject sem, ThreadContext tc) { if (sem instanceof SemaphoreInstance) ((SemaphoreInstance)sem).sem.release(); else throw ExceptionHandling.dieInternal(tc, "semrelease requires an operand with REPR Semaphore"); return sem; } public static SixModelObject queuepoll(SixModelObject queue, ThreadContext tc) { if (queue instanceof ConcBlockingQueueInstance) return ((ConcBlockingQueueInstance)queue).queue.poll(); else throw ExceptionHandling.dieInternal(tc, "queuepoll requires an operand with REPR ConcBlockingQueue"); } /* Asynchronousy operations. */ private static class AddToQueueTimerTask extends TimerTask implements IIOCancelable { private LinkedBlockingQueue<SixModelObject> queue; private SixModelObject schedulee; public AddToQueueTimerTask(LinkedBlockingQueue<SixModelObject> queue, SixModelObject schedulee) { this.queue = queue; this.schedulee = schedulee; } public void run() { queue.add(schedulee); } public void cancel(ThreadContext tc) { cancel(); } } public static SixModelObject timer(SixModelObject queue, SixModelObject schedulee, long timeout, long repeat, SixModelObject handle_type, ThreadContext tc) { if (!(queue instanceof ConcBlockingQueueInstance)) throw ExceptionHandling.dieInternal(tc, "timer's first argument should have REPR ConcBlockingQueue"); AddToQueueTimerTask tt = new AddToQueueTimerTask(((ConcBlockingQueueInstance)queue).queue, schedulee); if (repeat > 0) tc.gc.timer.scheduleAtFixedRate(tt, timeout, repeat); else tc.gc.timer.schedule(tt, timeout); /* XXX TODO: cancellation handle. */ AsyncTaskInstance handle = (AsyncTaskInstance) handle_type.st.REPR.allocate(tc, handle_type.st); handle.handle = tt; return handle; } public static SixModelObject cancel(SixModelObject handle, ThreadContext tc) { AsyncTaskInstance task = (AsyncTaskInstance) handle; if (task.handle instanceof IIOCancelable) { ((IIOCancelable)task.handle).cancel(tc); } else { throw ExceptionHandling.dieInternal(tc, "This handle does not support cancel"); } return handle; } /* Exception related. */ public static void die_s_c(String msg, ThreadContext tc) { // Construct exception object. SixModelObject exType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.exceptionType; VMExceptionInstance exObj = (VMExceptionInstance)exType.st.REPR.allocate(tc, exType.st); exObj.message = msg; exObj.category = ExceptionHandling.EX_CAT_CATCH; exObj.origin = tc.curFrame; exObj.nativeTrace = (new Throwable()).getStackTrace(); ExceptionHandling.handlerDynamic(tc, ExceptionHandling.EX_CAT_CATCH, true, exObj); } public static void throwcatdyn_c(long category, ThreadContext tc) { ExceptionHandling.handlerDynamic(tc, category, false, null); } public static SixModelObject exception(ThreadContext tc) { int numHandlers = tc.handlers.size(); if (numHandlers > 0) return tc.handlers.get(numHandlers - 1).exObj; else throw ExceptionHandling.dieInternal(tc, "Cannot get exception object ouside of exception handler"); } public static long getextype(SixModelObject obj, ThreadContext tc) { if (obj instanceof VMExceptionInstance) return ((VMExceptionInstance)obj).category; else throw ExceptionHandling.dieInternal(tc, "getextype needs an object with VMException representation"); } public static long setextype(SixModelObject obj, long category, ThreadContext tc) { if (obj instanceof VMExceptionInstance) { ((VMExceptionInstance)obj).category = category; return category; } else throw ExceptionHandling.dieInternal(tc, "setextype needs an object with VMException representation"); } public static String getmessage(SixModelObject obj, ThreadContext tc) { if (obj instanceof VMExceptionInstance) { String msg = ((VMExceptionInstance)obj).message; return msg == null ? "Died" : msg; } else { throw ExceptionHandling.dieInternal(tc, "getmessage needs an object with VMException representation"); } } public static String setmessage(SixModelObject obj, String msg, ThreadContext tc) { if (obj instanceof VMExceptionInstance) { ((VMExceptionInstance)obj).message = msg; return msg; } else { throw ExceptionHandling.dieInternal(tc, "setmessage needs an object with VMException representation"); } } public static SixModelObject getpayload(SixModelObject obj, ThreadContext tc) { if (obj instanceof VMExceptionInstance) return ((VMExceptionInstance)obj).payload; else throw ExceptionHandling.dieInternal(tc, "getpayload needs an object with VMException representation"); } public static SixModelObject setpayload(SixModelObject obj, SixModelObject payload, ThreadContext tc) { if (obj instanceof VMExceptionInstance) { ((VMExceptionInstance)obj).payload = payload; return payload; } else { throw ExceptionHandling.dieInternal(tc, "setpayload needs an object with VMException representation"); } } public static SixModelObject newexception(ThreadContext tc) { SixModelObject exType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.exceptionType; SixModelObject exObj = (VMExceptionInstance)exType.st.REPR.allocate(tc, exType.st); return exObj; } public static SixModelObject backtracestrings(SixModelObject obj, ThreadContext tc) { if (obj instanceof VMExceptionInstance) { SixModelObject Array = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.listType; SixModelObject Str = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.strBoxType; SixModelObject result = Array.st.REPR.allocate(tc, Array.st); List<String> lines = ExceptionHandling.backtraceStrings(((VMExceptionInstance)obj)); for (int i = 0; i < lines.size(); i++) result.bind_pos_boxed(tc, i, box_s(lines.get(i), Str, tc)); return result; } else { throw ExceptionHandling.dieInternal(tc, "backtracestring needs an object with VMException representation"); } } public static SixModelObject backtrace(SixModelObject obj, ThreadContext tc) { if (obj instanceof VMExceptionInstance) { SixModelObject Array = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.listType; SixModelObject Hash = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.hashType; SixModelObject Str = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.strBoxType; SixModelObject Int = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.intBoxType; SixModelObject result = Array.st.REPR.allocate(tc, Array.st); for (ExceptionHandling.TraceElement te : ExceptionHandling.backtrace(((VMExceptionInstance)obj))) { if (te.frame.codeRef.staticInfo.isThunk) continue; SixModelObject annots = Hash.st.REPR.allocate(tc, Hash.st); if (te.file != null) annots.bind_key_boxed(tc, "file", box_s(te.file, Str, tc)); if (te.line >= 0) annots.bind_key_boxed(tc, "line", box_i(te.line, Int, tc)); SixModelObject row = Hash.st.REPR.allocate(tc, Hash.st); row.bind_key_boxed(tc, "sub", te.frame.codeRef); row.bind_key_boxed(tc, "annotations", annots); result.push_boxed(tc, row); } return result; } else { throw ExceptionHandling.dieInternal(tc, "backtrace needs an object with VMException representation"); } } public static void _throw_c(SixModelObject obj, ThreadContext tc) { if (obj instanceof VMExceptionInstance) { VMExceptionInstance ex = (VMExceptionInstance)obj; ex.origin = tc.curFrame; ex.nativeTrace = (new Throwable()).getStackTrace(); ExceptionHandling.handlerDynamic(tc, ex.category, false, ex); } else { throw ExceptionHandling.dieInternal(tc, "throw needs an object with VMException representation"); } } public static void _is_same_label(UnwindException uwex, SixModelObject where, long outerHandler, ThreadContext tc) { if ((uwex.category & ExceptionHandling.EX_CAT_LABELED) == 0) return; if (uwex instanceof UnwindException) { if (uwex.payload.hashCode() == where.hashCode()) return; VMExceptionInstance vmex = (VMExceptionInstance)newexception(tc); /* We're moving to the outside so we do not rethrow to us. */ vmex.category = uwex.category; vmex.payload = uwex.payload; tc.curFrame.curHandler = outerHandler; ExceptionHandling.handlerDynamic(tc, vmex.category, false, vmex); } else { throw ExceptionHandling.dieInternal(tc, "_is_same_label needs an object with UnwindException representation"); } } public static void _rethrow_label(UnwindException uwex, long outerHandler, ThreadContext tc) { if ((uwex.category & ExceptionHandling.EX_CAT_LABELED) == 0) return; if (uwex instanceof UnwindException) { /* We're moving to the outside so we do not rethrow to us. */ VMExceptionInstance vmex = (VMExceptionInstance)newexception(tc); vmex.category = uwex.category; vmex.payload = uwex.payload; tc.curFrame.curHandler = outerHandler; ExceptionHandling.handlerDynamic(tc, vmex.category, false, vmex); } else { throw ExceptionHandling.dieInternal(tc, "_is_same_label needs an object with UnwindException representation"); } } public static void rethrow_c(SixModelObject obj, ThreadContext tc) { if (obj instanceof VMExceptionInstance) { VMExceptionInstance ex = (VMExceptionInstance)obj; ExceptionHandling.handlerDynamic(tc, ex.category, false, ex); } else { throw ExceptionHandling.dieInternal(tc, "rethrow needs an object with VMException representation"); } } private static ResumeException theResumer = new ResumeException(); public static SixModelObject resume(SixModelObject obj, ThreadContext tc) { throw theResumer; } /* compatibility shims for next bootstrap TODO */ public static String die_s(String msg, ThreadContext tc) { try { die_s_c(msg, tc); } catch (SaveStackException sse) { ExceptionHandling.dieInternal(tc, "control operator crossed continuation barrier"); } return result_s(tc.curFrame); } public static SixModelObject throwcatdyn(long category, ThreadContext tc) { try { throwcatdyn_c(category, tc); } catch (SaveStackException sse) { ExceptionHandling.dieInternal(tc, "control operator crossed continuation barrier"); } return result_o(tc.curFrame); } public static SixModelObject _throw(SixModelObject obj, ThreadContext tc) { try { _throw_c(obj, tc); } catch (SaveStackException sse) { ExceptionHandling.dieInternal(tc, "control operator crossed continuation barrier"); } return result_o(tc.curFrame); } public static SixModelObject rethrow(SixModelObject obj, ThreadContext tc) { try { rethrow_c(obj, tc); } catch (SaveStackException sse) { ExceptionHandling.dieInternal(tc, "control operator crossed continuation barrier"); } return result_o(tc.curFrame); } /* HLL configuration and compiler related options. */ public static SixModelObject sethllconfig(String language, SixModelObject configHash, ThreadContext tc) { HLLConfig config = tc.gc.getHLLConfigFor(language); if (configHash.exists_key(tc, "int_box") != 0) config.intBoxType = configHash.at_key_boxed(tc, "int_box"); if (configHash.exists_key(tc, "num_box") != 0) config.numBoxType = configHash.at_key_boxed(tc, "num_box"); if (configHash.exists_key(tc, "str_box") != 0) config.strBoxType = configHash.at_key_boxed(tc, "str_box"); if (configHash.exists_key(tc, "list") != 0) config.listType = configHash.at_key_boxed(tc, "list"); if (configHash.exists_key(tc, "hash") != 0) config.hashType = configHash.at_key_boxed(tc, "hash"); if (configHash.exists_key(tc, "slurpy_array") != 0) config.slurpyArrayType = configHash.at_key_boxed(tc, "slurpy_array"); if (configHash.exists_key(tc, "slurpy_hash") != 0) config.slurpyHashType = configHash.at_key_boxed(tc, "slurpy_hash"); if (configHash.exists_key(tc, "array_iter") != 0) config.arrayIteratorType = configHash.at_key_boxed(tc, "array_iter"); if (configHash.exists_key(tc, "hash_iter") != 0) config.hashIteratorType = configHash.at_key_boxed(tc, "hash_iter"); if (configHash.exists_key(tc, "foreign_type_int") != 0) config.foreignTypeInt = configHash.at_key_boxed(tc, "foreign_type_int"); if (configHash.exists_key(tc, "foreign_type_num") != 0) config.foreignTypeNum = configHash.at_key_boxed(tc, "foreign_type_num"); if (configHash.exists_key(tc, "foreign_type_str") != 0) config.foreignTypeStr = configHash.at_key_boxed(tc, "foreign_type_str"); if (configHash.exists_key(tc, "foreign_transform_int") != 0) config.foreignTransformInt = configHash.at_key_boxed(tc, "foreign_transform_int"); if (configHash.exists_key(tc, "foreign_transform_str") != 0) config.foreignTransformNum = configHash.at_key_boxed(tc, "foreign_transform_num"); if (configHash.exists_key(tc, "foreign_transform_num") != 0) config.foreignTransformStr = configHash.at_key_boxed(tc, "foreign_transform_str"); if (configHash.exists_key(tc, "foreign_transform_array") != 0) config.foreignTransformArray = configHash.at_key_boxed(tc, "foreign_transform_array"); if (configHash.exists_key(tc, "foreign_transform_hash") != 0) config.foreignTransformHash = configHash.at_key_boxed(tc, "foreign_transform_hash"); if (configHash.exists_key(tc, "foreign_transform_code") != 0) config.foreignTransformCode = configHash.at_key_boxed(tc, "foreign_transform_code"); if (configHash.exists_key(tc, "foreign_transform_any") != 0) config.foreignTransformAny = configHash.at_key_boxed(tc, "foreign_transform_any"); if (configHash.exists_key(tc, "null_value") != 0) config.nullValue = configHash.at_key_boxed(tc, "null_value"); if (configHash.exists_key(tc, "exit_handler") != 0) config.exitHandler = configHash.at_key_boxed(tc, "exit_handler"); return configHash; } public static SixModelObject getcomp(String name, ThreadContext tc) { return tc.gc.compilerRegistry.get(name); } public static SixModelObject bindcomp(String name, SixModelObject comp, ThreadContext tc) { tc.gc.compilerRegistry.put(name, comp); return comp; } public static SixModelObject getcurhllsym(String name, ThreadContext tc) { String hllName = tc.curFrame.codeRef.staticInfo.compUnit.hllName(); HashMap<String, SixModelObject> hllSyms = tc.gc.hllSyms.get(hllName); return hllSyms == null ? null : hllSyms.get(name); } public static SixModelObject bindcurhllsym(String name, SixModelObject value, ThreadContext tc) { String hllName = tc.curFrame.codeRef.staticInfo.compUnit.hllName(); HashMap<String, SixModelObject> hllSyms = tc.gc.hllSyms.get(hllName); if (hllSyms == null) { hllSyms = new HashMap<String, SixModelObject>(); tc.gc.hllSyms.put(hllName, hllSyms); } hllSyms.put(name, value); return value; } public static SixModelObject gethllsym(String hllName, String name, ThreadContext tc) { HashMap<String, SixModelObject> hllSyms = tc.gc.hllSyms.get(hllName); return hllSyms == null ? null : hllSyms.get(name); } public static SixModelObject bindhllsym(String hllName, String name, SixModelObject value, ThreadContext tc) { HashMap<String, SixModelObject> hllSyms = tc.gc.hllSyms.get(hllName); if (hllSyms == null) { hllSyms = new HashMap<String, SixModelObject>(); tc.gc.hllSyms.put(hllName, hllSyms); } hllSyms.put(name, value); return value; } public static String loadbytecode(String filename, ThreadContext tc) { new LibraryLoader().load(tc, filename); return filename; } public static SixModelObject settypehll(SixModelObject type, String language, ThreadContext tc) { type.st.hllOwner = tc.gc.getHLLConfigFor(language); return type; } public static SixModelObject settypehllrole(SixModelObject type, long role, ThreadContext tc) { type.st.hllRole = role; return type; } public static SixModelObject hllize(SixModelObject obj, ThreadContext tc) { HLLConfig wanted = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig; if (obj != null && obj.st.hllOwner == wanted) return obj; else return hllizeInternal(obj, wanted, tc); } public static SixModelObject hllizefor(SixModelObject obj, String language, ThreadContext tc) { HLLConfig wanted = tc.gc.getHLLConfigFor(language); if (obj != null && obj.st.hllOwner == wanted) return obj; else return hllizeInternal(obj, wanted, tc); } private static SixModelObject hllizeInternal(SixModelObject obj, HLLConfig wanted, ThreadContext tc) { /* Map nulls to the language's designated null value. */ if (obj == null) return wanted.nullValue; /* Go by what role the object plays. */ switch ((int)obj.st.hllRole) { case HLLConfig.ROLE_INT: if (wanted.foreignTypeInt != null) { return box_i(obj.get_int(tc), wanted.foreignTypeInt, tc); } else if (wanted.foreignTransformInt != null) { throw new RuntimeException("foreign_transform_int NYI"); } else { return obj; } case HLLConfig.ROLE_NUM: if (wanted.foreignTypeNum != null) { return box_n(obj.get_num(tc), wanted.foreignTypeNum, tc); } else if (wanted.foreignTransformNum != null) { throw new RuntimeException("foreign_transform_num NYI"); } else { return obj; } case HLLConfig.ROLE_STR: if (wanted.foreignTypeStr != null) { return box_s(obj.get_str(tc), wanted.foreignTypeStr, tc); } else if (wanted.foreignTransformStr != null) { throw new RuntimeException("foreign_transform_str NYI"); } else { return obj; } case HLLConfig.ROLE_ARRAY: if (wanted.foreignTransformArray != null) { invokeDirect(tc, wanted.foreignTransformArray, invocantCallSite, new Object[] { obj }); return result_o(tc.curFrame); } else { return obj; } case HLLConfig.ROLE_HASH: if (wanted.foreignTransformHash != null) { invokeDirect(tc, wanted.foreignTransformHash, invocantCallSite, new Object[] { obj }); return result_o(tc.curFrame); } else { return obj; } case HLLConfig.ROLE_CODE: if (wanted.foreignTransformCode != null) { invokeDirect(tc, wanted.foreignTransformCode, invocantCallSite, new Object[] { obj }); return result_o(tc.curFrame); } else { return obj; } default: if (wanted.foreignTransformAny != null) { invokeDirect(tc, wanted.foreignTransformAny, invocantCallSite, new Object[] { obj }); return result_o(tc.curFrame); } else { return obj; } } } /* NFA operations. */ public static SixModelObject nfafromstatelist(SixModelObject states, SixModelObject nfaType, ThreadContext tc) { /* Create NFA object. */ NFAInstance nfa = (NFAInstance)nfaType.st.REPR.allocate(tc, nfaType.st); /* The first state entry is the fates list. */ nfa.fates = states.at_pos_boxed(tc, 0); /* Go over the rest and convert to the NFA. */ int numStates = (int)states.elems(tc) - 1; nfa.numStates = numStates; nfa.states = new NFAStateInfo[numStates][]; for (int i = 0; i < numStates; i++) { SixModelObject edgeInfo = states.at_pos_boxed(tc, i + 1); int elems = (int)edgeInfo.elems(tc); int edges = elems / 3; int curEdge = 0; nfa.states[i] = new NFAStateInfo[edges]; for (int j = 0; j < elems; j += 3) { int act = (int)smart_numify(edgeInfo.at_pos_boxed(tc, j), tc); int to = (int)smart_numify(edgeInfo.at_pos_boxed(tc, j + 2), tc); nfa.states[i][curEdge] = new NFAStateInfo(); nfa.states[i][curEdge].act = act; nfa.states[i][curEdge].to = to; switch (act) { case NFA.EDGE_FATE: case NFA.EDGE_CODEPOINT: case NFA.EDGE_CODEPOINT_NEG: case NFA.EDGE_CHARCLASS: case NFA.EDGE_CHARCLASS_NEG: nfa.states[i][curEdge].arg_i = (int)smart_numify(edgeInfo.at_pos_boxed(tc, j + 1), tc); break; case NFA.EDGE_CHARLIST: case NFA.EDGE_CHARLIST_NEG: nfa.states[i][curEdge].arg_s = edgeInfo.at_pos_boxed(tc, j + 1).get_str(tc); break; case NFA.EDGE_CODEPOINT_I: case NFA.EDGE_CODEPOINT_I_NEG: { SixModelObject arg = edgeInfo.at_pos_boxed(tc, j + 1); nfa.states[i][curEdge].arg_lc = (char)smart_numify(arg.at_pos_boxed(tc, 0), tc); nfa.states[i][curEdge].arg_uc = (char)smart_numify(arg.at_pos_boxed(tc, 1), tc); break; } } curEdge++; } } return nfa; } public static SixModelObject nfatostatelist(SixModelObject nfa, ThreadContext tc) { throw ExceptionHandling.dieInternal(tc, "nfatostatelist NYI"); } public static SixModelObject nfarunproto(SixModelObject nfa, String target, long pos, ThreadContext tc) { /* Run the NFA. */ int[] fates = runNFA(tc, (NFAInstance)nfa, target, pos); /* Copy results into an RIA. */ SixModelObject BOOTIntArray = tc.gc.BOOTIntArray; SixModelObject fateRes = BOOTIntArray.st.REPR.allocate(tc, BOOTIntArray.st); for (int i = 0; i < fates.length; i++) { tc.native_i = fates[i]; fateRes.bind_pos_native(tc, i); } return fateRes; } public static SixModelObject nfarunalt(SixModelObject nfa, String target, long pos, SixModelObject bstack, SixModelObject cstack, SixModelObject marks, ThreadContext tc) { /* Run the NFA. */ int[] fates = runNFA(tc, (NFAInstance)nfa, target, pos); /* Push the results onto the bstack. */ long caps = cstack == null || cstack instanceof TypeObject ? 0 : cstack.elems(tc); for (int i = 0; i < fates.length; i++) { marks.at_pos_native(tc, fates[i]); bstack.push_native(tc); tc.native_i = pos; bstack.push_native(tc); tc.native_i = 0; bstack.push_native(tc); tc.native_i = caps; bstack.push_native(tc); } return nfa; } /* The NFA evaluator. */ private static int[] runNFA(ThreadContext tc, NFAInstance nfa, String target, long pos) { int eos = target.length(); int gen = 1; /* Allocate a "done states" array. */ int numStates = nfa.numStates; int[] done = new int[numStates + 1]; /* Clear out other re-used arrays. */ ArrayList<Integer> fates = tc.fates; ArrayList<Integer> curst = tc.curst; ArrayList<Integer> nextst = tc.nextst; curst.clear(); nextst.clear(); fates.clear(); nextst.add(1); while (!nextst.isEmpty() && pos <= eos) { /* Translation of: * my @curst := @nextst; * @nextst := []; * But avoids an extra allocation per offset. */ ArrayList<Integer> temp = curst; curst = nextst; temp.clear(); nextst = temp; /* Save how many fates we have before this position is considered. */ int prevFates = fates.size(); while (!curst.isEmpty()) { int top = curst.size() - 1; int st = curst.get(top); curst.remove(top); if (st <= numStates) { if (done[st] == gen) continue; done[st] = gen; } NFAStateInfo[] edgeInfo = nfa.states[st - 1]; for (int i = 0; i < edgeInfo.length; i++) { int act = edgeInfo[i].act; int to = edgeInfo[i].to; if (act == NFA.EDGE_FATE) { /* Crossed a fate edge. Check if we already saw this, and * if so bump the entry we already saw. */ int arg = edgeInfo[i].arg_i; boolean foundFate = false; for (int j = 0; j < fates.size(); j++) { if (foundFate) fates.set(j - 1, fates.get(j)); if (fates.get(j )== arg) { foundFate = true; if (j < prevFates) prevFates } } if (foundFate) fates.set(fates.size() - 1, arg); else fates.add(arg); } else if (act == NFA.EDGE_EPSILON && to <= numStates && done[to] != gen) { curst.add(to); } else if (pos >= eos) { /* Can't match, so drop state. */ } else if (act == NFA.EDGE_CODEPOINT) { char arg = (char)edgeInfo[i].arg_i; if (target.charAt((int)pos) == arg) nextst.add(to); } else if (act == NFA.EDGE_CODEPOINT_NEG) { char arg = (char)edgeInfo[i].arg_i; if (target.charAt((int)pos) != arg) nextst.add(to); } else if (act == NFA.EDGE_CHARCLASS) { if (iscclass(edgeInfo[i].arg_i, target, pos) != 0) nextst.add(to); } else if (act == NFA.EDGE_CHARCLASS_NEG) { if (iscclass(edgeInfo[i].arg_i, target, pos) == 0) nextst.add(to); } else if (act == NFA.EDGE_CHARLIST) { String arg = edgeInfo[i].arg_s; if (arg.indexOf(target.charAt((int)pos)) >= 0) nextst.add(to); } else if (act == NFA.EDGE_CHARLIST_NEG) { String arg = edgeInfo[i].arg_s; if (arg.indexOf(target.charAt((int)pos)) < 0) nextst.add(to); } else if (act == NFA.EDGE_CODEPOINT_I) { char uc_arg = edgeInfo[i].arg_uc; char lc_arg = edgeInfo[i].arg_lc; char ord = target.charAt((int)pos); if (ord == lc_arg || ord == uc_arg) nextst.add(to); } else if (act == NFA.EDGE_CODEPOINT_I_NEG) { char uc_arg = edgeInfo[i].arg_uc; char lc_arg = edgeInfo[i].arg_lc; char ord = target.charAt((int)pos); if (ord != lc_arg && ord != uc_arg) nextst.add(to); } } } /* Move to next character and generation. */ pos++; gen++; /* If we got multiple fates at this offset, sort them by the * declaration order (represented by the fate number). In the * future, we'll want to factor in longest literal prefix too. */ int charFates = fates.size() - prevFates; if (charFates > 1) { List<Integer> charFateList = fates.subList(prevFates, fates.size()); Collections.sort(charFateList, Collections.reverseOrder()); } } int[] result = new int[fates.size()]; for (int i = 0; i < fates.size(); i++) result[i] = fates.get(i); return result; } /* Regex engine mark stack operations. */ public static void rxmark(SixModelObject bstack, long mark, long pos, long rep, ThreadContext tc) { long elems = bstack.elems(tc); long caps; if (elems > 0) { bstack.at_pos_native(tc, elems - 1); caps = tc.native_i; } else { caps = 0; } tc.native_i = mark; bstack.push_native(tc); tc.native_i = pos; bstack.push_native(tc); tc.native_i = rep; bstack.push_native(tc); tc.native_i = caps; bstack.push_native(tc); } public static long rxpeek(SixModelObject bstack, long mark, ThreadContext tc) { long ptr = bstack.elems(tc); while (ptr >= 0) { bstack.at_pos_native(tc, ptr); if (tc.native_i == mark) break; ptr -= 4; } return ptr; } public static void rxcommit(SixModelObject bstack, long mark, ThreadContext tc) { long ptr = bstack.elems(tc); long caps; if (ptr > 0) { bstack.at_pos_native(tc, ptr - 1); caps = tc.native_i; } else { caps = 0; } while (ptr >= 0) { bstack.at_pos_native(tc, ptr); if (tc.native_i == mark) break; ptr -= 4; } bstack.set_elems(tc, ptr); if (caps > 0) { if (ptr > 0) { /* top mark frame is an autofail frame, reuse it to hold captures */ bstack.at_pos_native(tc, ptr - 3); if (tc.native_i < 0) { tc.native_i = caps; bstack.bind_pos_native(tc, ptr - 1); } } /* push a new autofail frame onto bstack to hold the captures */ tc.native_i = 0; bstack.push_native(tc); tc.native_i = -1; bstack.push_native(tc); tc.native_i = 0; bstack.push_native(tc); tc.native_i = caps; bstack.push_native(tc); } } /* Coercions. */ public static long coerce_s2i(String in) { try { return Long.parseLong(in); } catch (NumberFormatException e) { return 0; } } public static double coerce_s2n(String in) { try { return Double.parseDouble(in); } catch (NumberFormatException e) { if (in.equals("Inf")) return Double.POSITIVE_INFINITY; if (in.equals("-Inf")) return Double.NEGATIVE_INFINITY; if (in.equals("NaN")) return Double.NaN; return 0.0; } } public static String coerce_i2s(long in) { return Long.toString(in); } public static String coerce_n2s(double in) { if (in == (long)in) { if (in == 0 && Double.toString(in).equals("-0.0")) { return "-0"; } return Long.toString((long)in); } else { if (in == Double.POSITIVE_INFINITY) return "Inf"; if (in == Double.NEGATIVE_INFINITY) return "-Inf"; if (in != in) return "NaN"; return Double.toString(in); } } /* Long literal workaround. */ public static String join_literal(String[] parts) { StringBuilder retval = new StringBuilder(parts.length * 65535); for (int i = 0; i < parts.length; i++) retval.append(parts[i]); return retval.toString(); } /* Big integer operations. */ private static BigInteger getBI(ThreadContext tc, SixModelObject obj) { if (obj instanceof P6bigintInstance) return ((P6bigintInstance)obj).value; /* What follows is a bit of a hack, relying on the first field being the * big integer. */ obj.get_attribute_native(tc, null, null, 0); return (BigInteger)tc.native_j; } private static SixModelObject makeBI(ThreadContext tc, SixModelObject type, BigInteger value) { SixModelObject res = type.st.REPR.allocate(tc, type.st); if (res instanceof P6bigintInstance) { ((P6bigintInstance)res).value = value; } else { tc.native_j = value; res.bind_attribute_native(tc, null, null, 0); } return res; } public static SixModelObject fromstr_I(String str, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, new BigInteger(str)); } public static String tostr_I(SixModelObject value, ThreadContext tc) { return getBI(tc, value).toString(); } public static String base_I(SixModelObject value, long radix, ThreadContext tc) { return getBI(tc, value).toString((int)radix).toUpperCase(); } public static long isbig_I(SixModelObject value, ThreadContext tc) { /* Check if it needs more bits than a long can offer; note that * bitLength excludes sign considerations, thus 32 rather than * 32. */ return getBI(tc, value).bitLength() > 31 ? 1 : 0; } public static SixModelObject fromnum_I(double num, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, BigDecimal.valueOf(num).toBigInteger()); } public static double tonum_I(SixModelObject value, ThreadContext tc) { return getBI(tc, value).doubleValue(); } public static long bool_I(SixModelObject a, ThreadContext tc) { return getBI(tc, a).compareTo(BigInteger.ZERO) == 0 ? 0 : 1; } public static long cmp_I(SixModelObject a, SixModelObject b, ThreadContext tc) { return getBI(tc, a).compareTo(getBI(tc, b)); } public static long iseq_I(SixModelObject a, SixModelObject b, ThreadContext tc) { return getBI(tc, a).compareTo(getBI(tc, b)) == 0 ? 1 : 0; } public static long isne_I(SixModelObject a, SixModelObject b, ThreadContext tc) { return getBI(tc, a).compareTo(getBI(tc, b)) == 0 ? 0 : 1; } public static long islt_I(SixModelObject a, SixModelObject b, ThreadContext tc) { return getBI(tc, a).compareTo(getBI(tc, b)) < 0 ? 1 : 0; } public static long isle_I(SixModelObject a, SixModelObject b, ThreadContext tc) { return getBI(tc, a).compareTo(getBI(tc, b)) <= 0 ? 1 : 0; } public static long isgt_I(SixModelObject a, SixModelObject b, ThreadContext tc) { return getBI(tc, a).compareTo(getBI(tc, b)) > 0 ? 1 : 0; } public static long isge_I(SixModelObject a, SixModelObject b, ThreadContext tc) { return getBI(tc, a).compareTo(getBI(tc, b)) >= 0 ? 1 : 0; } public static SixModelObject add_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).add(getBI(tc, b))); } public static SixModelObject sub_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).subtract(getBI(tc, b))); } public static SixModelObject mul_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).multiply(getBI(tc, b))); } public static SixModelObject div_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { BigInteger dividend = getBI(tc, a); BigInteger divisor = getBI(tc, b); long dividend_sign = dividend.signum(); long divisor_sign = divisor.signum(); if (dividend_sign * divisor_sign == -1) { if (dividend.mod(divisor.abs ()).compareTo(BigInteger.ZERO) != 0) { return makeBI(tc, type, dividend.divide(divisor).subtract(BigInteger.ONE)); } } return makeBI(tc, type, dividend.divide(divisor)); } public static double div_In(SixModelObject a, SixModelObject b, ThreadContext tc) { return new BigDecimal(getBI(tc, a)).divide(new BigDecimal(getBI(tc, b)), 309, RoundingMode.HALF_UP).doubleValue(); } public static SixModelObject mod_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { BigInteger divisor = getBI(tc, b); if (divisor.compareTo(BigInteger.ZERO) < 0) { BigInteger negDivisor = divisor.negate(); BigInteger res = getBI(tc, a).mod(negDivisor); return makeBI(tc, type, res.equals(BigInteger.ZERO) ? res : divisor.add(res)); } else { return makeBI(tc, type, getBI(tc, a).mod(divisor)); } } public static SixModelObject expmod_I(SixModelObject a, SixModelObject b, SixModelObject c, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).modPow(getBI(tc, b), getBI(tc, c))); } public static long isprime_I(SixModelObject a, long certainty, ThreadContext tc) { BigInteger bi = getBI(tc, a); if (bi.compareTo(BigInteger.valueOf(1)) <= 0) { return 0; } return bi.isProbablePrime((int)certainty) ? 1 : 0; } public static SixModelObject rand_I(SixModelObject a, SixModelObject type, ThreadContext tc) { BigInteger size = getBI(tc, a); BigInteger random = new BigInteger(size.bitLength(), tc.random); while (random.compareTo (size) != -1) { random = new BigInteger(size.bitLength(), tc.random); } return makeBI(tc, type, random); } public static double pow_n(double a, double b) { if (a == 1 && !Double.isNaN(b)) { return 1.0; } return Math.pow(a, b); } public static double mod_n(double a, double b) { return a - Math.floor(a / b) * b; } public static SixModelObject pow_I(SixModelObject a, SixModelObject b, SixModelObject nType, SixModelObject biType, ThreadContext tc) { BigInteger base = getBI(tc, a); BigInteger exponent = getBI(tc, b); int cmp = exponent.compareTo(BigInteger.ZERO); if (cmp == 0 || base.compareTo(BigInteger.ONE) == 0) { return makeBI(tc, biType, BigInteger.ONE); } else if (cmp > 0) { if (exponent.bitLength() > 31) { /* Overflows integer. Terrifyingly huge, but try to cope somehow. */ cmp = base.compareTo(BigInteger.ZERO); if (cmp == 0 || base.compareTo(BigInteger.ONE) == 0) { /* 0 ** $big_number and 1 ** big_number are easy to do: */ return makeBI(tc, biType, base); } else if (base.compareTo(BigInteger.ONE.negate ()) == 0) { /* -1 ** exponent depends on whether b is odd or even */ return makeBI(tc, biType, exponent.mod(BigInteger.valueOf(2)) == BigInteger.ZERO ? BigInteger.ONE : BigInteger.ONE.negate ()); } else { /* Otherwise, do floating point infinity of the right sign. */ SixModelObject result = nType.st.REPR.allocate(tc, nType.st); result.set_num(tc, exponent.mod(BigInteger.valueOf(2)) == BigInteger.ZERO ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY); return result; } } else { /* Can safely take its integer value. */ return makeBI(tc, biType, base.pow(exponent.intValue())); } } else { double fBase = base.doubleValue(); double fExponent = exponent.doubleValue(); SixModelObject result = nType.st.REPR.allocate(tc, nType.st); result.set_num(tc, Math.pow(fBase, fExponent)); return result; } } public static SixModelObject neg_I(SixModelObject a, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).negate()); } public static SixModelObject abs_I(SixModelObject a, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).abs()); } public static SixModelObject radix_I(long radix_l, String str, long zpos, long flags, SixModelObject type, ThreadContext tc) { BigInteger zvalue = BigInteger.ZERO; BigInteger zbase = BigInteger.ONE; int chars = str.length(); BigInteger value = zvalue; BigInteger base = zbase; long pos = -1; char ch; boolean neg = false; BigInteger radix = BigInteger.valueOf(radix_l); if (radix_l > 36) { throw ExceptionHandling.dieInternal(tc, "Cannot convert radix of " + radix_l + " (max 36)"); } ch = (zpos < chars) ? str.charAt((int)zpos) : 0; if ((flags & 0x02) != 0 && (ch == '+' || ch == '-')) { neg = (ch == '-'); zpos++; ch = (zpos < chars) ? str.charAt((int)zpos) : 0; } while (zpos < chars) { if (ch >= '0' && ch <= '9') ch = (char)(ch - '0'); else if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 'a' + 10); else if (ch >= 'A' && ch <= 'Z') ch = (char)(ch - 'A' + 10); else break; if (ch >= radix_l) break; zvalue = zvalue.multiply(radix).add(BigInteger.valueOf(ch)); zbase = zbase.multiply(radix); zpos++; pos = zpos; if (ch != 0 || (flags & 0x04) == 0) { value=zvalue; base=zbase; } if (zpos >= chars) break; ch = str.charAt((int)zpos); if (ch != '_') continue; zpos++; if (zpos >= chars) break; ch = str.charAt((int)zpos); } if (neg || (flags & 0x01) != 0) { value = value.negate(); } HLLConfig hllConfig = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig; SixModelObject result = hllConfig.slurpyArrayType.st.REPR.allocate(tc, hllConfig.slurpyArrayType.st); result.push_boxed(tc, makeBI(tc, type, value)); result.push_boxed(tc, makeBI(tc, type, base)); result.push_boxed(tc, makeBI(tc, type, BigInteger.valueOf(pos))); return result; } public static SixModelObject bitor_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).or(getBI(tc, b))); } public static SixModelObject bitxor_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).xor(getBI(tc, b))); } public static SixModelObject bitand_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).and(getBI(tc, b))); } public static SixModelObject bitneg_I(SixModelObject a, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).not()); } public static SixModelObject bitshiftl_I(SixModelObject a, long b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).shiftLeft((int)b)); } public static SixModelObject bitshiftr_I(SixModelObject a, long b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).shiftRight((int)b)); } /* Evaluation of code; JVM-specific ops. */ public static SixModelObject compilejast(SixModelObject jast, SixModelObject jastNodes, ThreadContext tc) { EvalResult res = new EvalResult(); res.jc = JASTCompiler.buildClass(jast, jastNodes, false, tc); return res; } public static SixModelObject compilejasttofile(SixModelObject jast, SixModelObject jastNodes, String filename, ThreadContext tc) { JASTCompiler.writeClass(jast, jastNodes, filename, tc); return jast; } public static SixModelObject loadcompunit(SixModelObject obj, long compileeHLL, ThreadContext tc) { try { EvalResult res = (EvalResult)obj; Class<?> cuClass = tc.gc.byteClassLoader.defineClass(res.jc.name, res.jc.bytes); res.cu = (CompilationUnit) cuClass.newInstance(); if (compileeHLL != 0) usecompileehllconfig(tc); res.cu.initializeCompilationUnit(tc); if (compileeHLL != 0) usecompilerhllconfig(tc); res.jc = null; return obj; } catch (ControlException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } public static long iscompunit(SixModelObject obj, ThreadContext tc) { return obj instanceof EvalResult ? 1 : 0; } public static SixModelObject compunitmainline(SixModelObject obj, ThreadContext tc) { EvalResult res = (EvalResult)obj; return res.cu.lookupCodeRef(res.cu.mainlineQbid()); } public static SixModelObject compunitcodes(SixModelObject obj, ThreadContext tc) { EvalResult res = (EvalResult)obj; SixModelObject Array = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.listType; SixModelObject result = Array.st.REPR.allocate(tc, Array.st); for (int i = 0; i < res.cu.codeRefs.length; i++) result.bind_pos_boxed(tc, i, res.cu.codeRefs[i]); return result; } public static SixModelObject jvmclasspaths(ThreadContext tc) { SixModelObject Array = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.listType; SixModelObject Str = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.strBoxType; SixModelObject result = Array.st.REPR.allocate(tc, Array.st); String cpStr = System.getProperty("java.class.path"); String[] cps = cpStr.split("[:;]"); for (int i = 0; i < cps.length; i++) result.push_boxed(tc, box_s(cps[i], Str, tc)); return result; } public static long usecompileehllconfig(ThreadContext tc) { if (tc.gc.compileeDepth == 0) tc.gc.useCompileeHLLConfig(); tc.gc.compileeDepth++; return 1; } public static long usecompilerhllconfig(ThreadContext tc) { tc.gc.compileeDepth if (tc.gc.compileeDepth == 0) tc.gc.useCompilerHLLConfig(); return 1; } private static MethodHandle reset_reenter; static { try { reset_reenter = MethodHandles.insertArguments( MethodHandles.publicLookup().findStatic(Ops.class, "continuationreset", MethodType.methodType(Void.TYPE, SixModelObject.class, SixModelObject.class, ThreadContext.class, ResumeStatus.Frame.class)), 0, null, null, null); } catch (Exception e) { throw new RuntimeException(e); } } // this is the most complicated one because it's not doing a tailcall, so we need to actually use the resumeframe public static void continuationreset(SixModelObject key, SixModelObject run, ThreadContext tc) throws Throwable { continuationreset(key, run, tc, null); } public static void continuationreset(SixModelObject key, SixModelObject run, ThreadContext tc, ResumeStatus.Frame resume) throws Throwable { SixModelObject cont = null; if (resume != null) { // reload stuff here, then don't goto because java source doesn't have that Object[] bits = resume.saveSpace; key = (SixModelObject) bits[0]; tc = resume.tc; } while (true) { try { if (resume != null) { resume.resumeNext(); } else if (cont != null) { invokeDirect(tc, run, invocantCallSite, false, new Object[] { cont }); } else { if (run instanceof ResumeStatus) { /* Got a continuation to invoke immediately (done by * Rakudo cope with lack of tail calls). */ ResumeStatus.Frame root = ((ResumeStatus)run).top; fixupContinuation(tc, root, null); root.resume(); } else { /* Code a normal code ref to invoke. */ invokeDirect(tc, run, emptyCallSite, false, emptyArgList); } } // If we get here, the reset argument or something placed using control returned normally // so we should just return. return; } catch (SaveStackException sse) { if (sse.key != null && sse.key != key) { // This is intended for an outer scope, so just append ourself throw sse.pushFrame(0, reset_reenter, new Object[] { key }, null); } // Ooo! This is ours! resume = null; STable contType = tc.gc.Continuation.st; cont = contType.REPR.allocate(tc, contType); ((ResumeStatus)cont).top = sse.top; run = sse.handler; if (!sse.protect) break; } } // now, if we get HERE, it means we saw an unprotected control operator // so run it without protection invokeDirect(tc, run, invocantCallSite, false, new Object[] { cont }); } public static SixModelObject continuationclone(SixModelObject in, ThreadContext tc) { if (!(in instanceof ResumeStatus)) ExceptionHandling.dieInternal(tc, "applied continuationinvoke to non-continuation"); ResumeStatus.Frame read = ((ResumeStatus)in).top; ResumeStatus.Frame nroot = null, ntail = null, nnew; while (read != null) { CallFrame cf = read.callFrame == null ? null : read.callFrame.cloneContinuation(); nnew = new ResumeStatus.Frame(read.method, read.resumePoint, read.saveSpace, cf, null); if (ntail != null) { ntail.next = nnew; } else { nroot = nnew; } ntail = nnew; read = read.next; } STable contType = tc.gc.Continuation.st; SixModelObject cont = contType.REPR.allocate(tc, contType); ((ResumeStatus)cont).top = nroot; return cont; } public static void continuationcontrol(long protect, SixModelObject key, SixModelObject run, ThreadContext tc) { throw new SaveStackException(key, protect != 0, run); } public static void continuationinvoke(SixModelObject cont, SixModelObject arg, ThreadContext tc) throws Throwable { if (!(cont instanceof ResumeStatus)) ExceptionHandling.dieInternal(tc, "applied continuationinvoke to non-continuation"); ResumeStatus.Frame root = ((ResumeStatus)cont).top; fixupContinuation(tc, root, arg); root.resume(); } private static void fixupContinuation(ThreadContext tc, ResumeStatus.Frame csr, SixModelObject arg) { // fixups: safe to do more than once, but not concurrently // these are why continuationclone is needed... while (csr != null) { csr.tc = tc; // csr.callFrame.{csr,tc} will be set on resume if (csr.next == null) csr.thunk = arg; csr = csr.next; } } /* noop, exists only so you can set a breakpoint in it */ public static SixModelObject debugnoop(SixModelObject in, ThreadContext tc) { return in; } public static long jvmeqaddr(SixModelObject a, SixModelObject b, ThreadContext tc) { if (a instanceof TypeObject) { return (b instanceof TypeObject) ? 1 : 0; } else { return (b instanceof TypeObject || ((JavaObjectWrapper)a).theObject != ((JavaObjectWrapper)b).theObject) ? 0 : 1; } } public static long jvmisnull(SixModelObject a, ThreadContext tc) { if (a instanceof TypeObject) { return 1; } else { return ((JavaObjectWrapper)a).theObject == null ? 1 : 0; } } public static SixModelObject jvmbootinterop(ThreadContext tc) { return BootJavaInterop.RuntimeSupport.boxJava(tc.gc.bootInterop, tc.gc.bootInterop.getSTableForClass(BootJavaInterop.class)); } public static SixModelObject jvmgetconfig(ThreadContext tc) { SixModelObject hashType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.hashType; SixModelObject strType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.strBoxType; SixModelObject res = hashType.st.REPR.allocate(tc, hashType.st); try { InputStream is = Ops.class.getResourceAsStream("/jvmconfig.properties"); Properties config = new Properties(); config.load(is); for (String name : config.stringPropertyNames()) res.bind_key_boxed(tc, name, box_s(config.getProperty(name), strType, tc)); } catch (Throwable e) { die_s("Failed to load config.properties", tc); } return res; } }
package model; import io.Preface; import io.Sentence; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import lexicon.Categories; import cat_combination.SuperCategory; public class Features { // FeatureCat final public static short catRoot = 1; final public static short catLex = 4; // FeatureCatHead final public static short catRootWord = 2; final public static short catRootPos = 3; final public static short catLexWord = 5; final public static short catLexPos = 6; // FeatureRule final public static short ruleBinary = 7; final public static short ruleUnary = 8; // FeatureRuleHead final public static short ruleBinaryWord = 9; final public static short ruleBinaryPos = 10; final public static short ruleUnaryWord = 11; final public static short ruleUnaryPos = 12; // FeatureRuleHeadHead final public static short ruleBinaryWordWord = 13; final public static short ruleBinaryWordPos = 14; final public static short ruleBinaryPosWord = 15; final public static short ruleBinaryPosPos = 16; // FeatureRuleHeadDist final public static short ruleBinaryWordDistAdj = 17; // adjacency distance measure final public static short ruleBinaryWordDistPunct = 18; // punctuation distance measure final public static short ruleBinaryWordDistVerb = 19; // verb distance measure final public static short ruleBinaryPosDistAdj = 20; final public static short ruleBinaryPosDistPunct = 21; final public static short ruleBinaryPosDistVerb = 22; // FeatureRuleHead // unary 1 final public static short ruleUnaryWord2 = 300; final public static short ruleUnaryPos2 = 301; // FeatureRuleHeadHead // unary 1 final public static short ruleBinaryWordWord2 = 310; final public static short ruleBinaryWordPos2 = 311; final public static short ruleBinaryPosWord2 = 312; final public static short ruleBinaryPosPos2 = 313; // binary 1 final public static short ruleUnaryUnaryWordWord2 = 320; final public static short ruleUnaryUnaryWordPos2 = 321; final public static short ruleUnaryUnaryPosWord2 = 322; final public static short ruleUnaryUnaryPosPos2 = 323; final public static short ruleNullUnaryWordWord2 = 3200; final public static short ruleNullUnaryWordPos2 = 3210; final public static short ruleNullUnaryPosWord2 = 3220; final public static short ruleNullUnaryPosPos2 = 3230; final public static short ruleUnaryNullWordWord2 = 3201; final public static short ruleUnaryNullWordPos2 = 3211; final public static short ruleUnaryNullPosWord2 = 3221; final public static short ruleUnaryNullPosPos2 = 3231; final public static short ruleUnaryBinaryWordWord2 = 330; final public static short ruleUnaryBinaryWordPos2 = 331; final public static short ruleUnaryBinaryPosWord2 = 332; final public static short ruleUnaryBinaryPosPos2 = 333; final public static short ruleBinaryUnaryWordWord2 = 340; final public static short ruleBinaryUnaryWordPos2 = 341; final public static short ruleBinaryUnaryPosWord2 = 342; final public static short ruleBinaryUnaryPosPos2 = 343; final public static short ruleBinaryBinaryWordWord2 = 350; final public static short ruleBinaryBinaryWordPos2 = 351; final public static short ruleBinaryBinaryPosWord2 = 352; final public static short ruleBinaryBinaryPosPos2 = 353; final public static short ruleNullBinaryWordWord2 = 3500; final public static short ruleNullBinaryWordPos2 = 3510; final public static short ruleNullBinaryPosWord2 = 3520; final public static short ruleNullBinaryPosPos2 = 3530; final public static short ruleBinaryNullWordWord2 = 3501; final public static short ruleBinaryNullWordPos2 = 3511; final public static short ruleBinaryNullPosWord2 = 3521; final public static short ruleBinaryNullPosPos2 = 3531; final public static short ruleRuleUnaryLeftWord = 4010; final public static short ruleRuleUnaryLeftPos = 4020; final public static short ruleRuleUnaryRightWord = 4011; final public static short ruleRuleUnaryRightPos = 4021; final public static short ruleRuleBinaryLeftWordWord = 4110; final public static short ruleRuleBinaryLeftWordPos = 4120; final public static short ruleRuleBinaryLeftPosWord = 4130; final public static short ruleRuleBinaryLeftPosPos= 4140; final public static short ruleRuleBinaryRightWordWord = 4111; final public static short ruleRuleBinaryRightWordPos = 4121; final public static short ruleRuleBinaryRightPosWord = 4131; final public static short ruleRuleBinaryRightPosPos= 4141; public FeatureIDs<FeatureCat> featureCatIDs; public FeatureIDs<FeatureCatHead> featureCatHeadIDs; public FeatureIDs<FeatureRule> featureRuleIDs; public FeatureIDs<FeatureRuleHead> featureRuleHeadIDs; public FeatureIDs<FeatureRuleHeadHead> featureRuleHeadHeadIDs; public FeatureIDs<FeatureRuleHeadDist> featureRuleHeadDistIDs; public FeatureIDs<FeatureRuleRuleHead> featureRuleRuleHeadIDs; public FeatureIDs<FeatureRuleRuleHeadHead> featureRuleRuleHeadHeadIDs; public int numFeatures; private static boolean newFeatures; public static void setNewFeatures(boolean n) { newFeatures = n; } public static boolean getNewFeatures() { return newFeatures; } public Features(String featuresFile, Categories categories, boolean newFeatures) throws IOException { this.featureCatIDs = new FeatureIDs<FeatureCat>(); this.featureCatHeadIDs = new FeatureIDs<FeatureCatHead>(); this.featureRuleIDs = new FeatureIDs<FeatureRule>(); this.featureRuleHeadIDs = new FeatureIDs<FeatureRuleHead>(); this.featureRuleHeadHeadIDs = new FeatureIDs<FeatureRuleHeadHead>(); this.featureRuleHeadDistIDs = new FeatureIDs<FeatureRuleHeadDist>(); this.featureRuleRuleHeadIDs = new FeatureIDs<FeatureRuleRuleHead>(); this.featureRuleRuleHeadHeadIDs = new FeatureIDs<FeatureRuleRuleHeadHead>(); readFeatures(featuresFile, categories); Features.setNewFeatures(newFeatures); } public Features(String featuresFile, String weightsFile, Weights weights, Categories categories, boolean newFeatures) throws IOException { this.featureCatIDs = new FeatureIDs<FeatureCat>(); this.featureCatHeadIDs = new FeatureIDs<FeatureCatHead>(); this.featureRuleIDs = new FeatureIDs<FeatureRule>(); this.featureRuleHeadIDs = new FeatureIDs<FeatureRuleHead>(); this.featureRuleHeadHeadIDs = new FeatureIDs<FeatureRuleHeadHead>(); this.featureRuleHeadDistIDs = new FeatureIDs<FeatureRuleHeadDist>(); this.featureRuleRuleHeadIDs = new FeatureIDs<FeatureRuleRuleHead>(); this.featureRuleRuleHeadHeadIDs = new FeatureIDs<FeatureRuleRuleHeadHead>(); readFeaturesWeights(featuresFile, weightsFile, weights, categories); Features.setNewFeatures(newFeatures); } private void readFeatures(String featuresFile, Categories categories) throws IOException { BufferedReader featuresIn = new BufferedReader(new FileReader(featuresFile)); Preface.readPreface(featuresIn); String featuresLine = null; int ID = 1; while ((featuresLine = featuresIn.readLine()) != null) { readFeature(featuresLine, ID, categories); ID++; } numFeatures = ID; // ID starts at 1 (because of logp) // and gets incremented after each feature has been read System.out.println("Total number of features read in: " + numFeatures); } private void readFeaturesWeights(String featuresFile, String weightsFile, Weights weights, Categories categories) throws IOException { ArrayList<Double> weightsList = new ArrayList<Double>(); BufferedReader featuresIn = new BufferedReader(new FileReader(featuresFile)); BufferedReader weightsIn = new BufferedReader(new FileReader(weightsFile)); Preface.readPreface(featuresIn); Preface.readPreface(weightsIn); String featuresLine = null; // first line in weights is for logp String weightsLine = weightsIn.readLine(); if ( weightsLine != null ) { weightsList.add(Double.valueOf(weightsLine)); } else { throw new IllegalArgumentException("Unexpected end of stream"); } int ID = 1; Double weight; while ((featuresLine = featuresIn.readLine()) != null) { weightsLine = weightsIn.readLine(); if ( weightsLine != null ) { weight = Double.valueOf(weightsLine); } else { throw new IllegalArgumentException("Unexpected end of stream"); } if ( weight == 0.0 ) { continue; } else { weightsList.add(weight); } readFeature(featuresLine, ID, categories); ID++; } double[] weightsListArray = new double[weightsList.size()]; for ( int i = 0; i < weightsList.size(); i++ ) { weightsListArray[i] = weightsList.get(i); } weights.setWeights(weightsListArray); numFeatures = ID; // ID starts at 1 (because of logp) // and gets incremented after each feature has been read System.out.println("Total number of features read in: " + numFeatures); } private void readFeature(String featuresLine, int ID, Categories categories) { String[] tokens = featuresLine.split("\\s"); short featureType = Short.parseShort(tokens[0]); switch (featureType) { case Features.catRoot: // fall through case Features.catLex: if (tokens.length != 3) { throw new Error("catRoot and catLex features should have 3 fields!"); } FeatureCat.readFeature(featureType, tokens, featureCatIDs, ID, categories); break; case Features.catRootWord: // fall through case Features.catRootPos: case Features.catLexWord: case Features.catLexPos: if (tokens.length != 4) { throw new Error("catRootWord and catLexWord features should have 4 fields!"); } FeatureCatHead.readFeature(featureType, tokens, featureCatHeadIDs, ID, categories); break; case Features.ruleBinary: // fall through case Features.ruleUnary: if (tokens.length != 5) { throw new Error("ruleBinary and ruleUnary features should have 5 fields!"); } FeatureRule.readFeature(featureType, tokens, featureRuleIDs, ID, categories); break; case Features.ruleBinaryWord: // fall through case Features.ruleBinaryPos: case Features.ruleUnaryWord: case Features.ruleUnaryPos: if (tokens.length != 6) { throw new Error("ruleBinaryWord and ruleUnaryWord features should have 6 fields!"); } FeatureRuleHead.readFeature(featureType, tokens, featureRuleHeadIDs, ID, categories); break; case Features.ruleBinaryWordWord: // fall through case Features.ruleBinaryWordPos: case Features.ruleBinaryPosWord: case Features.ruleBinaryPosPos: if (tokens.length != 7) { throw new Error("ruleBinaryWordWord features should have 7 fields!"); } FeatureRuleHeadHead.readFeature(featureType, tokens, featureRuleHeadHeadIDs, ID, categories); break; case Features.ruleBinaryWordDistAdj: // fall through case Features.ruleBinaryWordDistPunct: case Features.ruleBinaryWordDistVerb: case Features.ruleBinaryPosDistAdj: case Features.ruleBinaryPosDistPunct: case Features.ruleBinaryPosDistVerb: if (tokens.length != 7) { throw new Error("ruleBinaryWordDist features should have 7 fields!"); } FeatureRuleHeadDist.readFeature(featureType, tokens, featureRuleHeadDistIDs, ID, categories); break; case Features.ruleUnaryWord2: // fall through case Features.ruleUnaryPos2: if (tokens.length != 6) { throw new Error("features should have 6 fields!"); } FeatureRuleHead.readFeature(featureType, tokens, featureRuleHeadIDs, ID, categories); break; case Features.ruleBinaryWordWord2: // fall through case Features.ruleBinaryWordPos2: case Features.ruleBinaryPosWord2: case Features.ruleBinaryPosPos2: case Features.ruleUnaryUnaryWordWord2: case Features.ruleUnaryUnaryWordPos2 : case Features.ruleUnaryUnaryPosWord2: case Features.ruleUnaryUnaryPosPos2: case Features.ruleNullUnaryWordWord2: case Features.ruleNullUnaryWordPos2 : case Features.ruleNullUnaryPosWord2: case Features.ruleNullUnaryPosPos2: case Features.ruleUnaryNullWordWord2: case Features.ruleUnaryNullWordPos2 : case Features.ruleUnaryNullPosWord2: case Features.ruleUnaryNullPosPos2: case Features.ruleUnaryBinaryWordWord2: case Features.ruleUnaryBinaryWordPos2: case Features.ruleUnaryBinaryPosWord2: case Features.ruleUnaryBinaryPosPos2: case Features.ruleBinaryUnaryWordWord2: case Features.ruleBinaryUnaryWordPos2: case Features.ruleBinaryUnaryPosWord2: case Features.ruleBinaryUnaryPosPos2: case Features.ruleBinaryBinaryWordWord2: case Features.ruleBinaryBinaryWordPos2: case Features.ruleBinaryBinaryPosWord2: case Features.ruleBinaryBinaryPosPos2: case Features.ruleNullBinaryWordWord2: case Features.ruleNullBinaryWordPos2: case Features.ruleNullBinaryPosWord2: case Features.ruleNullBinaryPosPos2: case Features.ruleBinaryNullWordWord2: case Features.ruleBinaryNullWordPos2: case Features.ruleBinaryNullPosWord2: case Features.ruleBinaryNullPosPos2: if (tokens.length != 7) { throw new Error("features should have 7 fields!"); } FeatureRuleHeadHead.readFeature(featureType, tokens, featureRuleHeadHeadIDs, ID, categories); break; case Features.ruleRuleUnaryLeftWord: case Features.ruleRuleUnaryLeftPos: case Features.ruleRuleUnaryRightWord: case Features.ruleRuleUnaryRightPos: if (tokens.length != 6) { throw new Error("features should have 6 fields!"); } FeatureRuleRuleHead.readFeature(featureType, tokens, featureRuleRuleHeadIDs, ID, categories); break; case Features.ruleRuleBinaryLeftWordWord: case Features.ruleRuleBinaryLeftWordPos: case Features.ruleRuleBinaryLeftPosWord: case Features.ruleRuleBinaryLeftPosPos: case Features.ruleRuleBinaryRightWordWord: case Features.ruleRuleBinaryRightWordPos: case Features.ruleRuleBinaryRightPosWord: case Features.ruleRuleBinaryRightPosPos: if (tokens.length != 8) { throw new Error("features should have 8 fields!"); } FeatureRuleRuleHeadHead.readFeature(featureType, tokens, featureRuleRuleHeadHeadIDs, ID, categories); break; default: throw new Error("run out of feature types!"); } } public void collectLeafFeatures(SuperCategory superCat, Sentence sentence, ArrayList<Integer> featureIDs) { FeatureCat.collectFeatures(superCat, catLex, featureCatIDs, featureIDs); FeatureCatHead.collectFeatures(superCat, catLexWord, sentence.wordIDs, featureCatHeadIDs, featureIDs); FeatureCatHead.collectFeatures(superCat, catLexPos, sentence.postagIDs, featureCatHeadIDs, featureIDs); } public void collectUnaryFeatures(SuperCategory superCat, Sentence sentence, ArrayList<Integer> featureIDs) { FeatureRule.collectFeatures(superCat.leftChild, superCat.leftChild, superCat, ruleUnary, featureRuleIDs, featureIDs); FeatureRuleHead.collectFeatures(superCat.leftChild, superCat.leftChild, superCat, ruleUnaryWord, sentence.wordIDs, featureRuleHeadIDs, featureIDs); FeatureRuleHead.collectFeatures(superCat.leftChild, superCat.leftChild, superCat, ruleUnaryPos, sentence.postagIDs, featureRuleHeadIDs, featureIDs); if ( Features.newFeatures ) { if ( superCat.leftChild.leftChild!= null ) { if ( superCat.leftChild.rightChild != null ) { FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat, ruleBinaryWordWord2, sentence.wordIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat, ruleBinaryWordPos2, sentence.wordIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat, ruleBinaryPosWord2, sentence.postagIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat, ruleBinaryPosPos2, sentence.postagIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat.leftChild, superCat, ruleRuleBinaryLeftWordWord, sentence.wordIDs, sentence.wordIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat.leftChild, superCat, ruleRuleBinaryLeftWordPos, sentence.wordIDs, sentence.postagIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat.leftChild, superCat, ruleRuleBinaryLeftPosWord, sentence.postagIDs, sentence.wordIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat.leftChild, superCat, ruleRuleBinaryLeftPosPos, sentence.postagIDs, sentence.postagIDs, featureRuleRuleHeadHeadIDs, featureIDs); } else { FeatureRuleHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.leftChild, superCat, ruleUnaryWord2, sentence.wordIDs, featureRuleHeadIDs, featureIDs); FeatureRuleHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.leftChild, superCat, ruleUnaryPos2, sentence.postagIDs, featureRuleHeadIDs, featureIDs); FeatureRuleRuleHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild, superCat, ruleRuleUnaryLeftWord, sentence.wordIDs, featureRuleRuleHeadIDs, featureIDs); FeatureRuleRuleHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild, superCat, ruleRuleUnaryLeftPos, sentence.postagIDs, featureRuleRuleHeadIDs, featureIDs); } } } } public void collectBinaryFeatures(SuperCategory superCat, Sentence sentence, ArrayList<Integer> featureIDs) { // just the rule: FeatureRule.collectFeatures(superCat.leftChild, superCat.rightChild, superCat, ruleBinary, featureRuleIDs, featureIDs); // rule + result head: FeatureRuleHead.collectFeatures(superCat.leftChild, superCat.rightChild, superCat, ruleBinaryWord, sentence.wordIDs, featureRuleHeadIDs, featureIDs); FeatureRuleHead.collectFeatures(superCat.leftChild, superCat.rightChild, superCat, ruleBinaryPos, sentence.postagIDs, featureRuleHeadIDs, featureIDs); // rule + combining heads: FeatureRuleHeadHead.collectFeatures(superCat.leftChild, superCat.rightChild, superCat, ruleBinaryWordWord, sentence.wordIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild, superCat.rightChild, superCat, ruleBinaryWordPos, sentence.wordIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild, superCat.rightChild, superCat, ruleBinaryPosWord, sentence.postagIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild, superCat.rightChild, superCat, ruleBinaryPosPos, sentence.postagIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); // rule + result head + distance: FeatureRuleHeadDist.collectFeatures(superCat.leftChild, superCat.rightChild, superCat, ruleBinaryWordDistAdj, sentence.wordIDs, sentence.postags, featureRuleHeadDistIDs, featureIDs); FeatureRuleHeadDist.collectFeatures(superCat.leftChild, superCat.rightChild, superCat, ruleBinaryWordDistPunct, sentence.wordIDs, sentence.postags, featureRuleHeadDistIDs, featureIDs); FeatureRuleHeadDist.collectFeatures(superCat.leftChild, superCat.rightChild, superCat, ruleBinaryWordDistVerb, sentence.wordIDs, sentence.postags, featureRuleHeadDistIDs, featureIDs); FeatureRuleHeadDist.collectFeatures(superCat.leftChild, superCat.rightChild, superCat, ruleBinaryPosDistAdj, sentence.wordIDs, sentence.postags, featureRuleHeadDistIDs, featureIDs); FeatureRuleHeadDist.collectFeatures(superCat.leftChild, superCat.rightChild, superCat, ruleBinaryPosDistPunct, sentence.wordIDs, sentence.postags, featureRuleHeadDistIDs, featureIDs); FeatureRuleHeadDist.collectFeatures(superCat.leftChild, superCat.rightChild, superCat, ruleBinaryPosDistVerb, sentence.wordIDs, sentence.postags, featureRuleHeadDistIDs, featureIDs); if ( Features.newFeatures ) { if ( superCat.leftChild.leftChild != null ) { if ( superCat.leftChild.rightChild != null ) { if ( superCat.rightChild.leftChild != null ) { if ( superCat.rightChild.rightChild != null ) { // case 8: binary, binary, binary FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild.rightChild, superCat, ruleBinaryBinaryWordWord2, sentence.wordIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild.rightChild, superCat, ruleBinaryBinaryWordPos2, sentence.wordIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild.rightChild, superCat, ruleBinaryBinaryPosWord2, sentence.postagIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild.rightChild, superCat, ruleBinaryBinaryPosPos2, sentence.postagIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat.leftChild, superCat, ruleRuleBinaryLeftWordWord, sentence.wordIDs, sentence.wordIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat.leftChild, superCat, ruleRuleBinaryLeftWordPos, sentence.wordIDs, sentence.postagIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat.leftChild, superCat, ruleRuleBinaryLeftPosWord, sentence.postagIDs, sentence.wordIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat.leftChild, superCat, ruleRuleBinaryLeftPosPos, sentence.postagIDs, sentence.postagIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild.rightChild, superCat.rightChild, superCat, ruleRuleBinaryRightWordWord, sentence.wordIDs, sentence.wordIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild.rightChild, superCat.rightChild, superCat, ruleRuleBinaryRightWordPos, sentence.wordIDs, sentence.postagIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild.rightChild, superCat.rightChild, superCat, ruleRuleBinaryRightPosWord, sentence.postagIDs, sentence.wordIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild.rightChild, superCat.rightChild, superCat, ruleRuleBinaryRightPosPos, sentence.postagIDs, sentence.postagIDs, featureRuleRuleHeadHeadIDs, featureIDs); } else { // case 7: binary, binary, unary FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild.leftChild, superCat, ruleBinaryUnaryWordWord2, sentence.wordIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild.leftChild, superCat, ruleBinaryUnaryWordPos2, sentence.wordIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild.leftChild, superCat, ruleBinaryUnaryPosWord2, sentence.postagIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild.leftChild, superCat, ruleBinaryUnaryPosPos2, sentence.postagIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat.leftChild, superCat, ruleRuleBinaryLeftWordWord, sentence.wordIDs, sentence.wordIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat.leftChild, superCat, ruleRuleBinaryLeftWordPos, sentence.wordIDs, sentence.postagIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat.leftChild, superCat, ruleRuleBinaryLeftPosWord, sentence.postagIDs, sentence.wordIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat.leftChild, superCat, ruleRuleBinaryLeftPosPos, sentence.postagIDs, sentence.postagIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild, superCat, ruleRuleUnaryRightWord, sentence.wordIDs, featureRuleRuleHeadIDs, featureIDs); FeatureRuleRuleHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild, superCat, ruleRuleUnaryRightPos, sentence.postagIDs, featureRuleRuleHeadIDs, featureIDs); } } else { // case 3: binary, binary, null FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild, superCat, ruleBinaryNullWordWord2, sentence.wordIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild, superCat, ruleBinaryNullWordPos2, sentence.wordIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild, superCat, ruleBinaryNullPosWord2, sentence.postagIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild, superCat, ruleBinaryNullPosPos2, sentence.postagIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat.leftChild, superCat, ruleRuleBinaryLeftWordWord, sentence.wordIDs, sentence.wordIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat.leftChild, superCat, ruleRuleBinaryLeftWordPos, sentence.wordIDs, sentence.postagIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat.leftChild, superCat, ruleRuleBinaryLeftPosWord, sentence.postagIDs, sentence.wordIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild.rightChild, superCat.leftChild, superCat, ruleRuleBinaryLeftPosPos, sentence.postagIDs, sentence.postagIDs, featureRuleRuleHeadHeadIDs, featureIDs); } } else { if ( superCat.rightChild.leftChild != null ) { if ( superCat.rightChild.rightChild != null ) { // case 6: binary, unary, binary FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild.rightChild, superCat, ruleUnaryBinaryWordWord2, sentence.wordIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild.rightChild, superCat, ruleUnaryBinaryWordPos2, sentence.wordIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild.rightChild, superCat, ruleUnaryBinaryPosWord2, sentence.postagIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild.rightChild, superCat, ruleUnaryBinaryPosPos2, sentence.postagIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild, superCat, ruleRuleUnaryLeftWord, sentence.wordIDs, featureRuleRuleHeadIDs, featureIDs); FeatureRuleRuleHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild, superCat, ruleRuleUnaryLeftPos, sentence.postagIDs, featureRuleRuleHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild.rightChild, superCat.rightChild, superCat, ruleRuleBinaryRightWordWord, sentence.wordIDs, sentence.wordIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild.rightChild, superCat.rightChild, superCat, ruleRuleBinaryRightWordPos, sentence.wordIDs, sentence.postagIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild.rightChild, superCat.rightChild, superCat, ruleRuleBinaryRightPosWord, sentence.postagIDs, sentence.wordIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild.rightChild, superCat.rightChild, superCat, ruleRuleBinaryRightPosPos, sentence.postagIDs, sentence.postagIDs, featureRuleRuleHeadHeadIDs, featureIDs); } else { // case 5: binary, unary, unary FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild.leftChild, superCat, ruleUnaryUnaryWordWord2, sentence.wordIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild.leftChild, superCat, ruleUnaryUnaryWordPos2, sentence.wordIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild.leftChild, superCat, ruleUnaryUnaryPosWord2, sentence.postagIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild.leftChild, superCat, ruleUnaryUnaryPosPos2, sentence.postagIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild, superCat, ruleRuleUnaryLeftWord, sentence.wordIDs, featureRuleRuleHeadIDs, featureIDs); FeatureRuleRuleHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild, superCat, ruleRuleUnaryLeftPos, sentence.postagIDs, featureRuleRuleHeadIDs, featureIDs); FeatureRuleRuleHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild, superCat, ruleRuleUnaryRightWord, sentence.wordIDs, featureRuleRuleHeadIDs, featureIDs); FeatureRuleRuleHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild, superCat, ruleRuleUnaryRightPos, sentence.postagIDs, featureRuleRuleHeadIDs, featureIDs); } } else { // case 1: binary, unary, null FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild, superCat, ruleUnaryNullWordWord2, sentence.wordIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild, superCat, ruleUnaryNullWordPos2, sentence.wordIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild, superCat, ruleUnaryNullPosWord2, sentence.postagIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild.leftChild, superCat.rightChild, superCat, ruleUnaryNullPosPos2, sentence.postagIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild, superCat, ruleRuleUnaryLeftWord, sentence.wordIDs, featureRuleRuleHeadIDs, featureIDs); FeatureRuleRuleHead.collectFeatures(superCat.leftChild.leftChild, superCat.leftChild, superCat, ruleRuleUnaryLeftPos, sentence.postagIDs, featureRuleRuleHeadIDs, featureIDs); } } } else { if ( superCat.rightChild.leftChild != null ) { if ( superCat.rightChild.rightChild != null ) { // case 4: binary, null, binary FeatureRuleHeadHead.collectFeatures(superCat.leftChild, superCat.rightChild.rightChild, superCat, ruleNullBinaryWordWord2, sentence.wordIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild, superCat.rightChild.rightChild, superCat, ruleNullBinaryWordPos2, sentence.wordIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild, superCat.rightChild.rightChild, superCat, ruleNullBinaryPosWord2, sentence.postagIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild, superCat.rightChild.rightChild, superCat, ruleNullBinaryPosPos2, sentence.postagIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild.rightChild, superCat.rightChild, superCat, ruleRuleBinaryRightWordWord, sentence.wordIDs, sentence.wordIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild.rightChild, superCat.rightChild, superCat, ruleRuleBinaryRightWordPos, sentence.wordIDs, sentence.postagIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild.rightChild, superCat.rightChild, superCat, ruleRuleBinaryRightPosWord, sentence.postagIDs, sentence.wordIDs, featureRuleRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHeadHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild.rightChild, superCat.rightChild, superCat, ruleRuleBinaryRightPosPos, sentence.postagIDs, sentence.postagIDs, featureRuleRuleHeadHeadIDs, featureIDs); } else { // case 2: binary, null, unary FeatureRuleHeadHead.collectFeatures(superCat.leftChild, superCat.rightChild.leftChild, superCat, ruleNullUnaryWordWord2, sentence.wordIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild, superCat.rightChild.leftChild, superCat, ruleNullUnaryWordPos2, sentence.wordIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild, superCat.rightChild.leftChild, superCat, ruleNullUnaryPosWord2, sentence.postagIDs, sentence.wordIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleHeadHead.collectFeatures(superCat.leftChild, superCat.rightChild.leftChild, superCat, ruleNullUnaryPosPos2, sentence.postagIDs, sentence.postagIDs, featureRuleHeadHeadIDs, featureIDs); FeatureRuleRuleHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild, superCat, ruleRuleUnaryRightWord, sentence.wordIDs, featureRuleRuleHeadIDs, featureIDs); FeatureRuleRuleHead.collectFeatures(superCat.rightChild.leftChild, superCat.rightChild, superCat, ruleRuleUnaryRightPos, sentence.postagIDs, featureRuleRuleHeadIDs, featureIDs); } } } } } public void collectRootFeatures(SuperCategory superCat, Sentence sentence, ArrayList<Integer> featureIDs) { FeatureCat.collectFeatures(superCat, catRoot, featureCatIDs, featureIDs); FeatureCatHead.collectFeatures(superCat, catRootWord, sentence.wordIDs, featureCatHeadIDs, featureIDs); FeatureCatHead.collectFeatures(superCat, catRootPos, sentence.postagIDs, featureCatHeadIDs, featureIDs); } public void print(PrintWriter out) { featureCatIDs.print(out); featureCatHeadIDs.print(out); featureRuleIDs.print(out); featureRuleHeadIDs.print(out); featureRuleHeadHeadIDs.print(out); featureRuleHeadDistIDs.print(out); featureRuleRuleHeadIDs.print(out); featureRuleRuleHeadHeadIDs.print(out); } public void printWeights(Weights weights, PrintWriter out) { out.println(weights.getWeight(0)); featureCatIDs.printWeights(weights, out); featureCatHeadIDs.printWeights(weights, out); featureRuleIDs.printWeights(weights, out); featureRuleHeadIDs.printWeights(weights, out); featureRuleHeadHeadIDs.printWeights(weights, out); featureRuleHeadDistIDs.printWeights(weights, out); featureRuleRuleHeadIDs.printWeights(weights, out); featureRuleRuleHeadHeadIDs.printWeights(weights, out); } }
package org.jaudiotagger.issues; import org.jaudiotagger.AbstractTestCase; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.audio.mp3.MP3File; import org.jaudiotagger.tag.FieldKey; import org.jaudiotagger.tag.id3.AbstractID3v2Frame; import org.jaudiotagger.tag.id3.framebody.FrameBodyTIPL; import java.io.File; /** * Able to read and write to file with repeated (and incomplete) MOOV atom at the end of the file. Fixed so that ignores it * when reading and writing, but would be nice if on write it actually deleted the offending data */ public class Issue406Test extends AbstractTestCase { public void testIssue() throws Exception { Exception caught = null; try { File orig = new File("testdata", "test103.m4a"); if (!orig.isFile()) { System.err.println("Unable to test file - not available"); return; } File testFile = AbstractTestCase.copyAudioToTmp("test103.m4a"); AudioFile af = AudioFileIO.read(testFile); assertEquals(af.getTag().getFirst(FieldKey.TITLE),"London Calling"); assertEquals(af.getTag().getFirst(FieldKey.ARTIST),"The Clash"); assertEquals(af.getTag().getFirst(FieldKey.YEAR),"1979"); af.getTag().setField(FieldKey.TITLE,"Bridport Calling"); af.commit(); af = AudioFileIO.read(testFile); assertEquals(af.getTag().getFirst(FieldKey.TITLE),"Bridport Calling"); } catch(Exception e) { caught=e; e.printStackTrace(); } assertNull(caught); } }
/** * The main frame of the entire suite. * Calls for the main GUI panels for other classes and adds them to a tabbed * frame. * * @author Amanda Fisher * @contrib Aidan Sawyer [rit: aks5238 | sf daniels-ai] */ import javax.swing.JFrame; import javax.swing.JTabbedPane; import java.awt.Toolkit; import one.d.electrophoresis.Electrophoresis; /** * The main frame for the JBioFramework program. * -Adds Welcome, Electrophoresis, Electro2D, MassSpec and MarvinSketch * applications to the JFrame it extends with a JTabbedPane. */ public class JBioFrameworkMain extends JFrame { public static final long serialVersionUID = 1L; private static JTabbedPane tabbedPane; private Welcome welcome; private Electrophoresis oneDE; private Electro2D electro2D; private MassSpecMain spectrometer; private MarvinTab marvin; /*private [NameOfClass] [user-created reference]*/ /** * Main method for entire program. * Creates a new instantiation of the JBioFramework class (calls constructor) */ public static void main(String[] args) { JBioFrameworkMain jbfMain = new JBioFrameworkMain(); } /** * Constructor for JBioFrameworkMain Frame object. * -sets frame to visible, sets some general behaviors, adds * panels from Electro1D, Electro2d, etc. and adjusts size. */ public JBioFrameworkMain() { //calls JFrame constructor with String parametr which sets the displayed //name at the top of the window. super("JBioFramework"); //swing component which facilitates switching between different panels. tabbedPane = new JTabbedPane(); //add all of the relevant panels for each application's GUI to tabbedPane tabbedPane.addTab("Welcome", new Welcome()); tabbedPane.addTab("Electro1D", new Electrophoresis()); tabbedPane.addTab("Electro2D", new Electro2D()); tabbedPane.addTab("Mass Spectrometer", new MassSpecMain()); tabbedPane.addTab("Marvin Sketch", new MarvinTab().createMainPanel()); /*tabbedPane.addTab(["name (to be displayed)"], [object]);*/ //add tabbedPane to frame add(tabbedPane); /**various last steps for the JFrame.*/ // Method inherited from Window by JFrame which "Causes this Window to be // sized to fit the preferred size and layouts of its subcomponents. super.pack(); // Use a toolkit to find the screen size of the user's monitor // and set the window size to it. super.setSize(Toolkit.getDefaultToolkit().getScreenSize()); //ensure that the program stops when the Window for the GUI is closed. //TODO create WindowManager to set prompt for review or session log. super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //make the completed, correctly-sized window visible. // [should be the last thing called, to prevent the user from seeing // the window get resized] super.setVisible(true); } /** * returns the JTabbedPane which holds all of our simulation panels. * tabbedPane is a Swing component which facilitates the switching between * multiple components. */ public static JTabbedPane getTabs() { return tabbedPane; } }
package com.microsoft.tang; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public interface Aspect { /** * Note, it is inject()'s responsibility to call ret.getInstance() if ret instanceof ExternalConstructor. */ <T> T inject(Constructor<T> c, Object[] args) throws InvocationTargetException, IllegalAccessException, IllegalArgumentException, InstantiationException; /** * TANG calls this the first time get() is called on an injection future. This informs the aspect of * the relationship between InjectionFutures (that were already passed into inject()) and the instantiated * object. * * @param f An InjectionFuture that was passed to the args[] array of inject at some point in the past. * @param t An object instance that was returned by inject(). */ <T> void injectionFutureInstantiated(InjectionFuture<T> f, T t); Aspect createChildAspect(); }
package gov.va.isaac; import gov.va.isaac.dialog.ErrorDialog; import java.net.URL; import javafx.application.Application; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.stage.WindowEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.javafx.tk.Toolkit; /** * Taxonomy viewer app class. * * @author ocarlsen */ public class App extends Application { @SuppressWarnings("unused") private static final Logger LOG = LoggerFactory.getLogger(App.class); private ErrorDialog errorDialog; @Override public void start(Stage primaryStage) throws Exception { URL fxmlURL = this.getClass().getResource("App.fxml"); FXMLLoader loader = new FXMLLoader(fxmlURL); Parent root = (Parent) loader.load(); final AppController controller = loader.getController(); controller.setApp(this); primaryStage.setTitle("Taxonomy Viewer"); primaryStage.setScene(new Scene(root)); primaryStage.sizeToScene(); primaryStage.show(); // Set minimum dimensions. primaryStage.setMinHeight(primaryStage.getHeight()); primaryStage.setMinWidth(primaryStage.getWidth()); // Handle window close event. primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { controller.shutdown(); } }); // Reusable error dialog. this.errorDialog = new ErrorDialog(primaryStage); } public void showErrorDialog(final String title, final String message, final String details) { // Make sure in application thread. Toolkit.getToolkit().checkFxUserThread(); errorDialog.setVariables(title, message, details); errorDialog.showAndWait(); } public static void main(String[] args) { Application.launch(args); } }
package org.dita.dost.log; import static org.junit.Assert.*; import java.io.File; import java.util.Properties; import org.junit.BeforeClass; import org.junit.AfterClass; import org.junit.Test; public class MessageUtilsTest { private static final File resourceDir = new File("test-stub", MessageUtilsTest.class.getSimpleName()); @BeforeClass public static void setUp() throws Exception { final File f = new File(resourceDir, "messages.xml"); MessageUtils.loadMessages(f.getAbsolutePath()); } @Test public void testLoadDefaultMessages() { MessageUtils.loadDefaultMessages(); } @Test public void testLoadMessages() { final File f = new File(resourceDir, "messages.xml"); MessageUtils.loadMessages(f.getAbsolutePath()); } @Test public void testGetMessageString() { final MessageBean exp = new MessageBean(); exp.setId("XXX123F"); exp.setType("FATAL"); exp.setReason("Fatal reason."); exp.setResponse("Fatal response."); assertEquals(exp.toString(), MessageUtils.getMessage("XXX123F").toString()); } @Test public void testGetMessageStringProperties() { final Properties props = new Properties(); props.put("%1", "foo"); props.put("%2", "bar baz"); final MessageBean exp = new MessageBean(); exp.setId("XXX234E"); exp.setType("ERROR"); exp.setReason("Error foo reason bar baz."); exp.setResponse("Error foo response bar baz."); assertEquals(exp.toString(), MessageUtils.getMessage("XXX234E", props).toString()); } @Test public void testGetMessageStringMissing() { final Properties props = new Properties(); props.put("%1", "foo"); final MessageBean exp = new MessageBean(); exp.setId("XXX234E"); exp.setType("ERROR"); exp.setReason("Error foo reason %2."); exp.setResponse("Error foo response %2."); assertEquals(exp.toString(), MessageUtils.getMessage("XXX234E", props).toString()); } @Test public void testGetMessageStringExtra() { final Properties props = new Properties(); props.put("%1", "foo"); props.put("%2", "bar baz"); props.put("%3", "qux"); final MessageBean exp = new MessageBean(); exp.setId("XXX234E"); exp.setType("ERROR"); exp.setReason("Error foo reason bar baz."); exp.setResponse("Error foo response bar baz."); assertEquals(exp.toString(), MessageUtils.getMessage("XXX234E", props).toString()); } @AfterClass public static void tearDown() throws Exception { final File f = new File("resource/messages.xml"); MessageUtils.loadMessages(f.getAbsolutePath()); } }
package org.exist.xquery; import junit.framework.TestCase; import junit.textui.TestRunner; import org.exist.storage.DBBroker; import org.exist.xmldb.DatabaseInstanceManager; import org.xmldb.api.DatabaseManager; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Database; import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.CollectionManagementService; import org.xmldb.api.modules.XQueryService; public class DocumentUpdateTest extends TestCase { private static final String TEST_COLLECTION_NAME = "testup"; private Database database; private Collection testCollection; /** * Test if the doc, collection and document functions are correctly * notified upon document updates. Call a function once on the empty collection, * then call it again after a document was added, and compare the results. */ public void testUpdate() { String imports = "import module namespace xdb='http://exist-db.org/xquery/xmldb';\n" + "import module namespace util='http://exist-db.org/xquery/util';\n"; try { System.out.println("-- TEST 1: doc() function --"); String query = imports + "declare function local:get-doc($path as xs:string) {\n" + " if (doc-available($path)) then doc($path) else ()\n" + "};\n" + "let $col := xdb:create-collection('/db', 'testup')\n" + "let $path := '/db/testup/test1.xml'\n" + "let $doc := xdb:store($col, 'test1.xml', <test><n>1</n></test>)\n" + "let $d1 := local:get-doc($path)\n" + "let $remove := xdb:remove('/db/testup', 'test1.xml')\n" + "return string-join((string(count(local:get-doc($path))), string(doc-available($path))), ' ')"; String result = execQuery(query); assertEquals(result, "0 false"); System.out.println("-- TEST 2: xmldb:document() function --"); query = imports + "declare function local:get-doc($path as xs:string) {\n" + " if (doc-available($path)) then xmldb:document($path) else ()\n" + "};\n" + "let $col := xdb:create-collection('/db', 'testup')\n" + "let $path := '/db/testup/test1.xml'\n" + "let $d1 := local:get-doc($path)\n" + "let $doc := xdb:store($col, 'test1.xml', <test><n>1</n></test>)\n" + "return string-join((string(count(local:get-doc($path))), string(doc-available($path))), ' ')"; result = execQuery(query); assertEquals(result, "1 true"); System.out.println("-- TEST 3: collection() function --"); query = imports + "declare function local:xpath($collection as xs:string) {\n" + " for $c in collection($collection) return $c "};\n" + "let $col := xdb:create-collection('/db', 'testup')\n" + "let $path := '/db/testup'\n" + "let $d1 := local:xpath($path)//n/text()\n" + "let $doc := xdb:store($col, 'test1.xml', <test><n>1</n></test>)\n" + "return local:xpath($path)/text()"; result = execQuery(query); assertEquals(result, "1"); System.out.println("-- TEST 4: 'update insert' statement --"); query = imports + "declare function local:xpath($collection as xs:string) {\n" + " collection($collection)\n" + "};\n" + "let $col := xdb:create-collection('/db', 'testup')\n" + "let $path := '/db/testup'\n" + "let $d1 := local:xpath($path) "let $doc := xdb:store($col, 'test1.xml', <test><n>1</n></test>)\n" + "return (\n" + " update insert <n>2</n> into collection($path)/test,\n" + " count(local:xpath($path) ")"; result = execQuery(query); assertEquals(result, "2"); System.out.println("-- TEST 5: 'update replace' statement --"); query = imports + "let $doc := xdb:store('/db', 'test1.xml', " + "<test> " + "<link href=\"features\"/> " + "(: it works with only 1 link :) " + "<link href=\"features/test\"/> " + "</test>) " + "let $links := doc($doc)/test/link/@href " + "return " + "for $link in $links " + "return ( " + "update replace $link with \"123\", " + "(: without the output on the next line, it works :) " + "xs:string($link) " + ")"; XQueryService service = (XQueryService) testCollection.getService("XQueryService", "1.0"); ResourceSet r = service.query(query); assertEquals(r.getSize(), 2); assertEquals(r.getResource(0).getContent().toString(), "123"); assertEquals(r.getResource(1).getContent().toString(), "123"); } catch (XMLDBException e) { e.printStackTrace(); fail(e.getMessage()); } } public void testUpdateAttribute(){ String query1="let $content :=" +"<A><B><C d=\"xxx\">ccc1</C><C d=\"yyy\" e=\"zzz\">ccc2</C></B></A> " +"let $uri := xmldb:store(\"/db/\", \"marktest7.xml\", $content) " +"let $doc := doc($uri) " +"let $xxx := update delete $doc +"return $doc"; String query2="let $doc := doc(\"/db/marktest7.xml\") " +"return " /* * @see TestCase#tearDown() */ protected void tearDown() { try { Collection root = DatabaseManager.getCollection("xmldb:exist://" + DBBroker.ROOT_COLLECTION, "admin", null); CollectionManagementService service = (CollectionManagementService) root.getService( "CollectionManagementService", "1.0"); service.removeCollection(TEST_COLLECTION_NAME); DatabaseManager.deregisterDatabase(database); DatabaseInstanceManager dim = (DatabaseInstanceManager) testCollection.getService( "DatabaseInstanceManager", "1.0"); dim.shutdown(); database = null; testCollection = null; System.out.println("tearDown PASSED"); } catch (XMLDBException e) { fail(e.getMessage()); } } public static void main(String[] args) { TestRunner.run(DocumentUpdateTest.class); } }
package ch.unibe.scg.regex; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.regex.MatchResult; import org.junit.Before; import org.junit.Test; import ch.unibe.scg.regex.TransitionTriple.Priority; /** Testing {@link TDFAInterpreter} */ @SuppressWarnings("javadoc") public class TDFAInterpreterTest { private TDFAInterpreter interpreter; @Before public void setUp() throws Exception { interpreter = new TDFAInterpreter(new TNFAToTDFA(makeTheNFA())); } TNFA makeTheNFA() { State.resetCount(); final State s0 = State.get(); final State s1 = State.get(); final State s2 = State.get(); final TNFA tnfa = mock(TNFA.class); final Tag t0 = mock(Tag.class); final CaptureGroup cg = mock(CaptureGroup.class); when(cg.getNumber()).thenReturn(0); when(t0.toString()).thenReturn("t0"); when(t0.getGroup()).thenReturn(cg); when(tnfa.allInputRanges()).thenReturn(Arrays.asList(InputRange.make('a'))); when(tnfa.getInitialState()).thenReturn(s0); when(tnfa.allTags()).thenReturn(Arrays.asList(Tag.NONE)); when(tnfa.availableTransitionsFor(eq(s0), isNull(Character.class))).thenReturn( Arrays.asList(new TransitionTriple(s1, Priority.NORMAL, t0), new TransitionTriple(s0, Priority.LOW, Tag.NONE))); when(tnfa.availableTransitionsFor(eq(s0), eq('a'))).thenReturn( Arrays.asList(new TransitionTriple(s0, Priority.LOW, Tag.NONE))); when(tnfa.availableTransitionsFor(s1, 'a')).thenReturn( Arrays.asList(new TransitionTriple(s2, Priority.NORMAL, Tag.NONE), new TransitionTriple(s1, Priority.LOW, Tag.NONE))); when(tnfa.availableTransitionsFor(s2, 'a')).thenReturn(new ArrayList<TransitionTriple>()); when(tnfa.isAccepting(eq(s2))).thenReturn(true); when(tnfa.getFinalStates()).thenReturn(new HashSet<>(Arrays.asList(s2))); when(tnfa.isAccepting(eq(s1))).thenReturn(false); when(tnfa.isAccepting(eq(s0))).thenReturn(false); return tnfa; } @Test public void testBuiltAutomaton() { interpreter.interpret("aaaaaa"); assertThat(interpreter.tdfaBuilder.build().toString(), is("q0-a-a -> q1 [1<- pos]\nq1-a-a -> q1 [1->0, 1<- pos]\n")); } @Test public void testInvalidString() { assertThat(interpreter.interpret("b"), is((MatchResult) RealMatchResult.NoMatchResult.SINGLETON)); } @Test public void testInvalidStringCompiled() { final MatchResult matcher = interpreter.interpret("b"); assertThat(interpreter.tdfaBuilder.build().toString(), is("")); assertThat(matcher.toString(), is("NO_MATCH")); } @Test public void testMatch() { final MatchResult matchResult = interpreter.interpret("aaaaaa"); assertThat(matchResult.toString(), is("4-0")); } }
package com.kii.thingif; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; /** Represents Application on Kii Cloud */ public class KiiApp implements Parcelable { private String appID; private String appKey; private String hostName; private String baseUrl; private String siteName; public KiiApp(String appID, String appKey, Site site) { if (TextUtils.isEmpty(appID)) { throw new IllegalArgumentException("appID is null or empty."); } if (TextUtils.isEmpty(appKey)) { throw new IllegalArgumentException("appKey is null or empty."); } if (site == null) { throw new IllegalArgumentException("site is null."); } this.appID = appID; this.appKey = appKey; this.hostName = site.getHostName(); this.baseUrl = site.getBaseUrl(); this.siteName = site.name(); } public KiiApp(String appID, String appKey, String hostName) { if (TextUtils.isEmpty(appID)) { throw new IllegalArgumentException("appID is null or empty."); } if (TextUtils.isEmpty(appKey)) { throw new IllegalArgumentException("appKey is null or empty."); } if (TextUtils.isEmpty(hostName)) { throw new IllegalArgumentException("hostName is null or empty."); } this.appID = appID; this.appKey = appKey; this.hostName = hostName; this.baseUrl = "https://" + hostName; this.siteName = "CUSTOM"; } /** Instantiate Kii App with Host Name and Site Name. * Who host Kii Cloud in private/ dedicated location * Will use this constructor to instantiate KiiApp. * (Private/ Dedicated location is only available in Enterprise subscription.) * If you're using public Kii Cloud, please use {@link KiiApp(String, String, Site)} * siteName is used by Gateway Agent to resolve the server location stored with the siteName * in the Gateway configuration. * @param appID ID of the app. * @param appKey Key of the app. * @param hostName Host name of the app. * @param siteName Site name of the app. (Corresponds to Gateway Agent configuration.) */ public KiiApp(String appID, String appKey, String hostName, String siteName) { if (TextUtils.isEmpty(appID)) { throw new IllegalArgumentException("appID is null or empty."); } if (TextUtils.isEmpty(appKey)) { throw new IllegalArgumentException("appKey is null or empty."); } if (TextUtils.isEmpty(hostName)) { throw new IllegalArgumentException("hostName is null or empty."); } this.appID = appID; this.appKey = appKey; this.hostName = hostName; this.baseUrl = "https://" + hostName; this.siteName = siteName; } protected KiiApp(Parcel in) { appID = in.readString(); appKey = in.readString(); hostName = in.readString(); baseUrl = in.readString(); siteName = in.readString(); } public static final Creator<KiiApp> CREATOR = new Creator<KiiApp>() { @Override public KiiApp createFromParcel(Parcel in) { return new KiiApp(in); } @Override public KiiApp[] newArray(int size) { return new KiiApp[size]; } }; public String getAppID() { return this.appID; } public String getAppKey() { return this.appKey; } public String getHostName() { return this.hostName; } public String getBaseUrl() { return this.baseUrl; } public String getSiteName() { return this.siteName; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(appID); dest.writeString(appKey); dest.writeString(hostName); dest.writeString(baseUrl); dest.writeString(siteName); } public static class Builder { final private String hostName; final private String appID; final private String appKey; private String siteName; private int port; private String schema; Builder(String appID, String appKey, String hostName) { this.appID = appID; this.appKey = appKey; this.hostName = hostName; this.port = -1; this.schema = "https"; } /** Build with host name * @param appID ID of the app. * @param appKey Key of the app. * @param hostName Hostname where the private/ dedicated Kii Cloud is hosted. * @return builder instance. */ public static Builder builderWithHostName(String appID, String appKey, String hostName) { Builder b = new Builder(appID, appKey, hostName); b.siteName = "CUSTOM"; return b; } /** Set port number * Optional. By default no port is specified. * @param port port number. 0 or less than 0 would be ignored. * @return builder instance. */ public Builder setPort(int port) { this.port = port; return this; } /** Set schema * Optional. By default https is used. * @param schema url schema. * @return builder instance. */ public Builder setSchema(String schema) { this.schema = schema; return this; } /** Set site name. * Optional. by Default "CUSTOM" is applied. * This site name should match with your Gateway Agent configuration * if you interact Gateway Agent with this SDK. * @param siteName * @return builder instance */ public Builder setSiteName(String siteName) { this.siteName = siteName; return this; } /** Build KiiApp instance. * @return KiiApp instance. */ public KiiApp build() { KiiApp app = new KiiApp(appID, appKey, hostName); app.baseUrl = this.schema + "://" + this.hostName; if (this.port > 0) { app.baseUrl = app.baseUrl + ":" + this.port; } app.siteName = this.siteName; return app; } } }
package org.antlr.v4.codegen; import org.antlr.v4.codegen.target.*; /** * Utility class to escape Unicode code points using various * languages' syntax. */ public class UnicodeEscapes { public static String escapeCodePoint(int codePoint, String language) { StringBuilder result = new StringBuilder(); appendEscapedCodePoint(result, codePoint, language); return result.toString(); } public static void appendEscapedCodePoint(StringBuilder sb, int codePoint, String language) { switch (language) { case CSharpTarget.key: case Python2Target.key: case Python3Target.key: case CppTarget.key: case GoTarget.key: case PHPTarget.key: String format = Character.isSupplementaryCodePoint(codePoint) ? "\\U%08X" : "\\u%04X"; sb.append(String.format(format, codePoint)); break; case SwiftTarget.key: sb.append(String.format("\\u{%04X}", codePoint)); break; case JavaTarget.key: case JavaScriptTarget.key: case DartTarget.key: default: if (Character.isSupplementaryCodePoint(codePoint)) { // char is not an 'integral' type, so we have to explicitly convert // to int before passing to the %X formatter or else it throws. sb.append(String.format("\\u%04X", (int)Character.highSurrogate(codePoint))); sb.append(String.format("\\u%04X", (int)Character.lowSurrogate(codePoint))); } else { sb.append(String.format("\\u%04X", codePoint)); } break; } } }
package org.antlr.v4.parse; import org.antlr.runtime.Token; import org.antlr.v4.Tool; import org.antlr.v4.codegen.CodeGenerator; import org.antlr.v4.tool.ErrorType; import org.antlr.v4.tool.Grammar; import org.antlr.v4.tool.ast.GrammarAST; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TokenVocabParser { protected final Grammar g; public TokenVocabParser(Grammar g) { this.g = g; } /** Load a vocab file {@code <vocabName>.tokens} and return mapping. */ public Map<String,Integer> load() { Map<String,Integer> tokens = new LinkedHashMap<String,Integer>(); int maxTokenType = -1; File fullFile = getImportedVocabFile(); FileInputStream fis = null; BufferedReader br = null; Tool tool = g.tool; String vocabName = g.getOptionString("tokenVocab"); try { Pattern tokenDefPattern = Pattern.compile("([^\n]+?)[ \\t]*?=[ \\t]*?([0-9]+)"); fis = new FileInputStream(fullFile); InputStreamReader isr; if (tool.grammarEncoding != null) { isr = new InputStreamReader(fis, tool.grammarEncoding); } else { isr = new InputStreamReader(fis); } br = new BufferedReader(isr); String tokenDef = br.readLine(); int lineNum = 1; while ( tokenDef!=null ) { Matcher matcher = tokenDefPattern.matcher(tokenDef); if ( matcher.find() ) { String tokenID = matcher.group(1); String tokenTypeS = matcher.group(2); int tokenType; try { tokenType = Integer.valueOf(tokenTypeS); } catch (NumberFormatException nfe) { tool.errMgr.toolError(ErrorType.TOKENS_FILE_SYNTAX_ERROR, vocabName + CodeGenerator.VOCAB_FILE_EXTENSION, " bad token type: "+tokenTypeS, lineNum); tokenType = Token.INVALID_TOKEN_TYPE; } tool.log("grammar", "import "+tokenID+"="+tokenType); tokens.put(tokenID, tokenType); maxTokenType = Math.max(maxTokenType,tokenType); lineNum++; } else { if ( tokenDef.length()>0 ) { // ignore blank lines tool.errMgr.toolError(ErrorType.TOKENS_FILE_SYNTAX_ERROR, vocabName + CodeGenerator.VOCAB_FILE_EXTENSION, " bad token def: " + tokenDef, lineNum); } } tokenDef = br.readLine(); } } catch (FileNotFoundException fnfe) { GrammarAST inTree = g.ast.getOptionAST("tokenVocab"); String inTreeValue = inTree.getToken().getText(); if ( vocabName.equals(inTreeValue) ) { tool.errMgr.grammarError(ErrorType.CANNOT_FIND_TOKENS_FILE_REFD_IN_GRAMMAR, g.fileName, inTree.getToken(), fullFile); } else { // must be from -D option on cmd-line not token in tree tool.errMgr.toolError(ErrorType.CANNOT_FIND_TOKENS_FILE_GIVEN_ON_CMDLINE, fullFile, g.name); } } catch (Exception e) { tool.errMgr.toolError(ErrorType.ERROR_READING_TOKENS_FILE, e, fullFile, e.getMessage()); } finally { try { if ( br!=null ) br.close(); } catch (IOException ioe) { tool.errMgr.toolError(ErrorType.ERROR_READING_TOKENS_FILE, ioe, fullFile, ioe.getMessage()); } } return tokens; } /** Return a File descriptor for vocab file. Look in library or * in -o output path. antlr -o foo T.g4 U.g4 where U needs T.tokens * won't work unless we look in foo too. If we do not find the * file in the lib directory then must assume that the .tokens file * is going to be generated as part of this build and we have defined * .tokens files so that they ALWAYS are generated in the base output * directory, which means the current directory for the command line tool if there * was no output directory specified. */ public File getImportedVocabFile() { String vocabName = g.getOptionString("tokenVocab"); File f = new File(g.tool.libDirectory, File.separator + vocabName + CodeGenerator.VOCAB_FILE_EXTENSION); if (f.exists()) { return f; } // We did not find the vocab file in the lib directory, so we need // to look for it in the output directory which is where .tokens // files are generated (in the base, not relative to the input // location.) f = new File(g.tool.outputDirectory, vocabName + CodeGenerator.VOCAB_FILE_EXTENSION); return f; } }
package org.frc1675; import com.sun.squawk.util.MathUtils; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.Button; import edu.wpi.first.wpilibj.buttons.JoystickButton; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.frc1675.commands.EncoderShooter.EncoderShooterBumpDown; import org.frc1675.commands.EncoderShooter.EncoderShooterBumpUp; import org.frc1675.commands.EncoderShooter.EncoderShooterIdle; import org.frc1675.commands.EncoderShooter.EncoderShooterSetToVoltage; import org.frc1675.commands.EncoderShooter.EncoderShooterTurnOff; import org.frc1675.commands.EncoderShooter.EncoderShooterTurnOn; import org.frc1675.commands.Index; import org.frc1675.commands.climber.ClimberExtend; import org.frc1675.commands.climber.ClimberRetract; import org.frc1675.commands.drive.edrive.SlowLeft; import org.frc1675.commands.drive.edrive.SlowRight; import org.frc1675.commands.foot.FootDown; import org.frc1675.commands.foot.FootUp; /** * This class is the glue that binds the controls on the physical operator * interface to the commands and command groups that allow control of the robot. */ public class OI { public Joystick driverController = new Joystick(RobotMap.DRIVER_CONTROLLER); private Button driverBButton = new JoystickButton(driverController, XBoxControllerMap.B_BUTTON); private Button driverXButton = new JoystickButton(driverController, XBoxControllerMap.X_BUTTON); private Button driverYButton = new JoystickButton(driverController, XBoxControllerMap.Y_BUTTON); private Button driverAButton = new JoystickButton(driverController, XBoxControllerMap.A_BUTTON); private Button driverRightBumper = new JoystickButton(driverController, XBoxControllerMap.RIGHT_BUMPER_BUTTON); private Button driverLeftBumper = new JoystickButton(driverController, XBoxControllerMap.LEFT_BUMPER_BUTTON); private Button driverLeftJoystickButton = new JoystickButton(driverController, XBoxControllerMap.RIGHT_JOYSTICK_BUTTON); private Button driverRightJoystickButton = new JoystickButton(driverController, XBoxControllerMap.LEFT_JOYSTICK_BUTTON); public Joystick operatorController = new Joystick(RobotMap.OPERATOR_CONTROLLER); private Button operatorBButton = new JoystickButton(operatorController, XBoxControllerMap.B_BUTTON); private Button operatorXButton = new JoystickButton(operatorController, XBoxControllerMap.X_BUTTON); private Button operatorYButton = new JoystickButton(operatorController, XBoxControllerMap.Y_BUTTON); private Button operatorAButton = new JoystickButton(operatorController, XBoxControllerMap.A_BUTTON); private Button operatorRightBumper = new JoystickButton(operatorController, XBoxControllerMap.RIGHT_BUMPER_BUTTON); private Button operatorLeftBumper = new JoystickButton(operatorController, XBoxControllerMap.LEFT_BUMPER_BUTTON); private Button operatorLeftJoystickButton = new JoystickButton(operatorController, XBoxControllerMap.RIGHT_JOYSTICK_BUTTON); private Button operatorRightJoystickButton = new JoystickButton(operatorController, XBoxControllerMap.LEFT_JOYSTICK_BUTTON); private Button operatorDPadRightButton = new DPadButton(operatorController, DPadButton.RIGHT); private Button operatorDPadLeftButton = new DPadButton(operatorController, DPadButton.LEFT); public OI() { operatorXButton.whenPressed(new FootDown()); operatorBButton.whenPressed(new FootUp()); operatorYButton.whenPressed(new ClimberExtend()); operatorAButton.whenPressed(new ClimberRetract()); // operatorRightBumper.whenPressed(new GoToShootingSpeed()); // operatorLeftBumper.whenPressed(new GoToIdleSpeed()); // operatorDPadLeftButton.whenPressed(new BumpDown()); // operatorDPadRightButton.whenPressed(new BumpUp()); if(operatorController.getRawAxis(XBoxControllerMap.LEFT_Y_AXIS)> .8){ operatorRightBumper.whenPressed(new EncoderShooterSetToVoltage(RobotMap.BACK_SHOOTING_SPEED, RobotMap.FRONT_SHOOTING_SPEED)); SmartDashboard.putBoolean("Encoder Mode", false); }else{ operatorRightBumper.whenPressed(new EncoderShooterTurnOn()); operatorDPadLeftButton.whenPressed(new EncoderShooterBumpDown()); operatorDPadRightButton.whenPressed(new EncoderShooterBumpUp()); SmartDashboard.putBoolean("Encoder Mode", true); } operatorRightJoystickButton.whenPressed(new EncoderShooterSetToVoltage(RobotMap.BACK_SHOOTING_SPEED, 1)); operatorLeftBumper.whenPressed(new EncoderShooterTurnOff()); // used to be idle driverAButton.whenPressed(new Index()); // driverYButton.whenPressed(new StopShooter()); driverYButton.whenPressed(new EncoderShooterTurnOff()); driverLeftBumper.whileHeld(new SlowLeft()); driverRightBumper.whileHeld(new SlowRight()); } public double getMecanumMagnitude() { double x = driverController.getRawAxis(XBoxControllerMap.LEFT_X_AXIS); double y = driverController.getRawAxis(XBoxControllerMap.LEFT_Y_AXIS); double returnMagnitude = 0.0; double squareMagnitude = Math.sqrt(MathUtils.pow(x, 2.0) + MathUtils.pow(y, 2.0)); if(x != 0.0 && y != 0.0){ double borderX; double borderY; if(Math.abs(x) > Math.abs(y)){ //scale x to 1.0 borderX = x / Math.abs(x); borderY = y / Math.abs(x); } else { //scale y to 1.0 borderX = x / Math.abs(y); borderY = y / Math.abs(y); } double borderMagnitude = Math.sqrt(MathUtils.pow(borderX, 2.0) + MathUtils.pow(borderY, 2.0)); returnMagnitude = squareMagnitude / borderMagnitude; } else { returnMagnitude = squareMagnitude; } if (returnMagnitude < RobotMap.DEADZONE_RADIUS) { returnMagnitude = 0.0; } return returnMagnitude; } public double getMecanumRotation() { double x = driverController.getRawAxis(XBoxControllerMap.RIGHT_X_AXIS); double rotation = x; if (Math.abs(rotation) < RobotMap.DEADZONE_RADIUS) { rotation = 0; } return rotation; } public double getMecanumDirection() { double direction; double x = driverController.getRawAxis(XBoxControllerMap.LEFT_X_AXIS); double y = driverController.getRawAxis(XBoxControllerMap.LEFT_Y_AXIS); //y *= -1.0; <-- Created a flip problem double magnitude = getMecanumMagnitude(); if (magnitude < RobotMap.DEADZONE_RADIUS) { direction = 0.0; } else { direction = MathUtils.atan2(y, x); } direction -= Math.PI / 2; return direction; } public double getLeftTankCommand() { double leftY = -driverController.getRawAxis(XBoxControllerMap.LEFT_Y_AXIS); double returnValue = Math.abs(leftY); if(returnValue <= RobotMap.DEADZONE_RADIUS){ returnValue = 0.0; } else { returnValue = leftY; } return returnValue; } public double getRightTankCommand() { double rightY = -driverController.getRawAxis(XBoxControllerMap.RIGHT_Y_AXIS); double returnValue = Math.abs(rightY); if(returnValue <= RobotMap.DEADZONE_RADIUS){ returnValue = 0.0; } else { returnValue = rightY; } return returnValue; } public double getRightVectorX(){ double x = driverController.getRawAxis(XBoxControllerMap.RIGHT_X_AXIS); if(Math.abs(x) < RobotMap.DEADZONE_RADIUS){ x = 0.0; } return x; } public double getLeftVectorY(){ double x = driverController.getRawAxis(XBoxControllerMap.LEFT_Y_AXIS); if(Math.abs(x) < RobotMap.DEADZONE_RADIUS){ return 0; } else{ return x; } } }
package scenario; // Libraries import players.Player; /** * <b>Scenario - Water</b><br> * Take care with the water: it cannot be * destroyed, but can stuck robots. */ @Deprecated public class Water implements Scenario { public int takeDamage(int damage) { // Water cannot be destroyed... return 0; } public int getHP() { return 42; } public String toString() { return "(≈) Water"; } public Player getTeam() { return Player.Nature; } public String name() { return "WATER"; } }
package fredboat; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import fredboat.agent.CarbonitexAgent; import fredboat.api.API; import fredboat.audio.MusicPersistenceHandler; import fredboat.commandmeta.CommandInitializer; import fredboat.event.EventListenerBoat; import fredboat.event.EventListenerSelf; import fredboat.util.BotConstants; import fredboat.util.DiscordUtil; import fredboat.util.DistributionEnum; import fredboat.util.log.SimpleLogToSLF4JAdapter; import frederikam.jca.JCA; import frederikam.jca.JCABuilder; import net.dv8tion.jda.core.AccountType; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.JDAInfo; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.VoiceChannel; import net.dv8tion.jda.core.events.ReadyEvent; import net.dv8tion.jda.core.utils.SimpleLog; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.security.auth.login.LoginException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; public abstract class FredBoat { private static final Logger log = LoggerFactory.getLogger(FredBoat.class); static final int SHARD_CREATION_SLEEP_INTERVAL = 5100; private static final ArrayList<FredBoat> shards = new ArrayList<>(); public static JCA jca; public static final long START_TIME = System.currentTimeMillis(); public static DistributionEnum distribution = DistributionEnum.DEVELOPMENT; public static final int UNKNOWN_SHUTDOWN_CODE = -991023; public static int shutdownCode = UNKNOWN_SHUTDOWN_CODE;//Used when specifying the intended code for shutdown hooks static EventListenerBoat listenerBot; static EventListenerSelf listenerSelf; /* Config */ private static JSONObject config = null; private static int scopes = 0; public static int numShards = 4; private static AtomicInteger numShardsReady = new AtomicInteger(0); /* Credentials */ private static JSONObject credsjson; static String accountToken; static String clientToken; public static String mashapeKey; public static String MALPassword; private final static List<String> GOOGLE_KEYS = new ArrayList<>(); private static String[] lavaplayerNodes = new String[64]; private static boolean lavaplayerNodesEnabled = false; private static String carbonKey; JDA jda; private static FredBoatClient fbClient; public static void main(String[] args) throws LoginException, IllegalArgumentException, InterruptedException, IOException { Runtime.getRuntime().addShutdownHook(new Thread(ON_SHUTDOWN)); //Attach log adapter SimpleLog.addListener(new SimpleLogToSLF4JAdapter()); //Make JDA not print to console, we have Logback for that SimpleLog.LEVEL = SimpleLog.Level.OFF; try { scopes = Integer.parseInt(args[0]); } catch (NumberFormatException | ArrayIndexOutOfBoundsException ignored) { log.info("Invalid scope, defaulting to scopes 0x111"); scopes = 0x111; } log.info("Starting with scopes:" + "\n\tMain: " + ((scopes & 0x100) == 0x100) + "\n\tMusic: " + ((scopes & 0x010) == 0x010) + "\n\tSelf: " + ((scopes & 0x001) == 0x001)); log.info("JDA version:\t" + JDAInfo.VERSION); //Load credentials and config files InputStream is = new FileInputStream(new File("./credentials.json")); Scanner scanner = new Scanner(is); credsjson = new JSONObject(scanner.useDelimiter("\\A").next()); scanner.close(); is = new FileInputStream(new File("./config.json")); scanner = new Scanner(is); config = new JSONObject(scanner.useDelimiter("\\A").next()); scanner.close(); mashapeKey = credsjson.optString("mashapeKey"); clientToken = credsjson.optString("clientToken"); MALPassword = credsjson.optString("malPassword"); carbonKey = credsjson.optString("carbonKey"); JSONArray nodesArray = credsjson.optJSONArray("lavaplayerNodes"); if(nodesArray != null) { lavaplayerNodesEnabled = true; Iterator<Object> itr = nodesArray.iterator(); int i = 0; while(itr.hasNext()) { lavaplayerNodes[i] = (String) itr.next(); i++; } } JSONArray gkeys = credsjson.optJSONArray("googleServerKeys"); if (gkeys != null) { log.info("Using lavaplayer nodes"); gkeys.forEach((Object str) -> GOOGLE_KEYS.add((String) str)); } if (config.optBoolean("patron")) { distribution = DistributionEnum.PATRON; } else //Determine distribution if (config.optBoolean("development")) { distribution = DistributionEnum.DEVELOPMENT; } else { distribution = DiscordUtil.isMainBot() ? DistributionEnum.MAIN : DistributionEnum.MUSIC; } accountToken = credsjson.getJSONObject("token").getString(distribution.getId()); log.info("|||||||/||||||" + accountToken); log.info("Determined distribution: " + distribution); //Initialise event listeners listenerBot = new EventListenerBoat(scopes & 0x110, distribution == DistributionEnum.DEVELOPMENT ? BotConstants.DEFAULT_BOT_PREFIX_BETA : BotConstants.DEFAULT_BOT_PREFIX); listenerSelf = new EventListenerSelf(scopes & 0x001, distribution == DistributionEnum.DEVELOPMENT ? BotConstants.DEFAULT_SELF_PREFIX_BETA : BotConstants.DEFAULT_SELF_PREFIX); /* Init JDA */ if ((scopes & 0x110) != 0) { initBotShards(); } if ((scopes & 0x001) != 0) { fbClient = new FredBoatClient(); } try { API.start(); } catch (Exception e) { log.info("Failed to ignite Spark, FredBoat API unavailable", e); } //Initialise JCA String cbUser = credsjson.optString("cbUser"); String cbKey = credsjson.optString("cbKey"); if(cbUser != null && cbKey != null && !cbUser.equals("") && !cbKey.equals("")) { log.info("Starting CleverBot"); jca = new JCABuilder().setKey(cbKey).setUser(cbUser).buildBlocking(); } else { log.warn("Credentials not found for cleverbot authentication. Skipping..."); } if (distribution == DistributionEnum.MAIN && carbonKey != null) { CarbonitexAgent carbonitexAgent = new CarbonitexAgent(carbonKey); carbonitexAgent.setDaemon(true); carbonitexAgent.start(); } } private static void initBotShards() { if(distribution == DistributionEnum.DEVELOPMENT) { log.info("Development distribution; forcing 2 shards"); numShards = 2; } else { try { numShards = DiscordUtil.getRecommendedShardCount(accountToken); } catch (UnirestException e) { throw new RuntimeException("Unable to get recommended shard count!", e); } log.info("Discord recommends " + numShards + " shard(s)"); } for(int i = 0; i < numShards; i++){ shards.add(i, new FredBoatBot(i)); try { Thread.sleep(SHARD_CREATION_SLEEP_INTERVAL); } catch (InterruptedException e) { throw new RuntimeException("Got interrupted while setting up bot shards!", e); } } log.info(numShards + " shards have been constructed"); } public static void onInit(ReadyEvent readyEvent) { int ready = numShardsReady.incrementAndGet(); log.info("Received ready event for " + FredBoat.getInstance(readyEvent.getJDA()).getShardInfo().getShardString()); //Commands CommandInitializer.initCommands(); if(ready == numShards) { log.info("All " + ready + " shards are ready."); MusicPersistenceHandler.reloadPlaylists(); } } //Shutdown hook private static final Runnable ON_SHUTDOWN = () -> { int code = shutdownCode != UNKNOWN_SHUTDOWN_CODE ? shutdownCode : -1; try { MusicPersistenceHandler.handlePreShutdown(code); } catch (Exception e) { log.error("Critical error while handling music persistence.", e); } for(FredBoat fb : shards) { fb.getJda().shutdown(false); } try { Unirest.shutdown(); } catch (IOException ignored) {} }; public static void shutdown(int code) { log.info("Shutting down with exit code " + code); shutdownCode = code; System.exit(code); } public static int getScopes() { return scopes; } public static List<String> getGoogleKeys() { return GOOGLE_KEYS; } public static String getRandomGoogleKey() { return GOOGLE_KEYS.get((int) Math.floor(Math.random() * GOOGLE_KEYS.size())); } public static EventListenerBoat getListenerBot() { return listenerBot; } public static EventListenerSelf getListenerSelf() { return listenerSelf; } public static String[] getLavaplayerNodes() { return lavaplayerNodes; } public static boolean isLavaplayerNodesEnabled() { return lavaplayerNodesEnabled; } /* Sharding */ public JDA getJda() { return jda; } public static List<FredBoat> getShards() { return shards; } public static List<Guild> getAllGuilds() { ArrayList<Guild> list = new ArrayList<>(); for (FredBoat fb : shards) { list.addAll(fb.getJda().getGuilds()); } return list; } public static Map<String, User> getAllUsersAsMap() { HashMap<String, User> map = new HashMap<>(); for (FredBoat fb : shards) { for (User usr : fb.getJda().getUsers()) { map.put(usr.getId(), usr); } } return map; } public static TextChannel getTextChannelById(String id) { for (FredBoat fb : shards) { for (TextChannel channel : fb.getJda().getTextChannels()) { if(channel.getId().equals(id)) return channel; } } return null; } public static VoiceChannel getVoiceChannelById(String id) { for (FredBoat fb : shards) { for (VoiceChannel channel : fb.getJda().getVoiceChannels()) { if(channel.getId().equals(id)) return channel; } } return null; } public static FredBoatClient getClient() { return fbClient; } public static FredBoat getInstance(JDA jda) { if(jda.getAccountType() == AccountType.CLIENT) { return fbClient; } else { int sId = jda.getShardInfo() == null ? 0 : jda.getShardInfo().getShardId(); for(FredBoat fb : shards) { if(((FredBoatBot) fb).getShardId() == sId) { return fb; } } } throw new IllegalStateException("Attempted to get instance for JDA shard that is not indexed"); } public ShardInfo getShardInfo() { int sId = jda.getShardInfo() == null ? 0 : jda.getShardInfo().getShardId(); if(jda.getAccountType() == AccountType.CLIENT) { return new ShardInfo(0, 1); } else { return new ShardInfo(sId, numShards); } } public class ShardInfo { int shardId; int shardTotal; ShardInfo(int shardId, int shardTotal) { this.shardId = shardId; this.shardTotal = shardTotal; } public int getShardId() { return this.shardId; } public int getShardTotal() { return this.shardTotal; } public String getShardString() { return "[" + this.shardId + " / " + this.shardTotal + "]"; } } }
package fredboat; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import fredboat.agent.CarbonitexAgent; import fredboat.api.API; import fredboat.audio.MusicPersistenceHandler; import fredboat.commandmeta.CommandInitializer; import fredboat.event.EventListenerBoat; import fredboat.event.EventListenerSelf; import fredboat.util.BotConstants; import fredboat.util.DiscordUtil; import fredboat.util.DistributionEnum; import fredboat.util.log.SimpleLogToSLF4JAdapter; import frederikam.jca.JCA; import frederikam.jca.JCABuilder; import net.dv8tion.jda.core.AccountType; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.JDAInfo; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.VoiceChannel; import net.dv8tion.jda.core.events.ReadyEvent; import net.dv8tion.jda.core.utils.SimpleLog; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.security.auth.login.LoginException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; public abstract class FredBoat { private static final Logger log = LoggerFactory.getLogger(FredBoat.class); static final int SHARD_CREATION_SLEEP_INTERVAL = 5100; private static final ArrayList<FredBoat> shards = new ArrayList<>(); public static JCA jca; public static final long START_TIME = System.currentTimeMillis(); public static DistributionEnum distribution = DistributionEnum.DEVELOPMENT; public static final int UNKNOWN_SHUTDOWN_CODE = -991023; public static int shutdownCode = UNKNOWN_SHUTDOWN_CODE;//Used when specifying the intended code for shutdown hooks static EventListenerBoat listenerBot; static EventListenerSelf listenerSelf; /* Config */ private static JSONObject config = null; private static int scopes = 0; public static int numShards = 4; private static AtomicInteger numShardsReady = new AtomicInteger(0); /* Credentials */ private static JSONObject credsjson; static String accountToken; static String clientToken; public static String mashapeKey; public static String MALPassword; private final static List<String> GOOGLE_KEYS = new ArrayList<>(); private static String[] lavaplayerNodes = new String[64]; private static boolean lavaplayerNodesEnabled = false; private static String carbonKey; JDA jda; private static FredBoatClient fbClient; public static void main(String[] args) throws LoginException, IllegalArgumentException, InterruptedException, IOException { Runtime.getRuntime().addShutdownHook(new Thread(ON_SHUTDOWN)); //Attach log adapter SimpleLog.addListener(new SimpleLogToSLF4JAdapter()); //Make JDA not print to console, we have Logback for that SimpleLog.LEVEL = SimpleLog.Level.OFF; try { scopes = Integer.parseInt(args[0]); } catch (NumberFormatException | ArrayIndexOutOfBoundsException ignored) { log.info("Invalid scope, defaulting to scopes 0x111"); scopes = 0x111; } log.info("Starting with scopes:" + "\n\tMain: " + ((scopes & 0x100) == 0x100) + "\n\tMusic: " + ((scopes & 0x010) == 0x010) + "\n\tSelf: " + ((scopes & 0x001) == 0x001)); log.info("JDA version:\t" + JDAInfo.VERSION); //Load credentials and config files InputStream is = new FileInputStream(new File("./credentials.json")); Scanner scanner = new Scanner(is); credsjson = new JSONObject(scanner.useDelimiter("\\A").next()); scanner.close(); is = new FileInputStream(new File("./config.json")); scanner = new Scanner(is); config = new JSONObject(scanner.useDelimiter("\\A").next()); scanner.close(); mashapeKey = credsjson.optString("mashapeKey"); clientToken = credsjson.optString("clientToken"); MALPassword = credsjson.optString("malPassword"); carbonKey = credsjson.optString("carbonKey"); JSONArray nodesArray = credsjson.optJSONArray("lavaplayerNodes"); if(nodesArray != null) { lavaplayerNodesEnabled = true; Iterator<Object> itr = nodesArray.iterator(); int i = 0; while(itr.hasNext()) { lavaplayerNodes[i] = (String) itr.next(); i++; } } JSONArray gkeys = credsjson.optJSONArray("googleServerKeys"); if (gkeys != null) { log.info("Using lavaplayer nodes"); gkeys.forEach((Object str) -> GOOGLE_KEYS.add((String) str)); } if (config.optBoolean("patron")) { distribution = DistributionEnum.PATRON; } else //Determine distribution if (config.optBoolean("development")) { distribution = DistributionEnum.DEVELOPMENT; } else { distribution = DiscordUtil.isMainBot() ? DistributionEnum.MAIN : DistributionEnum.MUSIC; } accountToken = System.getenv("serverToken"); log.info("Determined distribution: " + distribution); //Initialise event listeners listenerBot = new EventListenerBoat(scopes & 0x110, distribution == DistributionEnum.DEVELOPMENT ? BotConstants.DEFAULT_BOT_PREFIX_BETA : BotConstants.DEFAULT_BOT_PREFIX); listenerSelf = new EventListenerSelf(scopes & 0x001, distribution == DistributionEnum.DEVELOPMENT ? BotConstants.DEFAULT_SELF_PREFIX_BETA : BotConstants.DEFAULT_SELF_PREFIX); /* Init JDA */ if ((scopes & 0x110) != 0) { initBotShards(); } if ((scopes & 0x001) != 0) { fbClient = new FredBoatClient(); } try { API.start(); } catch (Exception e) { log.info("Failed to ignite Spark, FredBoat API unavailable", e); } //Initialise JCA String cbUser = credsjson.optString("cbUser"); String cbKey = credsjson.optString("cbKey"); if(cbUser != null && cbKey != null && !cbUser.equals("") && !cbKey.equals("")) { log.info("Starting CleverBot"); jca = new JCABuilder().setKey(cbKey).setUser(cbUser).buildBlocking(); } else { log.warn("Credentials not found for cleverbot authentication. Skipping..."); } if (distribution == DistributionEnum.MAIN && carbonKey != null) { CarbonitexAgent carbonitexAgent = new CarbonitexAgent(carbonKey); carbonitexAgent.setDaemon(true); carbonitexAgent.start(); } } private static void initBotShards() { if(distribution == DistributionEnum.DEVELOPMENT) { log.info("Development distribution; forcing 2 shards"); numShards = 2; } else { try { numShards = DiscordUtil.getRecommendedShardCount(accountToken); } catch (UnirestException e) { throw new RuntimeException("Unable to get recommended shard count!", e); } log.info("Discord recommends " + numShards + " shard(s)"); } for(int i = 0; i < numShards; i++){ shards.add(i, new FredBoatBot(i)); try { Thread.sleep(SHARD_CREATION_SLEEP_INTERVAL); } catch (InterruptedException e) { throw new RuntimeException("Got interrupted while setting up bot shards!", e); } } log.info(numShards + " shards have been constructed"); } public static void onInit(ReadyEvent readyEvent) { int ready = numShardsReady.incrementAndGet(); log.info("Received ready event for " + FredBoat.getInstance(readyEvent.getJDA()).getShardInfo().getShardString()); //Commands CommandInitializer.initCommands(); if(ready == numShards) { log.info("All " + ready + " shards are ready."); MusicPersistenceHandler.reloadPlaylists(); } } //Shutdown hook private static final Runnable ON_SHUTDOWN = () -> { int code = shutdownCode != UNKNOWN_SHUTDOWN_CODE ? shutdownCode : -1; try { MusicPersistenceHandler.handlePreShutdown(code); } catch (Exception e) { log.error("Critical error while handling music persistence.", e); } for(FredBoat fb : shards) { fb.getJda().shutdown(false); } try { Unirest.shutdown(); } catch (IOException ignored) {} }; public static void shutdown(int code) { log.info("Shutting down with exit code " + code); shutdownCode = code; System.exit(code); } public static int getScopes() { return scopes; } public static List<String> getGoogleKeys() { return GOOGLE_KEYS; } public static String getRandomGoogleKey() { return GOOGLE_KEYS.get((int) Math.floor(Math.random() * GOOGLE_KEYS.size())); } public static EventListenerBoat getListenerBot() { return listenerBot; } public static EventListenerSelf getListenerSelf() { return listenerSelf; } public static String[] getLavaplayerNodes() { return lavaplayerNodes; } public static boolean isLavaplayerNodesEnabled() { return lavaplayerNodesEnabled; } /* Sharding */ public JDA getJda() { return jda; } public static List<FredBoat> getShards() { return shards; } public static List<Guild> getAllGuilds() { ArrayList<Guild> list = new ArrayList<>(); for (FredBoat fb : shards) { list.addAll(fb.getJda().getGuilds()); } return list; } public static Map<String, User> getAllUsersAsMap() { HashMap<String, User> map = new HashMap<>(); for (FredBoat fb : shards) { for (User usr : fb.getJda().getUsers()) { map.put(usr.getId(), usr); } } return map; } public static TextChannel getTextChannelById(String id) { for (FredBoat fb : shards) { for (TextChannel channel : fb.getJda().getTextChannels()) { if(channel.getId().equals(id)) return channel; } } return null; } public static VoiceChannel getVoiceChannelById(String id) { for (FredBoat fb : shards) { for (VoiceChannel channel : fb.getJda().getVoiceChannels()) { if(channel.getId().equals(id)) return channel; } } return null; } public static FredBoatClient getClient() { return fbClient; } public static FredBoat getInstance(JDA jda) { if(jda.getAccountType() == AccountType.CLIENT) { return fbClient; } else { int sId = jda.getShardInfo() == null ? 0 : jda.getShardInfo().getShardId(); for(FredBoat fb : shards) { if(((FredBoatBot) fb).getShardId() == sId) { return fb; } } } throw new IllegalStateException("Attempted to get instance for JDA shard that is not indexed"); } public ShardInfo getShardInfo() { int sId = jda.getShardInfo() == null ? 0 : jda.getShardInfo().getShardId(); if(jda.getAccountType() == AccountType.CLIENT) { return new ShardInfo(0, 1); } else { return new ShardInfo(sId, numShards); } } public class ShardInfo { int shardId; int shardTotal; ShardInfo(int shardId, int shardTotal) { this.shardId = shardId; this.shardTotal = shardTotal; } public int getShardId() { return this.shardId; } public int getShardTotal() { return this.shardTotal; } public String getShardString() { return "[" + this.shardId + " / " + this.shardTotal + "]"; } } }
package com.parc.ccn.library; import java.io.IOException; import java.security.InvalidParameterException; import java.security.Security; import java.util.ArrayList; import org.bouncycastle.jce.provider.BouncyCastleProvider; import com.parc.ccn.CCNBase; import com.parc.ccn.Library; import com.parc.ccn.config.ConfigurationException; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.ContentObject; import com.parc.ccn.data.MalformedContentNameStringException; import com.parc.ccn.data.ContentObject.SimpleVerifier; import com.parc.ccn.data.query.ExcludeFilter; import com.parc.ccn.data.query.Interest; import com.parc.ccn.data.security.ContentVerifier; import com.parc.ccn.data.security.PublisherPublicKeyDigest; import com.parc.ccn.network.CCNNetworkManager; import com.parc.ccn.security.keys.KeyManager; /** * An implementation of the basic CCN library. * rides on top of the CCNBase low-level interface. It uses * CCNNetworkManager to interface with a "real" virtual CCN, * and KeyManager to interface with the user's collection of * signing and verification keys. * * Need to expand get-side interface to allow querier better * access to signing information and trust path building. * * @author smetters,rasmussen * * * <META> tag under which to store metadata (either on name or on version) * <V> tag under which to put versions * n/<V>/<number> -> points to header * <B> tag under which to put actual fragments * n/<V>/<number>/<B>/<number> -> fragments * n/<latest>/1/2/... has pointer to latest version * -- use latest to get header of latest version, otherwise get via <v>/<n> * configuration parameters: * blocksize -- size of chunks to fragment into * * get always reconstructs fragments and traverses links * can getLink to get link info * */ public class CCNLibrary extends CCNBase { static { Security.addProvider(new BouncyCastleProvider()); } protected static CCNLibrary _library = null; /** * Do we want to do this this way, or everything static? */ protected KeyManager _userKeyManager = null; public static CCNLibrary open() throws ConfigurationException, IOException { synchronized (CCNLibrary.class) { try { return new CCNLibrary(); } catch (ConfigurationException e) { Library.logger().severe("Configuration exception initializing CCN library: " + e.getMessage()); throw e; } catch (IOException e) { Library.logger().severe("IO exception initializing CCN library: " + e.getMessage()); throw e; } } } public static CCNLibrary open(KeyManager keyManager) { synchronized (CCNLibrary.class) { return new CCNLibrary(keyManager); } } public static CCNLibrary getLibrary() { if (null != _library) return _library; try { return createCCNLibrary(); } catch (ConfigurationException e) { Library.logger().warning("Configuration exception attempting to create library: " + e.getMessage()); Library.warningStackTrace(e); throw new RuntimeException("Error in system configuration. Cannot create library.",e); } catch (IOException e) { Library.logger().warning("IO exception attempting to create library: " + e.getMessage()); Library.warningStackTrace(e); throw new RuntimeException("Error in system IO. Cannot create library.",e); } } protected static synchronized CCNLibrary createCCNLibrary() throws ConfigurationException, IOException { if (null == _library) { _library = new CCNLibrary(); } return _library; } protected CCNLibrary(KeyManager keyManager) { _userKeyManager = keyManager; // force initialization of network manager try { _networkManager = new CCNNetworkManager(); } catch (IOException ex){ Library.logger().warning("IOException instantiating network manager: " + ex.getMessage()); ex.printStackTrace(); _networkManager = null; } } protected CCNLibrary() throws ConfigurationException, IOException { this(KeyManager.getDefaultKeyManager()); } /* * For testing only */ protected CCNLibrary(boolean useNetwork) {} public void setKeyManager(KeyManager keyManager) { if (null == keyManager) { Library.logger().warning("StandardCCNLibrary::setKeyManager: Key manager cannot be null!"); throw new IllegalArgumentException("Key manager cannot be null!"); } _userKeyManager = keyManager; } public KeyManager keyManager() { return _userKeyManager; } public PublisherPublicKeyDigest getDefaultPublisher() { return keyManager().getDefaultKeyID(); } public ContentObject get(ContentName name, long timeout) throws IOException { Interest interest = new Interest(name); return get(interest, timeout); } /** * TODO -- ignores publisher. * @param name * @param publisher * @param timeout * @return * @throws IOException */ public ContentObject get(ContentName name, PublisherPublicKeyDigest publisher, long timeout) throws IOException { Interest interest = new Interest(name); return get(interest, timeout); } /** * Return data the specified number of levels below us in the * hierarchy, with order preference of leftmost. * * @param name * @param level * @param timeout * @return * @throws IOException */ public ContentObject getLower(ContentName name, int level, long timeout) throws IOException { Interest interest = new Interest(name); interest.maxSuffixComponents(level); interest.minSuffixComponents(level); return get(interest, timeout); } /** * Enumerate matches below query name in the hierarchy * TODO: maybe filter out fragments, possibly other metadata. * TODO: add in communication layer to talk just to * local repositories for v 2.0 protocol. * @param query * @param timeout - microseconds * @return * @throws IOException */ public ArrayList<ContentObject> enumerate(Interest query, long timeout) throws IOException { ArrayList<ContentObject> result = new ArrayList<ContentObject>(); // This won't work without a correct order preference int count = query.name().count(); while (true) { ContentObject co = null; co = get(query, timeout == NO_TIMEOUT ? 5000 : timeout); if (co == null) break; Library.logger().info("enumerate: retrieved " + co.name() + " digest: " + ContentName.componentPrintURI(co.contentDigest()) + " on query: " + query.name()); result.add(co); for (int i = co.name().count() - 1; i > count; i result.addAll(enumerate(new Interest(new ContentName(i, co.name().components())), timeout)); } query = Interest.next(co, count); } Library.logger().info("enumerate: retrieved " + result.size() + " objects."); return result; } /** * Medium level interface for retrieving pieces of a file * * getNext - get next content after specified content * * @param name - ContentName for base of get * @param prefixCount - next follows components of the name * through this count. * @param omissions - ExcludeFilter * @param timeout - milliseconds * @return * @throws MalformedContentNameStringException * @throws IOException * @throws InvalidParameterException */ public ContentObject getNext(ContentName name, byte[][] omissions, long timeout) throws IOException { return get(Interest.next(name, omissions, null), timeout); } public ContentObject getNext(ContentName name, long timeout) throws IOException, InvalidParameterException { return getNext(name, null, timeout); } public ContentObject getNext(ContentName name, int prefixCount, long timeout) throws IOException, InvalidParameterException { return get(Interest.next(name, prefixCount), timeout); } public ContentObject getNext(ContentObject content, int prefixCount, byte[][] omissions, long timeout) throws IOException { return getNext(contentObjectToContentName(content, prefixCount), omissions, timeout); } /** * Get last content that follows name in similar manner to * getNext * * @param name * @param omissions * @param timeout * @return * @throws MalformedContentNameStringException * @throws IOException * @throws InvalidParameterException */ public ContentObject getLatest(ContentName name, ExcludeFilter exclude, long timeout) throws IOException, InvalidParameterException { return get(Interest.last(name, exclude, name.count() - 1), timeout); } public ContentObject getLatest(ContentName name, long timeout) throws InvalidParameterException, IOException { return getLatest(name, null, timeout); } public ContentObject getLatest(ContentName name, int prefixCount, long timeout) throws InvalidParameterException, IOException { return get(Interest.last(name, prefixCount), timeout); } public ContentObject getLatest(ContentObject content, int prefixCount, long timeout) throws InvalidParameterException, IOException { return getLatest(contentObjectToContentName(content, prefixCount), null, timeout); } /** * * @param name * @param omissions * @param timeout * @return * @throws InvalidParameterException * @throws MalformedContentNameStringException * @throws IOException */ public ContentObject getExcept(ContentName name, byte[][] omissions, long timeout) throws InvalidParameterException, MalformedContentNameStringException, IOException { return get(Interest.exclude(name, omissions), timeout); } private ContentName contentObjectToContentName(ContentObject content, int prefixCount) { ContentName cocn = content.name().clone(); cocn.components().add(content.contentDigest()); return new ContentName(prefixCount, cocn.components()); } /** * Shutdown the library and it's associated resources */ public void close() { if (null != _networkManager) _networkManager.shutdown(); _networkManager = null; } /** * Allow default verification behavior to be replaced. * @return */ public ContentVerifier defaultVerifier() { return SimpleVerifier.getDefaultVerifier(); } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragSource; import java.awt.dnd.DragSourceDragEvent; import java.awt.dnd.DragSourceDropEvent; import java.awt.dnd.DragSourceEvent; import java.awt.dnd.DragSourceListener; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetContext; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.dnd.InvalidDnDOperationException; import java.io.IOException; import javax.swing.*; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); JTabbedPane tabs = new JTabbedPane(); tabs.addTab("00000000", new JScrollPane(makeList(0))); tabs.addTab("11111111", new JScrollPane(makeList(1))); tabs.addTab("22222222", new JScrollPane(makeList(2))); add(tabs); new DropTarget(tabs, DnDConstants.ACTION_MOVE, new TabTitleDropTargetListener(), true); setPreferredSize(new Dimension(320, 240)); } private static JList<String> makeList(int index) { DefaultListModel<String> model = new DefaultListModel<>(); model.addElement(index + " - 1111"); model.addElement(index + " - 22222222"); model.addElement(index + " - 333333333333"); model.addElement(index + " - asdfasdfasdfasdfasd"); model.addElement(index + " - AAAAAAAAAAAAAA"); model.addElement(index + " - ****"); return new DnDList<>(model); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class DnDList<E> extends JList<E> implements DragGestureListener, DragSourceListener, Transferable { private static final String NAME = "test"; protected DnDList() { this(null); } protected DnDList(ListModel<E> model) { super(model); DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer( (Component) this, DnDConstants.ACTION_MOVE, (DragGestureListener) this); } // Interface: DragGestureListener @Override public void dragGestureRecognized(DragGestureEvent e) { try { e.startDrag(DragSource.DefaultMoveDrop, (Transferable) this, (DragSourceListener) this); } catch (InvalidDnDOperationException ex) { throw new IllegalStateException(ex); } } // Interface: DragSourceListener @Override public void dragEnter(DragSourceDragEvent e) { e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop); } @Override public void dragExit(DragSourceEvent e) { e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop); } @Override public void dragOver(DragSourceDragEvent e) { /* not needed */ } @Override public void dragDropEnd(DragSourceDropEvent e) { /* not needed */ } @Override public void dropActionChanged(DragSourceDragEvent e) { /* not needed */ } // Interface: Transferable // private final DataFlavor FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, NAME); // private final DataFlavor FLAVOR = new DataFlavor(Object.class, DataFlavor.javaJVMLocalObjectMimeType); @Override public Object getTransferData(DataFlavor flavor) { return this; } @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] {new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, NAME)}; } @Override public boolean isDataFlavorSupported(DataFlavor flavor) { return flavor.getHumanPresentableName().equals(NAME); // return flavor.getRepresentationClass().equals(Object.class); } } class TabTitleDropTargetListener implements DropTargetListener { private int targetTabIndex = -1; @Override public void dropActionChanged(DropTargetDragEvent e) { // repaint(); } @Override public void dragExit(DropTargetEvent e) { // repaint(); } @Override public void dragEnter(DropTargetDragEvent e) { // repaint(); } @Override public void dragOver(DropTargetDragEvent e) { if (isDropAcceptable(e)) { e.acceptDrag(e.getDropAction()); } else { e.rejectDrag(); } e.getDropTargetContext().getComponent().repaint(); } @SuppressWarnings("unchecked") @Override public void drop(DropTargetDropEvent e) { try { DropTargetContext c = e.getDropTargetContext(); Component o = c.getComponent(); Transferable t = e.getTransferable(); DataFlavor[] f = t.getTransferDataFlavors(); if (o instanceof JTabbedPane) { JTabbedPane jtp = (JTabbedPane) o; JScrollPane sp = (JScrollPane) jtp.getComponentAt(targetTabIndex); JViewport vp = sp.getViewport(); JList<String> targetList = (JList<String>) SwingUtilities.getUnwrappedView(vp); JList<String> sourceList = (JList<String>) t.getTransferData(f[0]); DefaultListModel<String> tm = (DefaultListModel<String>) targetList.getModel(); DefaultListModel<String> sm = (DefaultListModel<String>) sourceList.getModel(); int[] indices = sourceList.getSelectedIndices(); for (int j = indices.length - 1; j >= 0; j tm.addElement(sm.remove(indices[j])); } e.dropComplete(true); } else { e.dropComplete(false); } } catch (UnsupportedFlavorException | IOException ex) { e.dropComplete(false); } } private boolean isDropAcceptable(DropTargetDragEvent e) { DropTargetContext c = e.getDropTargetContext(); Transferable t = e.getTransferable(); DataFlavor[] f = t.getTransferDataFlavors(); Point pt = e.getLocation(); targetTabIndex = -1; Component o = c.getComponent(); if (o instanceof JTabbedPane) { JTabbedPane jtp = (JTabbedPane) o; for (int i = 0; i < jtp.getTabCount(); i++) { if (jtp.getBoundsAt(i).contains(pt)) { targetTabIndex = i; break; } } return targetTabIndex >= 0 && targetTabIndex != jtp.getSelectedIndex() && t.isDataFlavorSupported(f[0]); } return false; } }
package org.bdgp.MMSlide.DB; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; @DatabaseTable public class ROI { @DatabaseField(generatedId=true) private int id; @DatabaseField private double x1; @DatabaseField private double y1; @DatabaseField private double x2; @DatabaseField private double y2; public ROI() {} public ROI(int id, int imageId, double x1, double y1, double x2, double y2) { this.id = id; this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public int getId() {return this.id;} public double getX1() {return this.x1;} public double getY1() {return this.y1;} public double getX2() {return this.x2;} public double getY2() {return this.y2;} }
import datamodel.Request; import httpserver.RequestSenderWithMessage; import httpserver.WebServer; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; public class Controller { public TextField response; private WebServer ws = new WebServer(); public TextField command; @FXML public TextArea results; @FXML public void initialize(){ ws.setResults(results); } public void runCommand(ActionEvent actionEvent) { results.setText(""); response.setText(""); Thread th = new Thread() { @Override public void run() { String commandString = command.getText(); Request request = new Request(); request.setClientId("13"); request.setCommand(commandString); request.setResponseAddress("http://192.168.56.1:8008/jobFinished"); String[] tocCommandString = commandString.split("\\s+"); switch (tocCommandString[0]) { case "availability": request.setProcessors(new String[] {"availability.HttpStatusCodeFilter"}); break; case "security": switch (tocCommandString[1]) { case "tls": request.setProcessors(new String[] { "XmlToJsonConverter", "security.TlsCiphersuitesFilter"}); break; case "ecrypt2lvl": request.setProcessors(new String[] { "XmlToJsonConverter", "security.TlsCiphersuitesFilter", "security.TlsEcrypt2Level"}); break; case "open_ports": request.setProcessors(new String[]{"XmlToJsonConverter"}); break; } break; default: request.setProcessors(new String[]{}); } request.setAdapter("adapters.EventHubAdapter"); String requestResponse = RequestSenderWithMessage.sendRequest("http://192.168.56.107:8080/request", request); Platform.runLater(new Runnable() { public void run() { response.setText(requestResponse); } }); } }; th.start(); } }
package de.nenick.espressomacchiato.elements; import android.support.test.InstrumentationRegistry; import junit.framework.AssertionFailedError; import org.junit.Test; import de.nenick.espressomacchiato.test.views.LongListActivity; import de.nenick.espressomacchiato.testbase.EspressoTestCase; import static android.support.test.espresso.matcher.ViewMatchers.withId; public class EspViewListSupportedTest extends EspressoTestCase<LongListActivity> { private EspPage espPage = EspPage.byId(LongListActivity.rootLayout); private EspTextView firstItemTextView = EspTextView.byText("item: 0"); @Test public void testSwipe() { firstItemTextView.assertIsDisplayedOnScreen(); espPage.swipeUp(); firstItemTextView.assertNotExist(); espPage.swipeDown(); espPage.swipeDown(); firstItemTextView.assertIsDisplayedOnScreen(); } @Test public void testAssertIsHiddenFailureWhenOnlyPartialHidden() { scrollListPixelDistance(100); firstItemTextView.assertIsHidden(); scrollListPixelDistance(-62); firstItemTextView.assertIsPartiallyDisplayedOnly(); exception.expect(AssertionFailedError.class); firstItemTextView.assertIsHidden(); } @Test public void testAssertIsDisplayedOnScreenFailureWhenOnlyPartialHidden() { scrollListPixelDistance(100); exception.expect(AssertionFailedError.class); firstItemTextView.assertIsDisplayedOnScreen(); } private void scrollListPixelDistance(final int distance) { InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { getActivity().findViewById(LongListActivity.listViewId).scrollBy(0, distance); } }); } class MyEspListView extends EspListView { public MyEspListView(EspListView template) { super(template); } @Override public MyEspAdapterViewItem itemByVisibleIndex(int index) { return new MyEspAdapterViewItem(super.itemByVisibleIndex(index)); } } class MyEspAdapterViewItem extends EspAdapterViewItem { public MyEspAdapterViewItem(EspAdapterViewItem template) { super(template); } public EspTextView textView() { return new EspTextView(baseMatcherForItemChild(withId(LongListActivity.itemTextViewId))); } } }
package io.hops.hopsworks.api.featurestore.trainingdataset; import com.google.common.base.Strings; import io.hops.hopsworks.api.featurestore.FeaturestoreKeywordResource; import io.hops.hopsworks.api.featurestore.FsQueryBuilder; import io.hops.hopsworks.api.featurestore.activities.ActivityResource; import io.hops.hopsworks.api.featurestore.statistics.StatisticsResource; import io.hops.hopsworks.api.featurestore.tag.TagsBuilder; import io.hops.hopsworks.api.featurestore.tag.TagsDTO; import io.hops.hopsworks.api.featurestore.tag.TagsExpansionBeanParam; import io.hops.hopsworks.api.filter.AllowedProjectRoles; import io.hops.hopsworks.api.filter.Audience; import io.hops.hopsworks.api.filter.NoCacheResponse; import io.hops.hopsworks.api.filter.apiKey.ApiKeyRequired; import io.hops.hopsworks.api.jobs.JobDTO; import io.hops.hopsworks.api.jobs.JobsBuilder; import io.hops.hopsworks.api.jwt.JWTHelper; import io.hops.hopsworks.api.provenance.ProvArtifactResource; import io.hops.hopsworks.common.dataset.DatasetController; import io.hops.hopsworks.common.featurestore.OptionDTO; import io.hops.hopsworks.common.featurestore.app.FsJobManagerController; import io.hops.hopsworks.common.featurestore.query.FsQueryDTO; import io.hops.hopsworks.common.featurestore.tag.AttachTagResult; import io.hops.hopsworks.common.featurestore.query.ServingPreparedStatementDTO; import io.hops.hopsworks.common.featurestore.tag.FeatureStoreTagControllerIface; import io.hops.hopsworks.common.api.ResourceRequest; import io.hops.hopsworks.common.dao.user.activity.ActivityFacade; import io.hops.hopsworks.common.featurestore.FeaturestoreController; import io.hops.hopsworks.common.featurestore.FeaturestoreDTO; import io.hops.hopsworks.common.featurestore.trainingdatasets.TrainingDatasetController; import io.hops.hopsworks.common.featurestore.trainingdatasets.TrainingDatasetDTO; import io.hops.hopsworks.common.util.Settings; import io.hops.hopsworks.exceptions.DatasetException; import io.hops.hopsworks.exceptions.FeatureStoreTagException; import io.hops.hopsworks.exceptions.FeaturestoreException; import io.hops.hopsworks.exceptions.GenericException; import io.hops.hopsworks.exceptions.JobException; import io.hops.hopsworks.exceptions.MetadataException; import io.hops.hopsworks.exceptions.ProjectException; import io.hops.hopsworks.exceptions.ProvenanceException; import io.hops.hopsworks.exceptions.ServiceException; import io.hops.hopsworks.jwt.annotation.JWTRequired; import io.hops.hopsworks.persistence.entity.dataset.Dataset; import io.hops.hopsworks.persistence.entity.featurestore.Featurestore; import io.hops.hopsworks.persistence.entity.featurestore.trainingdataset.TrainingDataset; import io.hops.hopsworks.persistence.entity.jobs.description.Jobs; import io.hops.hopsworks.persistence.entity.project.Project; import io.hops.hopsworks.persistence.entity.user.Users; import io.hops.hopsworks.persistence.entity.user.activity.ActivityFlag; import io.hops.hopsworks.persistence.entity.user.security.apiKey.ApiScope; import io.hops.hopsworks.restutils.RESTCodes; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import javax.ejb.EJB; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.ws.rs.BeanParam; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.stream.Collectors; /** * A Stateless RESTful service for the training datasets in a featurestore on Hopsworks. * Base URL: project/projectId/featurestores/featurestoreId/trainingdatasets/ */ @RequestScoped @TransactionAttribute(TransactionAttributeType.NEVER) @Api(value = "TrainingDataset service", description = "A service that manages a feature store's training datasets") public class TrainingDatasetService { @EJB private NoCacheResponse noCacheResponse; @EJB private FeaturestoreController featurestoreController; @EJB private TrainingDatasetController trainingDatasetController; @EJB private ActivityFacade activityFacade; @EJB private JWTHelper jWTHelper; @EJB private TagsBuilder tagBuilder; @Inject private FeatureStoreTagControllerIface tagController; @Inject private StatisticsResource statisticsResource; @EJB private FsQueryBuilder fsQueryBuilder; @Inject private ProvArtifactResource provenanceResource; @EJB private DatasetController datasetController; @Inject private FeaturestoreKeywordResource featurestoreKeywordResource; @Inject private ActivityResource activityResource; @EJB private FsJobManagerController fsJobManagerController; @EJB private JobsBuilder jobsBuilder; @EJB private PreparedStatementBuilder preparedStatementBuilder; private Project project; private Featurestore featurestore; /** * Set the project of the featurestore (provided by parent resource) * * @param project the project where the featurestore resides */ public void setProject(Project project) { this.project = project; } /** * Sets the featurestore of the training datasets (provided by parent resource) * * @param featurestoreId id of the featurestore * @throws FeaturestoreException */ public void setFeaturestoreId(Integer featurestoreId) throws FeaturestoreException { //This call verifies that the project have access to the featurestoreId provided FeaturestoreDTO featurestoreDTO = featurestoreController.getFeaturestoreForProjectWithId(project, featurestoreId); this.featurestore = featurestoreController.getFeaturestoreWithId(featurestoreDTO.getFeaturestoreId()); } /** * Endpoint for getting a list of all training datasets in the feature store. * * @return a JSON representation of the training datasets in the features store */ @GET @Produces(MediaType.APPLICATION_JSON) @AllowedProjectRoles({AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST}) @JWTRequired(acceptedTokens = {Audience.API}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) @ApiKeyRequired( acceptedScopes = {ApiScope.FEATURESTORE}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) @ApiOperation(value = "Get the list of training datasets for a featurestore", response = TrainingDatasetDTO.class, responseContainer = "List") public Response getAll(@Context SecurityContext sc) throws ServiceException, FeaturestoreException { Users user = jWTHelper.getUserPrincipal(sc); List<TrainingDatasetDTO> trainingDatasetDTOs = trainingDatasetController.getTrainingDatasetsForFeaturestore(user, project, featurestore); GenericEntity<List<TrainingDatasetDTO>> trainingDatasetsGeneric = new GenericEntity<List<TrainingDatasetDTO>>(trainingDatasetDTOs) {}; return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(trainingDatasetsGeneric).build(); } /** * Endpoint for creating a new trainingDataset * * @param trainingDatasetDTO the JSON payload with the data of the new trainingDataset * @return JSON representation of the created trainingDataset */ @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @AllowedProjectRoles({AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST}) @JWTRequired(acceptedTokens = {Audience.API, Audience.JOB}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) @ApiKeyRequired( acceptedScopes = {ApiScope.FEATURESTORE}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) @ApiOperation(value = "Create training dataset for a featurestore", response = TrainingDatasetDTO.class) public Response create(@Context SecurityContext sc, TrainingDatasetDTO trainingDatasetDTO) throws FeaturestoreException, ProvenanceException, IOException, ServiceException { if(trainingDatasetDTO == null){ throw new IllegalArgumentException("Input JSON for creating a new Training Dataset cannot be null"); } Users user = jWTHelper.getUserPrincipal(sc); TrainingDatasetDTO createdTrainingDatasetDTO = trainingDatasetController.createTrainingDataset(user, project, featurestore, trainingDatasetDTO); activityFacade.persistActivity(ActivityFacade.CREATED_TRAINING_DATASET + createdTrainingDatasetDTO.getName(), project, user, ActivityFlag.SERVICE); GenericEntity<TrainingDatasetDTO> createdTrainingDatasetDTOGeneric = new GenericEntity<TrainingDatasetDTO>(createdTrainingDatasetDTO) {}; return noCacheResponse.getNoCacheResponseBuilder(Response.Status.CREATED).entity(createdTrainingDatasetDTOGeneric) .build(); } /** * Endpoint for getting a training dataset with a particular id * * @param trainingdatasetid id of the training dataset to get * @return return a JSON representation of the training dataset with the given id * @throws FeaturestoreException * * @deprecated : use getTrainingDatasetByName instead */ @Deprecated @GET @Path("/{trainingdatasetid: [0-9]+}") @Produces(MediaType.APPLICATION_JSON) @AllowedProjectRoles({AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST}) @JWTRequired(acceptedTokens = {Audience.API, Audience.JOB}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) @ApiKeyRequired( acceptedScopes = {ApiScope.FEATURESTORE}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) @ApiOperation(value = "Get a training datasets with a specific id from a featurestore", response = TrainingDatasetDTO.class) public Response getById(@ApiParam(value = "Id of the training dataset", required = true) @PathParam("trainingdatasetid") Integer trainingdatasetid, @Context SecurityContext sc) throws FeaturestoreException, ServiceException { verifyIdProvided(trainingdatasetid); Users user = jWTHelper.getUserPrincipal(sc); TrainingDatasetDTO trainingDatasetDTO = trainingDatasetController .getTrainingDatasetWithIdAndFeaturestore(user, project, featurestore, trainingdatasetid); GenericEntity<TrainingDatasetDTO> trainingDatasetGeneric = new GenericEntity<TrainingDatasetDTO>(trainingDatasetDTO) {}; return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(trainingDatasetGeneric).build(); } /** * Endpoint for getting a list of training dataset based on the name * * @param name name of the training dataset to get * @return return a JSON representation of the training dataset with the given id * @throws FeaturestoreException */ @GET @Path("/{name: [a-z0-9_]*(?=[a-z])[a-z0-9_]+}") @Produces(MediaType.APPLICATION_JSON) @AllowedProjectRoles({AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST}) @JWTRequired(acceptedTokens = {Audience.API, Audience.JOB}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) @ApiKeyRequired( acceptedScopes = {ApiScope.FEATURESTORE}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) @ApiOperation(value = "Get a list of training datasets with a specific name, filter by version", response = List.class) public Response getByName(@ApiParam(value = "Name of the training dataset", required = true) @PathParam("name") String name, @ApiParam(value = "Filter by a specific version") @QueryParam("version") Integer version, @Context SecurityContext sc) throws FeaturestoreException, ServiceException { verifyNameProvided(name); Users user = jWTHelper.getUserPrincipal(sc); List<TrainingDatasetDTO> trainingDatasetDTO; if (version == null) { trainingDatasetDTO = trainingDatasetController.getWithNameAndFeaturestore(user, project, featurestore, name); } else { trainingDatasetDTO = Arrays.asList(trainingDatasetController .getWithNameVersionAndFeaturestore(user, project, featurestore, name, version)); } GenericEntity<List<TrainingDatasetDTO>> trainingDatasetGeneric = new GenericEntity<List<TrainingDatasetDTO>>(trainingDatasetDTO) {}; return Response.ok().entity(trainingDatasetGeneric).build(); } /** * Endpoint for deleting a training dataset, this will delete both the metadata and the data storage * * @param trainingdatasetid the id of the trainingDataset * @return JSON representation of the deleted trainingDataset * @throws FeaturestoreException * @throws DatasetException * @throws ProjectException */ @DELETE @Path("/{trainingdatasetid: [0-9]+}") @Produces(MediaType.APPLICATION_JSON) @AllowedProjectRoles({AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST}) @JWTRequired(acceptedTokens = {Audience.API, Audience.JOB}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) @ApiKeyRequired( acceptedScopes = {ApiScope.FEATURESTORE}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) @ApiOperation(value = "Delete a training datasets with a specific id from a featurestore", response = TrainingDatasetDTO.class) public Response delete( @Context SecurityContext sc, @ApiParam(value = "Id of the training dataset", required = true) @PathParam("trainingdatasetid") Integer trainingdatasetid) throws FeaturestoreException { verifyIdProvided(trainingdatasetid); Users user = jWTHelper.getUserPrincipal(sc); String trainingDsName = trainingDatasetController.delete(user, project, featurestore, trainingdatasetid); activityFacade.persistActivity(ActivityFacade.DELETED_TRAINING_DATASET + trainingDsName, project, user, ActivityFlag.SERVICE); return Response.ok().build(); } /** * Endpoint for updating the metadata of a training dataset * * @param trainingdatasetid the id of the trainingDataset to update * @param trainingDatasetDTO the JSON payload with the new metadat * @return JSON representation of the updated trainingDataset * @throws FeaturestoreException * @throws DatasetException * @throws ProjectException */ @PUT @Path("/{trainingdatasetid: [0-9]+}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @AllowedProjectRoles({AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST}) @JWTRequired(acceptedTokens = {Audience.API, Audience.JOB}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) @ApiKeyRequired( acceptedScopes = {ApiScope.FEATURESTORE}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) @ApiOperation(value = "Update a training datasets with a specific id from a featurestore", response = TrainingDatasetDTO.class) public Response updateTrainingDataset(@Context SecurityContext sc, @ApiParam(value = "Id of the training dataset", required = true) @PathParam("trainingdatasetid") Integer trainingdatasetid, @ApiParam(value = "updateMetadata", example = "true") @QueryParam("updateMetadata") @DefaultValue("false") Boolean updateMetadata, @ApiParam(value = "updateStatsConfig", example = "true") @QueryParam("updateStatsConfig") @DefaultValue("false") Boolean updateStatsConfig, TrainingDatasetDTO trainingDatasetDTO) throws FeaturestoreException, ServiceException { if(trainingDatasetDTO == null){ throw new IllegalArgumentException("Input JSON for updating a Training Dataset cannot be null"); } verifyIdProvided(trainingdatasetid); trainingDatasetDTO.setId(trainingdatasetid); Users user = jWTHelper.getUserPrincipal(sc); TrainingDatasetDTO oldTrainingDatasetDTO = trainingDatasetController .getTrainingDatasetWithIdAndFeaturestore(user, project, featurestore, trainingdatasetid); if(updateMetadata){ oldTrainingDatasetDTO = trainingDatasetController.updateTrainingDatasetMetadata(user, project, featurestore, trainingDatasetDTO); activityFacade.persistActivity(ActivityFacade.EDITED_TRAINING_DATASET + trainingDatasetDTO.getName(), project, user, ActivityFlag.SERVICE); } if (updateStatsConfig) { oldTrainingDatasetDTO = trainingDatasetController.updateTrainingDatasetStatsConfig(user, project, featurestore, trainingDatasetDTO); } GenericEntity<TrainingDatasetDTO> trainingDatasetDTOGenericEntity = new GenericEntity<TrainingDatasetDTO>(oldTrainingDatasetDTO) {}; return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(trainingDatasetDTOGenericEntity) .build(); } @ApiOperation( value = "Create or update tags(bulk) for a training dataset", response = TagsDTO.class) @PUT @Path("/{trainingdatasetId}/tags/{name}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @AllowedProjectRoles({AllowedProjectRoles.DATA_SCIENTIST, AllowedProjectRoles.DATA_OWNER}) @JWTRequired(acceptedTokens={Audience.API, Audience.JOB}, allowedUserRoles={"HOPS_ADMIN", "HOPS_USER"}) @ApiKeyRequired( acceptedScopes = {ApiScope.FEATURESTORE}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) public Response putTag(@Context SecurityContext sc, @Context UriInfo uriInfo, @ApiParam(value = "Id of the training dataset", required = true) @PathParam("trainingdatasetId") Integer trainingdatasetId, @ApiParam(value = "Name of the tag", required = true) @PathParam("name") String name, @ApiParam(value = "Value to set for the tag") String value) throws MetadataException, FeaturestoreException, FeatureStoreTagException { verifyIdProvided(trainingdatasetId); Users user = jWTHelper.getUserPrincipal(sc); TrainingDataset trainingDataset = trainingDatasetController.getTrainingDatasetById(featurestore, trainingdatasetId); AttachTagResult result = tagController.upsert(project, user, featurestore, trainingDataset, name, value); ResourceRequest resourceRequest = new ResourceRequest(ResourceRequest.Name.TAGS); TagsDTO dto = tagBuilder.build(uriInfo, resourceRequest, project, featurestore.getId(), ResourceRequest.Name.TRAININGDATASETS.name(), trainingdatasetId, result.getItems()); UriBuilder builder = uriInfo.getAbsolutePathBuilder(); if(result.isCreated()) { return Response.created(builder.build()).entity(dto).build(); } else { return Response.ok(builder.build()).entity(dto).build(); } } @ApiOperation( value = "Create or update tags(bulk) for a training dataset", response = TagsDTO.class) @PUT @Path("/{trainingDatasetId}/tags") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @AllowedProjectRoles({AllowedProjectRoles.DATA_SCIENTIST, AllowedProjectRoles.DATA_OWNER}) @JWTRequired(acceptedTokens={Audience.API, Audience.JOB}, allowedUserRoles={"HOPS_ADMIN", "HOPS_USER"}) @ApiKeyRequired( acceptedScopes = {ApiScope.FEATURESTORE}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) public Response bulkPutTags(@Context SecurityContext sc, @Context UriInfo uriInfo, @ApiParam(value = "Id of the training dataset", required = true) @PathParam("trainingDatasetId") Integer trainingDatasetId, TagsDTO tags) throws MetadataException, FeaturestoreException, FeatureStoreTagException { verifyIdProvided(trainingDatasetId); Users user = jWTHelper.getUserPrincipal(sc); TrainingDataset trainingDataset = trainingDatasetController.getTrainingDatasetById(featurestore, trainingDatasetId); AttachTagResult result; if(tags.getItems().size() == 0) { result = tagController.upsert(project, user, featurestore, trainingDataset, tags.getName(), tags.getValue()); } else { Map<String, String> newTags = new HashMap<>(); for(TagsDTO tag : tags.getItems()) { newTags.put(tag.getName(), tag.getValue()); } result = tagController.upsert(project, user, featurestore, trainingDataset, newTags); } ResourceRequest resourceRequest = new ResourceRequest(ResourceRequest.Name.TAGS); TagsDTO dto = tagBuilder.build(uriInfo, resourceRequest, project, featurestore.getId(), ResourceRequest.Name.TRAININGDATASETS.name(), trainingDatasetId, result.getItems()); UriBuilder builder = uriInfo.getAbsolutePathBuilder(); if(result.isCreated()) { return Response.created(builder.build()).entity(dto).build(); } else { return Response.ok(builder.build()).entity(dto).build(); } } @ApiOperation( value = "Get all tags attached to a training dataset", response = TagsDTO.class) @GET @Path("/{trainingDatasetId}/tags") @Produces(MediaType.APPLICATION_JSON) @AllowedProjectRoles({AllowedProjectRoles.DATA_SCIENTIST, AllowedProjectRoles.DATA_OWNER}) @JWTRequired(acceptedTokens={Audience.API, Audience.JOB}, allowedUserRoles={"HOPS_ADMIN", "HOPS_USER"}) @ApiKeyRequired( acceptedScopes = {ApiScope.FEATURESTORE}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) public Response getTags(@Context SecurityContext sc, @Context UriInfo uriInfo, @ApiParam(value = "Id of the training dataset", required = true) @PathParam("trainingDatasetId") Integer trainingDatasetId, @BeanParam TagsExpansionBeanParam tagsExpansionBeanParam) throws DatasetException, MetadataException, FeaturestoreException, FeatureStoreTagException { verifyIdProvided(trainingDatasetId); Users user = jWTHelper.getUserPrincipal(sc); TrainingDataset trainingDataset = trainingDatasetController.getTrainingDatasetById(featurestore, trainingDatasetId); Map<String, String> result = tagController.getAll(project, user, featurestore, trainingDataset); ResourceRequest resourceRequest = new ResourceRequest(ResourceRequest.Name.TAGS); resourceRequest.setExpansions(tagsExpansionBeanParam.getResources()); TagsDTO dto = tagBuilder.build(uriInfo, resourceRequest, project, featurestore.getId(), ResourceRequest.Name.TRAININGDATASETS.name(), trainingDatasetId, result); return Response.status(Response.Status.OK).entity(dto).build(); } @ApiOperation( value = "Get tag attached to a training dataset", response = TagsDTO.class) @GET @Path("/{trainingDatasetId}/tags/{name}") @Produces(MediaType.APPLICATION_JSON) @AllowedProjectRoles({AllowedProjectRoles.DATA_SCIENTIST, AllowedProjectRoles.DATA_OWNER}) @JWTRequired(acceptedTokens={Audience.API, Audience.JOB}, allowedUserRoles={"HOPS_ADMIN", "HOPS_USER"}) @ApiKeyRequired( acceptedScopes = {ApiScope.FEATURESTORE}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) public Response getTag(@Context SecurityContext sc, @Context UriInfo uriInfo, @ApiParam(value = "Id of the training dataset", required = true) @PathParam("trainingDatasetId") Integer trainingDatasetId, @ApiParam(value = "Name of the tag", required = true) @PathParam("name") String name, @BeanParam TagsExpansionBeanParam tagsExpansionBeanParam) throws DatasetException, MetadataException, FeaturestoreException, FeatureStoreTagException { verifyIdProvided(trainingDatasetId); Users user = jWTHelper.getUserPrincipal(sc); TrainingDataset trainingDataset = trainingDatasetController.getTrainingDatasetById(featurestore, trainingDatasetId); Map<String, String> result = tagController.get(project, user, featurestore,trainingDataset, name); ResourceRequest resourceRequest = new ResourceRequest(ResourceRequest.Name.TAGS); resourceRequest.setExpansions(tagsExpansionBeanParam.getResources()); TagsDTO dto = tagBuilder.build(uriInfo, resourceRequest, project, featurestore.getId(), ResourceRequest.Name.TRAININGDATASETS.name(), trainingDatasetId, result); return Response.status(Response.Status.OK).entity(dto).build(); } @ApiOperation( value = "Delete all attached tags to training dataset") @DELETE @Path("/{trainingDatasetId}/tags") @Produces(MediaType.APPLICATION_JSON) @AllowedProjectRoles({AllowedProjectRoles.DATA_SCIENTIST, AllowedProjectRoles.DATA_OWNER}) @JWTRequired(acceptedTokens={Audience.API, Audience.JOB}, allowedUserRoles={"HOPS_ADMIN", "HOPS_USER"}) @ApiKeyRequired( acceptedScopes = {ApiScope.FEATURESTORE}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) public Response deleteTags(@Context SecurityContext sc, @ApiParam(value = "Id of the training dataset", required = true) @PathParam("trainingDatasetId") Integer trainingDatasetId) throws DatasetException, MetadataException, FeaturestoreException { verifyIdProvided(trainingDatasetId); Users user = jWTHelper.getUserPrincipal(sc); TrainingDataset trainingDataset = trainingDatasetController.getTrainingDatasetById(featurestore, trainingDatasetId); tagController.deleteAll(project, user, featurestore, trainingDataset); return Response.noContent().build(); } @ApiOperation( value = "Delete tag attached to training dataset") @DELETE @Path("/{trainingDatasetId}/tags/{name}") @Produces(MediaType.APPLICATION_JSON) @AllowedProjectRoles({AllowedProjectRoles.DATA_SCIENTIST, AllowedProjectRoles.DATA_OWNER}) @JWTRequired(acceptedTokens={Audience.API, Audience.JOB}, allowedUserRoles={"HOPS_ADMIN", "HOPS_USER"}) @ApiKeyRequired( acceptedScopes = {ApiScope.FEATURESTORE}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) public Response deleteTag(@Context SecurityContext sc, @ApiParam(value = "Id of the trainingdatasetid", required = true) @PathParam("trainingDatasetId") Integer trainingDatasetId, @ApiParam(value = "Name of the tag", required = true) @PathParam("name") String name) throws DatasetException, MetadataException, FeaturestoreException { verifyIdProvided(trainingDatasetId); Users user = jWTHelper.getUserPrincipal(sc); TrainingDataset trainingDataset = trainingDatasetController.getTrainingDatasetById(featurestore, trainingDatasetId); tagController.delete(project, user, featurestore, trainingDataset, name); return Response.noContent().build(); } @Path("/{trainingDatasetId}/statistics") public StatisticsResource statistics(@PathParam("trainingDatasetId") Integer trainingDatsetId) throws FeaturestoreException { this.statisticsResource.setProject(project); this.statisticsResource.setFeaturestore(featurestore); this.statisticsResource.setTrainingDatasetId(trainingDatsetId); return statisticsResource; } @ApiOperation(value = "Get the query used to generated the training dataset", response = FsQueryDTO.class) @GET @Path("/{trainingdatasetid}/query") @Produces(MediaType.APPLICATION_JSON) @AllowedProjectRoles({AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST}) @JWTRequired(acceptedTokens={Audience.API, Audience.JOB}, allowedUserRoles={"HOPS_ADMIN", "HOPS_USER"}) @ApiKeyRequired( acceptedScopes = {ApiScope.FEATURESTORE}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) public Response getQuery(@Context SecurityContext sc, @Context UriInfo uriInfo, @ApiParam(value = "Id of the trainingdatasetid", required = true) @PathParam("trainingdatasetid") Integer trainingdatasetid, @ApiParam(value = "get query with label features", example = "true") @QueryParam("withLabel") @DefaultValue("true") boolean withLabel) throws FeaturestoreException, ServiceException { verifyIdProvided(trainingdatasetid); Users user = jWTHelper.getUserPrincipal(sc); FsQueryDTO fsQueryDTO = fsQueryBuilder.build(uriInfo, project, user, featurestore, trainingdatasetid, withLabel); return Response.ok().entity(fsQueryDTO).build(); } @POST @Path("/{trainingDatasetId}/compute") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Setup a job to compute and write a training dataset", response = JobDTO.class) @AllowedProjectRoles({AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST}) @JWTRequired(acceptedTokens = {Audience.API, Audience.JOB}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) @ApiKeyRequired(acceptedScopes = {ApiScope.DATASET_VIEW, ApiScope.FEATURESTORE}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) public Response compute(@Context UriInfo uriInfo, @Context SecurityContext sc, @PathParam("trainingDatasetId") Integer trainingDatasetId, TrainingDatasetJobConf trainingDatasetJobConf) throws FeaturestoreException, ServiceException, JobException, ProjectException, GenericException { verifyIdProvided(trainingDatasetId); Users user = jWTHelper.getUserPrincipal(sc); TrainingDataset trainingDataset = trainingDatasetController.getTrainingDatasetById(featurestore, trainingDatasetId); Map<String, String> writeOptions = null; if (trainingDatasetJobConf.getWriteOptions() != null) { writeOptions = trainingDatasetJobConf.getWriteOptions() .stream().collect(Collectors.toMap(OptionDTO::getName, OptionDTO::getValue)); } Jobs job = fsJobManagerController.setupTrainingDatasetJob(project, user, trainingDataset, trainingDatasetJobConf.getQuery(), trainingDatasetJobConf.getOverwrite(), writeOptions, trainingDatasetJobConf.getSparkJobConfiguration()); JobDTO jobDTO = jobsBuilder.build(uriInfo, new ResourceRequest(ResourceRequest.Name.JOBS), job); return Response.created(jobDTO.getHref()).entity(jobDTO).build(); } @Path("/{trainingDatasetId}/provenance") public ProvArtifactResource provenance(@PathParam("trainingDatasetId") Integer trainingDatasetId) throws FeaturestoreException, GenericException { String tdName = featurestore.getProject().getName() + "_" + Settings.ServiceDataset.TRAININGDATASETS.getName(); Dataset targetEndpoint; try { targetEndpoint = datasetController.getByName(featurestore.getProject(), tdName); } catch (DatasetException ex) { throw new GenericException(RESTCodes.GenericErrorCode.ILLEGAL_ARGUMENT, Level.FINE, "training dataset not found"); } this.provenanceResource.setContext(project, targetEndpoint); TrainingDataset td = trainingDatasetController.getTrainingDatasetById(featurestore, trainingDatasetId); this.provenanceResource.setArtifactId(td.getName(), td.getVersion()); return provenanceResource; } @Path("/{trainingDatasetId}/keywords") public FeaturestoreKeywordResource keywords ( @ApiParam(value = "Id of the training dataset") @PathParam("trainingDatasetId") Integer trainingDatasetId) throws FeaturestoreException { this.featurestoreKeywordResource.setProject(project); this.featurestoreKeywordResource.setFeaturestore(featurestore); this.featurestoreKeywordResource.setTrainingDatasetId(trainingDatasetId); return featurestoreKeywordResource; } @Path("/{trainingDatasetId}/activity") public ActivityResource activity(@ApiParam(value = "Id of the training dataset") @PathParam("trainingDatasetId") Integer trainingDatasetId) throws FeaturestoreException { this.activityResource.setProject(project); this.activityResource.setFeaturestore(featurestore); this.activityResource.setTrainingDatasetId(trainingDatasetId); return this.activityResource; } /** * Verify that the user id was provided as a path param * * @param trainingDatasetId the training dataset id to verify */ private void verifyIdProvided(Integer trainingDatasetId) { if (trainingDatasetId == null) { throw new IllegalArgumentException(RESTCodes.FeaturestoreErrorCode.TRAINING_DATASET_ID_NOT_PROVIDED.getMessage()); } } /** * Verify that the name was provided as a path param * * @param trainingDatasetName the training dataset id to verify */ private void verifyNameProvided(String trainingDatasetName) { if (Strings.isNullOrEmpty(trainingDatasetName)) { throw new IllegalArgumentException(RESTCodes.FeaturestoreErrorCode. TRAINING_DATASET_NAME_NOT_PROVIDED.getMessage()); } } @ApiOperation(value = "Get prepared statements used to generate model serving vector from training dataset query", response = ServingPreparedStatementDTO.class) @GET @Path("/{trainingdatasetid}/preparedstatements") @Produces(MediaType.APPLICATION_JSON) @AllowedProjectRoles({AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST}) @JWTRequired(acceptedTokens={Audience.API, Audience.JOB}, allowedUserRoles={"HOPS_ADMIN", "HOPS_USER"}) @ApiKeyRequired( acceptedScopes = {ApiScope.FEATURESTORE}, allowedUserRoles = {"HOPS_ADMIN", "HOPS_USER"}) public Response getQuery(@Context SecurityContext sc, @Context UriInfo uriInfo, @ApiParam(value = "Id of the trainingdatasetid", required = true) @PathParam("trainingdatasetid") Integer trainingdatasetid) throws FeaturestoreException { verifyIdProvided(trainingdatasetid); Users user = jWTHelper.getUserPrincipal(sc); ServingPreparedStatementDTO servingPreparedStatementDTO = preparedStatementBuilder.build(uriInfo, new ResourceRequest(ResourceRequest.Name.PREPAREDSTATEMENTS), project, user, featurestore, trainingdatasetid); return Response.ok().entity(servingPreparedStatementDTO).build(); } }
package org.opennms.netmgt.jasper.resource; import java.io.File; import java.util.Arrays; import org.opennms.netmgt.jasper.helper.JRobinDirectoryUtil; public class ResourceQuery { private String m_rrdDir; private String m_node; private String m_resourceName; private String m_foriegnSource; private String m_foriegnId; private String[] m_filters; private String[] m_strProperties; private JRobinDirectoryUtil m_dirUtil = new JRobinDirectoryUtil(); public ResourceQuery() { } public String getRrdDir() { return m_rrdDir; } public void setRrdDir(String rrdDir) { m_rrdDir = rrdDir; } public String getNodeId() { return m_node; } public void setNodeId(String node) { m_node = node; } public String getResourceName() { return m_resourceName; } public void setResourceName(String resourceName) { m_resourceName = resourceName; } public String[] getFilters() { return m_filters; } public void setFilters(String[] filters) { m_filters = Arrays.copyOf(filters, filters.length); } public String getForeignSource() { return m_foreignSource; } public void setForeignSource(String foreignSource) { m_foreignSource = foreignSource; } public String getForeignId() { return m_foreignId; } public void setForeignId(String foreignId) { m_foreignId = foreignId; } public String constructBasePath() { if (!m_dirUtil.isStoreByForeignSource()) { return getRrdDir() + File.separator + getNodeId() + File.separator + getResourceName(); } else { return m_dirUtil.getNodeLevelResourceDirectory(getRrdDir(), getNodeId(), getForeignSource(), getForeignId()) + File.separator + getResourceName(); } } public String[] getStringProperties() { return m_strProperties; } public void setStringProperties(String[] strProperties) { m_strProperties = Arrays.copyOf(strProperties, strProperties.length); } }
package org.mozartoz.truffle.runtime; import org.mozartoz.truffle.nodes.OzNode; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.source.SourceSection; public abstract class Variable { private @CompilationFinal Object value = null; private boolean needed = false; /** A circular list of linked Variable */ private Variable next = this; protected SourceSection declaration; public boolean isBound() { return value != null; } public Object getBoundValue(OzNode currentNode) { final Object value = this.value; if (!isBound()) { CompilerDirectives.transferToInterpreterAndInvalidate(); throw new OzException(currentNode, "unbound var"); } return value; } public void link(Variable other) { assert !isBound(); assert !other.isBound(); assert !isLinkedTo(other); // Link both circular lists Variable oldNext = this.next; this.next = other.next; other.next = oldNext; } public boolean isLinkedTo(Variable other) { Variable var = this; do { if (var == other) { return true; } var = var.next; } while (var != this); return false; } public Variable getNext() { return next; } public void setInternalValue(Object value, Variable from) { assert !isBound(); assert !(value instanceof Variable); assert !(this instanceof OzFuture) || from instanceof OzFuture; this.value = value; } public void bind(Object value) { setInternalValue(value, this); Variable var = next; while (var != this) { var.setInternalValue(value, this); var = var.next; } } public boolean isNeeded() { Variable var = this; do { if (var.needed) { return true; } var = var.next; } while (var != this); return false; } public void makeNeeded() { this.needed = true; } public Object waitValue(OzNode currentNode) { makeNeeded(); return waitValueQuiet(currentNode); } @TruffleBoundary public Object waitValueQuiet(OzNode currentNode) { assert !isBound(); while (!isBound()) { OzThread.getCurrent().suspend(currentNode); } return getBoundValue(currentNode); } @Override public abstract String toString(); }
package edu.nettester; import edu.nettester.db.MeasureContract.MeasureLog; import edu.nettester.db.MeasureDBHelper; import edu.nettester.task.RTTTask; import edu.nettester.util.CommonMethod; import edu.nettester.util.Constant; import android.support.v7.app.ActionBar.Tab; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.SimpleCursorAdapter; import android.support.v4.widget.SimpleCursorAdapter.ViewBinder; import android.app.Activity; import android.content.Intent; import android.content.res.AssetManager; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; /** * Main UI Activity * * @author Daoyuan */ public class MainActivity extends ActionBarActivity implements Constant { @Override protected void onCreate(Bundle savedInstanceState) { if (DEBUG) Log.d(TAG, "enter MainActivity: onCreate"); super.onCreate(savedInstanceState); // Notice that setContentView() is not used, because we use the root // android.R.id.content as the container for each fragment // see ft.add(android.R.id.content, mFragment, mTag); //setContentView(R.layout.activity_main); /* * init server list */ try { if (!CommonMethod.isFileExists(ServerListPath)) { // copy the default server list AssetManager am = getAssets(); InputStream is = am.open(ServerListName); CommonMethod.writeFile(ServerListPath, is); is.close(); } CommonMethod.readServerList(ServerListPath); } catch (IOException e) { Log.e(TAG, e.toString()); } // setup action bar for tabs ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayShowTitleEnabled(true); Tab tab1, tab2; tab1 = actionBar.newTab() .setText(R.string.tab_measure) .setTabListener(new TabListener<MeasureFragment>( this, "Measure", MeasureFragment.class)); tab2 = actionBar.newTab() .setText(R.string.tab_result) .setTabListener(new TabListener<ResultFragment>( this, "Result", ResultFragment.class)); if (savedInstanceState == null) { actionBar.addTab(tab1); actionBar.addTab(tab2); } else { actionBar.addTab(tab1, false); actionBar.addTab(tab2, false); } if (DEBUG) Log.d(TAG, "exit MainActivity: onCreate"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch (id) { case R.id.action_settings: openSettingsActivity(); return true; default: return super.onOptionsItemSelected(item); } } /** * jump to SettingsActivity */ private void openSettingsActivity() { Intent intent = new Intent(MainActivity.this, SettingsActivity.class); startActivity(intent); } @Override protected void onSaveInstanceState(Bundle outState) { if (DEBUG) Log.d(TAG, "enter MainActivity: onSaveInstanceState"); super.onSaveInstanceState(outState); int i = getSupportActionBar().getSelectedNavigationIndex(); outState.putInt(selectedTab, i); if (DEBUG) Log.d(TAG, "exit MainActivity: onSaveInstanceState"); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { if (DEBUG) Log.d(TAG, "enter MainActivity: onRestoreInstanceState"); super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState != null) { int index = savedInstanceState.getInt(selectedTab); getSupportActionBar().setSelectedNavigationItem(index); } if (DEBUG) Log.d(TAG, "exit MainActivity: onRestoreInstanceState"); } /** * A fragment for measure tab * @author Daoyuan */ public static class MeasureFragment extends Fragment { private Button btn_test; private Spinner spinner; private String target = null; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View rootView = inflater.inflate(R.layout.fragment_measure, container, false); btn_test = (Button) rootView.findViewById(R.id.btn_test); spinner = (Spinner) rootView.findViewById(R.id.spinner); initButtons(); initSpinner(); return rootView; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } private void initSpinner() { ArrayList<String> arrayList1 = new ArrayList<String>(servermap.keySet()); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<String> adapter = new ArrayAdapter<String> ( getActivity(), android.R.layout.simple_spinner_dropdown_item, arrayList1); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { target = parent.getItemAtPosition(position).toString(); Toast.makeText(getActivity(), servermap.get(target), Toast.LENGTH_SHORT) .show(); } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback } }); } private void initButtons() { btn_test.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "Prepare to test", Toast.LENGTH_SHORT) .show(); new RTTTask(getActivity()).execute(target); } }); } } /** * A fragment for result tab * @author Daoyuan */ public static class ResultFragment extends Fragment { private TextView text_result; private ListView list_result; private MeasureDBHelper mDbHelper; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View rootView = inflater.inflate(R.layout.fragment_result, container, false); text_result = (TextView) rootView.findViewById(R.id.text_result); list_result = (ListView) rootView.findViewById(R.id.list_result); initListView(); return rootView; } private void initListView() { mDbHelper = new MeasureDBHelper(getActivity()); Cursor cursor = mDbHelper.fetchAllLogs(); String[] fromColumns = {MeasureLog.M_NET_INFO, MeasureLog.DOWN_TP, MeasureLog.UP_TP, MeasureLog.AVG_RTT}; //int[] toViews = {R.id.mlog_mid, R.id.mlog_time, R.id.mlog_rtt}; int[] toViews = {R.id.item1, R.id.text2, R.id.text3, R.id.text4}; if (DEBUG) Log.d(TAG, "Count: " + cursor.getCount()); SimpleCursorAdapter adapter = new SimpleCursorAdapter( getActivity(), //android.R.layout.simple_list_item_1, //R.layout.list_item, R.layout.mylist_item_single_choice, cursor, fromColumns, toViews, 0); // set auto transmission adapter.setViewBinder(new ViewBinder() { public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex) { if (aColumnIndex == aCursor.getColumnIndex(MeasureLog.M_NET_INFO)) { if (DEBUG) Log.d(TAG, "Enter into M_NET_INFO"); String value = aCursor.getString(aColumnIndex); ImageView imageView = (ImageView) aView; if (value.equals("WIFI")) imageView.setImageResource(R.drawable.result_ic_wifi_highlighted); else imageView.setImageResource(R.drawable.result_ic_cell_highlighted); return true; } if (aColumnIndex == aCursor.getColumnIndex(MeasureLog.DOWN_TP)) { String value = aCursor.getString(aColumnIndex); TextView textView = (TextView) aView; textView.setText(CommonMethod.transferTP(value)); return true; } else if (aColumnIndex == aCursor.getColumnIndex(MeasureLog.UP_TP)) { String value = aCursor.getString(aColumnIndex); TextView textView = (TextView) aView; textView.setText(CommonMethod.transferTP(value)); return true; } else if (aColumnIndex == aCursor.getColumnIndex(MeasureLog.AVG_RTT)) { String value = aCursor.getString(aColumnIndex); TextView textView = (TextView) aView; textView.setText(CommonMethod.transferAVG_RTT(value)); return true; } return false; } }); list_result.setAdapter(adapter); list_result.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Get the cursor, positioned to the corresponding row in the result set Cursor cursor = (Cursor) list_result.getItemAtPosition(position); String muid = cursor.getString(cursor.getColumnIndex(MeasureLog.MUID)); Toast.makeText(getActivity(), muid, Toast.LENGTH_SHORT) .show(); } }); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @Override public void onResume() { super.onResume(); //new DisplayResult(getActivity(), text_result).execute(); } } public static class TabListener<T extends Fragment> implements ActionBar.TabListener { private Fragment mFragment; private final Activity mActivity; private final String mTag; private final Class<T> mClass; /** Constructor used each time a new tab is created. * @param activity The host Activity, used to instantiate the fragment * @param tag The identifier tag for the fragment * @param clz The fragment's Class, used to instantiate the fragment */ public TabListener(Activity activity, String tag, Class<T> clz) { mActivity = activity; mTag = tag; mClass = clz; } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { // Check if the fragment is already initialized if (mFragment == null) { // If not, instantiate and add it to the activity mFragment = Fragment.instantiate(mActivity, mClass.getName()); ft.replace(android.R.id.content, mFragment, mTag); //http://code.google.com/p/android/issues/detail?id=58602#c30 } else { // If it exists, simply attach it in order to show it ft.attach(mFragment); } } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { if (mFragment != null) { // Detach the fragment, because another one is being attached ft.detach(mFragment); } } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { // User selected the already selected tab. Usually do nothing. } } }
package com.lucafontanili.designpatterns.factorymethod; import org.apache.log4j.Logger; public class SystemTrace implements TraceInterface { private boolean debug; private static final Logger LOGGER = Logger.getRootLogger(); @Override public void setDebug(boolean debug) { this.debug = debug; } @Override public void debug(String message) { if (this.debug) { System.out.println("DEBUG: " + message); } } @Override public void error(String message) { LOGGER.error("ERROR: " + message); } }
package org.navalplanner.business.costcategories.entities; import java.math.BigDecimal; import org.apache.commons.lang.StringUtils; import org.hibernate.validator.NotEmpty; import org.navalplanner.business.common.IntegrationEntity; import org.navalplanner.business.common.Registry; import org.navalplanner.business.costcategories.daos.ITypeOfWorkHoursDAO; /** * @author Jacobo Aragunde Perez <jaragunde@igalia.com> */ public class TypeOfWorkHours extends IntegrationEntity { private String name; private BigDecimal defaultPrice; boolean enabled = true; // Default constructor, needed by Hibernate protected TypeOfWorkHours() { } public static TypeOfWorkHours create() { return (TypeOfWorkHours) create(new TypeOfWorkHours()); } public static TypeOfWorkHours create(String code, String name) { return (TypeOfWorkHours) create(new TypeOfWorkHours(code, name)); } public static TypeOfWorkHours createUnvalidated(String code, String name, Boolean enabled, BigDecimal defaultPrice) { TypeOfWorkHours typeOfWorkHours = create( new TypeOfWorkHours(code, name), code); if (enabled != null) { typeOfWorkHours.enabled = enabled; } if (defaultPrice != null) { typeOfWorkHours.defaultPrice = defaultPrice; } return typeOfWorkHours; } public void updateUnvalidated(String name, Boolean enabled, BigDecimal defaultPrice) { if (!StringUtils.isBlank(name)) { this.name = name; } if (enabled != null) { this.enabled = enabled; } if (defaultPrice != null) { this.defaultPrice = defaultPrice; } } protected TypeOfWorkHours(String code, String name) { setCode(code); this.name = name; } @NotEmpty(message = "name not specified") public String getName() { return name; } public void setName(String name) { this.name = name; } public BigDecimal getDefaultPrice() { return defaultPrice; } public void setDefaultPrice(BigDecimal price) { this.defaultPrice = price; } public boolean getEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } @Override protected ITypeOfWorkHoursDAO getIntegrationEntityDAO() { return Registry.getTypeOfWorkHoursDAO(); } }